OCaml linter enforcing modern coding conventions
README.md

Merlint #

An opinionated linter for modern OCaml development.

The OCaml compiler rejects a program that does not type-check, and it accepts an Obj.magic in a parser, a handler that catches every exception, a module with no interface or a test directory that dune never runs. Merlint looks for these and about 120 other conventions, on code quality, style, naming, documentation, project structure and testing. It runs with no configuration and lists issues by severity, the most serious first.

Most rules read the typed trees that dune writes. A typed tree is the compiler's abstract syntax tree after type checking: every identifier is resolved to its definition and every expression carries its type. ocamlc -bin-annot saves it as a .cmt file for an implementation and a .cmti file for an interface. A rule that reads it knows that magic is Obj.magic even behind an open or a module alias, where a search of the source text would miss it, so it sees the program as the compiler saw it.

The reference for every rule is at https://samoht.github.io/merlint/.

Output #

Issues are grouped by category, and each one carries an error code and a short note on how to fix it:

Analysing 15 files

✓ Code Quality (0 total issues)
✗ Code Style (2 total issues)
  [E100] Unsafe Type Casting
  This issue means you're using unsafe type casting that can crash your program.
  Fix it by replacing Obj.magic with proper type definitions.
  - src/utils.ml:33:8: Never use Obj.magic
  [E200] Deprecated Str Module
  This issue means you're using the outdated Str module. Fix it by using the
  modern Re module which is more powerful and has better performance.
  - src/parser.ml:45:2: Use Re module instead of Str
✗ Naming Conventions (1 total issues)
  [E300] Variant Naming Convention
  This issue means your variant names don't follow OCaml conventions. Fix them
  by using Snake_case (e.g., Some_value, Waiting_for_input).
  - src/types.ml:8:2: Variant 'waitingForInput' should be 'Waiting_for_input'

Summary: ✗ 3 total issues

Installation #

On macOS or Linux, the quickest way is the Homebrew tap:

$ brew install samoht/monopam/merlint

That auto-taps samoht/monopam; equivalently, brew tap samoht/monopam once and then brew install merlint.

Or install with opam:

$ opam install merlint

If opam cannot find the package, it has not yet landed in the public opam-repository. Add the overlay repository, then install it:

$ opam repo add samoht https://tangled.org/gazagnaire.org/opam-overlay.git
$ opam update
$ opam install merlint

Requirements #

  • OCaml 5.2 or later, which Eio requires.
  • Dune. Merlint reads the .cmt and .cmti files that dune writes, so run it inside a dune project after dune build @check, or pass --build to have it build them. A file whose typed tree is missing or stale has its typed-tree rules skipped, and merlint names each such file. The bytes --overlay reads in place of a file's are typed as the build typed that file, against the same load path and with the same typing flags, unless a preprocessor made what the build compiled; bytes that do not type there are named the same way.
  • A compiler that builds the tree: OCaml 5.3, 5.4 or 5.5. Merlint reads no typed tree itself: it carries the source of a reader that links the compiler's compiler-libs and nothing else. The first run over a tree compiles the reader with the compiler dune builds that tree with, and keeps it in $XDG_CACHE_HOME/merlint/readers, or ~/.cache/merlint/readers, one per typed-tree format; later runs reuse it. Every rule that reads a unit's typed tree or imports, or a source's parse, asks that reader, so one merlint lints a tree any of these compilers built. A run over a tree whose compiler does not compile the reader is refused, naming the compiler and what it said.

Usage #

$ # Analyse the entire project
$ merlint

$ # Analyse specific files or directories
$ merlint lib/ bin/

$ # Filter rules (e.g., run all rules except E110)
$ merlint --rules all-E110

$ # Emit a machine-readable JSON report instead of the formatted tables
$ merlint --json

merlint --help lists every option. Two are useful early on: --exclude 'vendor/**' skips vendored or generated code (subtrees any dune file marks (vendored_dirs ...) or (data_only_dirs ...) are skipped already, by every rule; --include-vendored lints the vendored ones), and --bail stops at the first issue in report order, which is enough to tell whether a tree passes.

