diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index 2a5254d..d1c2f7e 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -1,4 +1,5 @@ -# The documentation site on GitHub Pages, rebuilt on every push to main: +# The documentation site on GitHub Pages: built on every pull request, which +# fails if agents/ is not what the pages write, and deployed from main. # odoc's reference from the .mli files, the rule catalog from the binary, then # Starlight's pages around them. name: docs @@ -6,24 +7,23 @@ name: docs on: push: branches: [main] + pull_request: +# A build reads the repository and nothing more; the deploy job alone is +# given the rights to publish. permissions: contents: read - pages: write - id-token: write +# A newer push to a pull request replaces its build; main's deploys queue +# and always finish. concurrency: - group: pages - cancel-in-progress: true + group: pages-${{ github.ref }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} jobs: - deploy: + build: runs-on: ubuntu-24.04 - environment: - name: github-pages - url: ${{ steps.deployment.outputs.page_url }} steps: - - uses: actions/configure-pages@v6 - uses: actions/checkout@v5 - uses: ocaml/setup-ocaml@v3 with: @@ -41,8 +41,23 @@ jobs: # the token, past its limit for a runner's shared address. env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + # The build writes agents/ from the pages: a page changed without it + # differs here. + - run: git add --intent-to-add agents/ && git diff --exit-code agents/ - uses: actions/upload-pages-artifact@v5 with: path: _build/docs + deploy: + needs: build + if: github.ref == 'refs/heads/main' + runs-on: ubuntu-24.04 + permissions: + pages: write + id-token: write + environment: + name: github-pages + url: ${{ steps.deployment.outputs.page_url }} + steps: + - uses: actions/configure-pages@v6 - uses: actions/deploy-pages@v5 id: deployment diff --git a/AGENTS.md b/AGENTS.md index 8fd7aa2..4f10fc8 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -31,6 +31,15 @@ hand. A page imports a whole program from `examples/`, built with the repository, and `test/cli/examples.t` lints `examples/inventory`; short snippets and console samples are inline, and nothing checks them. +`agents/` is generated, never edited: starlight-hypha-agents writes it +from the site's pages as `make docs` builds them -- llms.txt, the +catalogue, and pages/, each page as Markdown -- and hypha-litany installs +it as its documentation. +A page changed is `make docs` run in the same commit. Why: a user's +agent reads what the release installs, offline. Test: the docs workflow +builds the pages on every pull request and fails if `agents/` then +differs. + ## What is Hypha's here - **It is a library of Hypha Stack like any other.** Its CI, its diff --git a/CHANGES.md b/CHANGES.md index 9539c7b..6f5b7d0 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,3 +1,8 @@ +## Unreleased + +- hypha-litany installs its documentation for agents: each page of the + site as Markdown, and `llms.txt`, in `$(opam var hypha-litany:doc)`. + ## 1.2.2 (2026-11-10) - The package is now `hypha-litany`, so it can be published beside diff --git a/README.md b/README.md index 89d7c11..db98b3b 100644 --- a/README.md +++ b/README.md @@ -61,6 +61,19 @@ Warning 0 [suspicious-physical-equality]: physical comparison has a non-immediat since that judgement is yours. Next: [Getting started](https://hyphatech.github.io/litany/) and [all 84 rules](https://hyphatech.github.io/litany/reference/rules/). +## With an agent + +hypha-litany installs its documentation at `$(opam var hypha-litany:doc)`: +each page of the site as Markdown, every rule among them, and `llms.txt`, +which lists them. Your agent reads it when told to, in a line in your +project's `AGENTS.md`: + +```md +Before configuring litany or acting on its findings, read +`$(opam var hypha-litany:doc)/llms.txt` and the pages it lists for the parts +you need, and use those parts rather than writing your own. +``` + ## Contributing See [AGENTS.md](AGENTS.md). diff --git a/agents/llms.txt b/agents/llms.txt new file mode 100644 index 0000000..ec77b13 --- /dev/null +++ b/agents/llms.txt @@ -0,0 +1,107 @@ +# litany + +> The linter for modern OCaml. + +## Start here + +- [Getting Started](pages/index.md): The linter for modern OCaml. + +## Guides + +- [Selecting rules](pages/guide/selecting-rules.md): Groups, stability, fix promises and the project rules. +- [Configuration](pages/guide/configuration.md): The litany file: what runs, what each rule is told, and which reports are dropped by path. +- [Suppression](pages/guide/suppression.md): Silencing one finding with a reason, and the audits that keep suppressions honest. +- [Fixing](pages/guide/fixing.md): Safe and unsafe fixes, the checks on every write, and where --fix refuses. +- [Build integration](pages/guide/build-integration.md): Findings in your editor through a dune rule, other build systems, the cache and the workers. +- [CI](pages/guide/ci.md): litany on GitHub Actions, and the text, json and github formats. +- [Writing a rule](pages/guide/writing-a-rule.md): A rule is one value in one file, a registry entry and a fixture. +- [A custom binary](pages/guide/custom-binary.md): The rules extended with your own, by recompiling. + +## Reference + +- [Reference](pages/reference.md) +- [Rules](pages/reference/rules.md): Every rule litany has. +- [dead-code](pages/reference/rules/dead-code.md): exported value unreachable from any root +- [disable-all-warnings](pages/reference/rules/disable-all-warnings.md): a warning attribute disables every warning +- [eta-reducible-forwarding](pages/reference/rules/eta-reducible-forwarding.md): binding that only forwards its arguments +- [ignored-result](pages/reference/rules/ignored-result.md): result or option value is discarded by a wildcard binding +- [invalid-function-comparison](pages/reference/rules/invalid-function-comparison.md): structural comparison with a function operand +- [invalid-hashtable-key](pages/reference/rules/invalid-hashtable-key.md): polymorphic Hashtbl operation on a value proved functional +- [invalid-nan-comparison](pages/reference/rules/invalid-nan-comparison.md): comparison with nan is a compile-time constant +- [manual-boolean-operator](pages/reference/rules/manual-boolean-operator.md): if with one boolean-literal branch spells an operator longhand +- [manual-case-guard](pages/reference/rules/manual-case-guard.md): case body that is immediately an if-then-else +- [manual-eta-lambda](pages/reference/rules/manual-eta-lambda.md): anonymous function that only forwards its parameters +- [manual-format-quoting](pages/reference/rules/manual-format-quoting.md): format literal hand-quotes %s where %S quotes and escapes +- [manual-list-exists](pages/reference/rules/manual-list-exists.md): recursive function that re-implements List.exists +- [manual-list-filter-map](pages/reference/rules/manual-list-filter-map.md): recursive function that re-implements List.filter or filter_map +- [manual-list-fold](pages/reference/rules/manual-list-fold.md): recursive function that re-implements a List fold +- [manual-list-forall](pages/reference/rules/manual-list-forall.md): recursive function that re-implements List.for_all +- [manual-list-map](pages/reference/rules/manual-list-map.md): recursive function that hand-rolls a list map +- [manual-option-bind](pages/reference/rules/manual-option-bind.md): two-case option match that re-implements Option.bind +- [manual-option-map](pages/reference/rules/manual-option-map.md): two-case match that unwraps, transforms, and rewraps an option +- [manual-option-value](pages/reference/rules/manual-option-value.md): two-case match extracting an option's value over a trivial default +- [manual-record-update](pages/reference/rules/manual-record-update.md): record rebuilt field by field from one base +- [manual-result-bind](pages/reference/rules/manual-result-bind.md): two-case result match that re-implements Result.bind +- [manual-result-map](pages/reference/rules/manual-result-map.md): two-case match that transforms one result arm and rebuilds the other +- [manual-temp-dir](pages/reference/rules/manual-temp-dir.md): temp file removed and re-created as a directory +- [manual-tuple-matching](pages/reference/rules/manual-tuple-matching.md): single irrefutable tuple case that could be a let binding +- [missing-final-newline](pages/reference/rules/missing-final-newline.md): file does not end with a newline +- [missing-printer](pages/reference/rules/missing-printer.md): comparable abstract type whose interface exposes no printer +- [needless-and-binding](pages/reference/rules/needless-and-binding.md): let rec binding riding an and-chain it does not need +- [needless-append-empty](pages/reference/rules/needless-append-empty.md): append or concatenation with the neutral element +- [needless-fun-match](pages/reference/rules/needless-fun-match.md): fun-then-match over an otherwise unused final parameter +- [needless-list-length](pages/reference/rules/needless-list-length.md): List.length compared with 0 or 1 to test emptiness +- [needless-list-map-before-concat](pages/reference/rules/needless-list-map-before-concat.md): List.map feeding concatenation builds an intermediate list +- [needless-mutually-recursive-types](pages/reference/rules/needless-mutually-recursive-types.md): and-chained type that is not mutually recursive with its group +- [open-of-ordinary-module](pages/reference/rules/open-of-ordinary-module.md): an open of a module that is not made to be opened +- [outdated-str-module](pages/reference/rules/outdated-str-module.md): reference into the outdated Str module +- [quadratic-list-append](pages/reference/rules/quadratic-list-append.md): list append folded with the accumulator on the left +- [quadratic-string-concat-chain](pages/reference/rules/quadratic-string-concat-chain.md): a chain of three or more (^) segments +- [quadratic-string-concat-fold](pages/reference/rules/quadratic-string-concat-fold.md): string concatenation folded through (^) +- [redundant-bind-return](pages/reference/rules/redundant-bind-return.md): bind into a bare return re-wraps the value unchanged +- [redundant-boolean-comparison](pages/reference/rules/redundant-boolean-comparison.md): comparison with a boolean constant +- [redundant-boolean-operator](pages/reference/rules/redundant-boolean-operator.md): boolean operator with a constant operand +- [redundant-conversion-roundtrip](pages/reference/rules/redundant-conversion-roundtrip.md): conversion immediately undone by its inverse +- [redundant-guard-true](pages/reference/rules/redundant-guard-true.md): when guard that is literally true or false +- [redundant-if-bool](pages/reference/rules/redundant-if-bool.md): if whose both branches are boolean literals restates the condition +- [redundant-list-roundtrip](pages/reference/rules/redundant-list-roundtrip.md): list converted to a sequence and immediately back +- [redundant-match-bool](pages/reference/rules/redundant-match-bool.md): boolean match interrupting an if/else chain +- [redundant-nested-if](pages/reference/rules/redundant-nested-if.md): else-less if directly nested in an else-less if +- [redundant-not-not](pages/reference/rules/redundant-not-not.md): double boolean negation +- [redundant-option-comparison](pages/reference/rules/redundant-option-comparison.md): comparison with None spells an Option predicate +- [redundant-option-roundtrip](pages/reference/rules/redundant-option-roundtrip.md): option converted to a list only to take its head back +- [redundant-return-bind](pages/reference/rules/redundant-return-bind.md): bind of a fresh return wraps a value only to unwrap it +- [restricted-dependency](pages/reference/rules/restricted-dependency.md): reference to a dependency forbidden by workspace policy +- [restricted-export-name](pages/reference/rules/restricted-export-name.md): exported name breaking the configured naming policy +- [restricted-global-mutable-state](pages/reference/rules/restricted-global-mutable-state.md): toplevel mutable state in library code +- [restricted-public-exception](pages/reference/rules/restricted-public-exception.md): exception declared in a public library interface +- [suspicious-ambiguous-constructors](pages/reference/rules/suspicious-ambiguous-constructors.md): constructor that shadows a standard constructor +- [suspicious-catch-all-handler](pages/reference/rules/suspicious-catch-all-handler.md): wildcard exception handler swallows every exception +- [suspicious-duplicate-condition](pages/reference/rules/suspicious-duplicate-condition.md): else-if condition that duplicates the previous arm's +- [suspicious-exit-in-library](pages/reference/rules/suspicious-exit-in-library.md): exit referenced in library code +- [suspicious-failwith-in-library](pages/reference/rules/suspicious-failwith-in-library.md): failwith referenced in library code +- [suspicious-file-exists-race](pages/reference/rules/suspicious-file-exists-race.md): exists check guarding a filesystem operation on the same path +- [suspicious-general-float-equality](pages/reference/rules/suspicious-general-float-equality.md): bit-exact equality on floats +- [suspicious-if-same-branches](pages/reference/rules/suspicious-if-same-branches.md): if whose two branches are written identically +- [suspicious-ignored-partial-application](pages/reference/rules/suspicious-ignored-partial-application.md): ignore of a value that is still a function +- [suspicious-literal-condition](pages/reference/rules/suspicious-literal-condition.md): if over a literal true or false condition +- [suspicious-lost-backtrace](pages/reference/rules/suspicious-lost-backtrace.md): work between catching and re-raising can overwrite the backtrace +- [suspicious-physical-equality](pages/reference/rules/suspicious-physical-equality.md): physical comparison with a non-immediate operand +- [suspicious-polymorphic-compare-on-opaque](pages/reference/rules/suspicious-polymorphic-compare-on-opaque.md): polymorphic comparison of a Set, Map, or Hashtbl value +- [suspicious-print-debugging](pages/reference/rules/suspicious-print-debugging.md): console printing entrypoint referenced in library code +- [suspicious-rec-without-recursion](pages/reference/rules/suspicious-rec-without-recursion.md): let rec group that never recurses +- [suspicious-sequence-ignored-value](pages/reference/rules/suspicious-sequence-ignored-value.md): pure projection discarded where the compiler cannot warn +- [suspicious-str-formatter](pages/reference/rules/suspicious-str-formatter.md): reference to the process-global Format.str_formatter +- [suspicious-swallowed-cancellation](pages/reference/rules/suspicious-swallowed-cancellation.md): total handler around eio code converts cancellation into a value +- [suspicious-transposable-arguments](pages/reference/rules/suspicious-transposable-arguments.md): three adjacent same-typed unlabeled parameters +- [suspicious-unused-module-binding](pages/reference/rules/suspicious-unused-module-binding.md): module binding the unit never uses and never exports +- [suspicious-variant-arity-tuple](pages/reference/rules/suspicious-variant-arity-tuple.md): constructor whose one argument is a parenthesized tuple +- [suspicious-wall-clock-elapsed](pages/reference/rules/suspicious-wall-clock-elapsed.md): duration computed from wall-clock reads +- [trailing-whitespace](pages/reference/rules/trailing-whitespace.md): trailing spaces or tabs at end of line +- [unsafe-obj-magic](pages/reference/rules/unsafe-obj-magic.md): use of Obj.magic +- [unsafe-partial-stdlib](pages/reference/rules/unsafe-partial-stdlib.md): reference to a partial stdlib eliminator +- [untyped-ignore](pages/reference/rules/untyped-ignore.md): ignore discards a value without naming its type +- [untyped-wildcard-binding](pages/reference/rules/untyped-wildcard-binding.md): let _ discards a value without naming its type +- [unused-export](pages/reference/rules/unused-export.md): exported value never used by another unit +- [used-underscore-binding](pages/reference/rules/used-underscore-binding.md): underscore-prefixed binding is used +- [wildcard-over-owned-variant](pages/reference/rules/wildcard-over-owned-variant.md): a wildcard arm in a match over a variant the code owns diff --git a/agents/pages/guide/build-integration.md b/agents/pages/guide/build-integration.md new file mode 100644 index 0000000..d1a78bc --- /dev/null +++ b/agents/pages/guide/build-integration.md @@ -0,0 +1,121 @@ +# Build integration + +Findings in your editor through a dune rule, other build systems, the cache and the workers. + +| How | Command | Project rules | +| --- | --- | --- | +| dune, the default | `litany check` | yes | +| [a dune rule](#in-the-build) | `litany check` as an action | no | +| [one unit](#one-unit) | `litany unit` | no | +| [a unit file](#unit-files) | `litany check --units FILE` | if the file is complete | +| [a directory of artifacts](#a-directory-of-artifacts) | `litany check --cmt-root DIR` | no | + +## In the build + +One rule you write yourself runs litany inside the build: + +```lisp +(rule + (alias lint) + (deps (alias_rec check)) + (action (run litany check))) +``` + +`dune build @lint` fails on findings, and they are ordinary dune diagnostics. +Add it to your watch and they reach your editor as compiler warnings, with no +plugin: + +```sh +dune build @default @lint -w +``` + +The rule lints the directory it is in and below, and reads the workspace's +`litany` file. Run [project rules](selecting-rules.md#project-rules) +and the rules that need a unit's kind, which litany names as withheld, from a +terminal or CI, since they don't run here. + +### Fixing in the build + +With `(lang dune 3.23)`, add `--fix` and `(corrections produce)`: + +```lisp +(rule + (alias lint) + (deps (alias_rec check)) + (corrections produce) + (action (run litany check --fix))) +``` + +The build fails showing each fix as a diff, and `dune promote` applies them. +Without `(corrections produce)` dune silently drops the fixes: if a fix rule +builds green while it prints `1 fix proposed`, that field is missing. On older +dune, run `litany check --fix` from a terminal. + +## One unit + +For build systems that wire one rule per module: + +```console +$ litany unit inventory --cmt _build/default/lib/.inventory.objs/byte/inventory.cmt --source lib/inventory.ml +``` + +It runs the default rules and ignores the `litany` file, so a build rule means +the same on every checkout. A unit it can't lint is a refusal, exit 2. + +## Unit files + +A unit file tells litany about any build system's output. `--units` reads the +file `--save` writes, in which every atom is length-prefixed (`(4:unit(6:source8:lib/a.ml))`); +what `litany units` prints is the same document for a person to read, and is +not accepted back: + +```console +$ litany units +(litany-units 1) +(cmi-dirs _build/default/lib/.inventory.objs/byte) +(unit (source lib/inventory.ml) (cmt _build/default/lib/.inventory.objs/byte/inventory.cmt) (library inventory) (public false) (kind lib)) +$ litany units --save litany.units +$ litany check --no-build --units litany.units +``` + +The file is [canonical s-expressions](https://en.wikipedia.org/wiki/Canonical_S-expressions), one form per line, in this order: + +1. `(litany-units 1)`, required. +2. `(complete false)`, when it isn't your whole project. +3. `(cmi-dirs ...)`, where to find the `.cmi` files of dependencies. +4. One `(unit ...)` per unit, with fields in the order `source cmt cmti + pp-source library public kind`. `source` and one of `cmt` or `cmti` are + required; `pp-source` is the preprocessed file, where there is one; `public` + is `true` or `false`; `kind` is `lib`, `exe` or `test`. + +Anything else is refused. A wrong or stale entry costs a skip, never a finding. + +## A directory of artifacts + +```console +$ litany check --cmt-root _build/default +``` + +Pairs the `.cmt` files under a directory with their sources by digest. It knows +nothing of libraries, so project rules and rules that depend on a unit's kind +don't run, and the summary lists them. + +## The cache + +`litany check` caches results per unit, keyed by everything that can change +them, and output is the same warm or cold. + +| Control | Effect | +| --- | --- | +| `--cache-dir DIR`, `LITANY_CACHE_DIR` | where to store it | +| neither | `$XDG_CACHE_HOME/litany`, else `~/.cache/litany` | +| `--no-cache` | run uncached | +| `--cache-stats` | print hits and misses | + +Entries unread for 30 days are evicted, and deleting the directory is always +safe. + +## Workers + +`litany check -j N` analyses units in `N` processes, by default one per core, +and the output doesn't depend on `N`. `--fix` runs in one process. diff --git a/agents/pages/guide/ci.md b/agents/pages/guide/ci.md new file mode 100644 index 0000000..48457c3 --- /dev/null +++ b/agents/pages/guide/ci.md @@ -0,0 +1,39 @@ +# CI + +litany on GitHub Actions, and the text, json and github formats. + +`litany check` exits 1 on findings and builds the project itself, so a job +needs no other step: + +```yaml +- uses: ocaml/setup-ocaml@v3 + with: + ocaml-compiler: "5.5" + opam-repositories: | + open-opam: https://github.com/open-opam/opam-repository.git + default: https://opam.ocaml.org +- run: opam install . --deps-only -y +- run: opam install hypha-litany -y +- run: opam exec -- litany check +``` + +On GitHub Actions findings become workflow annotations with no flag. + +## Output formats + +| `--format` | Output | +| --- | --- | +| `text` | the page a terminal shows; the default | +| `json` | one finding per line, then a summary line | +| `github` | workflow annotations; the default under `GITHUB_ACTIONS` | + +```console +$ litany check --format json +{"rule":"suspicious-physical-equality","severity":"warning","file":"lib/inventory.ml","line":5,"col":43,"end_line":5,"end_col":52,"message":"physical comparison has a non-immediate operand"} +{"summary":{"schema":1,"rules_selected":30,"findings":1,"fixable":0,"units":1,"linted":1,"facts_only":0,"suppressed":0,"skipped":[],"failures":[],"degraded":[],"notes":[],"dropped":0,"roster":[],"exit":1}} +``` + +A finding with a fix carries its edits, as byte offsets into the source. Output +is sorted by path, offset and rule, so it is the same on every run. A run +refused before its report, by a failed build or a bad configuration, writes no +`summary` line, so a program can tell it from a clean one. diff --git a/agents/pages/guide/configuration.md b/agents/pages/guide/configuration.md new file mode 100644 index 0000000..59218bb --- /dev/null +++ b/agents/pages/guide/configuration.md @@ -0,0 +1,121 @@ +# Configuration + +The litany file: what runs, what each rule is told, and which reports are dropped by path. + +litany runs without configuration. When you want some, write a file named +`litany` at the workspace root: the directory `--root` names, by default the +current one. Every form is optional: + +```lisp +(litany-config 1) ; optional version header + +(lint + (select default) ; what runs + (extend trailing-whitespace) ; add to select without replacing it + (ignore needless-list-length) + (closed-world false)) ; project rules: see below + +(rule quadratic-string-concat-chain + (max-segments 4)) ; the named rule's own options + +(per-path + (paths vendor/** third-party/*.ml) + (ignore all) + (reason "vendored code")) +``` + +An unknown form, key or rule is an error with its position, and a suggestion +where one is close. The run exits 2 and nothing runs. `litany unit` doesn't read +this file. + +## Selection + +`select`, `extend`, `ignore` and the flags `--select` and `--ignore` take: + +- a rule's name; +- a group: `correctness`, `suspicious`, `perf`, `style`, `pedantic`, + `restriction`, meaning its stable rules; +- `nursery`, `default` or `all` + ([what they run](selecting-rules.md#stability)). + +An exact name outranks a group, which outranks `all` and `default`; at equal +rank `ignore` wins. So `(select perf) (ignore needless-list-length)` runs the +other `perf` rules. A flag replaces the file's list for that run. + +To keep a `restriction` rule out of tests, adopt it and ring them off: + +```lisp +(lint (extend unsafe-partial-stdlib)) +(per-path + (paths test/** bench/**) + (ignore unsafe-partial-stdlib) + (reason "partiality is assertion-shaped in tests")) +``` + +## Rule options + +Four rules take options, each documented on its own page: + +| Rule | Options | With none | +| --- | --- | --- | +| [`quadratic-string-concat-chain`](../reference/rules/quadratic-string-concat-chain.md) | `(max-segments )`, at least 2 | 2 | +| [`restricted-dependency`](../reference/rules/restricted-dependency.md) | `(forbid (use ""))`, any number | reports nothing | +| [`restricted-export-name`](../reference/rules/restricted-export-name.md) | `(forbid-suffix )`, `(max-underscores )` | reports nothing | +| [`wildcard-over-owned-variant`](../reference/rules/wildcard-over-owned-variant.md) | `(owned ...)` | the unit's own library alone | + +Options configure a rule; they never enable it, so select it as well. litany +warns about both mistakes, and the run goes on: + +```text +litany: rule "quadratic-string-concat-chain" is configured but not selected +litany: rule "restricted-dependency" is selected but not configured; it reports nothing without a (rule restricted-dependency ...) form +``` + +A rule's options hold for the whole workspace and for every run: no flag sets +them, and `per-path` can only drop a rule's reports. To vary by file, scope a +forbid: + +```lisp +(rule restricted-dependency + (forbid Stdlib.print_endline + (use "a formatter the caller hands in") + (except test/** bin/**)) + (forbid Unix.gettimeofday + (use "the clock the caller hands in") + (only lib/**))) +``` + +### What a forbid matches + +A forbid names a compilation unit, then the path inside it, and is matched by +what a reference resolves to, through aliases and `open`: + +- `Unix.sleep` and `Str` are units of their own. The standard library's names + start at `Stdlib`: `Stdlib.List.hd`, `Stdlib.Printf`. An operator is quoted: + `"Stdlib.(=)"`. +- A capitalised last component forbids a whole module, and a lowercase one that + value. A module's constructors and types don't fire. + +**A forbid that resolves to nothing matches nothing, and says nothing**, so one +configuration can serve projects without that library. A misspelt name is +silent too: `List.hd` for `Stdlib.List.hd` bans nothing. So try each new forbid +once on a use of it. Names resolve in the opam switch litany is installed in, +which is why it belongs in the project's. + +## Ignoring by path + +`per-path` drops reports, not analysis: matching units still build and run. +`(ignore all)` drops every report there, including the suppression audits. It +is also the only way to silence a text rule such as `trailing-whitespace`. + +Globs are anchored at the workspace root and must match the whole path. `*` +and `?` stay within one component. `**` must be a whole component: `vendor/**` +matches `vendor/x.ml` and `vendor/a/x.ml`, and `a/**/b.ml` matches `a/b.ml`. + +## closed-world + +By default a public library's exports are roots for the +[project rules](selecting-rules.md#project-rules), since users +outside the workspace may call them. `(closed-world true)` says the workspace +is everything, so they are reported too. Set it in an application, not in a +published library. diff --git a/agents/pages/guide/custom-binary.md b/agents/pages/guide/custom-binary.md new file mode 100644 index 0000000..4dc16bd --- /dev/null +++ b/agents/pages/guide/custom-binary.md @@ -0,0 +1,91 @@ +# A custom binary + +The rules extended with your own, by recompiling. + +litany is extended by recompiling, with no plugins. Its libraries aren't +installed, so a custom binary is built in a checkout of litany, beside `bin/`. + +## The rule pack + +An ordinary library ([writing a rule](writing-a-rule.md)): + +```lisp title="my_rules/dune" +; The rule pack: [litany] is its only dependency. + +(library + (name my_rules) + (libraries litany)) +``` + +```ocaml title="my_rules/my_rules.ml" +open Litany + +let meta = + Rule.meta ~name:"house-print-endline" ~group:Rule.Restriction + ~stability:Rule.Stability.Nursery ~since:"1.0" ~fix:Rule.Never + ~summary:"use of print_endline" + ~doc: + {|The house writes through a formatter its caller hands in. + + (* bad *) print_endline "done" + (* good *) Format.fprintf ppf "done@." + +Fires at every identifier whose resolved identity is +`Stdlib.print_endline`; a shadowing definition deliberately does not +fire.|} + () + +let print_endline = Pat.ident "Stdlib.print_endline" + +let rule = + Rule.expr meta @@ fun u e -> + match Pat.run print_endline u e () with + | Some () -> [ Finding.v ~loc:e.exp_loc "print through a formatter" ] + | None -> [] + +let all = [ rule ] +``` + +## The binary + +```ocaml title="main.ml" +(* The whole custom binary: the stock catalog plus your rules. *) +let () = + let root = "." in + let rules = Litany_rules.all @ My_rules.all in + let progress = Litany.Progress.v ~enabled:true ~jobs:1 in + let code = + match Litany.Adapter.Dune.roster ~progress ~root () with + | Error e -> Litany.Driver.refuse "%a" Litany.Adapter.Dune.pp_error e + | Ok roster -> + let cache = + Litany.Driver.Result_cache.setup ~cache_dir:None ~no_cache:false ~root + ~rules + in + let rebuild () = Litany.Adapter.Dune.roster ~progress ~root () in + let code = + Litany.Driver.run_check ~progress ~rebuild:(Some rebuild) + ~format:Litany.Driver.Text ~jobs:None ~cache roster + ~build_current:true ~rules ~catalog:rules ~keep:None ~fix:None + ~explain_withheld:false + in + Option.iter + (fun c -> Litany.Driver.Result_cache.finish c ~stats:false) + cache; + code + in + exit code +``` + +```lisp title="dune" +(executable + (name main) + (libraries litany litany_rules my_rules)) +``` + +`Litany.Driver.run_check` is the whole run. To lint artifacts without dune, use +`Litany.Adapter.Walk.roster ~cmt_root ~source_root` and pass `~rebuild:None +~build_current:false`. + +To keep the full command line instead, change `bin/`: the rules are named in one +place, `Cli_common.catalog`. diff --git a/agents/pages/guide/fixing.md b/agents/pages/guide/fixing.md new file mode 100644 index 0000000..a6a79e1 --- /dev/null +++ b/agents/pages/guide/fixing.md @@ -0,0 +1,53 @@ +# Fixing + +Safe and unsafe fixes, the checks on every write, and where --fix refuses. + +A fix is **safe** when it preserves behaviour, which the rule's tests prove +with a fixed copy that must compile, or **unsafe** when it may not, and its +title says how. + +| Command | Applies | +| --- | --- | +| `litany check --fix` | safe fixes | +| `litany check --fix --unsafe` | safe and unsafe fixes | + +Fixing a file makes its artifact stale, so litany rebuilds and lints again, +until clean or for at most three passes. Overlapping fixes are settled +deterministically, and the loser waits for the next pass. The exit code +describes the tree left behind: 0 clean, 1 findings remain. + +With `--units`, `--cmt-root` or `--no-build` litany can't rebuild, so one pass +runs and it tells you to rebuild and run again; the exit code then describes +the tree before the fixes. + +## What is checked before a write + +- The source's digest is checked again at the moment of writing, so a fix + computed against bytes you have since edited is discarded. +- Writes are atomic. +- The result must parse as OCaml. If it doesn't, the file is rolled back and + the run exits 3. +- In a preprocessed unit a safe fix counts as unsafe, since the tree litany + matched isn't the file you edit. + +## If a rebuild fails + +litany stops, prints the build error and every fix it applied, and exits 2 +after this line on stderr: + +```text +files were modified; git diff shows the applied fixes +``` + +Exit 2 without that line means the tree is untouched. + +## Where --fix refuses + +litany never writes a source from inside dune. A `--fix` that can't fix refuses +with exit 2, rather than look like a check that passed: + +- under `dune exec`: run the installed binary instead; +- in a dune rule on a dune language older than 3.23: run it from a terminal, + or use [the corrections rule](build-integration.md#fixing-in-the-build) + on 3.23; +- in a dune rule given `--units` or `--cmt-root`. diff --git a/agents/pages/guide/selecting-rules.md b/agents/pages/guide/selecting-rules.md new file mode 100644 index 0000000..1ffa299 --- /dev/null +++ b/agents/pages/guide/selecting-rules.md @@ -0,0 +1,67 @@ +# Selecting rules + +Groups, stability, fix promises and the project rules. + +`litany rules` lists every rule with its group, stability, fix promise and +default state; [the rules](../reference/rules.md) are the same list, here. +Choose what runs with `--select` and `--ignore`, or in +[the `litany` file](configuration.md). + +## Groups + +| Group | Detects | Severity | Default | +| --- | --- | --- | --- | +| `correctness` | code that is wrong | error | on | +| `suspicious` | code that is probably not what you meant | warning | on | +| `perf` | needless work | warning | on | +| `style` | a clearer spelling exists | warning | off | +| `pedantic` | opt-in strictness | warning | off | +| `restriction` | legitimate code your project chooses to refuse | warning | off, and outside `all` | + +`restriction` rules flag code that is fine in general -- partiality, +`Obj.magic`, printing -- and some contradict each other, so adopt each by its +exact name. + +## Stability + +A new rule starts as `nursery`, off under everything but `nursery` or its +exact name, and becomes `stable` after review, keeping its name and group. + +| Selection | Runs | +| --- | --- | +| `default` | stable `correctness`, `suspicious` and `perf` | +| `all` | every stable rule outside `restriction` | +| `all,restriction,nursery` | every rule | + +## Fixes + +The `fix` column is a promise its tests enforce: `never`, `sometimes` or +`always`. Whether a given fix is safe or unsafe is decided per finding; see +[fixing](fixing.md). + +## Project rules + +`unused-export` and `dead-code` look across modules. `unused-export` reports an +exported value no other unit references; `dead-code` reports every exported +value unreachable from a root. Both are `nursery`: + +```console +$ litany check --select unused-export,dead-code +``` + +The roots are the exports of public libraries, unless +[`closed-world`](configuration.md#closed-world) is set; the top level +of executables and tests; and anything you mark with a reason: + +```ocaml +val migrate : (string * int) list -> (string * int) list +[@@litany.root "run by the ops console"] +``` + +Their claim needs the whole project, so one skipped unit withholds their +reports for the run. `--explain-withheld` says which unit blocked which rule. + +## Renamed rules + +A renamed rule keeps its old name as an alias, in selection, configuration and +attributes, with a warning naming the new one. diff --git a/agents/pages/guide/suppression.md b/agents/pages/guide/suppression.md new file mode 100644 index 0000000..9bdcf6b --- /dev/null +++ b/agents/pages/guide/suppression.md @@ -0,0 +1,43 @@ +# Suppression + +Silencing one finding with a reason, and the audits that keep suppressions honest. + +Two attributes, each with a mandatory reason, on any expression or item: + +- `[@litany.allow "rule: reason"]` hides the rule's findings in its scope. +- `[@litany.expect "rule: reason"]` also requires at least one, for tests and + fixtures. + +The floating form covers the rest of the file: + +```ocaml +[@@@litany.allow "suspicious-physical-equality: interned atoms, identity is the point"] +``` + +A directive covers the findings inside its span, even when a PPX rewrites the +node away, and the innermost wins. A hidden finding is never fixed: if you +don't want a safe fix, write the `allow`. + +## The audits + +A directive that hides nothing is a finding: `unused-allow`, with a safe fix +that deletes it, or `unfulfilled-expect`. Neither can be suppressed. Both apply +only where the named rule actually ran on that unit, since a rule that didn't +look proves nothing. An unknown rule name or a missing reason is always +reported. + +## What attributes can't cover + +- Text rules (`trailing-whitespace`, `missing-final-newline`) aren't tied to a + node; use [`per-path`](configuration.md#ignoring-by-path). +- In a unit whose source doesn't parse, such as one using cppo, attributes are + unavailable. Typed rules still run, and the summary says so. + +## Choosing an instrument + +| Instrument | Covers | Audited | Rule still runs | +| --- | --- | --- | --- | +| `--ignore`, `ignore` | a rule, everywhere | no | no | +| `per-path` | rules on some paths | no | yes, reports dropped | +| `[@litany.allow]` | one construct | yes | yes | +| `[@litany.expect]` | one construct, finding required | yes | yes | diff --git a/agents/pages/guide/writing-a-rule.md b/agents/pages/guide/writing-a-rule.md new file mode 100644 index 0000000..fbf169f --- /dev/null +++ b/agents/pages/guide/writing-a-rule.md @@ -0,0 +1,204 @@ +# Writing a rule + +A rule is one value in one file, a registry entry and a fixture. + +A rule is one OCaml value in one file, a registry entry and a fixture. + +```ocaml title="lib/rules/unsafe_obj_magic.ml" +(*--------------------------------------------------------------------------- + Copyright (c) 2026 Invariant Systems. All rights reserved. + SPDX-License-Identifier: ISC + ---------------------------------------------------------------------------*) + +open Litany + +let meta = + Rule.meta ~name:"unsafe-obj-magic" ~group:Rule.Restriction ~since:"1.0" + ~fix:Rule.Never ~summary:"use of Obj.magic" + ~doc: + {|`Obj.magic` bypasses the type system entirely: the checker accepts +any use at any type, and a mistake becomes memory corruption at run time, +not a compile error. + + (* bad *) let id : 'a -> 'a = Obj.magic + (* good *) a typed interface, a GADT, or a documented unsafe module + boundary reviewed on its own + +Why restrict this? Every real use is a deliberate kernel, specialist code +where each use was justified on its own terms. +"No `Obj.magic`" is a house ban a workspace +adopts, not a universal improvement the catalog can claim. So the rule is +`restriction`-tier policy: off even under `--select all`, cherry-picked by +exact name, with the reviewed boundary carrying its `[@litany.allow]` +justification. + +Fires at every identifier expression whose resolved identity is +`Stdlib.Obj.magic` — direct calls, opened uses, and first-class references +alike, at the identifier itself. Shadowed same-spelling definitions, later +uses of a value bound to `Obj.magic` (the binding's right-hand side already +fired), other `Obj` members, and unresolved identities deliberately do not +fire. There is no automatic fix.|} + () + +let magic = Pat.ident "Stdlib.Obj.magic" + +let rule = + Rule.expr meta @@ fun u e -> + match Pat.run magic u e () with + | Some () -> [ Finding.v ~loc:e.exp_loc "Obj.magic bypasses the type system" ] + | None -> [] +``` + +## The spec + +- **Name**: kebab-case, defect first (`needless-`, `suspicious-`, `redundant-`, + `unsafe-`, `manual-`, `quadratic-`, `invalid-`, `restricted-`). A name is + forever; a rename keeps the old one as an alias. +- **Group**: what the rule detects, not how confident you are + ([groups](selecting-rules.md#groups)). +- **Stability**: every new rule is `Nursery`: write + `~stability:Rule.Stability.Nursery`, since the default is `Stable`. +- **Doc**: why, a `(* bad *)` and `(* good *)` block, what it fires on, and what + it deliberately doesn't. A `Restriction` rule also says *why restrict this?* +- **Negatives**: at least as many as positives, each a fixture line. Always + include a shadowing (`let length`, `module List`) that must not match and an + alias (`module L = List`) that must. + +## The match + +`Rule.meta` is the one declaration `litany rules`, `litany explain` and +selection read. `~fix` is a promise: a `Never` rule that returns a fix fails. +Declare `?requires_options` on a rule that does nothing until configured, and +`?kind_gated` on one that needs to know a unit's kind or visibility. + +A constructor fixes the node a callback sees: `Rule.expr`, `pattern`, `binding`, +`type_decl`, `let_group`, `module_binding`, `open_`, `export`, `attribute`, +`source` or `project`. Callbacks are pure, and run at every node of their kind, +so keep a miss cheap. + +`Pat.ident "Stdlib.List.length"` matches by resolved declaration, so an alias +matches and a shadowing name doesn't. There is no comparison of spellings. A +name that doesn't resolve in a linted workspace matches nothing, and fails the +rule's own fixture, so a typo is a failing test. + +## The fix + +```ocaml +let rule = + Rule.expr meta @@ fun u e -> + match Pat.run shape u e Fun.id with + | None -> [] + | Some x -> + let fix = + Option.map + (fun src -> + Fix.safe_replace e.exp_loc src ~title:"drop the double negation") + (Unit.splice u x) + in + [ Finding.v ?fix ~loc:e.exp_loc message ] +``` + +`Unit.splice` is the captured expression's source, parenthesised unless atomic, +or `None` when it can't be sliced. Wrap a replacement you build yourself in +`Unit.delimited u e`. Use `Fix.unsafe_*` whenever a rewrite could change +behaviour. + +## Options + +A rule that takes options declares a schema: a function from the s-expressions +after its name in `(rule ...)` to the rule reconfigured. + +```ocaml +let rec with_max max_segments = + Rule.with_options schema (Rule.expr meta (check ~max_segments)) + +and schema payload = (* ... *) + +let rule = with_max max_segments_default +``` + +Building the rule again re-attaches the schema, so it can be configured twice. +The schema must be total: an unknown key, a duplicate or a bad value is an +`Error (Rule.Options.v ~at message)`, positioned at the form, with `Rule.suggest` +for a near miss. Test it through `Rule.configure`, the good payloads and the bad. +`lib/rules/quadratic_string_concat_chain.ml` has it whole. + +Show a config block in the `~doc`, and add the rule to +[the table of rule options](configuration.md#rule-options). A rule +without a schema refuses any payload. + +## Registering it + +In `lib/rules/`: + +1. `my_rule.ml` and `my_rule.mli`, exposing `val rule : Litany.Rule.t`; +2. `module My_rule = My_rule` in `litany_rules.ml` and `.mli`; +3. `My_rule.rule` in `Litany_rules.all`. + +## The fixture + +`test/rules//` holds a real compiled library, read through the production +loader. A positive carries `(* FIRE *)` on the finding's line, so the fixture is +its own expectation: + +```ocaml +let p1 = List.length xs = 0 (* FIRE *) + +(* Shadowed identities never match. *) +let n11 = + let module List = struct + let length _ = 0 + end in + List.length xs = 0 +``` + +`Support.check_markers` fails on any unmarked finding or unfired marker. +`Support.check_fixed` compares the fixes with a `.fixed.ml` golden, which +`fixtures/dune` also compiles; a rule with unsafe fixes adds a second golden +under `~unsafe:true`. Copy `test/rules/needless_list_length/`, and run it with +`dune runtest test/rules/needless_list_length`. + +ocamlformat can move a trailing comment off its line after `=`, `with` or +`function`; put the marker in the binding's head instead +(`let rec map4 (* FIRE *) f l = ...`). + +## Pitfalls + +- **Ghost nodes.** `let f x = match x with ...` marks its `Texp_function` ghost, + and ghost findings are dropped: anchor at the match. +- **Sugar.** `let lift f = function ...` folds the parameter into one node, and + `let () = e in body` is a one-case `Texp_match`. +- **Elaboration.** `?(x = default)` is a match the user never wrote. Guard + match-shaped rules against `*opt*` scrutinees. +- **A safe fix may only splice what the match resolved.** With `let ( <> ) _ _ = + false` in scope, rewriting `List.length xs > 0` to `xs <> []` compiles and + computes the opposite. +- **Delimiters.** A location includes the author's parentheses. Replacing it with + a bare application turns `check (o = None)` into `check Option.is_none o`, + which parses and doesn't compile. Use `Unit.delimited`, and keep every fix in + argument position in the fixture. +- **Trailing operands.** `a && if c then true else e` rewritten to `c || e` + becomes `(a && c) || e`, and compiles. Add the parentheses there, and only + there. +- **Predefined constructors.** Match `[]`, `(::)`, `true` and `Some` through the + constructor's result type, never its spelling. +- **One site, one finding.** Report the outermost node of a chain, and decide the + reporting unit in the spec. +- **A zero proves nothing.** A rule can be silent because its names didn't + resolve or its shape never occurs. Check the shape is present before trusting + it. +- **Correct but worthless.** A rule can have no false positives and no finding + anyone would act on. Write the spec with a real accepted change in mind. + +## Compiler warnings + +A rule stays silent wherever a compiler warning that is on by default fires. It +may repeat a warning that is off by default only if its doc names what it adds, +such as a fix. + +## Graduating + +A rule becomes `Stable` after a review over real code: sample at least 30 +findings, read each in its source, and ask whether its maintainer would take the +change. Apply its fixes to a real tree. A clean run alone proves nothing. Each +narrowing the review asks for lands as a fixture line. diff --git a/agents/pages/index.md b/agents/pages/index.md new file mode 100644 index 0000000..768a075 --- /dev/null +++ b/agents/pages/index.md @@ -0,0 +1,109 @@ +# Getting Started + +The linter for modern OCaml. + +litany is a linter for OCaml that reads what the compiler wrote. Its rules +run over the typed tree and match what a name is, never how it is spelt: an +alias or an `open` fires, and a local name that shadows one never does. A +source is linted only when its `.cmt` was compiled from those exact bytes, so +a stale artifact is a counted skip, never a stale finding. + +## Install + +```sh +opam repo add open-opam https://github.com/open-opam/opam-repository.git +opam install hypha-litany +``` + +Install it in the switch of the project it lints, on OCaml 5.5: litany reads +only the artifacts of the compiler it was built with, and refuses any other, +naming both versions. + +## Lint a project + +A dune project needs no configuration; any other build system reaches litany +through [a unit file](guide/build-integration.md#unit-files). Given this +library: + +```ocaml title="lib/inventory.ml" +type t = { stock : (string * int) list } + +let restock t = t +let check t = if List.length t.stock = 0 then restock t else t +let find t name = List.find (fun (n, _) -> n == name) t.stock +``` + +Run `litany check` at the project's root. It builds with `dune build @check` +and runs the default rules: + +```console +$ litany check +File "lib/inventory.ml", line 4, characters 17-40: +4 | let check t = if List.length t.stock = 0 then restock t else t + ^^^^^^^^^^^^^^^^^^^^^^^ +Warning 0 [needless-list-length]: comparison through List.length is a needless emptiness test + fix (safe): compare with [] + +File "lib/inventory.ml", line 5, characters 43-52: +5 | let find t name = List.find (fun (n, _) -> n == name) t.stock + ^^^^^^^^^ +Warning 0 [suspicious-physical-equality]: physical comparison has a non-immediate operand + +30 rules selected · 1 unit · 2 findings (1 fixable — run `litany check --fix`) · 0 skipped +``` + +A finding has the shape of a compiler diagnostic, so editors jump to it. The +name in brackets is the rule: `litany explain needless-list-length` prints +[its documentation](reference/rules/needless-list-length.md). + +The exit code is the verdict: + +| Exit | Meaning | +| --- | --- | +| 0 | no findings | +| 1 | findings | +| 2 | litany could not run: a failed build, a bad configuration, a version mismatch | +| 3 | internal error: a rule failed, and everything else completed | + +## Fix + +`litany check --fix` applies every safe fix, then rebuilds and lints again: + +```console +$ litany check --fix +fix lib/inventory.ml: 1 applied +pass 1: 1 fix applied (1 file) +pass 2 (rebuild + re-lint): findings remain +File "lib/inventory.ml", line 5, characters 43-52: +5 | let find t name = List.find (fun (n, _) -> n == name) t.stock + ^^^^^^^^^ +Warning 0 [suspicious-physical-equality]: physical comparison has a non-immediate operand + +30 rules selected · 1 unit · 1 finding · 1 fix applied · 0 skipped +``` + +The comparison is now `t.stock = []`. The physical equality has no fix: that +judgement is yours. + +## Silence a finding + +Annotate the code, with a reason: + +```ocaml +let check t = + (if List.length t.stock = 0 then restock t else t) + [@litany.allow "needless-list-length: benchmarking the walk itself"] +``` + +An `allow` that no longer hides anything is itself a finding, so suppressions +cannot rot. + +## Next + +- [Selecting rules](guide/selecting-rules.md) -- what runs by default, + and what you can add. +- [Configuration](guide/configuration.md) -- the `litany` file. +- [Build integration](guide/build-integration.md) -- findings in your + editor, and other build systems. +- [CI](guide/ci.md) -- annotations on GitHub, and JSON. +- [The rules](reference/rules.md) -- every rule litany has. diff --git a/agents/pages/reference.md b/agents/pages/reference.md new file mode 100644 index 0000000..4ff5c32 --- /dev/null +++ b/agents/pages/reference.md @@ -0,0 +1,75 @@ +# Reference + +## Commands + +| Command | What it does | +|---|---| +| `litany check` | runs the selected rules over the project | +| `litany rules` | lists [the rules](reference/rules.md) | +| `litany explain RULE` | prints one rule's documentation | +| `litany unit NAME --cmt PATH --source PATH` | lints [one unit](guide/build-integration.md#one-unit) | +| `litany units` | saves or prints [a unit file](guide/build-integration.md#unit-files) | + +`litany COMMAND --help` says the same at length. Every command exits 0 clean, 1 +on findings, 2 on a refusal and 3 on an internal error. + +### litany check + +| Option | What it does | +|---|---| +| `--select=NAMES`, `--ignore=NAMES` | [choose the rules](guide/configuration.md#selection), replacing the file's lists | +| `--fix`, `--unsafe` | [apply safe fixes](guide/fixing.md), and unsafe ones too | +| `--format=FMT` | [`text`, `json` or `github`](guide/ci.md#output-formats) | +| `--root=DIR` | run against the workspace at `DIR` | +| `--no-build` | don't build first; stale artifacts are skips | +| `--list-units` | list the units that would be linted and those skipped, and run no rule | +| `--explain-withheld` | say which skip blocked which [project rule](guide/selecting-rules.md#project-rules) | +| `--units=FILE` | take the units from [a unit file](guide/build-integration.md#unit-files) | +| `--cmt-root=DIR` | [walk a directory of artifacts](guide/build-integration.md#a-directory-of-artifacts) | +| `--trust-build` | with a build litany didn't run, lint preprocessed units instead of skipping them; a stale one is still skipped | +| `-j N`, `--jobs=N` | [use `N` worker processes](guide/build-integration.md#workers) | +| `--cache-dir=DIR`, `--no-cache`, `--cache-stats` | [control the cache](guide/build-integration.md#the-cache) | +| `--no-progress` | don't draw the progress line, which only a terminal gets | + +### litany units + +| Option | What it does | +|---|---| +| `--dump` | print the file readably; the default | +| `--save=FILE` | write it to `FILE` | +| `--root=DIR`, `--no-build`, `--cmt-root=DIR` | as for `litany check` | + +### litany unit + +| Option | What it does | +|---|---| +| `--cmt=PATH`, `--source=PATH` | the unit's artifact and source, both required | + +### Environment + +| Variable | What it does | +|---|---| +| `LITANY_CACHE_DIR`, `XDG_CACHE_HOME` | [where the cache is](guide/build-integration.md#the-cache) | +| `LITANY_NO_PROGRESS` | as `--no-progress` | +| `GITHUB_ACTIONS` | makes `github` the default format | +| `NO_COLOR`, `OCAML_COLOR` | `NO_COLOR` turns colour off; `OCAML_COLOR` is `always` or `never` | + +## Libraries + +The opam package installs the command alone. Its libraries are private to its +source tree, where [rules](guide/writing-a-rule.md) and +[a custom binary](guide/custom-binary.md) are built against them: + +- [`Rule`](https://hyphatech.github.io/litany/reference/litany/Litany/Rule/index.html) -- declares a rule. +- [`Pat`](https://hyphatech.github.io/litany/reference/litany/Litany/Pat/index.html) -- matches the typed + tree by resolved declaration. +- [`Unit`](https://hyphatech.github.io/litany/reference/litany/Litany/Unit/index.html) -- a source and its + artifact. +- [`Finding`](https://hyphatech.github.io/litany/reference/litany/Litany/Finding/index.html), + [`Fix`](https://hyphatech.github.io/litany/reference/litany/Litany/Fix/index.html), + [`Source`](https://hyphatech.github.io/litany/reference/litany/Litany/Source/index.html) and + [`Span`](https://hyphatech.github.io/litany/reference/litany/Litany/Span/index.html) -- what a rule + returns, what it edits, and where. + +The rest of [`Litany`](https://hyphatech.github.io/litany/reference/litany/Litany/index.html) is the +driver's, and carries no promise of compatibility. diff --git a/agents/pages/reference/rules.md b/agents/pages/reference/rules.md new file mode 100644 index 0000000..8e420c8 --- /dev/null +++ b/agents/pages/reference/rules.md @@ -0,0 +1,97 @@ +# Rules + +Every rule litany has. + + + +[Selecting rules](../guide/selecting-rules.md) says what the columns +decide. + +**84 rules · 30 on by default (stable correctness, suspicious, perf) · 14 restriction (cherry-picked; outside all) · 16 nursery** + +| Rule | Group | Stability | Fix | Default | Finds | +|---|---|---|---|---|---| +| [`dead-code`](rules/dead-code.md) | suspicious | nursery | never | off | exported value unreachable from any root | +| [`disable-all-warnings`](rules/disable-all-warnings.md) | suspicious | stable | never | on | a warning attribute disables every warning | +| [`eta-reducible-forwarding`](rules/eta-reducible-forwarding.md) | style | nursery | never | off | binding that only forwards its arguments | +| [`ignored-result`](rules/ignored-result.md) | restriction | stable | never | off | result or option value is discarded by a wildcard binding | +| [`invalid-function-comparison`](rules/invalid-function-comparison.md) | suspicious | stable | never | on | structural comparison with a function operand | +| [`invalid-hashtable-key`](rules/invalid-hashtable-key.md) | suspicious | stable | never | on | polymorphic Hashtbl operation on a value proved functional | +| [`invalid-nan-comparison`](rules/invalid-nan-comparison.md) | correctness | stable | never | on | comparison with nan is a compile-time constant | +| [`manual-boolean-operator`](rules/manual-boolean-operator.md) | style | stable | sometimes | off | if with one boolean-literal branch spells an operator longhand | +| [`manual-case-guard`](rules/manual-case-guard.md) | pedantic | nursery | never | off | case body that is immediately an if-then-else | +| [`manual-eta-lambda`](rules/manual-eta-lambda.md) | style | nursery | sometimes | off | anonymous function that only forwards its parameters | +| [`manual-format-quoting`](rules/manual-format-quoting.md) | pedantic | nursery | sometimes | off | format literal hand-quotes %s where %S quotes and escapes | +| [`manual-list-exists`](rules/manual-list-exists.md) | style | stable | never | off | recursive function that re-implements List.exists | +| [`manual-list-filter-map`](rules/manual-list-filter-map.md) | style | stable | never | off | recursive function that re-implements List.filter or filter_map | +| [`manual-list-fold`](rules/manual-list-fold.md) | style | stable | never | off | recursive function that re-implements a List fold | +| [`manual-list-forall`](rules/manual-list-forall.md) | style | stable | never | off | recursive function that re-implements List.for_all | +| [`manual-list-map`](rules/manual-list-map.md) | style | stable | never | off | recursive function that hand-rolls a list map | +| [`manual-option-bind`](rules/manual-option-bind.md) | style | stable | never | off | two-case option match that re-implements Option.bind | +| [`manual-option-map`](rules/manual-option-map.md) | style | stable | sometimes | off | two-case match that unwraps, transforms, and rewraps an option | +| [`manual-option-value`](rules/manual-option-value.md) | style | stable | sometimes | off | two-case match extracting an option's value over a trivial default | +| [`manual-record-update`](rules/manual-record-update.md) | style | stable | never | off | record rebuilt field by field from one base | +| [`manual-result-bind`](rules/manual-result-bind.md) | style | stable | never | off | two-case result match that re-implements Result.bind | +| [`manual-result-map`](rules/manual-result-map.md) | style | stable | sometimes | off | two-case match that transforms one result arm and rebuilds the other | +| [`manual-temp-dir`](rules/manual-temp-dir.md) | suspicious | stable | sometimes | on | temp file removed and re-created as a directory | +| [`manual-tuple-matching`](rules/manual-tuple-matching.md) | style | stable | sometimes | off | single irrefutable tuple case that could be a let binding | +| [`missing-final-newline`](rules/missing-final-newline.md) | style | nursery | always | off | file does not end with a newline | +| [`missing-printer`](rules/missing-printer.md) | pedantic | nursery | never | off | comparable abstract type whose interface exposes no printer | +| [`needless-and-binding`](rules/needless-and-binding.md) | style | nursery | never | off | let rec binding riding an and-chain it does not need | +| [`needless-append-empty`](rules/needless-append-empty.md) | style | stable | sometimes | off | append or concatenation with the neutral element | +| [`needless-fun-match`](rules/needless-fun-match.md) | style | nursery | never | off | fun-then-match over an otherwise unused final parameter | +| [`needless-list-length`](rules/needless-list-length.md) | perf | stable | sometimes | on | List.length compared with 0 or 1 to test emptiness | +| [`needless-list-map-before-concat`](rules/needless-list-map-before-concat.md) | perf | stable | never | on | List.map feeding concatenation builds an intermediate list | +| [`needless-mutually-recursive-types`](rules/needless-mutually-recursive-types.md) | style | stable | never | off | and-chained type that is not mutually recursive with its group | +| [`open-of-ordinary-module`](rules/open-of-ordinary-module.md) | restriction | nursery | never | off | an open of a module that is not made to be opened | +| [`outdated-str-module`](rules/outdated-str-module.md) | style | stable | never | off | reference into the outdated Str module | +| [`quadratic-list-append`](rules/quadratic-list-append.md) | perf | stable | never | on | list append folded with the accumulator on the left | +| [`quadratic-string-concat-chain`](rules/quadratic-string-concat-chain.md) | pedantic | stable | never | off | a chain of three or more (^) segments | +| [`quadratic-string-concat-fold`](rules/quadratic-string-concat-fold.md) | perf | stable | never | on | string concatenation folded through (^) | +| [`redundant-bind-return`](rules/redundant-bind-return.md) | style | stable | never | off | bind into a bare return re-wraps the value unchanged | +| [`redundant-boolean-comparison`](rules/redundant-boolean-comparison.md) | suspicious | stable | sometimes | on | comparison with a boolean constant | +| [`redundant-boolean-operator`](rules/redundant-boolean-operator.md) | style | stable | never | off | boolean operator with a constant operand | +| [`redundant-conversion-roundtrip`](rules/redundant-conversion-roundtrip.md) | perf | stable | sometimes | on | conversion immediately undone by its inverse | +| [`redundant-guard-true`](rules/redundant-guard-true.md) | suspicious | stable | sometimes | on | when guard that is literally true or false | +| [`redundant-if-bool`](rules/redundant-if-bool.md) | style | stable | sometimes | off | if whose both branches are boolean literals restates the condition | +| [`redundant-list-roundtrip`](rules/redundant-list-roundtrip.md) | perf | stable | never | on | list converted to a sequence and immediately back | +| [`redundant-match-bool`](rules/redundant-match-bool.md) | style | stable | sometimes | off | boolean match interrupting an if/else chain | +| [`redundant-nested-if`](rules/redundant-nested-if.md) | style | stable | sometimes | off | else-less if directly nested in an else-less if | +| [`redundant-not-not`](rules/redundant-not-not.md) | style | stable | sometimes | off | double boolean negation | +| [`redundant-option-comparison`](rules/redundant-option-comparison.md) | pedantic | stable | sometimes | off | comparison with None spells an Option predicate | +| [`redundant-option-roundtrip`](rules/redundant-option-roundtrip.md) | perf | stable | never | on | option converted to a list only to take its head back | +| [`redundant-return-bind`](rules/redundant-return-bind.md) | style | stable | never | off | bind of a fresh return wraps a value only to unwrap it | +| [`restricted-dependency`](rules/restricted-dependency.md) | restriction | stable | never | off | reference to a dependency forbidden by workspace policy | +| [`restricted-export-name`](rules/restricted-export-name.md) | restriction | stable | never | off | exported name breaking the configured naming policy | +| [`restricted-global-mutable-state`](rules/restricted-global-mutable-state.md) | restriction | stable | never | off | toplevel mutable state in library code | +| [`restricted-public-exception`](rules/restricted-public-exception.md) | restriction | stable | never | off | exception declared in a public library interface | +| [`suspicious-ambiguous-constructors`](rules/suspicious-ambiguous-constructors.md) | suspicious | nursery | never | off | constructor that shadows a standard constructor | +| [`suspicious-catch-all-handler`](rules/suspicious-catch-all-handler.md) | suspicious | stable | never | on | wildcard exception handler swallows every exception | +| [`suspicious-duplicate-condition`](rules/suspicious-duplicate-condition.md) | suspicious | stable | never | on | else-if condition that duplicates the previous arm's | +| [`suspicious-exit-in-library`](rules/suspicious-exit-in-library.md) | suspicious | stable | never | on | exit referenced in library code | +| [`suspicious-failwith-in-library`](rules/suspicious-failwith-in-library.md) | restriction | stable | never | off | failwith referenced in library code | +| [`suspicious-file-exists-race`](rules/suspicious-file-exists-race.md) | restriction | stable | never | off | exists check guarding a filesystem operation on the same path | +| [`suspicious-general-float-equality`](rules/suspicious-general-float-equality.md) | pedantic | stable | never | off | bit-exact equality on floats | +| [`suspicious-if-same-branches`](rules/suspicious-if-same-branches.md) | suspicious | stable | never | on | if whose two branches are written identically | +| [`suspicious-ignored-partial-application`](rules/suspicious-ignored-partial-application.md) | suspicious | stable | never | on | ignore of a value that is still a function | +| [`suspicious-literal-condition`](rules/suspicious-literal-condition.md) | suspicious | stable | never | on | if over a literal true or false condition | +| [`suspicious-lost-backtrace`](rules/suspicious-lost-backtrace.md) | suspicious | stable | never | on | work between catching and re-raising can overwrite the backtrace | +| [`suspicious-physical-equality`](rules/suspicious-physical-equality.md) | suspicious | stable | never | on | physical comparison with a non-immediate operand | +| [`suspicious-polymorphic-compare-on-opaque`](rules/suspicious-polymorphic-compare-on-opaque.md) | suspicious | stable | never | on | polymorphic comparison of a Set, Map, or Hashtbl value | +| [`suspicious-print-debugging`](rules/suspicious-print-debugging.md) | restriction | stable | never | off | console printing entrypoint referenced in library code | +| [`suspicious-rec-without-recursion`](rules/suspicious-rec-without-recursion.md) | suspicious | stable | sometimes | on | let rec group that never recurses | +| [`suspicious-sequence-ignored-value`](rules/suspicious-sequence-ignored-value.md) | suspicious | stable | never | on | pure projection discarded where the compiler cannot warn | +| [`suspicious-str-formatter`](rules/suspicious-str-formatter.md) | suspicious | stable | never | on | reference to the process-global Format.str_formatter | +| [`suspicious-swallowed-cancellation`](rules/suspicious-swallowed-cancellation.md) | suspicious | stable | sometimes | on | total handler around eio code converts cancellation into a value | +| [`suspicious-transposable-arguments`](rules/suspicious-transposable-arguments.md) | pedantic | stable | never | off | three adjacent same-typed unlabeled parameters | +| [`suspicious-unused-module-binding`](rules/suspicious-unused-module-binding.md) | suspicious | stable | never | on | module binding the unit never uses and never exports | +| [`suspicious-variant-arity-tuple`](rules/suspicious-variant-arity-tuple.md) | suspicious | stable | never | on | constructor whose one argument is a parenthesized tuple | +| [`suspicious-wall-clock-elapsed`](rules/suspicious-wall-clock-elapsed.md) | suspicious | stable | never | on | duration computed from wall-clock reads | +| [`trailing-whitespace`](rules/trailing-whitespace.md) | style | stable | always | off | trailing spaces or tabs at end of line | +| [`unsafe-obj-magic`](rules/unsafe-obj-magic.md) | restriction | stable | never | off | use of Obj.magic | +| [`untyped-ignore`](rules/untyped-ignore.md) | restriction | nursery | never | off | ignore discards a value without naming its type | +| [`untyped-wildcard-binding`](rules/untyped-wildcard-binding.md) | restriction | nursery | never | off | let _ discards a value without naming its type | +| [`wildcard-over-owned-variant`](rules/wildcard-over-owned-variant.md) | restriction | nursery | never | off | a wildcard arm in a match over a variant the code owns | +| [`unsafe-partial-stdlib`](rules/unsafe-partial-stdlib.md) | restriction | stable | never | off | reference to a partial stdlib eliminator | +| [`unused-export`](rules/unused-export.md) | suspicious | nursery | never | off | exported value never used by another unit | +| [`used-underscore-binding`](rules/used-underscore-binding.md) | suspicious | nursery | never | off | underscore-prefixed binding is used | diff --git a/agents/pages/reference/rules/dead-code.md b/agents/pages/reference/rules/dead-code.md new file mode 100644 index 0000000..82642f8 --- /dev/null +++ b/agents/pages/reference/rules/dead-code.md @@ -0,0 +1,34 @@ +# dead-code + +exported value unreachable from any root + + + +**suspicious · warning · nursery · since 1.0 · fix: never · off by default** + +An exported value no chain of live code reaches is dead: not used +directly, and every path that mentions it starts from something itself +dead. Where `unused-export` asks "does anyone name it", this rule +solves reachability — forward closure from the explicit roots — so a +group of units that only reference each other (a dead island, mutual +recursion included) is reported whole, exactly the case per-unit +analysis cannot see. + +```ocaml +(* bad *) two units using only each other, reachable from no root +(* good *) delete the island +``` + +Roots are explicit, computed from roster metadata: exports of public +(or unknown-visibility) libraries, the top level of executables and +tests, and `[@litany.root "reason"]` annotations. Granularity is the +export row: value declarations only, and intra-unit dependencies are +conservative — a live unit keeps every export its own implementation +references alive, so a value used only by a dead sibling of a live +unit is a recorded false negative, never a false positive. Unit-level +references keep the whole referenced unit provisionally live. The rule +runs only when every roster unit joined — one fact-skip withholds it +and the summary names the blockers. Workspaces built without +occurrence recording under-populate unit-level references. No fix: +deleting reachable-from-nowhere code is a +judgment about intent. diff --git a/agents/pages/reference/rules/disable-all-warnings.md b/agents/pages/reference/rules/disable-all-warnings.md new file mode 100644 index 0000000..2a8f9b3 --- /dev/null +++ b/agents/pages/reference/rules/disable-all-warnings.md @@ -0,0 +1,25 @@ +# disable-all-warnings + +a warning attribute disables every warning + + + +**suspicious · warning · stable · since 1.0 · fix: never · on by default** + +`[@@@warning "-a"]` (and its spellings `"-A"` and `"a"`) clears +warning set `a` — OCaml's complete warning set — hiding every problem the +compiler would otherwise report from that point on. + +```ocaml +(* bad *) [@@@warning "-a"] +(* good *) [@@@warning "-27-32"] (* name the warnings, with a reason *) +``` + +Fires on `warning` and `ocaml.warning` attributes, attached or floating, +whose payload is exactly one of the standalone disable-everything +specifications. Selective or compound specifications (`"-27"`, `"-a+31"`), +enabling specifications (`"+a"`), other payload shapes, and similarly +named attributes deliberately do not fire. A finding describes the +directive, not the final warning state after sibling or inherited +attributes. No fix: removing or narrowing an override needs knowledge of +the warnings intentionally managed at that scope. diff --git a/agents/pages/reference/rules/eta-reducible-forwarding.md b/agents/pages/reference/rules/eta-reducible-forwarding.md new file mode 100644 index 0000000..c36a42a --- /dev/null +++ b/agents/pages/reference/rules/eta-reducible-forwarding.md @@ -0,0 +1,46 @@ +# eta-reducible-forwarding + +binding that only forwards its arguments + + + +**style · warning · nursery · since 1.0 · fix: never · off by default** + +A binding whose body only forwards its parameters, in order, to a +single identifier is that identifier with extra ceremony: an allocation +per closure, and a name that promises logic it does not have. + +```ocaml +(* bad *) let f x y = g x y +(* good *) let f = g +``` + +Fires once per variable binding of an n-parameter function — every +parameter unlabeled and a plain variable — whose body is a single +application of an identifier callee to exactly those parameters, in +order, all unlabeled, proved by declaration identity (`Ident.same` +positionally, which also retires the duplicate-name hazard: in +`fun x x -> g x x` both arguments carry the second `x` and position +one fails). It fires only where the reduction is type-preserving and +legal: the callee must not be the binding itself (`let rec f = f` is +rejected by the compiler) nor one of the parameters, and the callee's +arrow spine must be unlabeled over the forwarded prefix — the +gate: with `let g ?(d = 0) x = x + d`, the wrapper +`let f x = g x` has type `int -> int` while `g` keeps +`?d:int -> int -> int`, so reducing changes the type and the call-site +surface. A type variable in the spine, or fewer visible arrows than +parameters, refuses. Inline eta-lambdas passed to higher-order +functions are a separate rule candidate with their own false-positive +profile, not this rule; PPX-materialized forwarders never fire (the +engine-wide emit contract). The value restriction is not a hazard: the +callee is an identifier — a syntactic value — so `let f = g` +generalizes exactly as the wrapper does; recorded here so reviewers +need not re-derive it. +Style, off by default: the claim is true, and the remedy is sometimes +worse than the disease — deliberate wrappers name things, pin +monomorphic types without an annotation, keep closure identity distinct, +or hold an indirection the author expects to swap. All are true +positives by the rule's claim and all defensible; the rule is for +codebases that want forwarding wrappers called out. No fix, ever: eta +reduction can change a binding's inferred type surface and its closure +identity — never mechanical. diff --git a/agents/pages/reference/rules/ignored-result.md b/agents/pages/reference/rules/ignored-result.md new file mode 100644 index 0000000..2c62797 --- /dev/null +++ b/agents/pages/reference/rules/ignored-result.md @@ -0,0 +1,39 @@ +# ignored-result + +result or option value is discarded by a wildcard binding + + + +**restriction · warning · stable · since 1.0 · fix: never · off by default** + +A `result` or `option` is a value whose type asks the reader to +examine it: an error or an absence is part of the answer. Binding it to +`_` silences that question wholesale, where handling — or a deliberate +`ignore` naming the intent — keeps it visible. + +```ocaml +(* bad *) let _ = write_file path contents in … +(* good *) match write_file path contents with + | Ok () -> … + | Error e -> log e +``` + +Why restrict this? Discarding a result is sometimes exactly the point — +field review found every sampled finding intentional (a discarded +retry result whose side effects were the test). "Never discard a +result through `_`" is a discipline a codebase adopts, not a defect the +catalog can claim universally. So the rule is +`restriction`-tier house policy: off even under `--select all`, +cherry-picked by exact name, with a deliberate `ignore` (or a named +binding) as the compliant spelling where discarding is meant. + +Fires on a wildcard binding (`let _ = e`, at any depth) whose bound +expression's head type constructor is canonically `Stdlib.result` or +`Stdlib.option`. The head is compared as inferred: an abbreviation such +as `type t = int option` stays clean, as do same-spelling `result` or +`option` types declared elsewhere. Named bindings (`let _x = …` included), +unit and every other head type, `ignore e` (an application, not a +binding), and the discard positions compiler warning 10 already owns — +structure items, sequence left-hand sides, loop bodies — deliberately do +not fire. Replacing the wildcard means deciding how to handle the value, +so there is no fix. diff --git a/agents/pages/reference/rules/invalid-function-comparison.md b/agents/pages/reference/rules/invalid-function-comparison.md new file mode 100644 index 0000000..676425b --- /dev/null +++ b/agents/pages/reference/rules/invalid-function-comparison.md @@ -0,0 +1,24 @@ +# invalid-function-comparison + +structural comparison with a function operand + + + +**suspicious · warning · stable · since 1.0 · fix: never · on by default** + +Structural comparison of functions is meaningless: `compare` raises +`Invalid_argument` on distinct closures, and `=` either raises or answers +by physical identity. + +```ocaml +(* bad *) f = g +(* good *) compare by a key the functions carry, or track identity + explicitly +``` + +Fires when `=`, `<>`, `<`, `>`, `<=`, `>=`, `compare`, `min`, or `max` +resolves to its `Stdlib` declaration, is applied to exactly two unlabeled +arguments, and an operand's type is a function arrow. Shadowed or rebound +comparisons, physical equality, partial applications, and operands whose +arrow type hides behind an abbreviation deliberately do not fire. No fix: +a meaningful comparison needs domain-specific intent. diff --git a/agents/pages/reference/rules/invalid-hashtable-key.md b/agents/pages/reference/rules/invalid-hashtable-key.md new file mode 100644 index 0000000..97d32f2 --- /dev/null +++ b/agents/pages/reference/rules/invalid-hashtable-key.md @@ -0,0 +1,29 @@ +# invalid-hashtable-key + +polymorphic Hashtbl operation on a value proved functional + + + +**suspicious · warning · stable · since 1.0 · fix: never · on by default** + +`Stdlib.Hashtbl`'s default operations hash and compare keys with the +polymorphic primitives. A functional key is broken at runtime, but not +by hashing: hashing a closure returns a value — different on every run +— and a lookup raises `Invalid_argument` only when a distinct +functional key shares its bucket, misses silently otherwise, and +succeeds only on physical identity. + +```ocaml +(* bad *) Hashtbl.mem callbacks handler +(* good *) Hashtbl.mem callbacks (Handler.id handler) +``` + +Fires when `Hashtbl.find`, `find_opt`, `find_all`, `mem`, `remove`, +`seeded_hash`, `hash`, `hash_param`, `add`, or `replace` resolves to its +`Stdlib` declaration at exact arity and the hashed argument's type +proves a function: an arrow, or a `list`, `array`, or `option` of one. The proof never guesses — type +variables and abbreviations (`type callback = int -> int`) stay clean, +as do shadowed `Hashtbl` modules, partial applications, and +`Hashtbl.Make` instances, whose operations carry the functor's own +identities and whose custom hash is exactly the remedy. No fix: choosing +a hashable key needs domain intent. diff --git a/agents/pages/reference/rules/invalid-nan-comparison.md b/agents/pages/reference/rules/invalid-nan-comparison.md new file mode 100644 index 0000000..2415fe7 --- /dev/null +++ b/agents/pages/reference/rules/invalid-nan-comparison.md @@ -0,0 +1,26 @@ +# invalid-nan-comparison + +comparison with nan is a compile-time constant + + + +**correctness · error · stable · since 1.0 · fix: never · on by default** + +IEEE 754 makes `nan` unordered with everything, itself included: `=`, +`<`, `>`, `<=`, and `>=` against `nan` are always `false` and `<>` is +always `true`, so the comparison never tests what it spells. + +```ocaml +(* bad *) x = nan +(* good *) Float.is_nan x +``` + +Fires when `=`, `<>`, `<`, `>`, `<=`, or `>=` resolves to its `Stdlib` +declaration with `Stdlib.nan` or `Stdlib.Float.nan` as an operand. +Shadowed operators or `nan` names, `nan` reached through an alias +(`let m = nan in x = m` — identity, not dataflow), `compare` and its kin +(a defined total order), physical equality (not constant: the same box +compares true), and other float constants deliberately do not fire. The +rewrite to `Float.is_nan` changes a constant answer into the intended +test — unsafe by policy. No automatic fix in this release — the promise +flips to `Sometimes` when that rewrite lands. diff --git a/agents/pages/reference/rules/manual-boolean-operator.md b/agents/pages/reference/rules/manual-boolean-operator.md new file mode 100644 index 0000000..db10a1c --- /dev/null +++ b/agents/pages/reference/rules/manual-boolean-operator.md @@ -0,0 +1,42 @@ +# manual-boolean-operator + +if with one boolean-literal branch spells an operator longhand + + + +**style · warning · stable · since 1.0 · fix: sometimes · off by default** + +An `if` with exactly one boolean-literal branch spells a boolean +operator in longhand: `if c then true else e` is `c || e`, `then false +else e` is `not c && e`, `then e else true` is `not c || e`, and `then +e else false` is `c && e`. Every rewrite preserves evaluation order and +effects. + +```ocaml +(* bad *) if found then true else retry () +(* good *) found || retry () +``` + +Fires when the condition is not itself a boolean literal (that is +suspicious-literal-condition's finding) and exactly one branch is a +boolean literal by predefined-constructor identity. Two-literal +branches are redundant-if-bool's, and integer 0/1 branches and +user-defined `True`/`False` constructors deliberately do not fire. + +Style: in a scanning loop -- +`if i = len then true else if … then false else aux (i + 1)` -- the +operator rewrite is a side-grade that folds match-, let-, and multi-line +arms into `||`/`&&` operands, so it is off by default and opt-in. +The unambiguous two-literal shapes are redundant-if-bool's. The fix performs the table's rewrite +from the condition's and surviving branch's source slices +(`Unit.splice`), parenthesizing non-atomic operands; every cell splices +`not`, `&&`, or `||` — spellings that resolve in the fix site's scope, +which the rule never checked — so all fixes are unsafe, applied only +under `--fix --unsafe`. The replacement is an infix expression, and an +`if` may legally sit unparenthesized as the right operand of an infix +operator (`a && if c then true else e`), where the bare rewrite would +re-associate — `a && c || e` is `(a && c) || e`, a silent behavior +change; when the `if` is an application's trailing operand the fix +parenthesizes the rewrite (`a && (c || e)`), and an `if` already +parenthesized keeps its pair through `Unit.delimited`. A standalone +`if`, or one that is a `let` body, takes the bare rewrite. diff --git a/agents/pages/reference/rules/manual-case-guard.md b/agents/pages/reference/rules/manual-case-guard.md new file mode 100644 index 0000000..af16d83 --- /dev/null +++ b/agents/pages/reference/rules/manual-case-guard.md @@ -0,0 +1,29 @@ +# manual-case-guard + +case body that is immediately an if-then-else + + + +**pedantic · warning · nursery · since 1.0 · fix: never · off by default** + +A case whose right-hand side is immediately `if c then a else b` can +often become two cases with a `when` guard, letting each outcome carry +its own pattern. + +```ocaml +(* bad *) | [x] -> if x > 0 then 1 else 2 +(* good *) | [x] when x > 0 -> 1 | [_] -> 2 +``` + +Fires on each guard-less case of a `match` or `function` whose body is +exactly an `if` with an `else` branch, anchored at the `if`. Cases that +already carry a guard (the author knows the feature), else-less `if`s +(the guard rewrite has no arm for the implicit unit), `if`s that are +only a subexpression of the body, and `try` handlers — where a failing +guard falls through to re-raise, a semantic trap the suggestion must +not walk users into — deliberately do not fire. No fix: the rewrite +restructures cases and changes exhaustiveness warnings. + +Pedantic: the rewrite often duplicates a non-trivial binding pattern, +re-evaluates an effectful condition, or explodes a three-way chain into +duplicated arms, so whether it reads better is a house's opinion. diff --git a/agents/pages/reference/rules/manual-eta-lambda.md b/agents/pages/reference/rules/manual-eta-lambda.md new file mode 100644 index 0000000..50138c6 --- /dev/null +++ b/agents/pages/reference/rules/manual-eta-lambda.md @@ -0,0 +1,76 @@ +# manual-eta-lambda + +anonymous function that only forwards its parameters + + + +**style · warning · nursery · since 1.0 · fix: sometimes · off by default** + +An anonymous function whose body only forwards its parameters, in +order, to a single identifier is that identifier wrapped in a closure: +`fun x -> parse x` is `parse`, and the wrapper adds an allocation and a +layer of reading without adding meaning. + +```ocaml +(* bad *) Result.map (fun x -> parse x) r +(* good *) Result.map parse r +``` + +Fires on an anonymous function expression (`fun`, not a `let`-bound +definition) in any position — an argument, the callee of an immediate +application, a list element, a pipeline stage — whose parameters are all +unlabeled plain variables and whose body is one application of an +identifier callee to exactly those parameters, in order, all unlabeled, +proved by declaration identity (`Ident.same` positionally, which also +retires the duplicate-name hazard: in `fun x x -> g x x` both arguments +carry the second `x` and position one fails). The gate is what makes +the reduction exact, and each clause is a deliberate non-firing: the +callee must be a plain identifier or module path (`(get ()) x` forces +`get ()` once per call, `f` once at the reduction; a staged `(add 1) x` +likewise), not one of the lambda's own parameters (`fun f -> f x`), and +not spelled as an operator (`fun x y -> x + y` is the section `( + )`, a +different edit — and the parser respells unary minus, so an operator's +slice is not its name); the application must apply all and only the +parameters as unlabeled positional arguments (a partial forward +`fun x y -> f x`, an extra argument `f x 0`, a repeated one `f x x`, a +swapped order, a labeled or optional argument — labels change arity +semantics); the callee's arrow spine must be unlabeled over the +forwarded prefix (with `g : ?d:int -> int -> int`, `fun x -> g x` has +type `int -> int` while `g` keeps the optional — the erasure gate eta-reducible-forwarding +records); and the lambda, its +parameters, its callee, its body, and its arguments carry no type +annotation, coercion, newtype, or attribute the reduction would drop — +`fun env -> f (env :> t)` forwards a coerced `env`, not `env`. A body that +is itself a function (`fun x -> fun y -> f x y`, `fun x -> function +...`) is not a forward. The callee's own arity is irrelevant: +`fun x -> f x` with a binary `f` is `f` at the same type. + +Two further non-firings keep the fix legal. A lambda that is the whole +right-hand side of a `let` binding (`let f = fun x -> g x`, and the +`let f x = g x` sugar the parser desugars to it) is +eta-reducible-forwarding's — that rule's doc records why reducing a +named definition is a judgment, not a mechanical edit (closure identity, +the type surface a wrapper pins); this rule never fires there. And a +lambda in tail position of a `let rec` right-hand side whose callee is +one of the recursively bound names (`let rec f = let g = 1 in fun x -> f +x`) does not fire: the reduced `let rec f = let g = 1 in f` is rejected +by the compiler's recursive-definition check, while under an intervening +`fun` (`let rec go = fun l -> List.map (fun x -> go x) l`) the use is +already delayed and the reduction is legal. + +Style, off by default: an eta-expanded lambda is sometimes deliberate — +an `[@inline]` site, a closure the author wants distinct from the callee, +or a forward reference to a not-yet-defined recursive binding. The fix +replaces the lambda with the callee's own spelling, restoring the +author's parentheses when the lambda's location included them +(`Result.map (fun x -> parse x) r` becomes `Result.map parse r`), and is +Safe: under the gate the two expressions are the same value at the same +type. The one observable difference is closure identity — the wrapper +is a fresh allocation, the callee is the one it already was, so `==` on +them differs — which is not a soundness concern: a program observing it +compares functions, itself flagged — physically by +suspicious-physical-equality, structurally (where it raises) by +invalid-function-comparison. Verified OCaml 5.5.0 arm64 non-flambda: +`fun x -> succ x` and `succ` compile to the same cmm up to symbol names +(the compiler eta-expands the primitive itself), so the rationale is +style and identity, never speed. diff --git a/agents/pages/reference/rules/manual-format-quoting.md b/agents/pages/reference/rules/manual-format-quoting.md new file mode 100644 index 0000000..044ad9c --- /dev/null +++ b/agents/pages/reference/rules/manual-format-quoting.md @@ -0,0 +1,27 @@ +# manual-format-quoting + +format literal hand-quotes %s where %S quotes and escapes + + + +**pedantic · warning · nursery · since 1.0 · fix: sometimes · off by default** + +A format string that hand-writes quotes around `%s` — `"name=\"%s\""` +— re-implements `%S` minus its escaping: `%S` prints the argument quoted +*and* OCaml-escaped, so payloads containing quotes, backslashes, or +control characters stay unambiguous. + +```ocaml +(* bad *) Printf.sprintf "name=\"%s\"" n +(* good *) Printf.sprintf "name=%S" n +``` + +Fires once per typed format literal containing the byte sequence +`"` `%` `s` `"`, whatever function consumes it — `Printf`, `Format`, and +every user of `format6` alike. Plain strings that merely contain the +sequence are never elaborated to a format constructor and are clean by +construction; dynamic formats have no literal. The fix replaces each +hand-quoted `%s` with `%S` and is Unsafe: `%S` escapes its argument +where the hand-written quotes do not, which changes output on payloads +containing quotes, backslashes, or control characters — usually the +improvement the author wants, but a behavior change. diff --git a/agents/pages/reference/rules/manual-list-exists.md b/agents/pages/reference/rules/manual-list-exists.md new file mode 100644 index 0000000..c3edd8a --- /dev/null +++ b/agents/pages/reference/rules/manual-list-exists.md @@ -0,0 +1,32 @@ +# manual-list-exists + +recursive function that re-implements List.exists + + + +**style · warning · stable · since 1.0 · fix: never · off by default** + +A recursive function whose body is the two-case list recursion +returning `false` on `[]` and `E || self … tl` on cons re-implements +`List.exists (fun x -> E)`: same left-to-right evaluation, same +short-circuit on the first `true`, same effect order when `E` is +effectful — and `List.exists` says what it does. + +```ocaml +(* bad *) let rec has p = function + | [] -> false + | x :: xs -> p x || has p xs +(* good *) let has p = List.exists p +``` + +Fires when the shape is proved: exactly two guard-less cases by +predefined-list identity, the nil case the literal `false`, and the +cons case `E || SELFCALL` where the step `E` uses neither the function +nor the bound tail and the self-call passes every parameter unchanged +with the bound tail in list position. A self-call left of `||` +(evaluation order differs), a `true` nil case (constant, not exists), +a same-named outer function without `rec`, a recursion argument other +than the bound tail, guards, extra cases, and user-defined `(::)`/`[]` +deliberately do not fire. The `if p x then true else self xs` spelling +is redundant-if-bool's inner `if`. No fix: the rewrite restructures +the whole binding. diff --git a/agents/pages/reference/rules/manual-list-filter-map.md b/agents/pages/reference/rules/manual-list-filter-map.md new file mode 100644 index 0000000..916f215 --- /dev/null +++ b/agents/pages/reference/rules/manual-list-filter-map.md @@ -0,0 +1,36 @@ +# manual-list-filter-map + +recursive function that re-implements List.filter or filter_map + + + +**style · warning · stable · since 1.0 · fix: never · off by default** + +The cons-or-skip list recursion — keep a (possibly transformed) +element in one branch, recurse past it in the other — re-implements +`List.filter_map`, or plain `List.filter` when the kept element is the +head unchanged. + +```ocaml +(* bad *) let rec evens = function + | [] -> [] + | x :: xs -> if x mod 2 = 0 then x :: evens xs + else evens xs +(* good *) let evens = List.filter (fun x -> x mod 2 = 0) +``` + +Fires when the shape is proved: the two-case recursion of +manual-list-map's scaffold whose cons case is either +`if C then E :: SELF else SELF` (or mirrored) or +`match G with Some y -> y :: SELF | None -> SELF` — both branches the +identical recursion with only the bound tail advanced, the condition or +scrutinee and the kept head using neither the tail, the function, nor — +in the match form — the scrutinized list parameter (rebound at every +recursive call); +predefined `Some`/`None` identity. The message names `List.filter` when +the kept head is exactly the bound element, `List.filter_map` +otherwise. Else-branches that are not the bare recursion (take-while +shapes), match-form kept heads other than the bound option payload, +guards, user-defined constructors, and same-named outer functions +deliberately do not fire. No fix: the rewrite restructures the whole +binding. diff --git a/agents/pages/reference/rules/manual-list-fold.md b/agents/pages/reference/rules/manual-list-fold.md new file mode 100644 index 0000000..a65350e --- /dev/null +++ b/agents/pages/reference/rules/manual-list-fold.md @@ -0,0 +1,35 @@ +# manual-list-fold + +recursive function that re-implements a List fold + + + +**style · warning · stable · since 1.0 · fix: never · off by default** + +A recursive function with an accumulator whose body is the two-case +list recursion returning the accumulator on `[]` re-implements +`List.fold_left` (accumulator transformed, tail call in tail position) +or `List.fold_right` (result rebuilt around the recursive call, +accumulator threaded unchanged). + +```ocaml +(* bad *) let rec sum acc = function + | [] -> acc + | x :: xs -> sum (acc + x) xs +(* good *) let sum acc = List.fold_left ( + ) acc +``` + +Fires when either shape is proved — the nil case returning one of the +parameters (that parameter is the accumulator), and the cons case +either the tail call with only the accumulator position transformed +(fold_left) or one self-call with every parameter unchanged inside a +step that touches neither the function nor the tail (fold_right); in +the match form the step must not read the scrutinized list parameter +either — it is rebound at every recursive call, so no fold callback +can see it. The message names the replacement. The step may be any +expression — an operator, not just an applied parameter. Nil cases +returning a literal +(no accumulator parameter to keep the signature), changed-and-wrapped +accumulators, two self-calls, guarded or extra cases, user-defined +`(::)`/`[]`, and same-named outer functions deliberately do not fire. +No fix: the rewrite restructures the whole binding. diff --git a/agents/pages/reference/rules/manual-list-forall.md b/agents/pages/reference/rules/manual-list-forall.md new file mode 100644 index 0000000..619a9f7 --- /dev/null +++ b/agents/pages/reference/rules/manual-list-forall.md @@ -0,0 +1,32 @@ +# manual-list-forall + +recursive function that re-implements List.for_all + + + +**style · warning · stable · since 1.0 · fix: never · off by default** + +A recursive function whose body is the two-case list recursion +returning `true` on `[]` and `E && self … tl` on cons re-implements +`List.for_all (fun x -> E)`: same left-to-right evaluation, same +short-circuit on the first `false`, same effect order when `E` is +effectful — and `List.for_all` says what it does. + +```ocaml +(* bad *) let rec all p = function + | [] -> true + | x :: xs -> p x && all p xs +(* good *) let all p = List.for_all p +``` + +Fires when the shape is proved: exactly two guard-less cases by +predefined-list identity, the nil case the literal `true`, and the +cons case `E && SELFCALL` where the step `E` uses neither the function +nor the bound tail and the self-call passes every parameter unchanged +with the bound tail in list position. A self-call left of `&&` +(evaluation order differs), a `false` nil case (constant, not +for_all), a same-named outer function without `rec`, a recursion +argument other than the bound tail, guards, extra cases, and +user-defined `(::)`/`[]` deliberately do not fire. The +`if p x then self xs else false` spelling is redundant-if-bool's inner +`if`. No fix: the rewrite restructures the whole binding. diff --git a/agents/pages/reference/rules/manual-list-map.md b/agents/pages/reference/rules/manual-list-map.md new file mode 100644 index 0000000..2cbc301 --- /dev/null +++ b/agents/pages/reference/rules/manual-list-map.md @@ -0,0 +1,33 @@ +# manual-list-map + +recursive function that hand-rolls a list map + + + +**style · warning · stable · since 1.0 · fix: never · off by default** + +A recursive function whose body is exactly the two-case list +recursion `[] -> []` / `x :: xs -> E :: self … xs` re-implements +`List.map (fun x -> E)`: more code, no TRMC, and a reader must +re-verify that the recursion is structural. + +```ocaml +(* bad *) let rec map1 f = function + | [] -> [] + | h :: tl -> f h :: map1 f tl +(* good *) let map1 f = List.map f +``` + +Fires when the whole shape is proved: the binding is a variable, every +parameter an unlabeled variable, the two cases guard-less with +predefined `[]`/`(::)` identity, every parameter passed through the +recursion unchanged with the bound tail in the list position (any +parameter position), and the head expression using neither the tail, the +function itself, nor — in the match form — the scrutinized list +parameter, which is rebound at every recursive call and so denotes a +different list per iteration. Guarded or extra cases, alias patterns, +heads that read the tail or the scrutinized list, arguments other than +the bound tail, user-defined +`(::)`/`[]` constructors, and same-named outer functions (identity, not +spelling) deliberately do not fire. No fix: the rewrite restructures +the whole binding; the message names the replacement. diff --git a/agents/pages/reference/rules/manual-option-bind.md b/agents/pages/reference/rules/manual-option-bind.md new file mode 100644 index 0000000..0065b16 --- /dev/null +++ b/agents/pages/reference/rules/manual-option-bind.md @@ -0,0 +1,29 @@ +# manual-option-bind + +two-case option match that re-implements Option.bind + + + +**style · warning · stable · since 1.0 · fix: never · off by default** + +`match o with Some y -> E | None -> None`, with `E` itself +option-typed (the match's typing guarantees it), is +`Option.bind o (fun y -> E)`: same single evaluation of `o`, same `E` +on `Some`, same `None` propagation. + +```ocaml +(* bad *) match find k m with Some v -> resolve v | None -> None +(* good *) Option.bind (find k m) resolve +``` + +Fires on the guard-less two-case match — or bare `function` — whose +`Some` case binds a variable and whose `None` case returns the +predefined `None`, in either case order. A `Some`-arm right-hand side +that is itself a `Some _` construction is refused: `Some (g y)` is +manual `Option.map` and exactly `Some y` is the identity roundtrip — +different findings, owned elsewhere. Guards, exception arms, +non-variable payload patterns (`Some (a, b)` — a recorded false +negative), `None` arms returning anything but the predefined `None` +(`Option.fold` territory), and user-defined option lookalikes +deliberately do not fire. No fix: the rewrite restructures the whole +expression into a lambda — the message shows the form. diff --git a/agents/pages/reference/rules/manual-option-map.md b/agents/pages/reference/rules/manual-option-map.md new file mode 100644 index 0000000..f836a4d --- /dev/null +++ b/agents/pages/reference/rules/manual-option-map.md @@ -0,0 +1,33 @@ +# manual-option-map + +two-case match that unwraps, transforms, and rewraps an option + + + +**style · warning · stable · since 1.0 · fix: sometimes · off by default** + +`match o with Some x -> Some E | None -> None` is `Option.map +(fun x -> E) o` written longhand: both forms evaluate the scrutinee once +and `E` only in the `Some` case. + +```ocaml +(* bad *) match o with Some x -> Some (x + 1) | None -> None +(* good *) Option.map (fun x -> x + 1) o +``` + +Fires on exactly two guard-less cases — `Some` with a bare-variable +payload rebuilding `Some`, and `None` rebuilding `None`, in either +order, by predefined-constructor identity — in both the `match` and the +`function` form. The degenerate rebuild `Some x -> Some x` is the +scrutinee itself and gets its own message. Guards, wildcard arms, deeper +payload patterns, aliases, `exception` arms, user-defined `Some`/`None` +constructors, and `Some` arms that do not rebuild `Some` (`Option.bind` +territory) deliberately do not fire. The fix rewrites the match form to +`Option.map (fun x -> E) o` — the tighter `Option.map f o` when `E` is +exactly `f x` for an identifier `f` other than `x`, and the scrutinee +alone for the degenerate rebuild — where the sources slice cleanly; the +`function` form has no scrutinee to name and ships none. The `Option.map` +rewrite is safe where `Option` is the standard library's and `E` names no +constructor or field the checker may have chosen by its expected type, and +unsafe, applied only under `--unsafe`, otherwise. The scrutinee alone names +nothing, and is safe. diff --git a/agents/pages/reference/rules/manual-option-value.md b/agents/pages/reference/rules/manual-option-value.md new file mode 100644 index 0000000..2efabc6 --- /dev/null +++ b/agents/pages/reference/rules/manual-option-value.md @@ -0,0 +1,31 @@ +# manual-option-value + +two-case match extracting an option's value over a trivial default + + + +**style · warning · stable · since 1.0 · fix: sometimes · off by default** + +`match o with Some x -> x | None -> D` is `Option.value o +~default:D` — but only when `D` is guaranteed cheap and effect-free: +`Option.value` evaluates its `default` argument always, the match only +on `None`. The rule proves `D` trivial before firing — a literal, an +identifier, or a nullary constructor — so every effectful or costly +default deliberately stays clean. + +```ocaml +(* bad *) match o with Some x -> x | None -> 0 +(* good *) Option.value o ~default:0 +``` + +Fires on exactly two guard-less cases — `Some` with a bare-variable +payload returned unchanged, and `None` returning a trivial `D`, in +either order, by predefined-constructor identity — in both the `match` +and the `function` form. Effectful or raising defaults, transforming +`Some` arms (`Option.fold` territory), guards, unused payloads, and +user-defined `Some`/`None` constructors deliberately do not fire. The +fix rewrites the match form to `Option.value o ~default:D` where the +sources slice cleanly; the `function` form has no scrutinee to name and +ships none. The fix is safe where `Option` is the +standard library's and the default names no constructor the checker may have +chosen by its expected type, and unsafe, applied only under `--unsafe`, otherwise. diff --git a/agents/pages/reference/rules/manual-record-update.md b/agents/pages/reference/rules/manual-record-update.md new file mode 100644 index 0000000..862e97a --- /dev/null +++ b/agents/pages/reference/rules/manual-record-update.md @@ -0,0 +1,40 @@ +# manual-record-update + +record rebuilt field by field from one base + + + +**style · warning · stable · since 1.0 · fix: never · off by default** + +A record expression that copies two or more fields verbatim from one +base record is `{ base with ... }` written longhand: more text, and the +reader must verify field by field that the copies are copies. When every +field is a verbatim copy of an immutable record, the expression is the +base itself. + +```ocaml +(* bad *) { x = r.x; y = r.y; z = 15 } +(* good *) { r with z = 15 } +``` + +Fires once per extension-less record expression in which some identifier +base has at least two fields copied verbatim — `l = b.l`, same label by +declaration identity: equal name and `Path.same` record head, so the +base necessarily has the constructed type and a cross-type rewrite — +suggesting `{ b with … }` against a different record type — is +structurally impossible. Fields copied from a different base, and +punned fields (which elaborate to bare identifiers, not accesses), +count as overrides and simply stay spelled out. When every field is a +copy the message says the record is the base itself — unless some +label is mutable, where the full rebuild is the deliberate copy idiom +and the rule stays silent. A base that is not an identifier +(`(get r).x`) never counts: re-evaluating it under `with` would change +effects. A one-copy record does not fire — `{ b with ... }` would +rewrite nearly the whole literal, a deliberate narrowing: one copied +field is not evidence of an update idiom. No fix: the rewrite deletes +and reorders fields; +the message shows the target form. Fields arrive in the record type's +declaration order (the typedtree does not record source order), so +multi-override messages list overrides in declaration order — a +cosmetic note, not a defect. Same-typed serialization boilerplate that +copies deliberately for explicitness is what Style/off respects. diff --git a/agents/pages/reference/rules/manual-result-bind.md b/agents/pages/reference/rules/manual-result-bind.md new file mode 100644 index 0000000..cd20860 --- /dev/null +++ b/agents/pages/reference/rules/manual-result-bind.md @@ -0,0 +1,41 @@ +# manual-result-bind + +two-case result match that re-implements Result.bind + + + +**style · warning · stable · since 1.0 · fix: never · off by default** + +`match r with Ok x -> E | Error e -> Error e`, with `E` itself +result-typed and the error returned unchanged, is +`Result.bind r (fun x -> E)`: same single evaluation of `r`, same `E` +on `Ok`, same error propagation. It is the single most recurrent manual +shape in the corpora — including per-directory hand-defined +`let ( let* ) = ` operators, whose definitions fire and +should: `let ( let* ) = Result.bind` is the tighter definition. + +```ocaml +(* bad *) match route t s with Error e -> Error e | Ok d -> submit d +(* good *) Result.bind (route t s) (fun d -> submit d) +``` + +Fires on the guard-less two-case match — or bare `function` — whose +`Ok` case binds a variable with a right-hand side that is not an +`Ok _` construction (that shape is manual-result-map's — exact +partition, no co-fire), and whose `Error` case is the payload rebuild +`Error e -> Error e`, in either case order. The rebuild's payload types +must agree on both sides: a coerced rebuild +(`Error (e :> wider)`) widens where `Result.bind` would not typecheck +and is refused. The alias spelling `Error _ as e -> e` is a recorded +false negative until a pattern-alias view lands. Guards, exception +arms, deeper payload patterns, transformed or dropped errors, `Error` +right-hand sides that are not `Error` constructions, and user variants +spelling `Ok`/`Error` deliberately do not fire. One definition site is +exempt — the self-definition gate: a module named `Result` defining the +like-named `bind` from this match (stdppx's shape; its `Result.bind` +is this match) must not be told to use `Result.bind`. The gate accepts +the match that is the eventual function body of a value binding named +`bind` inside a module binding named `Result`, or at the root of a +unit itself named `Result`; every other definition, `( let* )` +included, keeps firing. No fix: the rewrite restructures the `Ok` arm +into a lambda — the message shows the form. diff --git a/agents/pages/reference/rules/manual-result-map.md b/agents/pages/reference/rules/manual-result-map.md new file mode 100644 index 0000000..af7cab0 --- /dev/null +++ b/agents/pages/reference/rules/manual-result-map.md @@ -0,0 +1,35 @@ +# manual-result-map + +two-case match that transforms one result arm and rebuilds the other + + + +**style · warning · stable · since 1.0 · fix: sometimes · off by default** + +`match r with Ok x -> Ok E | Error e -> Error e` is `Result.map +(fun x -> E) r`: the error arm provably rebuilds the same payload. The +mirrored shape — identity `Ok` arm, +transforming `Error` arm — is `Result.map_error` and is matched too, +with its own message. + +```ocaml +(* bad *) match r with Ok x -> Ok (parse x) | Error e -> Error e +(* good *) Result.map (fun x -> parse x) r +``` + +Fires on exactly two guard-less cases — `Ok` and `Error` with +bare-variable payloads, in either order, identified by the constructors' +result-type head being the global `Stdlib.result` path — in both the +`match` and the `function` form, when exactly one arm transforms and the +other is an identity rebuild; when both arms are identity rebuilds the +match is the scrutinee itself and says so. Guards, deeper payload +patterns, wildcard payloads, arms that do not rebuild their constructor +(`Result.bind` territory), both arms transforming, and user variants +spelling `Ok`/`Error` deliberately do not fire. The fix rewrites the +match form to `Result.map (fun x -> E) r` / `Result.map_error (fun e -> +E) r` (the scrutinee alone for the double identity) where the sources +slice cleanly; the `function` form has no scrutinee to name and ships +none. The `Result` rewrites are safe +where `Result` is the standard library's and `E` names no constructor or field +the checker may have chosen by its expected type, and unsafe, applied only under +`--unsafe`, otherwise. The scrutinee alone names nothing, and is safe. diff --git a/agents/pages/reference/rules/manual-temp-dir.md b/agents/pages/reference/rules/manual-temp-dir.md new file mode 100644 index 0000000..839cc7d --- /dev/null +++ b/agents/pages/reference/rules/manual-temp-dir.md @@ -0,0 +1,41 @@ +# manual-temp-dir + +temp file removed and re-created as a directory + + + +**suspicious · warning · stable · since 1.0 · fix: sometimes · on by default** + +`Filename.temp_file` creates the file exclusively — that exclusivity +is its entire security contract. Removing the file and re-creating its +name as a directory forfeits it: between the remove and the mkdir any +other process can claim the now-predictable path in a shared temp +directory (CWE-377), making the mkdir fail — or succeed inside an +attacker-provided symlinked parent where the temp directory is shared. +`Filename.temp_dir` (stdlib since 5.1, always inside the support +window) is the atomic, dedicated form. + +```ocaml +(* bad *) let d = Filename.temp_file p "" in + Sys.remove d; Sys.mkdir d 0o700; ... +(* good *) let d = Filename.temp_dir p "" in ... +``` + +Fires on the three-step sequence: a binding of a `Filename.temp_file` +application (the omitted `?temp_dir` is tolerated) whose body removes +the bound path (`Sys.remove` or `Unix.unlink`) and then — directly, or +after one intervening statement — re-creates +it with `Unix.mkdir` or `Sys.mkdir`. Path identity is the bound +declaration's, never spelling: removing or making some other path +never counts. Anchored at the `temp_file` application. The fix +rewrites the direct shape to `Filename.temp_dir`, dropping the remove +and mkdir statements, when the unit is not preprocessed, the callee is +spelled exactly `Filename.temp_file`, the argument gaps are pure +whitespace (a written `~temp_dir:` refuses), the permission argument +is an integer literal (carried as `~perms:` unless it is `0o700`, +`temp_dir`'s default), the mkdir is followed by further statements +(so the binding still binds a path the rest uses), and no comment sits +in the deleted region. Any refused gate refuses the fix, never the +finding. The fix is safe where `Filename` is the standard library's, and unsafe, +applied only under `--unsafe`, otherwise. The sequence split across helper functions is a documented +false negative. diff --git a/agents/pages/reference/rules/manual-tuple-matching.md b/agents/pages/reference/rules/manual-tuple-matching.md new file mode 100644 index 0000000..32ec298 --- /dev/null +++ b/agents/pages/reference/rules/manual-tuple-matching.md @@ -0,0 +1,37 @@ +# manual-tuple-matching + +single irrefutable tuple case that could be a let binding + + + +**style · warning · stable · since 1.0 · fix: sometimes · off by default** + +A `match` with exactly one case whose pattern is an irrefutable tuple +does no branching: a single guard-less irrefutable case evaluates the +scrutinee, binds, and continues — which is `let`'s definition, and `let` +says so. + +```ocaml +(* bad *) match p with (a, b) -> a + b +(* good *) let (a, b) = p in a + b +``` + +Fires on a `match` with exactly one guard-less computation case whose +pattern is an unlabeled tuple of irrefutable components — variables, +wildcards, and nested unlabeled tuples of the same. Refutable +components (constants, constructors, records) refuse conservatively: +there the `let` form merely relocates the partiality, which is warning +8's business in both spellings. Guarded cases, multi-case matches, +`exception` arms, effect-handler matches, and the `function (a, b) ->` +spelling (`needless-fun-match`'s territory) do not fire. Alias +components (`(x, _) as whole`) and constraint components +(`((a : int), b)`) refuse conservatively, recorded false negatives. The fix rewrites `match ... with pat -> body` to +`let pat = scrutinee in body` when the unit is not preprocessed and +the keyword gaps normalize to exactly `match`, `with` (or `with |`), +and `->` — a comment in any gap refuses the fix, never the finding. +The pattern is spliced verbatim; the scrutinee through `Unit.splice`. +Purely stylistic; some houses prefer `match` even here for uniformity +with sibling arms — Style/off is the posture. `fun x -> match x with +(a, b) -> e` co-fires with `needless-fun-match` at distinct anchors +with converging remedies — both claims true; apply either fix and the +other finding clears. diff --git a/agents/pages/reference/rules/missing-final-newline.md b/agents/pages/reference/rules/missing-final-newline.md new file mode 100644 index 0000000..9dcf8d7 --- /dev/null +++ b/agents/pages/reference/rules/missing-final-newline.md @@ -0,0 +1,24 @@ +# missing-final-newline + +file does not end with a newline + + + +**style · warning · nursery · since 1.0 · fix: always · off by default** + +A file whose last line has no terminating LF confuses line-oriented +tools — `cat` runs files together, `wc -l` miscounts, diffs grow the +"no newline at end of file" wart — and appending a line churns the +previous one. + +```ocaml +(* bad *) …let x = 1⏹ +(* good *) …let x = 1␊⏹ +``` + +Reports a zero-width finding at the end-of-file insertion point when the +last byte of a non-empty file is not LF. Empty files are clean, and CRLF +endings are accepted because their final byte is LF. Every finding carries +the insertion fix (`add a final newline`), appending one line terminator +in the file's own style: `\r\n` when the file's last line break is CRLF, +one LF otherwise — a fix must not leave a file with mixed endings. diff --git a/agents/pages/reference/rules/missing-printer.md b/agents/pages/reference/rules/missing-printer.md new file mode 100644 index 0000000..e4117da --- /dev/null +++ b/agents/pages/reference/rules/missing-printer.md @@ -0,0 +1,37 @@ +# missing-printer + +comparable abstract type whose interface exposes no printer + + + +**pedantic · warning · nursery · since 1.0 · fix: never · off by default** + +An interface that already exposes `equal`, `compare`, or +`to_string` for its abstract type has declared it a +comparable/serializable value — and a value you can compare but not +print is a debugging dead end. Handle and machine types without that +value evidence are left alone: reasonable maintainers disagree there, +which is why this rule is Pedantic. + +```ocaml +(* bad *) type t val equal : t -> t -> bool (* no pp *) +(* good *) type t val equal : t -> t -> bool val pp : Format.formatter -> t -> unit +``` + +Fires once per abstract type — no manifest, no representation — in the +unit's interface whose same signature level exposes an +`equal : t -> t -> bool`, `compare : t -> t -> int`, or +`to_string : t -> string` (shapes checked against that type's own +identity, never by name alone) and no `pp` (or `pp_`) of type +`Format.formatter -> t -> unit`, anchored at the implementation's +matching toplevel type declaration — the emit contract owns findings to +the editable source, so the `.mli` declaration itself cannot anchor. +Units without an interface, abstract types without value evidence, +manifest and represented types, and printers for other types that +happen to be named `pp` deliberately do not fire. Recorded false +negatives: types declared in submodule signatures (the toplevel join +is what the `type_decl` seam supports today) and interface types +satisfied by an `include` in the implementation. An `equal` that +exists only to feed a container functor is the accepted Pedantic +price — `[@litany.expect]` covers it. No fix: naming and placing a +printer is authorship. diff --git a/agents/pages/reference/rules/needless-and-binding.md b/agents/pages/reference/rules/needless-and-binding.md new file mode 100644 index 0000000..f8df904 --- /dev/null +++ b/agents/pages/reference/rules/needless-and-binding.md @@ -0,0 +1,36 @@ +# needless-and-binding + +let rec binding riding an and-chain it does not need + + + +**style · warning · nursery · since 1.0 · fix: never · off by default** + +A `let rec … and …` chain asserts co-dependence. A binding that +neither calls itself through the group nor participates in any +reference cycle with its siblings is riding a chain it doesn't need: +readers assume the bindings are entangled, and the group resists being +split or moved. + +```ocaml +(* bad *) let rec is_even n = n = 0 || is_odd (n - 1) + and is_odd n = n <> 0 && is_even (n - 1) + and double x = x + x +(* good *) let rec is_even n = n = 0 || is_odd (n - 1) + and is_odd n = n <> 0 && is_even (n - 1) + let double x = x + x +``` + +Fires once per binding of a recursive multi-binding group that is +mutually reachable with no sibling over the identity-resolved +reference graph — self-recursive-only bindings extract as their own +`let rec`, inert bindings as a plain `let`; the message says which. +Members of a genuine cycle never fire, and groups where no binding +references the group at all are suspicious-rec-without-recursion's +finding, never this rule's — an exact partition. Edges are proved from +the unit's use index by declaration identity, so a same-spelled inner +rebinding contributes no edge; an unplaceable use or a non-variable +pattern refuses the group conservatively. Warning 39 is silent on +every positive here (it needs the whole group inert). No fix: +extraction reorders bindings above or below the group — guidance, not +an edit. diff --git a/agents/pages/reference/rules/needless-append-empty.md b/agents/pages/reference/rules/needless-append-empty.md new file mode 100644 index 0000000..7bf95a5 --- /dev/null +++ b/agents/pages/reference/rules/needless-append-empty.md @@ -0,0 +1,28 @@ +# needless-append-empty + +append or concatenation with the neutral element + + + +**style · warning · stable · since 1.0 · fix: sometimes · off by default** + +Appending the neutral element does nothing — except allocate. +`[] @ l` is `l` itself (the stdlib's append returns its second argument +on an empty first); `l @ []` walks and copies `l` to end where it +started; `"" ^ s` and `s ^ ""` allocate a fresh copy of `s` (`^` never +returns an operand). + +```ocaml +(* bad *) xs @ [] +(* good *) xs +``` + +Fires when `@` or `List.append` resolves to its `Stdlib` declaration +with the predefined `[]` as either operand, and when `^` or +`String.cat` does with the literal `""` as either operand; a both-empty +operation reports once. Singleton appends (`[x] @ l`), shadowed +operators, `String.concat`, and `Bytes.cat` deliberately do not fire. +The fix replaces the whole application with the other operand: safe for +`[] @ l` (result, effects, and physical identity all preserved), unsafe +for the other three legs — they remove a copy, and legacy code copies +strings via `s ^ ""` deliberately. diff --git a/agents/pages/reference/rules/needless-fun-match.md b/agents/pages/reference/rules/needless-fun-match.md new file mode 100644 index 0000000..992819e --- /dev/null +++ b/agents/pages/reference/rules/needless-fun-match.md @@ -0,0 +1,29 @@ +# needless-fun-match + +fun-then-match over an otherwise unused final parameter + + + +**style · warning · nursery · since 1.0 · fix: never · off by default** + +`fun x -> match x with …` where `x` is used only as the scrutinee is +`function` with an extra name: the binding adds nothing a reader can +use, and the match cases already bind what matters. + +```ocaml +(* bad *) fun x -> match x with [] -> 1 | _ -> 2 +(* good *) function [] -> 1 | _ -> 2 +``` + +Fires when the whole body is a match on the function's final parameter — +unlabeled, non-optional — and no case guard or body uses that +parameter. Case-side rebindings of the same name are different +identities and do not block. Labeled parameters (the rewrite would +change call sites), scrutinees that are not the bare parameter, matches +that are only part of the body, and matches with `exception` cases +(`function` cannot carry them) deliberately do not fire. Neither does a +scrutinee carrying an explicit type constraint — +`fun mty -> match (mty : Types.module_type) with …` — where the +annotation is load-bearing (constructor disambiguation) and the +`function` rewrite has nowhere to put it: so such a site is left alone. The drop-parameter rewrite has no automatic +fix. diff --git a/agents/pages/reference/rules/needless-list-length.md b/agents/pages/reference/rules/needless-list-length.md new file mode 100644 index 0000000..0b6e9f4 --- /dev/null +++ b/agents/pages/reference/rules/needless-list-length.md @@ -0,0 +1,31 @@ +# needless-list-length + +List.length compared with 0 or 1 to test emptiness + + + +**perf · warning · stable · since 1.0 · fix: sometimes · on by default** + +Comparing `List.length` with a constant zero or one to ask "is this +list empty?" walks the whole list to answer a constant-time question. + +```ocaml +(* bad *) if List.length xs = 0 then … +(* good *) if xs = [] then … +``` + +Fires only when `List.length` and the comparison operator both resolve to +their `Stdlib` declarations and the relation is logically equivalent to +emptiness or non-emptiness: `length = 0`, `length <> 0`, `length > 0`, +`length <= 0`, `length >= 1`, `length < 1`, in either operand order. +Shadowed or rebound names, other constants (`= 1` is a singleton test, not +an emptiness test), relations that are always or never true (`< 0`, +`>= 0`), and non-literal operands deliberately do not fire. The fix +(`compare with []`) rewrites to `xs = []` or `xs <> []`, preserving the +relation's polarity; it ships only when the operand's source slices +cleanly (`Unit.splice`). It is safe only in the cells whose matched +operator is the spliced one (`= 0` and `<> 0`, either operand order): +there the spliced spelling just resolved to its `Stdlib` declaration at +this very spot. The other cells splice an operator the rule never +resolved — a fix-site scope shadowing `=` or `<>` would change the +value — so their fix is unsafe, applied only under `--fix --unsafe`. diff --git a/agents/pages/reference/rules/needless-list-map-before-concat.md b/agents/pages/reference/rules/needless-list-map-before-concat.md new file mode 100644 index 0000000..84f5b62 --- /dev/null +++ b/agents/pages/reference/rules/needless-list-map-before-concat.md @@ -0,0 +1,25 @@ +# needless-list-map-before-concat + +List.map feeding concatenation builds an intermediate list + + + +**perf · warning · stable · since 1.0 · fix: never · on by default** + +`List.concat (List.map f xs)` builds a complete intermediate list of +lists only for the concatenation to traverse and discard it; +`List.concat_map f xs` fuses the two passes. + +```ocaml +(* bad *) List.concat (List.map f xs) +(* good *) List.concat_map f xs +``` + +Fires only when the concatenation (`List.concat` or `List.flatten`) and +`List.map` resolve to their `Stdlib` declarations and the two-argument +map application feeds the concatenation directly — including +`List.map f xs |> List.concat`, which the compiler collapses into that +shape. Shadowed or let-rebound names, `List.concat_map` itself, partial +applications (`xs |> List.map f |> List.concat` leaves one), and +anything between the map and the concatenation deliberately do not fire. +No automatic fix. diff --git a/agents/pages/reference/rules/needless-mutually-recursive-types.md b/agents/pages/reference/rules/needless-mutually-recursive-types.md new file mode 100644 index 0000000..54ba92f --- /dev/null +++ b/agents/pages/reference/rules/needless-mutually-recursive-types.md @@ -0,0 +1,32 @@ +# needless-mutually-recursive-types + +and-chained type that is not mutually recursive with its group + + + +**style · warning · stable · since 1.0 · fix: never · off by default** + +An `and`-chained type group asserts to the reader that its members +are mutually recursive. A member that participates in no reference +cycle with its siblings makes the assertion false coupling: the group +reads as co-dependent, refactors move it as a block, and the actual +dependency structure is hidden. + +```ocaml +(* bad *) type t1 = A of t2 and t2 = B of t1 and t3 = C of t1 +(* good *) type t1 = A of t2 and t2 = B of t1 + type t3 = C of t1 +``` + +Fires once per member of a multi-declaration group that is mutually +reachable with no sibling over the identity-resolved reference graph — +each such declaration can stand as its own `type` item (type +declarations are recursive by default, so even a self-recursive +singleton extracts cleanly, unlike `let`). Members of a genuine cycle +never fire, and a singleton group has no `and` to indict. Edges are by +declaration identity, so a same-named outer type never confuses the +graph, and under `nonrec` no sibling edge can exist — every member of +a multi-declaration `nonrec` group reports, derived rather than +special-cased. No fix: splitting the group is a reordering of +declarations, not a span edit, and computing a correct order is out of +scope. diff --git a/agents/pages/reference/rules/open-of-ordinary-module.md b/agents/pages/reference/rules/open-of-ordinary-module.md new file mode 100644 index 0000000..8dc528a --- /dev/null +++ b/agents/pages/reference/rules/open-of-ordinary-module.md @@ -0,0 +1,30 @@ +# open-of-ordinary-module + +an open of a module that is not made to be opened + + + +**restriction · warning · nursery · since 1.1 · fix: never · off by default** + +An `open` of an ordinary module makes every name of the file a +question -- where did it come from? -- and a name the module gains later +silently shadows one of the file's own. A module made to be opened is +one of binding operators and nothing else (`open Result.Syntax`). + +```ocaml +(* bad *) open Store +(* good *) module S = Store +``` + +Why restrict this? `open` is idiomatic OCaml in many houses; aliasing +every module instead is a discipline a house adopts. + +Fires at an `open` that is a structure item, at the root of a unit or +in a nested structure, through which the unit takes anything but +binding operators (`let*`, `and+`, ...) -- a value, a type, a constructor, +a record field or a member of a submodule -- or takes nothing at all. A +name written out in full is not taken through the open. An `open` of a module of binding +operators alone, and an `open` local to an expression -- `let open M in +e` or `M.(e)`, where a library of combinators or operators is opened +around the expression that uses it -- deliberately do not fire. No fix: +an alias names the module, and every use changes with it. diff --git a/agents/pages/reference/rules/outdated-str-module.md b/agents/pages/reference/rules/outdated-str-module.md new file mode 100644 index 0000000..58842c1 --- /dev/null +++ b/agents/pages/reference/rules/outdated-str-module.md @@ -0,0 +1,34 @@ +# outdated-str-module + +reference into the outdated Str module + + + +**style · warning · stable · since 1.0 · fix: never · off by default** + +`Str` funnels every match through one global state: each +`Str.string_match` stores its groups in hidden cells that the next match — +from any thread — silently overwrites, so `Str.matched_group` answers for +whichever match ran last. + +```ocaml +(* bad *) Str.string_match (Str.regexp "a+") s 0 +(* good *) Re.execp (Re.compile Re.(rep1 (char 'a'))) s +``` + +Fires once per referenced `Str` declaration per unit: every reference +to a value declared in the `Str` compilation unit — spelled directly, +through an alias, or via `open` — joins its declaration's cluster, and +the cluster is one finding anchored at the first reference, its +message carrying the count (`Str.matched_group referenced 30 times in +this unit`); a declaration referenced once keeps the plain message. A +project-local `module Str`, a functor parameter named `Str`, a value +named `str`, and `Re.Str` (Re's compatibility layer, declared in Re's +own units and a fine migration vehicle) deliberately do not fire; a +vendored unit literally named `Str` does, because the compilation unit +is the identity boundary. In preprocessed units the collapse is off +and every reference reports individually: a rewriter-spliced location +on a cluster's first reference is one the emit contract drops, and +dropping the anchor would silence references that are real. Off by +default — adopting Re is a dependency decision — +and no fix: the rewrite is a migration. diff --git a/agents/pages/reference/rules/quadratic-list-append.md b/agents/pages/reference/rules/quadratic-list-append.md new file mode 100644 index 0000000..bb83c39 --- /dev/null +++ b/agents/pages/reference/rules/quadratic-list-append.md @@ -0,0 +1,31 @@ +# quadratic-list-append + +list append folded with the accumulator on the left + + + +**perf · warning · stable · since 1.0 · fix: never · on by default** + +`(@)` copies its left operand and shares its right. A fold whose +accumulator sits on the left of `(@)` therefore copies everything +accumulated so far at every step — quadratic in the total length where +`List.concat` and `List.concat_map` are linear. + +```ocaml +(* bad *) List.fold_left (fun acc x -> acc @ [f x]) [] xs +(* good *) List.concat_map (fun x -> [f x]) xs +``` + +Fires when `List.fold_left`, `Array.fold_left`, or `Seq.fold_left` +resolves to its `Stdlib` declaration with `Stdlib.(@)`/`List.append` — +or a two-parameter lambda appending with its accumulator (first) +parameter on the left — as the first unlabeled argument, at any +saturation up to three; and when `List.fold_right`/`Array.fold_right` +takes a lambda with its accumulator (second) parameter on the left, the +quadratic reversal. `List.fold_right (@) xss []` is **linear** — each +element is copied once; it is `List.concat` itself — and deliberately +does not fire, and neither do element-on-the-left lambdas, consing, +rebound operators, or labeled folds. The recursive spelling +(`rev xs @ [x]`) is a recorded false negative: it needs a second rule +kind on one rule, which the engine does not yet allow. No fix: the +rewrites restructure the expression; the message names them. diff --git a/agents/pages/reference/rules/quadratic-string-concat-chain.md b/agents/pages/reference/rules/quadratic-string-concat-chain.md new file mode 100644 index 0000000..a395841 --- /dev/null +++ b/agents/pages/reference/rules/quadratic-string-concat-chain.md @@ -0,0 +1,40 @@ +# quadratic-string-concat-chain + +a chain of three or more (^) segments + + + +**pedantic · warning · stable · since 1.0 · fix: never · off by default** + +`(^)` associates to the right, so `a ^ b ^ c` builds `b ^ c` and then +copies it whole into `a ^ (b ^ c)`: every added segment recopies the ones +after it. + +```ocaml +(* bad *) dir ^ "/" ^ file +(* good *) String.concat "" [ dir; "/"; file ] +``` + +Fires when `Stdlib.(^)`'s right operand is itself a `Stdlib.(^)` +application — three or more segments in one chain. A two-segment +concatenation, a rebound `(^)`, and a left-parenthesized `(a ^ b) ^ c` +(the right operand is simple) deliberately do not fire. A chain of n +segments holds n − 2 matching nodes; the rule reports one finding per +maximal chain — at the innermost matching node, whose rightmost operand +is simple — so a nine-segment chain is one finding, not seven. Two +copies of three short segments rarely +matter, hence pedantic and off; no fix, because choosing the separator +layout is editorial. + +Option `(max-segments )` (n ≥ 2, default 2) raises the tolerated +chain length: only chains of more than n segments fire, anchored at the +node where the chain first exceeds n. This makes the recorded +narrowing — a higher segment threshold — configurable: + +```lisp +(rule quadratic-string-concat-chain + (max-segments 4)) +``` + +Pedantic: a chain of three or four segments in a message or a path costs nothing +anyone would measure, so reporting one is a house's choice. diff --git a/agents/pages/reference/rules/quadratic-string-concat-fold.md b/agents/pages/reference/rules/quadratic-string-concat-fold.md new file mode 100644 index 0000000..37e0076 --- /dev/null +++ b/agents/pages/reference/rules/quadratic-string-concat-fold.md @@ -0,0 +1,27 @@ +# quadratic-string-concat-fold + +string concatenation folded through (^) + + + +**perf · warning · stable · since 1.0 · fix: never · on by default** + +Folding `(^)` over a collection copies the whole accumulator for every +element: joining n segments allocates quadratically where `String.concat` +allocates the result once. + +```ocaml +(* bad *) List.fold_left ( ^ ) "" +(* good *) String.concat "" +``` + +Fires when `List.fold_left`, `List.fold_right`, `Array.fold_left`, +`Array.fold_right`, or `Seq.fold_left` resolves to its `Stdlib` +declaration with `Stdlib.(^)` as the first of one or two unlabeled +arguments — at any saturation, the partially applied `fold ( ^ )` and +`fold ( ^ ) ""` and the fully saturated three-argument call alike. A +rebound `(^)`, the eta-expanded `fun acc s -> acc ^ s`, labeled folds +(`ListLabels.fold_left ~f:( ^ )`), other operators, and Buffer +accumulation deliberately do not fire. The `String.concat ""` rewrite +of the saturated form lands with a later release; no automatic fix +until then — the promise flips to `Sometimes` with it. diff --git a/agents/pages/reference/rules/redundant-bind-return.md b/agents/pages/reference/rules/redundant-bind-return.md new file mode 100644 index 0000000..a93d731 --- /dev/null +++ b/agents/pages/reference/rules/redundant-bind-return.md @@ -0,0 +1,28 @@ +# redundant-bind-return + +bind into a bare return re-wraps the value unchanged + + + +**style · warning · stable · since 1.0 · fix: never · off by default** + +Binding a computation into its monad's own `return` is the right +identity law: every value is re-wrapped exactly as it arrived, so the +whole expression is the computation it started from. + +```ocaml +(* bad *) Option.bind o Option.some +(* good *) o +``` + +Fires when a known-lawful pair resolves by declaration: `Option.bind` +with `Option.some`, `Result.bind` with `Result.ok`, or `Lwt.bind` / +`Lwt.Infix.(>>=)` with `Lwt.return` — the return passed as the bare +callback, or as a lambda returning exactly the bound value +(`fun x -> Some x`, `function x -> Ok x`, `fun x -> Lwt.return x`; +constructor and function returns alike, by declaration or +predefined-constructor identity). A project's own `bind` and `return` +never fire, lawful or not: each listed pair is an audited lawfulness +claim, and other identities match nothing. `let*` syntax, guarded or +multi-case `function` callbacks, and callbacks returning anything but +the bound value deliberately do not fire. No automatic fix. diff --git a/agents/pages/reference/rules/redundant-boolean-comparison.md b/agents/pages/reference/rules/redundant-boolean-comparison.md new file mode 100644 index 0000000..0d94dce --- /dev/null +++ b/agents/pages/reference/rules/redundant-boolean-comparison.md @@ -0,0 +1,29 @@ +# redundant-boolean-comparison + +comparison with a boolean constant + + + +**suspicious · warning · stable · since 1.0 · fix: sometimes · on by default** + +Comparing a boolean with `true` or `false` restates the operand: +`x = true` is `x`, `x = false` is `not x`. The comparison adds noise and +often signals a leftover simplification. + +```ocaml +(* bad *) if flag = true then … +(* good *) if flag then … +``` + +Fires when `=` or `<>` resolves to its `Stdlib` declaration, is applied to +exactly two unlabeled arguments, and exactly one operand is a literal +`true` or `false` of the predefined `bool` type, in either operand order. +Shadowed or rebound operators, comparisons of two constants, other +operators (`==`, `<`, `Bool.equal`), and same-spelling constructors of +another type deliberately do not fire. The fix drops the constant: the +comparison becomes the operand itself (`x = true` → `x`, safe) or its +negation (`x = false` → `not x`, `x <> true` → `not x`) — the negation +splices a `not` the rule never resolved, so a fix-site scope shadowing +`not` would change the value: that cell's fix is unsafe, applied only +under `--fix --unsafe`. Either fix ships only when the operand's source +slices cleanly (`Unit.splice`). diff --git a/agents/pages/reference/rules/redundant-boolean-operator.md b/agents/pages/reference/rules/redundant-boolean-operator.md new file mode 100644 index 0000000..322efc1 --- /dev/null +++ b/agents/pages/reference/rules/redundant-boolean-operator.md @@ -0,0 +1,27 @@ +# redundant-boolean-operator + +boolean operator with a constant operand + + + +**style · warning · stable · since 1.0 · fix: never · off by default** + +A `&&` or `||` with a literal `true` or `false` operand computes +nothing the other operand does not already say: `x && true` is `x`, +`false || x` is `x`, `false && e` is `false` with `e` never evaluated. + +```ocaml +(* bad *) enabled && true +(* good *) enabled +``` + +Fires when `&&` or `||` resolves to its `Stdlib` declaration, is applied +to exactly two unlabeled arguments, exactly one operand is a literal +`true` or `false`, and dropping the operator preserves what the program +evaluates: any constant on the left (short-circuiting already decided +what runs), a neutral constant on the right (`&& true`, `|| false`), or +an absorbing constant on the right (`&& false`, `|| true`) only when the +discarded left operand is a bare identifier or constant and so provably +pure. Shadowed operators, two-constant operations, and absorbing cases +whose discarded operand could have effects deliberately do not fire. No +automatic fix. diff --git a/agents/pages/reference/rules/redundant-conversion-roundtrip.md b/agents/pages/reference/rules/redundant-conversion-roundtrip.md new file mode 100644 index 0000000..4cd3c42 --- /dev/null +++ b/agents/pages/reference/rules/redundant-conversion-roundtrip.md @@ -0,0 +1,31 @@ +# redundant-conversion-roundtrip + +conversion immediately undone by its inverse + + + +**perf · warning · stable · since 1.0 · fix: sometimes · on by default** + +Converting a value out of its type and immediately back does +allocation and parsing work to end where it started: +`int_of_string (string_of_int n)` is `n`. + +```ocaml +(* bad *) int_of_string (string_of_int n) +(* good *) n +``` + +Fires only on compositions proved identities by the stdlib's contracts, +with both conversions resolving to their `Stdlib` declarations and the +inner application feeding the outer directly: `int_of_string` of +`string_of_int`, `bool_of_string` of `string_of_bool`, `Char.chr` of +`Char.code`, `of_string` of `to_string` for `Int32`/`Int64`/`Nativeint`, +and `Bytes.to_string` of `Bytes.of_string`. Pipeline spellings collapse +and fire. The reverse directions deliberately do not: `string_of_int +(int_of_string s)` canonicalizes (`"+3"`, `"0x10"` change), +`Char.code (Char.chr n)` deletes a range check, `Bytes.of_string +(Bytes.to_string b)` must stay a fresh mutable copy, and the lossy float +pair is excluded; shadowed conversions and work between the two also +stay clean. The fix — the inner argument itself — is Safe for the +unboxed pairs (int, bool, char) and withheld for the boxed and copying +pairs, where replacement changes physical identity. diff --git a/agents/pages/reference/rules/redundant-guard-true.md b/agents/pages/reference/rules/redundant-guard-true.md new file mode 100644 index 0000000..8e1fd4b --- /dev/null +++ b/agents/pages/reference/rules/redundant-guard-true.md @@ -0,0 +1,31 @@ +# redundant-guard-true + +when guard that is literally true or false + + + +**suspicious · warning · stable · since 1.0 · fix: sometimes · on by default** + +A guard that is literally `true` never fails: the case behaves as +if unguarded, but the `when` costs the reader a double-take and costs +the compiler its exhaustiveness analysis. A guard that is literally +`false` never succeeds: the arm is dead. Both are almost always a +leftover or an unfinished edit — suspicious-literal-condition's +rationale, relocated to guards. + +```ocaml +(* bad *) match x with n when true -> n | _ -> 0 +(* good *) match x with n -> n +``` + +Fires on every case of a `match`, `function`, or `try` whose guard is +the boolean literal itself, by predefined-constructor identity, at the +guard. Real guards and named flags (`when debug`) deliberately do not +fire — there is no constant propagation — and `when true && debug` is +redundant-boolean-operator's node inside the guard. Matches carrying +effect-handler cases are refused (recorded false negative). The fix +deletes an always-true guard only on the final arm — dropping an +earlier arm's guard can render later arms warning-11 dead under +`-warn-error` — and only when the bytes after the pattern are exactly +`when` `true` with whitespace; an always-false guard never carries a +fix (deleting a dead arm is an intent decision). diff --git a/agents/pages/reference/rules/redundant-if-bool.md b/agents/pages/reference/rules/redundant-if-bool.md new file mode 100644 index 0000000..c0d811f --- /dev/null +++ b/agents/pages/reference/rules/redundant-if-bool.md @@ -0,0 +1,31 @@ +# redundant-if-bool + +if whose both branches are boolean literals restates the condition + + + +**style · warning · stable · since 1.0 · fix: sometimes · off by default** + +An `if` whose branches are the two boolean literals restates its own +condition: `if c then true else false` is `c`, and `then false else +true` is `not c`. Both rewrites preserve evaluation order and effects. + +```ocaml +(* bad *) if p x then true else false +(* good *) p x +``` + +Fires when the condition is not itself a boolean literal (that is +suspicious-literal-condition's finding) and both branches are boolean +literals — differing ones, by predefined-constructor identity. Equal +literals (`then true else true`) are a degenerate shape left to a +future same-arms analysis, and integer 0/1 branches and user-defined +`True`/`False` constructors deliberately do not fire. The +one-literal family (`then true else e`, and kin) is +`manual-boolean-operator`, Style and opt-in. The fix performs +the rewrite from the condition's source slice (`Unit.splice`), +parenthesizing a non-atomic slice; preprocessed units ship without +one. Only the `use the condition` cell is safe: negation splices +`not` — a spelling that resolves in the fix site's scope, which the +rule never checked — so its fix is unsafe, applied only under +`--fix --unsafe`. diff --git a/agents/pages/reference/rules/redundant-list-roundtrip.md b/agents/pages/reference/rules/redundant-list-roundtrip.md new file mode 100644 index 0000000..4509acc --- /dev/null +++ b/agents/pages/reference/rules/redundant-list-roundtrip.md @@ -0,0 +1,25 @@ +# redundant-list-roundtrip + +list converted to a sequence and immediately back + + + +**perf · warning · stable · since 1.0 · fix: never · on by default** + +`List.of_seq (List.to_seq xs)` walks the list twice and allocates a +fresh copy just to end where it started. + +```ocaml +(* bad *) List.of_seq (List.to_seq xs) +(* good *) xs +``` + +Fires only when both conversions resolve to their `Stdlib.List` +declarations and the inner application feeds the outer one directly; the +types then already prove the roundtrip. The compiler collapses `|>` into +direct applications, so `xs |> List.to_seq |> List.of_seq` fires too. +Shadowed or let-rebound names, sequence work between the conversions, +the reverse `to_seq (of_seq s)` direction, and other `of_seq` targets +(`Array.of_seq`) deliberately do not fire. No fix: `List.of_seq` +allocates a fresh list, so removing the roundtrip changes physical +identity. diff --git a/agents/pages/reference/rules/redundant-match-bool.md b/agents/pages/reference/rules/redundant-match-bool.md new file mode 100644 index 0000000..27385c7 --- /dev/null +++ b/agents/pages/reference/rules/redundant-match-bool.md @@ -0,0 +1,37 @@ +# redundant-match-bool + +boolean match interrupting an if/else chain + + + +**style · warning · stable · since 1.0 · fix: sometimes · off by default** + +A two-case match on a boolean — `match e with true -> a | false -> +b`, or the `function` form — is `if`/`else` in longhand. Standalone, +that longhand is a deliberate house style in wide use (cmdliner's +whole surface, sexplib0's parsers, ppxlib's printers) and is left +alone. What this rule reports is the boolean match that interrupts an +if/else cascade: one sitting as the `else` continuation of an +enclosing `if`, or whose own arms continue into `if`/`else` — there +the switch of form buries one branch of a multi-way decision, and +`if` keeps the cascade in one shape. + +```ocaml +(* bad *) if p then x else match c with true -> a | false -> b +(* good *) if p then x else if c then a else b +``` + +Fires on exactly two guard-less cases whose patterns are the boolean +literals (predefined-constructor identity) covering `true` and `false` +in either order, in both the `match` and the `function` form — and +only in the cascade positions: the match is an `else` branch, or an +arm's body is itself an `if`/`else` (the `function` form, never a +branch of an enclosing `if`, fires on the arm shape alone). A +standalone two-case boolean match never fires: the house styles are +recorded negatives. Guards, extra or wildcard cases, `exception` cases +(the `if` rewrite would change semantics), user-defined two-constructor +variants, and matches carrying effect handlers deliberately do not +fire. The fix rewrites the match form to `if`/`else` (the `function` +form has no scrutinee to build the condition from and ships none); it +applies only when the scrutinee's and both arms' source slices cleanly +(`Unit.splice`). diff --git a/agents/pages/reference/rules/redundant-nested-if.md b/agents/pages/reference/rules/redundant-nested-if.md new file mode 100644 index 0000000..a71d440 --- /dev/null +++ b/agents/pages/reference/rules/redundant-nested-if.md @@ -0,0 +1,30 @@ +# redundant-nested-if + +else-less if directly nested in an else-less if + + + +**style · warning · stable · since 1.0 · fix: sometimes · off by default** + +An else-less `if` whose then-branch is directly another else-less +`if` is one condition spelled as two: `&&`'s short-circuit evaluates +the inner condition exactly when the nested form does. + +```ocaml +(* bad *) if ok then if ready then launch () +(* good *) if ok && ready then launch () +``` + +Fires when both `if`s are else-less and the inner one is the entire +then-branch (`begin end` and parentheses are transparent), at the outer +`if`. Any `else` — outer or inner — refuses: collapsing would change +what runs when the conditions split. Literal conditions are +suspicious-literal-condition's finding, `else if` chains are the idiom +and are never looked into, and a nested `if` under a `let` or sequence +deliberately does not fire. Deeper nests report once per level. The +fix rewrites the head to `c1 && c2`, parenthesizing each condition +unless atomic; it ships only when the text between the conditions is +exactly `then` `if` with whitespace — a parenthesis, `begin`, or +comment in the gap withholds the fix, not the finding. The fix writes +`&&`, so it is safe where that is the standard library's, and unsafe, applied +only under `--unsafe`, where something else in scope may bind it. diff --git a/agents/pages/reference/rules/redundant-not-not.md b/agents/pages/reference/rules/redundant-not-not.md new file mode 100644 index 0000000..72b287d --- /dev/null +++ b/agents/pages/reference/rules/redundant-not-not.md @@ -0,0 +1,26 @@ +# redundant-not-not + +double boolean negation + + + +**style · warning · stable · since 1.0 · fix: sometimes · off by default** + +`not (not e)` is `e`: `not` is total and effect-free, and `e` is +evaluated exactly once in both forms, so the double negation is pure +noise — usually sediment from mechanical edits. + +```ocaml +(* bad *) not (not ready) +(* good *) ready +``` + +Fires when both applications resolve to `Stdlib.not` or +`Stdlib.Bool.not`, in any combination; `not @@ not x` collapses to +direct applications in the typedtree and fires too. A quadruple +negation reports at two nested nodes — the fixes' spans nest and the +applier defers the conflict. Single negations, shadowed or rebound +`not`, `lnot` (integer complement), and functions that merely rhyme +deliberately do not fire. The fix replaces the whole application with +the operand, parenthesized unless atomic; it ships only when the +operand's source slices cleanly (`Unit.splice`). diff --git a/agents/pages/reference/rules/redundant-option-comparison.md b/agents/pages/reference/rules/redundant-option-comparison.md new file mode 100644 index 0000000..2ce913d --- /dev/null +++ b/agents/pages/reference/rules/redundant-option-comparison.md @@ -0,0 +1,47 @@ +# redundant-option-comparison + +comparison with None spells an Option predicate + + + +**pedantic · warning · stable · since 1.0 · fix: sometimes · off by default** + +`o = None` and `o <> None` are `Option.is_none o` and +`Option.is_some o` spelled through the polymorphic comparison. The +named predicates state the intent and survive a payload type turning +uncomparable. That is a preference, not a defect: the comparison is a +constant-time tag test either way, and `x = None` is common, idiomatic +OCaml — hence Pedantic. Adopt it where a codebase wants the predicate +spelling; `!r = None` reads at least as well as `Option.is_none !r`. + +```ocaml +(* bad *) if o = None then default else run o +(* good *) if Option.is_none o then default else run o +``` + +Fires when `=` or `<>` resolves to its `Stdlib` declaration with +exactly one operand the predefined `None` constructor, in either +position. Comparisons against `Some e` are out of scope entirely — +payload equality may deep-traverse and raise, and is a meaningful +program. `None = None` (a two-constant expression), orderings, +`compare`, physical equality, user-defined `None` lookalikes, and +shadowed operators deliberately do not fire. The fix rewrites the whole +comparison to the predicate applied to the other operand — structural +comparison against the immediate `None` decides on the tag without +traversing the payload, so the predicate computes the same answer, even +for payloads whose comparison would raise. The fix is safe where `Option` is the +standard library's, and unsafe, applied only under `--unsafe`, otherwise. + +The reporting unit is the boolean chain, not the comparison: when two +or more such comparisons are direct operands of one `Stdlib` `&&`/`||` +chain (`s.arch <> None && s.layers <> None && s.rope <> None`), the +chain is one finding — anchored at +the whole chain, its fix rewriting every comparison at once — not one +per operand. A chain carrying exactly +one such comparison reports it as the standalone form does; a +comparison below anything other than a chain connective (an argument, a +`not`) keeps its own finding, and a rebound connective is no chain at +all. In preprocessed units the collapse is off and every comparison +reports individually: a rewriter-manufactured chain could anchor the +collapsed finding at a ghost location the emit contract drops, +silencing members that are real. diff --git a/agents/pages/reference/rules/redundant-option-roundtrip.md b/agents/pages/reference/rules/redundant-option-roundtrip.md new file mode 100644 index 0000000..a640049 --- /dev/null +++ b/agents/pages/reference/rules/redundant-option-roundtrip.md @@ -0,0 +1,23 @@ +# redundant-option-roundtrip + +option converted to a list only to take its head back + + + +**perf · warning · stable · since 1.0 · fix: never · on by default** + +`List.nth_opt (Option.to_list o) 0` allocates an intermediate list +just to rebuild the option it started from — the whole expression is `o`. + +```ocaml +(* bad *) List.nth_opt (Option.to_list o) 0 +(* good *) o +``` + +Fires only when both functions resolve to their `Stdlib` declarations and +the index is the integer literal `0`; the types then already prove the +roundtrip. Shadowed or let-rebound names, any other index (literal or +not), partial applications, operator pipelines, and anything between the +two conversions deliberately do not fire. No fix: replacing the +expression with `o` changes physical identity, which a caller may +observe. diff --git a/agents/pages/reference/rules/redundant-return-bind.md b/agents/pages/reference/rules/redundant-return-bind.md new file mode 100644 index 0000000..748c852 --- /dev/null +++ b/agents/pages/reference/rules/redundant-return-bind.md @@ -0,0 +1,26 @@ +# redundant-return-bind + +bind of a fresh return wraps a value only to unwrap it + + + +**style · warning · stable · since 1.0 · fix: never · off by default** + +Binding a freshly returned value is the left identity law: the wrap is +undone by the bind, so applying the callback to the value directly says +the same thing without the round trip. + +```ocaml +(* bad *) Option.bind (Option.some x) f +(* good *) f x +``` + +Fires when a known-lawful pair resolves by declaration and the scrutinee +is that pair's return applied to a value — the return function +(`Option.some`, `Result.ok`, `Lwt.return`) or its constructor form +(`Some x`, `Ok x`, by predefined/global constructor identity): +definitional for `Option` and `Result`, documented for `Lwt`. Arbitrary +scrutinees, `Error` (not a return), partial applications, and a +project's own `bind`/`return` deliberately do not fire — each listed +pair is an audited lawfulness claim. No fix: naming the callback's +argument is editorial. diff --git a/agents/pages/reference/rules/restricted-dependency.md b/agents/pages/reference/rules/restricted-dependency.md new file mode 100644 index 0000000..3e16bd1 --- /dev/null +++ b/agents/pages/reference/rules/restricted-dependency.md @@ -0,0 +1,70 @@ +# restricted-dependency + +reference to a dependency forbidden by workspace policy + + + +**restriction · warning · stable · since 1.0 · fix: never · off by default** + +A dependency the workspace has moved off — `Str` for `Re`, a bare +stdlib helper for the house wrapper — stays reachable forever, and the +policy against it lives in review comments until a linter carries it. +This rule is the configured deny-list: each forbid in the config names a +module or value and the replacement to use, and every reference +resolving to a forbidden declaration reports that replacement. + +```lisp +(rule restricted-dependency + (forbid Str + (use "Re — Str answers matches through global state")) + (forbid Stdlib.invalid_arg + (use "Import.invalid_arg' — house messages carry module and function"))) +``` + +```ocaml +(* bad *) let re = Str.regexp "a+" +(* good *) let re = Re.compile Re.(rep1 (char 'a')) +``` + +A forbid path ending in a capitalized component forbids a module: a +single component (`Str`) is a compilation unit, and a dotted path +(`Stdlib.Obj`, `Vendor.Internal`) resolves by signature walk from its +head unit, through module aliases — any value reference reaching through +the forbidden module fires. A path ending in a lowercase or operator +component (`Stdlib.invalid_arg`, quoted `"Stdlib.(=)"`) forbids that +one value. Matching is by resolved declaration UID, never by spelling: +`open`s and aliases (`module R = Str`) fire, and a forbidden path that +does not resolve in the linted workspace matches nothing — never an +error — so one house config serves projects that lack the library +entirely. Mind the spelling of separately compiled libraries: `Str` is +its own compilation unit, so write `(forbid Str ...)` — `Stdlib.Str` +names no declaration and matches nothing. Operator paths must be quoted +so the config reader keeps them one atom: `(forbid "Stdlib.(=)" ...)`. + +Why restrict this? Every forbidden name is legitimate OCaml — `Str` +ships with the distribution, `invalid_arg` is the stdlib's own +spelling — so no default may claim them as defects; which dependencies a +workspace bans is house policy, and the reason travels in the mandatory +`use` remedy so the finding argues its own case. Litany's own +`outdated-str-module` is this rule with a hard-coded list — it found a +real global-state race in field review. Resolution +by declaration UID makes this strictly sounder than path matching: a +rebound or shadowed name never matches, an alias always does. No fix: +every replacement is a migration. + +Fires once per value reference resolving to a forbidden declaration — +forbids are tried in configured order, the first match reports — with +the forbid's `use` replacement verbatim in the message (`... is a +restricted module; use ...` for a module forbid, `... is a restricted +value; use ...` for a value forbid). A forbid may be scoped after its +remedy: `(only ...)` applies it in those files alone, `(except + ...)` in every file but those, both in `per-path`'s glob grammar +against the workspace-relative path -- a library's ban that a test may +break, or a clock call one module alone may make. Without a +`(rule restricted-dependency ...)` form, or with one holding no forbids, +the rule is inert: nothing is forbidden, nothing fires. Project-local +modules or values shadowing a forbidden spelling, same-named wrapper +modules declared in other units (`Re.Str`, its own declarations), later +uses of a value bound to a forbidden one (the binding's right-hand side +already fired), and a forbidden module's constructors and types +(references, not types, are the finding unit) deliberately do not fire. diff --git a/agents/pages/reference/rules/restricted-export-name.md b/agents/pages/reference/rules/restricted-export-name.md new file mode 100644 index 0000000..a1db3de --- /dev/null +++ b/agents/pages/reference/rules/restricted-export-name.md @@ -0,0 +1,55 @@ +# restricted-export-name + +exported name breaking the configured naming policy + + + +**restriction · warning · stable · since 1.0 · fix: never · off by default** + +An exported name is API surface forever: a prime-suffixed `parse'` +or a five-underscore `total_count_of_all_things` in an interface makes +every consumer spell the house's least readable habit. Inside a +function those names are the author's business; on the export surface +they are policy, and this rule is that policy's closed vocabulary — +enumerated options, never a user-supplied regex (a regex option would +be a second pattern language smuggled through configuration). + +```lisp +(rule restricted-export-name + (forbid-suffix ') + (max-underscores 3)) +``` + +```ocaml +(* bad *) val parse' : string -> t +(* good *) val parse_exn : string -> t +``` + +Why restrict this? Every condemned spelling is legitimate OCaml — +`f'` is idiomatic mathematics, long underscored names are a taste — so +no default may claim them as defects; which spellings a house bans is +policy, cherry-picked, never in `all`. Litany's export index makes +these checks one walk over resolved exports instead of a text scan. No +fix: renaming an export is an interface decision. + +Fires once per exported name — a value or type of the unit's export +surface — that a configured restriction condemns: `(forbid-suffix )` +condemns a name ending in ``, `(max-underscores )` a name +carrying more than `` underscores. Restrictions are tried in +configured order and the first condemning one reports, its option named +in the message. The export surface is the seam's: the unit's interface +when it has one, the implementation's own inferred signature when it +does not — so an `.mli` decides what is exported, and an ml-only unit +exports every root declaration, executables and tests included: their +root names are surface to their own readers, and the tier keeps the +rule opt-in. Findings anchor at the implementation's matching root +declaration (`let`, `external`, or `type`), never in the `.mli`. + +Without a `(rule restricted-export-name ...)` form, or with one holding +no restrictions, the rule is inert. Names the interface hides, local +bindings and type abbreviations inside functions or nested modules, +module names, a forbidden suffix occurring mid-name, and names at the +underscore limit deliberately do not fire. Recorded false negatives, in +the safe direction: exported members of submodules (the export surface +joins interface to implementation at the unit's root only) and exports +satisfied by `include` (no root declaration to anchor at). diff --git a/agents/pages/reference/rules/restricted-global-mutable-state.md b/agents/pages/reference/rules/restricted-global-mutable-state.md new file mode 100644 index 0000000..68fdbaf --- /dev/null +++ b/agents/pages/reference/rules/restricted-global-mutable-state.md @@ -0,0 +1,53 @@ +# restricted-global-mutable-state + +toplevel mutable state in library code + + + +**restriction · warning · stable · since 1.0 · fix: never · off by default** + +A `ref`, `Hashtbl.t`, or mutable-record value bound at a library's +toplevel lives for the whole process: every consumer shares it, tests +interfere through it, two domains race on it, and no caller can create +a second independent instance. Litany's own law — pure core, state in +the driver — is this rule, self-applied. + +```ocaml +(* bad *) let registry : (string, handler) Hashtbl.t = Hashtbl.create 16 +(* good *) a table created by the caller and passed down, or a + `create`d value the API threads explicitly +``` + +Why restrict this? Deliberate globals are legitimate — fmt's style +store and cmdliner's uid counter are designed — and the field count is +small (2 sightings in ~9,700 reviewed lines), so a ban is house +policy, not a defect claim: off even under `--select all`, +cherry-picked by a +workspace whose libraries keep state in the caller. The known +false-positive shapes are named up front: memo tables, interning +pools, and caches are deliberate state, and `[@litany.allow]` with a +reason is the designed outlet — a lazy cache (`let table = lazy …`) +is already the blessed initialize-once spelling and stays clean by +shape. + +Fires once per variable bound by an item of the unit's root structure — +a root `include struct ... end`'s items included: they land on the +unit's export surface like any root item — whose type's head is +`Stdlib.ref`, `Stdlib.Hashtbl.t`, or a record type declared at the +unit's root with a `mutable` field, in units whose roster kind is +`Library`. Executables and tests own their +process and never fire; a unit whose roster carries no kind is +deliberately silent — a metadata-gated rule degrades to silence, +never to guessing. Local bindings inside functions and +let-expressions, `lazy` thunks, pure records, and functions that +merely return fresh state deliberately do not fire. Arrays are out of +scope in v1: the array type does not distinguish a buffer from state — +a lookup-table literal and a mutable accumulator spell the same type — +so an array ban would claim a structural proof the type cannot give. +Abbreviation heads are compared as inferred, never expanded +(`type counter = int ref` stays clean), a mutable-record head the +unit does not declare at its own root — a nested module's, one +`include`d from a named module, another unit's — stays clean, and a +binding that binds no variable or destructures stays clean: each is a +recorded false negative in the safe direction. No fix: moving state +into the caller is an API redesign. diff --git a/agents/pages/reference/rules/restricted-public-exception.md b/agents/pages/reference/rules/restricted-public-exception.md new file mode 100644 index 0000000..b935d69 --- /dev/null +++ b/agents/pages/reference/rules/restricted-public-exception.md @@ -0,0 +1,46 @@ +# restricted-public-exception + +exception declared in a public library interface + + + +**restriction · warning · stable · since 1.0 · fix: never · off by default** + +An exception in a public interface is an untyped failure path every +consumer inherits: the type checker tracks no `exception` the way it +tracks a `result`, so callers learn about the escape at run time, and +the interface's signatures stop telling the whole truth about what a +call can do. + +```ocaml +(* bad *) exception Parse_error of string +(* good *) type error = [ `Parse of string ] + val parse : string -> (t, error) result +``` + +Why restrict this? Declared exceptions are legitimate OCaml across the +ecosystem — `Not_found` and `Exit` in the standard library, +`Scanf.Scan_failure`, the error exception of nearly every parser — so +no default may claim them as defects and this is never a Suspicious +rule. A result-typed house style (errors as typed `result` values) is +policy a workspace adopts, cherry-picked by exact name, off even under +`--select all`. + +Fires once per exception of the export surface of a public library +unit — the interface when the unit has one, the implementation's own +inferred signature when it does not — anchored at the implementation's +matching root `exception` declaration (the emit contract owns findings +to the editable source). The gate is the roster's: only units whose +stanza kind is `Library` and whose visibility is `Public` fire +(`Unknown` visibility is treated as `Public`, the roster's own root +convention). Executables and tests have no consumers to protect and +never fire; a private library's exceptions are the workspace's own +business; a unit whose roster carries no kind is deliberately silent — +a metadata-gated rule degrades to silence, never to guessing. An +exception the `.mli` hides, a `let exception` inside a function, and +`type t += …` extension constructors deliberately do not fire. +Recorded false negatives, in the safe direction: exceptions of +submodule signatures (the export surface joins interface to +implementation at the unit's root only) and an interface exception +satisfied by `include` (no root declaration to anchor at). No fix: +replacing an exception with a `result` is an API redesign. diff --git a/agents/pages/reference/rules/suspicious-ambiguous-constructors.md b/agents/pages/reference/rules/suspicious-ambiguous-constructors.md new file mode 100644 index 0000000..c2006e2 --- /dev/null +++ b/agents/pages/reference/rules/suspicious-ambiguous-constructors.md @@ -0,0 +1,32 @@ +# suspicious-ambiguous-constructors + +constructor that shadows a standard constructor + + + +**suspicious · warning · nursery · since 1.0 · fix: never · off by default** + +A variant that declares a constructor named `Some`, `None`, `Ok`, +`Error`, `::`, or `[]` shadows a predefined or stdlib constructor for +the rest of the scope: every later unannotated `Some x` builds this +type, option/result code nearby starts needing type-directed +disambiguation, and the reader must track which `Some` is which. The +compiler's own diagnostics (warnings 41/42) fire only at use sites, +only when force-enabled, and are off in vanilla and dune-dev defaults +alike — the declaration, where the decision is actually made, is dark +everywhere. + +```ocaml +(* bad *) type str_option = Some of string | None +(* good *) type str_option = Found of string | Missing +``` + +Fires once per shadowing constructor, at its declaration. A re-export +(`type 'a maybe = 'a option = None | Some of 'a`) redeclares +constructors that already exist by construction and is exempt: a +variant kind with a manifest is necessarily the re-export form. +`exception Error of string` shadows identically but is an extension +constructor, not a variant declaration — a recorded false negative. No +fix: the remedy (rename, or prefix with the domain) is a design +decision, and a DSL that deliberately re-models this vocabulary should +carry `[@litany.allow]` with the reason at the declaration. diff --git a/agents/pages/reference/rules/suspicious-catch-all-handler.md b/agents/pages/reference/rules/suspicious-catch-all-handler.md new file mode 100644 index 0000000..1e4437b --- /dev/null +++ b/agents/pages/reference/rules/suspicious-catch-all-handler.md @@ -0,0 +1,27 @@ +# suspicious-catch-all-handler + +wildcard exception handler swallows every exception + + + +**suspicious · warning · stable · since 1.0 · fix: never · on by default** + +`try … with _ -> …` handles every exception — `Out_of_memory`, +`Stack_overflow`, `Assert_failure`, and the one the author never +anticipated — indistinguishably from the one it meant to catch, hiding +real failures. + +```ocaml +(* bad *) try f () with _ -> default +(* good *) try f () with Not_found -> default +``` + +Fires once per wildcard, guard-less handler case: in `try` handlers and +in `match` `exception` arms, anchored at the wildcard itself. A named +binder (`with e -> …`) deliberately does not fire even when unused — +warning 27 owns that, and a name at least admits `raise e`. Guarded +wildcards, wildcards inside deeper patterns (`Failure _`), or-patterns, +and wildcard value cases do not fire either. No fix: only the author +knows which exception was meant. + +The deliberate `with _ -> None` option-izer is one `[@litany.allow]` away. diff --git a/agents/pages/reference/rules/suspicious-duplicate-condition.md b/agents/pages/reference/rules/suspicious-duplicate-condition.md new file mode 100644 index 0000000..b75318e --- /dev/null +++ b/agents/pages/reference/rules/suspicious-duplicate-condition.md @@ -0,0 +1,29 @@ +# suspicious-duplicate-condition + +else-if condition that duplicates the previous arm's + + + +**suspicious · warning · stable · since 1.0 · fix: never · on by default** + +`if c then … else if c then e2 …` evaluates the second `c` with +nothing between the two evaluations except the first `c` itself: when +`c` is pure the second arm can never run, and the chain is almost +certainly an unedited paste. + +```ocaml +(* bad *) if x = 1 then a else if x = 1 then b else c +(* good *) if x = 1 then a else if x = 2 then b else c +``` + +Fires when, in a non-preprocessed unit, an `if`'s else branch is +directly another `if`, the two conditions' source slices are +byte-identical after whitespace normalization, and the condition is +syntactically pure — built only of identifiers, constants, constructors, +and applications of the `Stdlib` boolean and comparison operators. +Conditions with any other call (it may be effectful), dereferences, +field or array reads (another domain could write between evaluations), +and boolean-literal conditions (suspicious-literal-condition's) refuse. +Only adjacent arms are compared: `if a … else if b … else if a` is a +recorded false negative. No fix: which arm was meant is the author's +call. diff --git a/agents/pages/reference/rules/suspicious-exit-in-library.md b/agents/pages/reference/rules/suspicious-exit-in-library.md new file mode 100644 index 0000000..a49ce60 --- /dev/null +++ b/agents/pages/reference/rules/suspicious-exit-in-library.md @@ -0,0 +1,29 @@ +# suspicious-exit-in-library + +exit referenced in library code + + + +**suspicious · warning · stable · since 1.0 · fix: never · on by default** + +`Stdlib.exit` terminates the process, runs the `at_exit` handlers, +and denies every caller above the library a say. Inside library code +that is a policy usurpation and a classic source of test hostility: +the test runner dies with the library. Executables own their exit; +libraries raise. + +```ocaml +(* bad *) let load path = if bad path then exit 1 else parse path +(* good *) let load path = if bad path then invalid_arg "load" else parse path +``` + +Fires once per resolved reference to `Stdlib.exit` — aliasing an exit +is an exit — and only in units whose roster kind is `Library`; a unit +whose roster carries no kind is deliberately silent: a metadata-gated +rule degrades to silence, never to guessing. `raise Exit` constructs +the `Stdlib.Exit` exception, not a reference to `exit`; `at_exit` is a +different declaration; a shadowing local `exit` resolves to a local +declaration — none fire. A library's deliberate `fatal`/`usage` helper +is what `[@litany.allow "suspicious-exit-in-library: ..."]` with a +reason documents. No fix: the replacement error path is a design +decision. diff --git a/agents/pages/reference/rules/suspicious-failwith-in-library.md b/agents/pages/reference/rules/suspicious-failwith-in-library.md new file mode 100644 index 0000000..be84cbf --- /dev/null +++ b/agents/pages/reference/rules/suspicious-failwith-in-library.md @@ -0,0 +1,41 @@ +# suspicious-failwith-in-library + +failwith referenced in library code + + + +**restriction · warning · stable · since 1.0 · fix: never · off by default** + +`Failure` is anonymous — the one exception no caller can match +meaningfully — and `failwith` in a library manufactures it at the API +boundary: configuration failures, invariant violations, and stubs all +escape as the same unmatchable exception. + +```ocaml +(* bad *) let connect cfg = if bad cfg then failwith "bad TLS config" else … +(* good *) let connect cfg = if bad cfg then Error `Tls_config else Ok … +``` + +Why restrict this? The defect is the *escape* — an anonymous `Failure` +crossing the API boundary — and this rule cannot prove an escape: local +failwith trampolines (raise here, catch just above) are a legitimate +style established libraries practice, and the same reference-level +check would flag them. A rule that cannot prove the defect and flags +the practice is house policy by definition, so it sits in the +`restriction` tier: off even under `--select all`, cherry-picked by a +workspace whose libraries speak typed errors, with `[@litany.expect]` +as the justification trail for the trampolines it cannot see. + +Fires once per resolved reference to `Stdlib.failwith` — aliasing a +failwith is a failwith — in units whose roster kind is `Library`, +except references lexically enclosed in a `Texp_try` (the same-function +trampoline shape: raise here, catch just above). Executables and tests +fail fast by right and are clean by kind; a unit whose roster carries +no kind is deliberately silent — a metadata-gated rule degrades to +silence, never to guessing. A locally shadowed `failwith` resolves to a +local declaration and never fires. The exemption is meant for a try +whose handler matches `Stdlib.Failure` alone; handler +exception-constructor identity needs a pattern-side view that has not +landed, so any enclosing try exempts — a recorded false negative in +the safe direction. Cross-function trampolines take one `[@litany.expect]`. No +fix: the replacement error path is a design decision. diff --git a/agents/pages/reference/rules/suspicious-file-exists-race.md b/agents/pages/reference/rules/suspicious-file-exists-race.md new file mode 100644 index 0000000..2500509 --- /dev/null +++ b/agents/pages/reference/rules/suspicious-file-exists-race.md @@ -0,0 +1,50 @@ +# suspicious-file-exists-race + +exists check guarding a filesystem operation on the same path + + + +**restriction · warning · stable · since 1.0 · fix: never · off by default** + +`if Sys.file_exists p then ` is two non-atomic steps: +the world can change between them — a concurrent test run, an `at_exit` +cleanup, a watch loop — so the guard buys nothing (the guarded +operation can still raise) while adding a race window. The principled +form performs the operation and matches its exception; the ops this +rule watches each have a crisp one-errno rewrite (`ENOENT`/`EEXIST`). + +```ocaml +(* bad *) if Sys.file_exists path then Sys.remove path +(* good *) (try Sys.remove path with Sys_error _ -> ()) +``` + +Why restrict this? The race is real but widely tolerated: in +single-process test cleanup it never fires, so a report there is +robustness pedantry, while the same shape in library code (a `finally` +cleanup whose unguarded `Sys.remove` masks the body's result) earns +its keep. Whether the exception-matching discipline is worth demanding +everywhere is house policy, so the rule sits in the `restriction` +tier: off even under `--select all`, cherry-picked by workspaces that +adopt it. + +Fires, in non-preprocessed units, on an `if` whose condition is a +`Sys.file_exists E` probe — bare, under `not`, or as the left conjunct +of `&&` with a `Sys.is_directory` refinement — when either arm applies +`Sys.remove`, `Sys.mkdir`, `Sys.rename`, `Unix.unlink`, `Unix.mkdir`, +or `Unix.rmdir` (by resolved identity) to a path argument whose source +slice equals `E`'s after whitespace normalization, `E` itself being +syntactically pure: an identifier, a constant, or a constructor of +pure parts. Anchored at the condition, one finding per `if`. An +operation under a `try` — or under a `match` with an `exception` case +on its scrutinee — is tolerated: a handled operation is the remedy, +not the defect. Guarded reads (`Sys.readdir`), a computed or impure +path expression (`Filename.concat dir f` refuses the purity test — +identical slices could denote different files), operations on a +different path, operations deferred inside a function or `lazy`, +operations under a nested exists-guard (the inner `if` reports +itself), operations past a `let` that rebinds an identifier of the +probed path (the spelling now names a different file, so slice +equality would lie — the rebinding subtree is skipped whole), platform +probes, and existence checks used as values deliberately do not fire; +each is a recorded false negative in the safe direction. No fix: the +remedy restructures control flow around the operation's exception. diff --git a/agents/pages/reference/rules/suspicious-general-float-equality.md b/agents/pages/reference/rules/suspicious-general-float-equality.md new file mode 100644 index 0000000..087341d --- /dev/null +++ b/agents/pages/reference/rules/suspicious-general-float-equality.md @@ -0,0 +1,30 @@ +# suspicious-general-float-equality + +bit-exact equality on floats + + + +**pedantic · warning · stable · since 1.0 · fix: never · off by default** + +`=` and `<>` on floats ask for bit-exact equality of values that +arithmetic rarely reproduces bit-exactly: `0.1 +. 0.2 <> 0.3`. + +```ocaml +(* bad *) weight = 0.1 +(* good *) Float.abs (weight -. 0.1) < epsilon +``` + +Fires when `=` or `<>` resolves to its `Stdlib` declaration and at +least one operand's type head is the predefined `float`. Comparisons +against exactly representable anchors are excluded: a float literal +denoting zero (`0.`, `-0.0`, `0x0p0`) and the `infinity` and +`neg_infinity` constants. A `nan` constant operand is +invalid-nan-comparison's finding, never this rule's — the two rules +partition float `=`/`<>` exactly. Orderings are meaningful on floats +and out of scope; type abbreviations over `float` are conservatively +clean (no expansion); shadowed operators do not fire. Code that means +bit-exact equality writes `Float.equal x y` — a distinct declaration +this rule never matches — or carries `[@litany.allow +"suspicious-general-float-equality: exact comparison intended"]` where +the operator form must stay. No fix: a margin-of-error rewrite is +domain-specific. diff --git a/agents/pages/reference/rules/suspicious-if-same-branches.md b/agents/pages/reference/rules/suspicious-if-same-branches.md new file mode 100644 index 0000000..32da49a --- /dev/null +++ b/agents/pages/reference/rules/suspicious-if-same-branches.md @@ -0,0 +1,27 @@ +# suspicious-if-same-branches + +if whose two branches are written identically + + + +**suspicious · warning · stable · since 1.0 · fix: never · on by default** + +`if c then A else B` where `A` and `B` are the same bytes decides +nothing: either the condition is unnecessary or — more often — one +branch was meant to differ and a paste was never edited. + +```ocaml +(* bad *) if is_admin u then grant u else grant u +(* good *) if is_admin u then grant u else deny u +``` + +Fires when both branch slices of a non-preprocessed unit succeed and are +byte-identical after whitespace normalization (runs of spaces, tabs, and +newlines collapse to one space), and the condition is not a boolean +literal (suspicious-literal-condition owns those). Equality is the +source text, nothing deeper: branches differing only in a comment differ +in intent and do not fire, and `L.map` vs `List.map` — same resolution, +different spelling — is a deliberate false negative. Identical slices +imply identical effects, so no purity analysis is needed. No fix: +collapsing to one branch would bless the suspected copy-paste bug — the +author must decide which branch was meant to differ. diff --git a/agents/pages/reference/rules/suspicious-ignored-partial-application.md b/agents/pages/reference/rules/suspicious-ignored-partial-application.md new file mode 100644 index 0000000..8f51394 --- /dev/null +++ b/agents/pages/reference/rules/suspicious-ignored-partial-application.md @@ -0,0 +1,32 @@ +# suspicious-ignored-partial-application + +ignore of a value that is still a function + + + +**suspicious · warning · stable · since 1.0 · fix: never · on by default** + +`ignore e` where `e` is still a function discards a closure — a +partial application whose remaining arguments, and therefore whose +effects, never happen. The compiler's warning 5 already covers the +spelled-out half — `ignore (f x)` with arguments missing, and the +`let`/`match`/`if` spines ending in one; what it cannot see is a +function *value* reaching `ignore`: a partially applied closure bound +earlier, an alias, a literal `fun`. + +```ocaml +(* bad *) let flush = save fd in … ignore flush +(* good *) let flush = save fd in … flush data +``` + +Fires when `ignore` resolves to its `Stdlib` declaration with exactly +one unlabeled argument whose type head is an arrow and whose shape +warning 5 does not already flag; the pipeline spellings `e |> ignore` +and `ignore @@ e` reach the rule as the same application. Applications, +method sends, and statement spines stay clean — the compiler owns them — +as do constraint-annotated arguments (`ignore (f : _ -> _)`, warning 5's +documented escape and this rule's accepted discard idiom), shadowed +`ignore`, non-arrows, and abbreviation heads (`type cb = unit -> unit`). +A literal closure fires — the pinned decision. No fix: the remedy is +supplying the missing arguments, or the typed discard +`let (_ : _ -> _) = e` when the discard is deliberate. diff --git a/agents/pages/reference/rules/suspicious-literal-condition.md b/agents/pages/reference/rules/suspicious-literal-condition.md new file mode 100644 index 0000000..7700b3f --- /dev/null +++ b/agents/pages/reference/rules/suspicious-literal-condition.md @@ -0,0 +1,22 @@ +# suspicious-literal-condition + +if over a literal true or false condition + + + +**suspicious · warning · stable · since 1.0 · fix: never · on by default** + +A literal `true`/`false` condition makes one branch dead and the +`if` a lie — almost always a debugging leftover or an unfinished edit. + +```ocaml +(* bad *) if false then log_debug state +(* good *) delete the branch, or name the flag it was meant to test +``` + +Fires on `if` whose condition is the boolean literal itself, by +predefined-constructor identity. Named flags (`let debug = true … if +debug`) deliberately do not fire — there is no constant propagation — +and neither do runtime conditions, `while true` (the idiomatic infinite +loop, structurally not an `if`), or two-case matches on a boolean +(redundant-match-bool's business). No automatic fix. diff --git a/agents/pages/reference/rules/suspicious-lost-backtrace.md b/agents/pages/reference/rules/suspicious-lost-backtrace.md new file mode 100644 index 0000000..cbf7bb2 --- /dev/null +++ b/agents/pages/reference/rules/suspicious-lost-backtrace.md @@ -0,0 +1,32 @@ +# suspicious-lost-backtrace + +work between catching and re-raising can overwrite the backtrace + + + +**suspicious · warning · stable · since 1.0 · fix: never · on by default** + +`raise e` on a handler-bound exception compiles to a backtrace- +preserving reraise — but what it preserves is the *current* per-domain +backtrace buffer, and any raise that happens in between, even one that +is caught, rewrites that buffer. A handler that logs, unlocks, or cleans +up before re-raising can therefore report the wrong backtrace. + +```ocaml +(* bad *) try f () with e -> log_error e; raise e +(* good *) try f () with + | e -> + let bt = Printexc.get_raw_backtrace () in + log_error e; + Printexc.raise_with_backtrace e bt +``` + +Fires on `try` handlers and `match … with exception` arms that bind +their exception to a bare variable without a guard, do at least one +statement of work (a sequence or `let` spine), and end in `raise` of +exactly that variable; the finding anchors at the final reraise. The +bare `try f () with e -> raise e` already preserves the backtrace and +does not fire; neither do guards, `raise_notrace` (explicit discard), +`Printexc.raise_with_backtrace` (the remedy), re-raises of a different +or wrapped exception, or handlers matching a specific exception pattern. +No fix: the rewrite introduces a binding and reorders the handler. diff --git a/agents/pages/reference/rules/suspicious-physical-equality.md b/agents/pages/reference/rules/suspicious-physical-equality.md new file mode 100644 index 0000000..ab52aac --- /dev/null +++ b/agents/pages/reference/rules/suspicious-physical-equality.md @@ -0,0 +1,24 @@ +# suspicious-physical-equality + +physical comparison with a non-immediate operand + + + +**suspicious · warning · stable · since 1.0 · fix: never · on by default** + +`==` and `!=` compare identity, not contents: on boxed values two +structurally equal operands may or may not share one allocation, so the +answer depends on the program's allocation history. + +```ocaml +(* bad *) "a" ^ "b" == "ab" +(* good *) "a" ^ "b" = "ab" +``` + +Fires only when the operator resolves to `Stdlib.(==)` or `Stdlib.(!=)` +and at least one operand's type is proved non-immediate: a function, a +tuple, or a predefined boxed type (`string`, `bytes`, `float`, `array`, +and kin). Operands whose immediacy is unknown — type variables, +abbreviations, user-defined types — deliberately do not fire, and neither +do shadowed operators or partial applications. Physical identity can be +intentional, so there is no automatic fix. diff --git a/agents/pages/reference/rules/suspicious-polymorphic-compare-on-opaque.md b/agents/pages/reference/rules/suspicious-polymorphic-compare-on-opaque.md new file mode 100644 index 0000000..8ae65e9 --- /dev/null +++ b/agents/pages/reference/rules/suspicious-polymorphic-compare-on-opaque.md @@ -0,0 +1,33 @@ +# suspicious-polymorphic-compare-on-opaque + +polymorphic comparison of a Set, Map, or Hashtbl value + + + +**suspicious · warning · stable · since 1.0 · fix: never · on by default** + +`Set.Make` and `Map.Make` build balanced trees whose shape depends on +insertion history, and `Hashtbl.t` is a mutable record of bucket arrays: +structural comparison sees those representations, not the values they +encode. Two equal sets can compare unequal, `<` orders trees +meaninglessly, and `=` on tables compares bucket layout — the functors +export `equal` and `compare` precisely because polymorphic comparison +cannot work. + +```ocaml +(* bad *) if s1 = s2 then … +(* good *) if IntSet.equal s1 s2 then … +``` + +Fires when `=`, `<>`, `<`, `>`, `<=`, `>=`, `compare`, `min`, or `max` +resolves to its `Stdlib` declaration with an operand — or `List.mem`, +`List.assoc`, `List.assoc_opt`, or `List.mem_assoc` with its compared +key — whose type proves an opaque head: `Hashtbl.t`, a `Set.Make` or +`Map.Make` instance reached across a compilation-unit boundary, or a +`list`, `array`, or `option` of one. The proof never guesses: shadowed +operators, the modules' own `equal`/`compare`, abbreviation heads +(`type cache = … Hashtbl.t`), physical equality, and partial or labeled +applications deliberately do not fire. Functor instances declared in the +linted unit itself and tuple components are recorded false negatives. +No fix: the remedy is the module's own +`equal`/`compare` or a key redesign the author must choose. diff --git a/agents/pages/reference/rules/suspicious-print-debugging.md b/agents/pages/reference/rules/suspicious-print-debugging.md new file mode 100644 index 0000000..46ede3b --- /dev/null +++ b/agents/pages/reference/rules/suspicious-print-debugging.md @@ -0,0 +1,41 @@ +# suspicious-print-debugging + +console printing entrypoint referenced in library code + + + +**restriction · warning · stable · since 1.0 · fix: never · off by default** + +Library code that writes to stdout or stderr decides something only +the application may decide: whether, where, and how to print. A stray +`print_endline` in a library is usually a debugging leftover; a +deliberate one is a layering violation that corrupts the hosting +application's own output. + +```ocaml +(* bad *) let load path = print_endline path; parse path +(* good *) let load path = parse path +``` + +Why restrict this? Printing is fine in most programs — the claim here +is a boundary policy about which layer owns the console, and it is +wrong to impose on a CLI project whose libraries print by design. +Progress-reporting and CLI-support libraries print legitimately. The +rule is already kind-gated to libraries, and the gate is the tell that +it is policy, not defect detection — so it sits in the `restriction` +tier: off even under `--select all`, cherry-picked by a workspace that +has adopted the boundary, with +`[@litany.allow "suspicious-print-debugging: user-facing output"]` as +the audit trail for the deliberate printers. + +Fires once per resolved reference to `print_endline`, `print_string`, +`Printf.printf`, `Printf.eprintf`, or `prerr_endline` — aliases +included: `let log = Printf.printf` is a printer — and only in units +whose roster kind is `Library`. Executables and tests print by right, +and a unit whose roster carries no kind (common under adapters whose +rosters say nothing yet) is deliberately silent: a metadata-gated rule +degrades to silence, never to guessing. `Printf.sprintf` and kin build +strings, `Format.printf` is unlisted, and a shadowing +local `print_endline` resolves to a local declaration — none fire. No +fix: the remedy — a logging seam, a formatter parameter, deletion — is +a design decision. diff --git a/agents/pages/reference/rules/suspicious-rec-without-recursion.md b/agents/pages/reference/rules/suspicious-rec-without-recursion.md new file mode 100644 index 0000000..06ff21c --- /dev/null +++ b/agents/pages/reference/rules/suspicious-rec-without-recursion.md @@ -0,0 +1,38 @@ +# suspicious-rec-without-recursion + +let rec group that never recurses + + + +**suspicious · warning · stable · since 1.0 · fix: sometimes · on by default** + +A `let rec` whose bindings never reference the group is wearing a +costume: the reader budgets for recursion that never happens, and the +`rec` silently changes which same-named outer bindings the bodies see. +The compiler's warning 39 makes the same judgment — off in the vanilla +compiler, an error under dune's dev profile, so this rule's yield is +non-dune workspaces and permissive configurations — but cannot repair +it. + +```ocaml +(* bad *) let rec parse s = lex s in parse input +(* good *) let parse s = lex s in parse input +``` + +Fires once per `let rec` group — structure-level items and +expression-level `let … in` alike — none of whose bindings references +any binding of the group, proved by declaration identity: a use of a +group identity anywhere inside a group body blocks the finding however +deeply nested, while a same-spelled inner rebinding is a different +identity and never counts. Uses after the group — in the `in` body or +later in the unit — do not block; they are what the binding is for. +Partially recursive groups (`let rec f x = f x and g y = y`) never +fire: dropping `rec` is not their remedy, splitting the group is. +Class-body groups are a recorded false negative — the group dispatch +does not see them. The fix deletes the `rec` +keyword when the unit is not preprocessed and exactly whitespace, +`let`, whitespace, `rec`, whitespace separates the group start from +its first pattern — an attribute or comment there refuses the fix, +never the finding. The identity proof is what makes the deletion safe: +no body resolves any group name, so removing those names from the +bodies' scope retargets nothing. diff --git a/agents/pages/reference/rules/suspicious-sequence-ignored-value.md b/agents/pages/reference/rules/suspicious-sequence-ignored-value.md new file mode 100644 index 0000000..903b244 --- /dev/null +++ b/agents/pages/reference/rules/suspicious-sequence-ignored-value.md @@ -0,0 +1,29 @@ +# suspicious-sequence-ignored-value + +pure projection discarded where the compiler cannot warn + + + +**suspicious · warning · stable · since 1.0 · fix: never · on by default** + +In `e1; e2` the compiler warns on a non-unit `e1` (warning 10) — +except when `e1`'s type is a type variable, where it must stay silent +because `unit` is a possible instantiation. That hole swallows exactly +the discards most worth hearing about: applications of pure +projections whose entire purpose is the returned value, discarded +inside a function polymorphic in that value. + +```ocaml +(* bad *) let f xs = List.hd xs; List.length xs +(* good *) let f xs = let x = List.hd xs in use x; List.length xs +``` + +Fires on a sequence left-hand side that is a saturated application of +an enumerated pure projection — `List.hd`, `Option.get`, +`Result.get_ok`, `Result.get_error`, `fst`, `snd`, `List.nth`, +`List.assoc`, `List.assq`, `List.find`, `Hashtbl.find` — whose result +type is a bare type variable. Concrete result types are warning 10's +(the compiler already spoke — litany says nothing), `ignore (…)` is +the sanctioned discard, effectful pops (`Queue.pop`, `Stack.pop`) are +deliberate drops outside the set, and rebound or shadowed names never +match. No fix: the remedy is deciding what to do with the value. diff --git a/agents/pages/reference/rules/suspicious-str-formatter.md b/agents/pages/reference/rules/suspicious-str-formatter.md new file mode 100644 index 0000000..1962d6c --- /dev/null +++ b/agents/pages/reference/rules/suspicious-str-formatter.md @@ -0,0 +1,32 @@ +# suspicious-str-formatter + +reference to the process-global Format.str_formatter + + + +**suspicious · warning · stable · since 1.0 · fix: never · on by default** + +`Format.str_formatter` is one process-global buffer formatter. Two +interleaved users corrupt each other's output — in a multi-fiber or +multi-domain program interleaving is the normal case — and partial +output survives in the buffer across exceptions, so the next +`flush_str_formatter` answers with another computation's bytes +prepended. fmt guards its own API against the value by raising on it; +`Format.asprintf` is the total replacement. + +```ocaml +(* bad *) Format.fprintf Format.str_formatter "%a" pp v; + Format.flush_str_formatter () +(* good *) Format.asprintf "%a" pp v +``` + +Fires once per reference resolving to `Stdlib.Format.str_formatter` or +`Stdlib.Format.flush_str_formatter` in a Library-kind unit — spelled +directly, through an alias, or via `open`; a shadowing local +`Format` never fires. Units without kind metadata, and executables +(where a single-threaded scratch buffer can be correct in practice), +stay silent — the library boundary is where the value's process-global +sharing meets unknown callers. No body-shape analysis. The `ifprintf` +sink shape (`Format.ifprintf Format.str_formatter fmt`) is the known +benign case and still fires: suppress it with `[@litany.allow]` where a +sink formatter is deliberate. diff --git a/agents/pages/reference/rules/suspicious-swallowed-cancellation.md b/agents/pages/reference/rules/suspicious-swallowed-cancellation.md new file mode 100644 index 0000000..ede5cdc --- /dev/null +++ b/agents/pages/reference/rules/suspicious-swallowed-cancellation.md @@ -0,0 +1,42 @@ +# suspicious-swallowed-cancellation + +total handler around eio code converts cancellation into a value + + + +**suspicious · warning · stable · since 1.0 · fix: sometimes · on by default** + +Eio delivers fiber cancellation as the `Eio.Cancel.Cancelled` +exception out of any suspending operation, and a handler must let it +through, or the fiber keeps running with a corrupted notion of what +happened: cancellations get recorded as data errors, cleanup runs +twice, supervisors log garbage. + +```ocaml +(* bad *) try Ok (Eio.Path.read_dir dir) with exn -> Error exn +(* good *) try Ok (Eio.Path.read_dir dir) with + | Eio.Cancel.Cancelled _ as cancelled -> raise cancelled + | exn -> Error exn +``` + +Fires on a `try` handler or the `exception` cases of a `match` where a +guard-less total arm — a bare variable or wildcard — converts to a +value (a wrap-raise like `raise (Wrapped e)` still converts +cancellation and counts; a plain re-raise of the binder, or +`Printexc.raise_with_backtrace`, does not), no sibling arm passes the +exception through (an alias arm re-raising its own binder, +`| Eio.Cancel.Cancelled _ as e -> raise e` — the discipline real Eio +code practices), and the guarded region applies at least one function +declared in an `Eio`-family compilation unit (`Eio`, `Eio_unix`, +`Eio_main`, `Eio_posix`) — total handlers around pure code stay silent. +The pass-through condition is meant to be `Eio.Cancel.Cancelled` +constructor identity by UID; pattern-side exception-constructor +identity has not landed, so the alias-re-raise shape stands in — a bare +`Eio.Cancel.Cancelled _` sibling arm does not yet silence (a recorded +gap), and a sibling alias arm re-raising a non-Cancelled exception +silences (recorded false negative). Handlers inside +`Eio.Cancel.protect` and deliberate supervisor recorders are +`[@litany.allow]` cases. The fix inserts the guard arm on its own line +before the total one, and only when that arm sits on its own +`| `-prefixed line; it changes behavior — that is its point — so it +applies only under `--fix --unsafe`. diff --git a/agents/pages/reference/rules/suspicious-transposable-arguments.md b/agents/pages/reference/rules/suspicious-transposable-arguments.md new file mode 100644 index 0000000..8eee037 --- /dev/null +++ b/agents/pages/reference/rules/suspicious-transposable-arguments.md @@ -0,0 +1,38 @@ +# suspicious-transposable-arguments + +three adjacent same-typed unlabeled parameters + + + +**pedantic · warning · stable · since 1.0 · fix: never · off by default** + +Two adjacent same-typed unlabeled parameters include the symmetric +operations — `equal`, `compare`, `append`, `levenshtein` — where labels +would be noise. Three or more have no symmetric reading: every call +site is a silent transposition bug waiting, type-correct and wrong. + +```ocaml +(* bad *) val invalid_arg' : string -> string -> string -> 'a +(* good *) val invalid_arg' : m:string -> fn:string -> string -> 'a +``` + +Fires once per exported structure-level value binding of a +Library-kind unit whose arrow spine contains three or more consecutive +unlabeled parameters of equal type, anchored at the binding's name in +the implementation. Units without kind metadata degrade to silence; +labels break adjacency, which is exactly the remedy the rule teaches. +No fix: labeling is an API change. + +Narrowings, each in the false-negative-safe direction: the spine is +read from the implementation binding's type rather than the interface +val (there is no signature dispatch kind yet, and findings anchor only +in the editable source) — the interface type is always at least as +specific, so an implementation hit implies an interface hit, never the +reverse; type equality is syntactic (`Path.same` heads with equal +arguments, or the same type variable) without abbreviation expansion, +so `t -> string -> t` with `type t = string` stays silent; and for +mli-backed units the export gate joins the interface's value names at +the unit's root (module-level linking is nominal by name), so values +of nested modules are not reported. Variadic-ish combinator +signatures where order is conventional are the recorded false-positive +risk and what Pedantic/off absorbs. diff --git a/agents/pages/reference/rules/suspicious-unused-module-binding.md b/agents/pages/reference/rules/suspicious-unused-module-binding.md new file mode 100644 index 0000000..dbb9e7a --- /dev/null +++ b/agents/pages/reference/rules/suspicious-unused-module-binding.md @@ -0,0 +1,35 @@ +# suspicious-unused-module-binding + +module binding the unit never uses and never exports + + + +**suspicious · warning · stable · since 1.0 · fix: never · on by default** + +A named module binding that the unit never references, and that +nothing outside the unit can reference, is dead text: a local +`let module M = … in e` whose body never mentions `M`, or a toplevel +`module M = …` in a unit whose interface does not export `M`. The +compiler's warning 60 makes exactly this judgment soundly — and ships +disabled in every mainstream default, so in practice no one has ever +seen it. This rule makes the same judgment from the artifact, +config-independently: uses are counted by resolved identity over every +path the typedtree stores, and export is read from the unit's own +compiled interface. + +```ocaml +(* bad *) let module Tbl = Hashtbl.Make (Int) in body (* Tbl unseen *) +(* good *) module _ = struct let () = register () end (* effect-only *) +``` + +Fires at the binder's name when it is never used: for a `let module` +unit-wide emptiness is exactly body emptiness; for a toplevel binding +the interface must exist and hide the name — a unit without an `.mli` +exports everything through its inferred signature and stays silent, +exactly where an enabled warning 60 is also silent. Module bindings +nested inside sub-structures need per-path signature reasoning and are +recorded false negatives; `Pstr_recmodule` groups are not dispatched. +The anonymous `module _ = …` is the sanctioned effect-only spelling +and refuses by construction. A stale `.cmti` can misreport exports at this rule's gate. No fix: a +module body can perform effects at initialization, so deletion is +never mechanical. diff --git a/agents/pages/reference/rules/suspicious-variant-arity-tuple.md b/agents/pages/reference/rules/suspicious-variant-arity-tuple.md new file mode 100644 index 0000000..3d9b22c --- /dev/null +++ b/agents/pages/reference/rules/suspicious-variant-arity-tuple.md @@ -0,0 +1,33 @@ +# suspicious-variant-arity-tuple + +constructor whose one argument is a parenthesized tuple + + + +**suspicious · warning · stable · since 1.0 · fix: never · on by default** + +`C of int * int` declares a two-field constructor — one block, +fields inline. `C of (int * int)` declares a one-field constructor +whose field is a boxed tuple — an extra allocation and an extra +indirection on every construction and every match, invisible at most +use sites because the pattern `C (x, y)` happens to typecheck against +both. + +```ocaml +(* bad *) type t = Pair of (int * int) +(* good *) type t = Pair of int * int +(* good *) type point = int * int + type t = Pair of point +``` + +Fires once per constructor whose argument list is exactly one +parenthesized tuple type, at that type — GADT constructors included: +`B : (int * int) -> t` draws the same representation line as +`D of (int * int)`. Declarations under `[@@unboxed]` are exempt (the +attribute requires the single-argument form, so the boxing complaint +is void), as is a tuple among several fields (`C of (int * int) * +string` has no flat spelling — the parentheses are load-bearing) and a +named tuple type (`C of point` — the sanctioned spelling when the +tuple-as-one-value is the choice). No fix: flattening changes the +runtime representation and breaks every `C p`-as-value use site; the +remedy is a decision, stated in the message. diff --git a/agents/pages/reference/rules/suspicious-wall-clock-elapsed.md b/agents/pages/reference/rules/suspicious-wall-clock-elapsed.md new file mode 100644 index 0000000..c00b821 --- /dev/null +++ b/agents/pages/reference/rules/suspicious-wall-clock-elapsed.md @@ -0,0 +1,30 @@ +# suspicious-wall-clock-elapsed + +duration computed from wall-clock reads + + + +**suspicious · warning · stable · since 1.0 · fix: never · on by default** + +`Unix.gettimeofday` and `Unix.time` read the wall clock: NTP steps, +manual clock changes, and suspend/resume make it jump both ways. +Arithmetic that turns wall-clock reads into a duration — `now +. +timeout` deadlines, `now -. started` elapsed — silently produces +negative or wildly inflated durations under a clock step: watchdogs +kill healthy children, retry loops spin or hang. A monotonic counter +(`Mtime_clock`, the project's own clock module) is the remedy, and +choosing one is a dependency decision — no fix. + +```ocaml +(* bad *) let deadline = Unix.gettimeofday () +. timeout in … +(* good *) let deadline = Mtime.add_span (Mtime_clock.now ()) span in … +``` + +Fires on float `+.`/`-.` (and `Float.add`/`Float.sub`) applications +where either argument is directly a `Unix.gettimeofday ()` or +`Unix.time ()` call, anchored at the arithmetic expression. Storing the +function as a clock seam, passing a timestamp as data, scaling with +`*.`, monotonic counter subtraction, and `Sys.time` (process CPU time, +monotone) deliberately do not fire. A wall-clock read that flows +through a `let` binding before the arithmetic is a recorded false +negative. diff --git a/agents/pages/reference/rules/trailing-whitespace.md b/agents/pages/reference/rules/trailing-whitespace.md new file mode 100644 index 0000000..1e163e5 --- /dev/null +++ b/agents/pages/reference/rules/trailing-whitespace.md @@ -0,0 +1,22 @@ +# trailing-whitespace + +trailing spaces or tabs at end of line + + + +**style · warning · stable · since 1.0 · fix: always · off by default** + +Trailing whitespace is invisible, churns diffs, and survives only +until the next editor with different settings touches the line. + +```ocaml +(* bad *) let x = 1␣␣ +(* good *) let x = 1 +``` + +Reports each maximal run of ASCII space or tab immediately before LF, +CRLF, or end of file, outside a string literal, where it is the string's +content. A lone CR is ordinary source content, not a line +ending, so whitespace before one deliberately does not fire. Every finding +carries the deletion fix (`delete the trailing whitespace`), removing +exactly the reported run. diff --git a/agents/pages/reference/rules/unsafe-obj-magic.md b/agents/pages/reference/rules/unsafe-obj-magic.md new file mode 100644 index 0000000..f484fde --- /dev/null +++ b/agents/pages/reference/rules/unsafe-obj-magic.md @@ -0,0 +1,32 @@ +# unsafe-obj-magic + +use of Obj.magic + + + +**restriction · warning · stable · since 1.0 · fix: never · off by default** + +`Obj.magic` bypasses the type system entirely: the checker accepts +any use at any type, and a mistake becomes memory corruption at run time, +not a compile error. + +```ocaml +(* bad *) let id : 'a -> 'a = Obj.magic +(* good *) a typed interface, a GADT, or a documented unsafe module + boundary reviewed on its own +``` + +Why restrict this? Every real use is a deliberate kernel, specialist code +where each use was justified on its own terms. +"No `Obj.magic`" is a house ban a workspace +adopts, not a universal improvement the catalog can claim. So the rule is +`restriction`-tier policy: off even under `--select all`, cherry-picked by +exact name, with the reviewed boundary carrying its `[@litany.allow]` +justification. + +Fires at every identifier expression whose resolved identity is +`Stdlib.Obj.magic` — direct calls, opened uses, and first-class references +alike, at the identifier itself. Shadowed same-spelling definitions, later +uses of a value bound to `Obj.magic` (the binding's right-hand side already +fired), other `Obj` members, and unresolved identities deliberately do not +fire. There is no automatic fix. diff --git a/agents/pages/reference/rules/unsafe-partial-stdlib.md b/agents/pages/reference/rules/unsafe-partial-stdlib.md new file mode 100644 index 0000000..e8ed0f2 --- /dev/null +++ b/agents/pages/reference/rules/unsafe-partial-stdlib.md @@ -0,0 +1,37 @@ +# unsafe-partial-stdlib + +reference to a partial stdlib eliminator + + + +**restriction · warning · stable · since 1.0 · fix: never · off by default** + +The stdlib's partial eliminators raise on the case their type admits +but their contract excludes: `List.hd` and `List.tl` raise `Failure` on +`[]`, `List.nth` raises on short lists and negative indices, `Option.get` +raises `Invalid_argument` on `None`, and `Result.get_ok`/`get_error` +raise on the other constructor. Each has a total spelling — a match, +`List.nth_opt`, `Option.value`, or `Result.get_ok'` with its carried +message. + +```ocaml +(* bad *) Option.get (find_user id) +(* good *) match find_user id with Some u -> … | None -> … +``` + +Why restrict this? Partiality is a legitimate tool — a raise in a +failing test is the test doing its job, and field review measured +exactly that population (261 findings on one real workspace, 246 of +them in test code, the sampled remainder contract-true). A partial +eliminator is a finding only where the house has banned the idiom in +favor of total spellings, so the rule is house policy in the +`restriction` tier — off even under `--select all`, cherry-picked by +exact name, with `[@litany.expect]` as the per-call justification +trail. + +Fires once per reference that resolves to a listed `Stdlib` declaration +— saturated calls, partial applications, and first-class uses alike, and +through aliases and `open`. Shadowed modules, values merely named `hd`, +the `_opt`/`value` siblings, and the `Not_found` retrieval protocol +(`List.find`, `Hashtbl.find`, `Sys.getenv`, …) deliberately do not fire. +No fix: each remedy restructures control flow. diff --git a/agents/pages/reference/rules/untyped-ignore.md b/agents/pages/reference/rules/untyped-ignore.md new file mode 100644 index 0000000..a6cb16b --- /dev/null +++ b/agents/pages/reference/rules/untyped-ignore.md @@ -0,0 +1,30 @@ +# untyped-ignore + +ignore discards a value without naming its type + + + +**restriction · warning · nursery · since 1.1 · fix: never · off by default** + +`ignore` throws a value away; naming its type keeps the throw +honest. A function later given one more argument is then a partial +application discarded in silence, and a promise or a `result` the same: +a type named at the discard is a compile error the day the value +changes. `untyped-wildcard-binding` is the same rule for `let _ =`. + +```ocaml +(* bad *) ignore (Queue.pop q) +(* good *) ignore (Queue.pop q : int) +``` + +Why restrict this? Discarding is legitimate OCaml, and the compiler's +warnings own the cases nobody meant; naming the type of every discard +is a discipline a house adopts. + +Fires at `ignore e` -- the identity `Stdlib.ignore`, applied to one +argument -- whose argument carries no type constraint, or one that names +no type (`ignore (e : _)`, `ignore (e : 'a)`). `ignore (e : t)`, `ignore +(e :> t)`, `ignore` passed as a value, and a shadowing `ignore` deliberately +do not fire. Recorded false negative, in the safe direction: a value +bound to `ignore` and applied later (`let drop = ignore in drop x`). No +fix: only the author knows the type meant. diff --git a/agents/pages/reference/rules/untyped-wildcard-binding.md b/agents/pages/reference/rules/untyped-wildcard-binding.md new file mode 100644 index 0000000..a967e02 --- /dev/null +++ b/agents/pages/reference/rules/untyped-wildcard-binding.md @@ -0,0 +1,26 @@ +# untyped-wildcard-binding + +let _ discards a value without naming its type + + + +**restriction · warning · nursery · since 1.1 · fix: never · off by default** + +`let _ = e` throws a value away; naming its type keeps the throw +honest, so the day `e` returns a partial application, a promise or a +`result` the discard no longer compiles. `untyped-ignore` is the same +rule for `ignore`. + +```ocaml +(* bad *) let _ = write path text in ... +(* good *) let (_ : (unit, error) result) = write path text in ... +``` + +Why restrict this? Discarding is legitimate OCaml; naming the type of +every discard is a discipline a house adopts. + +Fires at a wildcard binding, at any depth, whose pattern carries no +type constraint, or one that names no type (`let (_ : _) = e`, `let (_ : +'a) = e`). `let (_ : t) = e`, a named binding (`let _x = e` +included), `let () = e`, and a wildcard nested in a pattern deliberately +do not fire. No fix: only the author knows the type meant. diff --git a/agents/pages/reference/rules/unused-export.md b/agents/pages/reference/rules/unused-export.md new file mode 100644 index 0000000..48040eb --- /dev/null +++ b/agents/pages/reference/rules/unused-export.md @@ -0,0 +1,36 @@ +# unused-export + +exported value never used by another unit + + + +**suspicious · warning · nursery · since 1.0 · fix: never · off by default** + +An exported value no other unit of the workspace references is +surface a maintainer must read, document, and keep compiling for +nobody. The finding anchors at the declaration — the `.mli` line when +the unit has one — and the claim is exact and non-transitive: the +value is used by no *other* unit, counting nothing about whether its +users are themselves alive (that judgment is `dead-code`'s). + +```ocaml +(* bad *) val helper : int -> int (* no other unit mentions it *) +(* good *) delete the export (and the binding, if nothing local uses it) +``` + +Roots are never candidates: exports of public (or unknown-visibility) +libraries — external consumers exist outside every universe litany can +enumerate — and declarations annotated `[@litany.root "reason"]`. +Executables and tests have no interface surface, so their values are +never candidates (`dead-code` covers them). Value declarations only: +types and modules have no always-on cross-unit use signal, so 1.0 +stays silent on them rather than guess. +A unit-level reference (a use the compiler recorded against the unit +without pinning a declaration) conservatively shields every export of +the referenced unit. Cross-module honesty: the rule runs only when +every roster unit joined — one fact-skip withholds it, and the summary +names the blockers. Workspaces built without occurrence recording +under-populate unit-level references; module-alias-only and +functor-argument uses can then be missed in the shielding direction — +a recorded nursery caveat. No fix: deleting an +export is an interface decision. diff --git a/agents/pages/reference/rules/used-underscore-binding.md b/agents/pages/reference/rules/used-underscore-binding.md new file mode 100644 index 0000000..613d91b --- /dev/null +++ b/agents/pages/reference/rules/used-underscore-binding.md @@ -0,0 +1,37 @@ +# used-underscore-binding + +underscore-prefixed binding is used + + + +**suspicious · warning · nursery · since 1.0 · fix: never · off by default** + +A leading underscore declares "this binding is intentionally unused" +and silences the compiler's unused warnings. Using the binding anyway +makes the name lie — and keeps the compiler from noticing when the +binding later becomes genuinely unused. + +```ocaml +(* bad *) let _count = tally xs in report _count +(* good *) let count = tally xs in report count +``` + +Fires once per binding, at the declaration, when a variable or alias +pattern binds a name beginning with exactly one underscore and the unit +uses that declaration anywhere — bare, or qualified through a module +path. The wildcard `_` binds nothing, names beginning with two +underscores follow a different convention, and unused underscore +bindings are the convention working as intended. A use through a +signature ascription carries the ascription's minted identity, not the +declaration's, and stays clean. + +Tool-minted names stay clean even when used: `_1` and kin (an +underscore followed by +digits only — menhir's semantic values) and `…__NNN_` shapes (a name +ending in a double underscore, digits, and a final underscore — +jane-street ppx internals, `_of_a__001_`). Both are bound-and-used by +generated code as a calling convention, not a lie the author told; in +field review they were 99.9% of the rule's volume. Committed generated +sources carry them verbatim, so the name gate applies everywhere; the +generated-unit gate rides separately. Renaming is a +refactor, not a mechanical edit, so there is no fix. diff --git a/agents/pages/reference/rules/wildcard-over-owned-variant.md b/agents/pages/reference/rules/wildcard-over-owned-variant.md new file mode 100644 index 0000000..c7900be --- /dev/null +++ b/agents/pages/reference/rules/wildcard-over-owned-variant.md @@ -0,0 +1,39 @@ +# wildcard-over-owned-variant + +a wildcard arm in a match over a variant the code owns + + + +**restriction · warning · nursery · since 1.1 · fix: never · off by default** + +A match over a variant the code owns names every case, so a +constructor added later is a compile error at every match that should +handle it -- warning 8 asks for it -- where a `_` arm takes it silently +into whatever the arm does. + +```ocaml +(* bad *) match s with Open -> "open" | _ -> "closed" +(* good *) match s with Open -> "open" | Done | Dropped -> "closed" +``` + +Why restrict this? A match over another library's variant ends in a +catch-all, since a variant grows in a minor release, so a wildcard is +not a defect in itself; which variants a house owns is its own to say. + +```lisp +(rule wildcard-over-owned-variant + (owned app_core app_http)) +``` + +Fires at a guard-less `_` value arm of a `match` whose other arms name a +constructor of a variant declared in the same compilation unit, in +another module of the same wrapped library, or in a library the +`(owned ...)` option names. A variant of any other library, +the predefined ones (`option`, `list`, `bool`), an extensible variant, +which has no last case to name, a guarded wildcard, a wildcard nested in +a pattern (`Some _`), an `exception _` arm, and a match whose arms name +no constructor deliberately do not fire. A module alias names the module +it aliases: `module E = Either` owns nothing. Recorded +false negatives, in the safe direction: `function` matches, and a +library built unwrapped. No fix: only the author knows what each case +should do. diff --git a/docs/astro.config.mjs b/docs/astro.config.mjs index a842624..f550fda 100644 --- a/docs/astro.config.mjs +++ b/docs/astro.config.mjs @@ -2,6 +2,7 @@ import { fileURLToPath } from "node:url"; import { defineConfig } from "astro/config"; import starlight from "@astrojs/starlight"; import links from "starlight-links-validator"; +import agents from "starlight-hypha-agents"; import hypha from "starlight-theme-hypha"; // litany's documentation site, published to GitHub Pages by @@ -44,6 +45,10 @@ export default defineConfig({ tabs: { "Start here": "rocket", Guides: "book-open", Reference: "library" }, links: [{ label: "Hypha Stack", href: "https://hyphatech.io/stack", icon: "layers" }], }), + // Each page as Markdown and llms.txt, written into agents/ + // by the build, for the hypha-litany package to install; the docs + // workflow holds it to the pages. + agents({ dir: "../agents" }), // The reference is odoc's, in public/, which the validator cannot see. links({ exclude: ["**/reference/litany/**"] }), ], diff --git a/docs/bun.lock b/docs/bun.lock index fc6d34e..4ac2feb 100644 --- a/docs/bun.lock +++ b/docs/bun.lock @@ -7,8 +7,9 @@ "devDependencies": { "@astrojs/starlight": "~0.42.6", "astro": "^7.3.3", + "starlight-hypha-agents": "github:hyphatech/starlight-hypha-agents#v0.2.0", "starlight-links-validator": "^0.27.0", - "starlight-theme-hypha": "github:hyphatech/starlight-theme-hypha#v0.6.3", + "starlight-theme-hypha": "github:hyphatech/starlight-theme-hypha#v0.8.0", }, }, }, @@ -295,6 +296,10 @@ "@ungap/structured-clone": ["@ungap/structured-clone@1.4.0", "", {}, "sha512-1mEZtMKPM09vDmQt5y7YvmN2+DFTP7Tg0EWXdic8/C6VRnpb33e4ghisCIE3WZjsE2N8mf+QV1Zqh7ZFYLWInQ=="], + "acorn": ["acorn@8.19.0", "", { "bin": { "acorn": "bin/acorn" } }, "sha512-oJlA3XiRm7Cyk6qFD2Jn8ak9B7jSy0qy00ADO3+8dpT0LSjFihQYv4C02LFCSYJV3Q37xYwwRy5m+IpIiUzqWw=="], + + "acorn-jsx": ["acorn-jsx@5.3.2", "", { "peerDependencies": { "acorn": "^6.0.0 || ^7.0.0 || ^8.0.0" } }, "sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ=="], + "am-i-vibing": ["am-i-vibing@0.5.0", "", { "dependencies": { "process-ancestry": "^0.1.0" }, "bin": { "am-i-vibing": "dist/cli.mjs" } }, "sha512-KLcsDhqf1XRrJmJr+9I/C0EX2K+sGrAGZFgkmd84c8TJO9zJBu+/kFInjazu1KfJWFhWDKdRWkpBzEs7s35DVA=="], "ansi-escapes": ["ansi-escapes@7.3.0", "", { "dependencies": { "environment": "^1.0.0" } }, "sha512-BvU8nYgGQBxcmMuEeUEmNTvrMVjJNSH7RgW24vXexN4Ven6qCvy4TntnvlnwnMLTVlcRQQdbRY8NKnaIoeWDNg=="], @@ -399,6 +404,10 @@ "es-module-lexer": ["es-module-lexer@3.0.4", "", {}, "sha512-BldNY5mwkVu+cQ5Ymn3e6hB9Sx8XHx4ZevWbiUyZbfKxJxYO27Hf0wfzkxIaD5CAJMaGl3YspKELj0ff/7nCMA=="], + "estree-util-is-identifier-name": ["estree-util-is-identifier-name@3.0.0", "", {}, "sha512-hFtqIDZTIUZ9BXLb8y4pYGyk6+wekIivNVTcmvk8NoOh+VeRn5y6cEHzbURrWbfp1fIqdVipilzj+lfaadNZmg=="], + + "estree-util-visit": ["estree-util-visit@2.0.0", "", { "dependencies": { "@types/estree-jsx": "^1.0.0", "@types/unist": "^3.0.0" } }, "sha512-m5KgiH85xAhhW8Wta0vShLcUvOsh3LLPI2YVwcbio1l7E09NTLL1EyMZFM1OyWowoH0skScNbhOPl4kcBgzTww=="], + "eventemitter3": ["eventemitter3@5.0.4", "", {}, "sha512-mlsTRyGaPBjPedk6Bvw+aqbsXDtoAyAzm5MO7JgU+yVRyMQ5O8bD4Kcci7BS85f93veegeCPkL8R4GLClnjLFw=="], "expressive-code": ["expressive-code@0.44.3", "", { "dependencies": { "@expressive-code/core": "^0.44.3", "@expressive-code/plugin-frames": "^0.44.3", "@expressive-code/plugin-shiki": "^0.44.3", "@expressive-code/plugin-text-markers": "^0.44.3" } }, "sha512-7RGslhJTNt01pdn5I3QmVh5C8ZIiSm0A+ORQ9j9r39oOgJVKjn/7dXl9rMT/SqmFLE6pJkTYI7UjW0BxJnW7OQ=="], @@ -535,8 +544,14 @@ "mdast-util-from-markdown": ["mdast-util-from-markdown@2.1.0", "", { "dependencies": { "@types/mdast": "^4.0.0", "@types/unist": "^3.0.0", "decode-named-character-reference": "^1.0.0", "devlop": "^1.0.0", "mdast-util-to-string": "^4.0.0", "micromark": "^4.0.0", "micromark-util-decode-numeric-character-reference": "^2.0.0", "micromark-util-decode-string": "^2.0.0", "micromark-util-normalize-identifier": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0", "unist-util-stringify-position": "^4.0.0" } }, "sha512-KRLgmPaP2H1ul2bpoJkOS+9pAcDAAj9Nu1mqLnh8NLeJG5tlvj42TH80PIGBpROWlRXLk0lDrWNuZCFy/tsB4A=="], + "mdast-util-mdx": ["mdast-util-mdx@3.0.0", "", { "dependencies": { "mdast-util-from-markdown": "^2.0.0", "mdast-util-mdx-expression": "^2.0.0", "mdast-util-mdx-jsx": "^3.0.0", "mdast-util-mdxjs-esm": "^2.0.0", "mdast-util-to-markdown": "^2.0.0" } }, "sha512-JfbYLAW7XnYTTbUsmpu0kdBUVe+yKVJZBItEjwyYJiDJuZ9w4eeaqks4HQO+R7objWgS2ymV60GYpI14Ug554w=="], + + "mdast-util-mdx-expression": ["mdast-util-mdx-expression@2.0.1", "", { "dependencies": { "@types/estree-jsx": "^1.0.0", "@types/hast": "^3.0.0", "@types/mdast": "^4.0.0", "devlop": "^1.0.0", "mdast-util-from-markdown": "^2.0.0", "mdast-util-to-markdown": "^2.0.0" } }, "sha512-J6f+9hUp+ldTZqKRSg7Vw5V6MqjATc+3E4gf3CFNcuZNWD8XdyI6zQ8GqH7f8169MM6P7hMBRDVGnn7oHB9kXQ=="], + "mdast-util-mdx-jsx": ["mdast-util-mdx-jsx@3.2.0", "", { "dependencies": { "@types/estree-jsx": "^1.0.0", "@types/hast": "^3.0.0", "@types/mdast": "^4.0.0", "@types/unist": "^3.0.0", "ccount": "^2.0.0", "devlop": "^1.1.0", "mdast-util-from-markdown": "^2.0.0", "mdast-util-to-markdown": "^2.0.0", "parse-entities": "^4.0.0", "stringify-entities": "^4.0.0", "unist-util-stringify-position": "^4.0.0", "vfile-message": "^4.0.0" } }, "sha512-lj/z8v0r6ZtsN/cGNNtemmmfoLAFZnjMbNyLzBafjzikOM+glrjNHPlf6lQDOTccj9n5b0PPihEBbhneMyGs1Q=="], + "mdast-util-mdxjs-esm": ["mdast-util-mdxjs-esm@2.0.1", "", { "dependencies": { "@types/estree-jsx": "^1.0.0", "@types/hast": "^3.0.0", "@types/mdast": "^4.0.0", "devlop": "^1.0.0", "mdast-util-from-markdown": "^2.0.0", "mdast-util-to-markdown": "^2.0.0" } }, "sha512-EcmOpxsZ96CvlP03NghtH1EsLtr0n9Tm4lPUJUBccV9RwUOneqSycg19n5HGzCf+10LozMRSObtVr3ee1WoHtg=="], + "mdast-util-phrasing": ["mdast-util-phrasing@4.1.0", "", { "dependencies": { "@types/mdast": "^4.0.0", "unist-util-is": "^6.0.0" } }, "sha512-TqICwyvJJpBwvGAMZjj4J2n0X8QWp21b9l0o7eXyVJ25YNWYbJDVIyD1bZXE6WtV6RmKJVYmQAKWa0zWOABz2w=="], "mdast-util-to-hast": ["mdast-util-to-hast@13.2.1", "", { "dependencies": { "@types/hast": "^3.0.0", "@types/mdast": "^4.0.0", "@ungap/structured-clone": "^1.0.0", "devlop": "^1.0.0", "micromark-util-sanitize-uri": "^2.0.0", "trim-lines": "^3.0.0", "unist-util-position": "^5.0.0", "unist-util-visit": "^5.0.0", "vfile": "^6.0.0" } }, "sha512-cctsq2wp5vTsLIcaymblUriiTcZd0CwWtCbLvrOzYCDZoWyMNV8sZ7krj09FSnsiJi3WVsHLM4k6Dq/yaPyCXA=="], @@ -553,10 +568,22 @@ "micromark-extension-directive": ["micromark-extension-directive@4.0.0", "", { "dependencies": { "devlop": "^1.0.0", "micromark-factory-space": "^2.0.0", "micromark-factory-whitespace": "^2.0.0", "micromark-util-character": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0", "parse-entities": "^4.0.0" } }, "sha512-/C2nqVmXXmiseSSuCdItCMho7ybwwop6RrrRPk0KbOHW21JKoCldC+8rFOaundDoRBUWBnJJcxeA/Kvi34WQXg=="], + "micromark-extension-mdx-expression": ["micromark-extension-mdx-expression@3.0.1", "", { "dependencies": { "@types/estree": "^1.0.0", "devlop": "^1.0.0", "micromark-factory-mdx-expression": "^2.0.0", "micromark-factory-space": "^2.0.0", "micromark-util-character": "^2.0.0", "micromark-util-events-to-acorn": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-dD/ADLJ1AeMvSAKBwO22zG22N4ybhe7kFIZ3LsDI0GlsNr2A3KYxb0LdC1u5rj4Nw+CHKY0RVdnHX8vj8ejm4Q=="], + + "micromark-extension-mdx-jsx": ["micromark-extension-mdx-jsx@3.0.2", "", { "dependencies": { "@types/estree": "^1.0.0", "devlop": "^1.0.0", "estree-util-is-identifier-name": "^3.0.0", "micromark-factory-mdx-expression": "^2.0.0", "micromark-factory-space": "^2.0.0", "micromark-util-character": "^2.0.0", "micromark-util-events-to-acorn": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0", "vfile-message": "^4.0.0" } }, "sha512-e5+q1DjMh62LZAJOnDraSSbDMvGJ8x3cbjygy2qFEi7HCeUT4BDKCvMozPozcD6WmOt6sVvYDNBKhFSz3kjOVQ=="], + + "micromark-extension-mdx-md": ["micromark-extension-mdx-md@2.0.0", "", { "dependencies": { "micromark-util-types": "^2.0.0" } }, "sha512-EpAiszsB3blw4Rpba7xTOUptcFeBFi+6PY8VnJ2hhimH+vCQDirWgsMpz7w1XcZE7LVrSAUGb9VJpG9ghlYvYQ=="], + + "micromark-extension-mdxjs": ["micromark-extension-mdxjs@3.0.0", "", { "dependencies": { "acorn": "^8.0.0", "acorn-jsx": "^5.0.0", "micromark-extension-mdx-expression": "^3.0.0", "micromark-extension-mdx-jsx": "^3.0.0", "micromark-extension-mdx-md": "^2.0.0", "micromark-extension-mdxjs-esm": "^3.0.0", "micromark-util-combine-extensions": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-A873fJfhnJ2siZyUrJ31l34Uqwy4xIFmvPY1oj+Ean5PHcPBYzEsvqvWGaWcfEIr11O5Dlw3p2y0tZWpKHDejQ=="], + + "micromark-extension-mdxjs-esm": ["micromark-extension-mdxjs-esm@3.0.0", "", { "dependencies": { "@types/estree": "^1.0.0", "devlop": "^1.0.0", "micromark-core-commonmark": "^2.0.0", "micromark-util-character": "^2.0.0", "micromark-util-events-to-acorn": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0", "unist-util-position-from-estree": "^2.0.0", "vfile-message": "^4.0.0" } }, "sha512-DJFl4ZqkErRpq/dAPyeWp15tGrcrrJho1hKK5uBS70BCtfrIFg81sqcTVu3Ta+KD1Tk5vAtBNElWxtAa+m8K9A=="], + "micromark-factory-destination": ["micromark-factory-destination@2.0.1", "", { "dependencies": { "micromark-util-character": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-Xe6rDdJlkmbFRExpTOmRj9N3MaWmbAgdpSrBQvCFqhezUn4AHqJHbaEnfbVYYiexVSs//tqOdY/DxhjdCiJnIA=="], "micromark-factory-label": ["micromark-factory-label@2.0.1", "", { "dependencies": { "devlop": "^1.0.0", "micromark-util-character": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-VFMekyQExqIW7xIChcXn4ok29YE3rnuyveW3wZQWWqF4Nv9Wk5rgJ99KzPvHjkmPXF93FXIbBp6YdW3t71/7Vg=="], + "micromark-factory-mdx-expression": ["micromark-factory-mdx-expression@2.0.3", "", { "dependencies": { "@types/estree": "^1.0.0", "devlop": "^1.0.0", "micromark-factory-space": "^2.0.0", "micromark-util-character": "^2.0.0", "micromark-util-events-to-acorn": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0", "unist-util-position-from-estree": "^2.0.0", "vfile-message": "^4.0.0" } }, "sha512-kQnEtA3vzucU2BkrIa8/VaSAsP+EJ3CKOvhMuJgOEGg9KDC6OAY6nSnNDVRiVNRqj7Y4SlSzcStaH/5jge8JdQ=="], + "micromark-factory-space": ["micromark-factory-space@2.1.0", "", { "dependencies": { "micromark-util-character": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-fS8hnLIjnjvdQIj39Geug8wWsR0HrYZ43KShKxNfwT7t2LOHo/LbWZEzEaSOjwtjdCsjoE6syHhonEzW0zv0+Q=="], "micromark-factory-title": ["micromark-factory-title@2.0.1", "", { "dependencies": { "micromark-factory-space": "^2.0.0", "micromark-util-character": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-5bZ+3CjhAd9eChYTHsjy6TGxpOFSKgKKJPJxr293jTbfry2KDoWkhBb6TcPVB4NmzaPhMs1Frm9AZH7OD4Cjzw=="], @@ -579,6 +606,8 @@ "micromark-util-encode": ["micromark-util-encode@2.0.1", "", {}, "sha512-c3cVx2y4KqUnwopcO9b/SCdo2O67LwJJ/UyqGfbigahfegL9myoEFoDYZgkT7f36T0bLrM9hZTAaAyH+PCAXjw=="], + "micromark-util-events-to-acorn": ["micromark-util-events-to-acorn@2.0.3", "", { "dependencies": { "@types/estree": "^1.0.0", "@types/unist": "^3.0.0", "devlop": "^1.0.0", "estree-util-visit": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0", "vfile-message": "^4.0.0" } }, "sha512-jmsiEIiZ1n7X1Rr5k8wVExBQCg5jy4UXVADItHmNk1zkwEVhBuIUKRu3fqv+hs4nxLISi2DQGlqIOGiFxgbfHg=="], + "micromark-util-html-tag-name": ["micromark-util-html-tag-name@2.0.1", "", {}, "sha512-2cNEiYDhCWKI+Gs9T0Tiysk136SnR13hhO8yW6BGNyhOC4qYFnwF1nKfD3HFAIXA5c45RrIG1ub11GiXeYd1xA=="], "micromark-util-normalize-identifier": ["micromark-util-normalize-identifier@2.0.1", "", { "dependencies": { "micromark-util-symbol": "^2.0.0" } }, "sha512-sxPqmo70LyARJs0w2UclACPUUEqltCkJ6PhKdMIDuJ3gSf/Q+/GIe3WKl0Ijb/GyH9lOpUkRAO2wp0GVkLvS9Q=="], @@ -691,9 +720,11 @@ "space-separated-tokens": ["space-separated-tokens@2.0.2", "", {}, "sha512-PEGlAwrG8yXGXRjW32fGbg66JAlOAwbObuqVoJpv/mRgoWDQfgH1wDPvtzWyUSNAXBGSk8h755YDbbcEy3SH2Q=="], + "starlight-hypha-agents": ["starlight-hypha-agents@github:hyphatech/starlight-hypha-agents#3ee7026", { "dependencies": { "mdast-util-from-markdown": "^2.0.2", "mdast-util-mdx": "^3.0.0", "micromark-extension-mdxjs": "^3.0.0", "yaml": "^2.9.1" }, "peerDependencies": { "@astrojs/starlight": "~0.42.6", "astro": "^7.3.3" } }, "hyphatech-starlight-hypha-agents-3ee7026", "sha512-CRpk3KikuTkpb+Sbq5wMWOibJyR9DScrqijg08vp17qul6BB/GVfYV4XVK9nGVUsGJVjfYgVlCr5j51ZmXHf+A=="], + "starlight-links-validator": ["starlight-links-validator@0.27.0", "", { "dependencies": { "@astrojs/markdown-satteri": "^0.4.0", "github-slugger": "^2.0.0", "hast-util-from-html": "^2.0.3", "is-absolute-url": "^5.0.0", "mdast-util-mdx-jsx": "^3.2.0", "mdast-util-to-hast": "^13.2.1", "picomatch": "^4.0.3", "satteri": "^0.10.3", "terminal-link": "^5.0.0", "unist-util-visit": "^5.1.0", "yaml": "^2.8.3" }, "peerDependencies": { "@astrojs/starlight": ">=0.42.0", "astro": ">=7.2.10" } }, "sha512-UvPl8L9hfWR+yWbLOEtljLmpJCGcM6AVseVy5IO9dmqdOjW4R+Y8FaYyVA5axCC8RvxM5xU7M1WTerpwU8rYbw=="], - "starlight-theme-hypha": ["starlight-theme-hypha@github:hyphatech/starlight-theme-hypha#4df8be9", { "dependencies": { "@fontsource-variable/roboto-slab": "^5.3.0", "@fontsource/inter-tight": "^5.3.0", "@lucide/astro": "1.48.0", "@tailwindcss/vite": "^4.3.3", "tailwindcss": "^4.3.3" }, "peerDependencies": { "@astrojs/starlight": "~0.42.6", "astro": "^7.3.3" } }, "hyphatech-starlight-theme-hypha-4df8be9", "sha512-3ksSin8zktNtDQ9xnP2ihRZkXVaPMTXGxrFykNrXBR3vQT/sQffOD2vpeL+ZvObUP/KmslY4RPWJEnyxwi1npA=="], + "starlight-theme-hypha": ["starlight-theme-hypha@github:hyphatech/starlight-theme-hypha#a105fa6", { "dependencies": { "@fontsource-variable/roboto-slab": "^5.3.0", "@fontsource/inter-tight": "^5.3.0", "@lucide/astro": "1.48.0", "@tailwindcss/vite": "^4.3.3", "tailwindcss": "^4.3.3" }, "peerDependencies": { "@astrojs/starlight": "~0.42.6", "astro": "^7.3.3" } }, "hyphatech-starlight-theme-hypha-a105fa6", "sha512-1lDTrqupxaVND5rueaGZVy2mokekMHaaDHAI3d4TBW8KujgEMRQ3Ftec3+CeXz4vG0NCEd8HCjyW13GBY/eUtQ=="], "std-env": ["std-env@4.3.0", "", {}, "sha512-OtU/EgQ1kIm5KwqQpBC6ZEMXrZRui11w8zgfTWp8cdO9B8OaPsbA8bTHO2P+HNo1VlUTGMVBwPhydu6poeXiag=="], @@ -745,6 +776,8 @@ "unist-util-position": ["unist-util-position@5.0.0", "", { "dependencies": { "@types/unist": "^3.0.0" } }, "sha512-fucsC7HjXvkB5R3kTCO7kUjRdrS0BJt3M/FPxmHMBOm8JQi2BsHAHFsy27E0EolP8rp0NzXsJ+jNPyDWvOJZPA=="], + "unist-util-position-from-estree": ["unist-util-position-from-estree@2.0.0", "", { "dependencies": { "@types/unist": "^3.0.0" } }, "sha512-KaFVRjoqLyF6YXCbVLNad/eS4+OfPQQn2yOd7zF/h5T/CSL2v8NpN6a5TPvtbXthAGw5nG+PuTtq+DdIZr+cRQ=="], + "unist-util-stringify-position": ["unist-util-stringify-position@4.0.0", "", { "dependencies": { "@types/unist": "^3.0.0" } }, "sha512-0ASV06AAoKCDkS2+xw5RXJywruurpbC4JZSm7nr7MOt1ojAzvyyaO+UxZf18j8FCF6kmzCZKcAgN/yu2gm2XgQ=="], "unist-util-visit": ["unist-util-visit@5.2.0", "", { "dependencies": { "@types/unist": "^3.0.0", "unist-util-is": "^6.0.0", "unist-util-visit-parents": "^6.1.0" } }, "sha512-fpsYs/VVoZxfGY9/j3FQpZmN8wdLJaV1Pt38AaJNZu9uKIHcFU3halCdBveEq1HGKO1OEfJY65w1zvoFV1b3qQ=="], diff --git a/docs/package.json b/docs/package.json index 9de8650..50eea6b 100644 --- a/docs/package.json +++ b/docs/package.json @@ -5,7 +5,8 @@ "devDependencies": { "@astrojs/starlight": "~0.42.6", "astro": "^7.3.3", + "starlight-hypha-agents": "github:hyphatech/starlight-hypha-agents#v0.2.0", "starlight-links-validator": "^0.27.0", - "starlight-theme-hypha": "github:hyphatech/starlight-theme-hypha#v0.6.3" + "starlight-theme-hypha": "github:hyphatech/starlight-theme-hypha#v0.8.0" } } diff --git a/dune b/dune index 61c6416..39dccd6 100644 --- a/dune +++ b/dune @@ -39,3 +39,13 @@ (universe)) (action (run %{bin:windtrap} coverage --min 89))) + +; The documentation for a user's agent, agents/, written from the site's pages +; by `make docs`: installed whole, so $(opam var hypha-litany:doc) holds +; llms.txt and each page. + +(install + (package hypha-litany) + (section doc) + (source_trees + (agents as .)))