Dune data-only and cram fixture directories hold data rather than compilation units. Explicit paths, including --files-from inputs, follow that ownership. Negative typing suites declare (data_only_dirs cases) and keep their compiler refusal rules. Imported sources and sources named by a compiled catalogue stay in scope. A source-location claim without current compiled provenance remains unclaimed; it never establishes a successful check.

--fix applies the rewrite a finding carries (E217's Fmt helpers and E420's odoc links) to the file it names, lists each finding it could not rewrite, and exits as a run that found only those.

--json prints a single JSON object for editors, CI jobs and git hooks to read. It drops the Dune root: banner and the summary tables and keeps the same exit status, so a JSON run still works as a gate. The object carries the file and rule counts, a passed boolean, the issues array with a location for each issue, and the excluded array.

Four more arrays say what the run did not check:

  • unclaimed_files: files that no dune stanza compiles, so no rule ran on them.
  • unchecked_files: sources for which a rule needed a typed tree and found no .cmt or .cmti.
  • skipped_paths: paths given on the command line that are neither .ml nor .mli; no rule reads them.
  • failed_checks: rules that raised an exception, so their findings are missing. Each entry is a bug in merlint, and says nothing about the code it read.

A file that no stanza compiles is listed in unclaimed_files only: what it lacks is a stanza, and a build would not help. passed is false as long as any of the four arrays has an entry. The arrays are complete at every verbosity, so one run over a repository lists all it could not check. The human-readable output shows ten entries of each (all of them with -v) and lists every skipped path under the summary.

unbuilt_files lists the sources dune does not compile in this build context: the branch of a (select ...) it did not pick, and the files of a stanza whose (enabled_if ...) is false here. merlint runs on them the rules that read the source and none that reads a typed tree, since typing them here would fail on what they select on and say nothing about the code. They leave passed and the exit status alone, and the human-readable output names each one under "Not in this build (type rules not run)", alongside the selected source or its disabled stanza. A run in the context that builds them, such as an OxCaml switch, checks them fully.

build_failure is null on a normal report. When merlint refuses to analyse, it holds a kind and the error behind it, with what dune said. contended means another dune process holds the build root, so the build never started; broken means the build ran and the project does not compile; unscoped means a directory merlint was asked to analyse lies outside the dune root, so there is no @check alias to build for it; unselected means a directory argument, or the dune root when no argument is given, holds no OCaml source the root reads, so the run would have read nothing there; and internal means the fault is merlint's own; compiler means the tree's compiler does not compile merlint's reader, and error names it and says what it said. A refused run has every count at zero and passed false, because no verdict was computed. All six kinds exit with status 4, and kind is the field a caller branches on.

Exit status #

Merlint answers three separate questions: whether the code has findings, whether merlint read everything it was pointed at, and whether it read anything at all. The status is therefore a bit set rather than one number. Bit 1 means findings and bit 2 means incomplete coverage, so 0 to 3 are their four combinations. Status 4 is never combined with them, because a refused run computes neither answer. Statuses 124 and 125 are set by cmdliner before merlint's own code runs, and lie outside the mask:

Status Meaning
0 complete run, no findings
1 findings: the code merlint read has issues to fix
2 incomplete coverage: merlint could not read part of it
3 both: findings, over a run that read only part of the tree
4 refused: nothing was analysed, so there is no verdict
124 cmdliner's: a command line merlint could not parse
125 cmdliner's: an unexpected internal error

Status 2 is an error, and should not be read as a warning. A run that read half of what it was given and exited 0 would be taken to mean that the code is clean, although no rule examined the files that no stanza claims. A path merlint has no rule for sets the same bit, because the run never opened it, and so does a rule that raised, where the fault is merlint's. Status 3 combines the two: the findings are real, and the list they come from is incomplete. A gate that only wants pass or fail treats any non-zero status as failure and needs no change.

Status 4 carries no verdict. Merlint refuses to analyse when a path it was given does not exist, when a directory it was given holds no source the dune root reads, when its merlint.toml or its -r filter does not parse, and when the project does not build: without the typed trees its rules read, it cannot tell a clean tree from one that does not typecheck. When another dune process holds the build root, merlint tries the build six times, 10 seconds apart, and each time says which root it is waiting on and for how long; after the sixth attempt, about 50 seconds in, it refuses with status 4. A busy tree costs time rather than getting a free pass. A project that does not compile is refused at once, with what dune said.

Merlint uses 4 rather than 124 because cmdliner exits 124 on a command line it cannot parse, and timeout(1) exits 124 when it kills the command it wrapped. CI usually runs linters under timeout, so a refusal reported as 124 would look like a run that never finished, which calls for different work. No status merlint uses clashes with one the shell, a signal or timeout already uses. The exit_status test suite checks this: it computes every status a run can return (each combination of the bits, and 4) and fails if one of them is reserved, that is 123 to 127 (124 for timeout, 126 and 127 for a command that is not executable or not found), 128 to 255 (a process killed by signal n exits 128 + n), or a value outside 0 to 255, which the shell reads modulo 256.

To see what a rule means and how to fix it, and to render the rule reference, ask merlint help:

$ merlint help E100                                       # one rule, with examples
$ merlint help config                                     # the merlint.toml reference
$ merlint help --all --format=html -o docs/index.html     # the full rule reference
$ merlint help --all --format=md -o STYLE_GUIDE.md

Configuration #

Merlint reads merlint.toml from your project root. Run merlint help config for the full reference: the settings keys, the workspace declaration a checkout built from a workspace elsewhere needs, the [[rules]] block format (single glob or list of globs), and the pattern syntax. The test suite passes every example it shows through the parser, so the reference and the implementation cannot disagree.

max_complexity = 15
max_function_length = 100

[[rules]]
files = ["lib/color.ml*", "lib/margin.ml*", "lib/padding.ml*"]
exclude = ["E330"]

Both escape hatches are narrow on purpose. allowed_words is for names taken verbatim from a published specification or registry, such as EdDSA (IANA COSE algorithms) or tBSCertList (RFC 5280), so that a reader can search the code for the name the standard uses; a name that is merely awkward to rename is renamed. For the whole-name rules (E325, E331, E332, E333) an entry may be qualified, Sqlite.create_table, to exempt one binding rather than every use of the name. A [[rules]] exclusion is for files no person writes, such as generated or proof-extracted code, excluded by path with a comment saying where they come from; a finding in hand-written code is fixed, not excluded. exclude = ["*"] takes a file out of every step of the run, as --exclude does: it is neither analysed, typechecked nor counted.

Rules #

Merlint sorts rules into categories, and within a run orders the issues by severity so the most serious appear first:

  • Code Quality: Obj.magic, catch-all exception handlers, high cyclomatic complexity, long functions, and deep nesting.
  • Code Style: modernisation such as Re over Str and Fmt over Printf.
  • Naming Conventions: variant, module, and identifier naming.
  • Documentation: interface documentation standards.
  • Project Structure: missing interfaces and dune/opam consistency.
  • Test Quality: test discipline and coverage of each rule's own examples.
  • Interop Testing and Code Generation: conventions for interop traces and generated code.

For the complete list of rules and error codes, see the official documentation; for the conventions behind them, the Style Guide.

E600 identifies executable entry modules from the names declared by Dune's executable and test stanzas. Those modules and their interfaces have a program role; other test_ modules in the same stanza retain the test suite interface convention.

AI transparency #

Merlint was developed with substantial help from an AI assistant, Claude Code by Anthropic. This has two consequences for users.

AI-generated code can contain unusual patterns or subtle bugs. Merlint runs on its own source and on a monorepo of more than 150 OCaml packages, but test it on your own code before relying on it.

The copyright status, licence implications and liability of AI-generated code have not been tested in court, and nobody can trace which training data shaped a given piece of code. The Software Freedom Conservancy and the FSF have written about these questions.

As with any tool that reports on code, keep your code under version control and review each change you make in response.

Licence #

ISC, see LICENSE.md for details.

Acknowledgements #

Many thanks to the Merlin maintainers for an indispensable API that makes OCaml tooling possible.