A configurable OCaml PPX that raises compile-time errors when forbidden functions or modules are used. Enforce coding standards automatically -- no more "please don't use X" in code review.
- Eio migration: ban blocking
Unix.open_process_in,Unix.sleep,Thread.create - Safety: ban
Obj.magicand other unsafe operations - TUI apps: ban
print_endline/Printf.printf(they corrupt the terminal) - Theming: ban hardcoded color functions, enforce themed helpers
- API migration: ban deprecated functions with actionable suggestions
opam install ppx_forbidAdd to your dune file:
(library
(name mylib)
(preprocess (pps ppx_forbid)))Create a .ppx_forbid config in your project:
module Obj "Obj is unsafe and breaks type safety"
function Unix.sleep "Use Eio.Time.sleep"
function Thread.create "Use Eio.Fiber.fork"
That's it. Any use of Obj, Unix.sleep, or Thread.create will now fail to compile:
File "src/myfile.ml", line 42, characters 10-30:
42 | let _ = Unix.sleep 5 in
^^^^^^^^^^
Error: Forbidden call: Unix.sleep is not allowed.
Suggestion: Use Eio.Time.sleep
Use [@allow_forbidden "reason"] to suppress.
Unqualified Stdlib functions are also caught -- prerr_endline matches a function Stdlib.prerr_endline rule.
# Comments start with #
# Forbid an entire module
module <ModuleName> "<reason>"
# Forbid a specific function
function <Module.function_name> "<suggestion>"
# Include another config file (paths relative to this file)
include ../base.ppx_forbid
# Allow one function of a forbidden module
allow <Module.function_name>
# Apply a rule only to some files, or exempt files from it
only <rule-target> <path-glob>
exempt <rule-target> <path-glob> "<reason>"
A module M rule matches every reference to M or to a module inside it,
by its full path:
- a qualified value (
M.f,M.Sub.f); open M/open! M,let open M inand a local openM.( ... );include M, an aliasmodule X = M, a functor argument and a packed module(module M : S);- a module type path
M.S; - the qualifier of a constructor or exception (
M.C, in expressions and patterns), a record label (r.M.l,{ M.l = ... }) and a class (new M.c,inherit M.c).
Aliasing or opening a forbidden module is therefore forbidden too, so a rule
cannot be bypassed through an alias. Paths are compared after
canonicalisation: Stdlib.Obj and Stdlib__Obj are Obj, and a
dune-mangled Lib__Mod is Lib.Mod. Names that only share a prefix (Mx,
M2) do not match. Type expressions (M.t) are not checked.
A function M.f rule matches the qualified call M.f (and f alone when M
is Stdlib).
Code generated by other derivers in the same pps list is checked as well.
Its locations are ghost locations (_none_), so [@allow_forbidden] cannot
reach it: scope the rule by path instead. For example, [@@deriving yojson]
output references Ppx_deriving_yojson_runtime but not Yojson.Safe.Util.
module Exec "async code must not call the executor"
allow Exec.digest
allow Exec.exact
Exec.digest and Exec.exact stay allowed when called by their qualified
name; any other Exec.* value, and open Exec or module P = Exec, are
rejected. An allow must name a function of a module forbidden in the same
config.
only and exempt name the target of a rule of the same config (M for
module M, M.f for function M.f) and a path glob. A glob is resolved
against the directory of the config file that declares it and matched against
the source file's path. * and ? never match a /, and there is no
recursive **: a directory tree needs one line per depth.
module Exec "async code must not call the executor"
only Exec lib/async_*.ml
module Yojson.Safe.Util "use a typed codec"
exempt Yojson.Safe.Util lib/json_codec.ml "the JSON codec boundary"
With one or more only lines, a rule applies only to the matching files. An
exempt line removes a file from a rule, and it needs a reason.
Inside a dune build, source paths are mapped back to the source tree through
INSIDE_DUNE and DUNE_SOURCEROOT, including dune's sandbox. Configs found
by walking up from the source file therefore also work with an external
--build-dir, a named build context and nested dune projects. A path already
in the source tree stays a source path even if the repository itself is
cloned below another project's _build directory. Genuine build-context and
sandbox paths are mapped first, including contexts inside the source root.
A path passed with --config is read as given, from the build context root. It must exist
there, so declare it with (preprocessor_deps ...). Declare walk-up configs
the same way, so that dune re-checks files when a config changes.
Limits:
- A typo in an
onlyglob matches nothing and turns the rule off. Keep the globs short, and check them with--report. - An exempted file can re-export a forbidden module (
module U = M) that other files then use asExempted_file.U. Keep exempted files small and named. allowcovers qualified values only. A constructor or label of a forbidden module has noallowform: use path scoping or[@allow_forbidden].- A
*or?in the config directory's own path is read as a wildcard.
A config error fails preprocessing. It is raised for:
- an unknown directive;
- a
moduleline without a reason, or afunctionline without a module or without a suggestion; - a malformed
allow,onlyorexemptline, or one naming no rule of the config; - an
includeof a missing file; - a
--configfile that does not exist.
As a result, a typo cannot silently drop a rule.
With --report (for example on a standalone driver:
driver.exe --config .ppx_forbid --report -impl lib/foo.ml), nothing fails:
every hit is printed to stderr, one per line, as
<file>:<line>:<column>: <status> <module|function> <target>, where status
is forbidden, suppressed (inside [@allow_forbidden]) or exempt
(matched by an exempt line). A project can compare this output with a
checked-in allowlist that may only shrink: a new forbidden line is a new
violation, and an allowlist entry with no matching line is stale.
The PPX searches for .ppx_forbid starting from the source file's directory and walking up to the project root. This lets you have stricter rules for specific subdirectories:
project/
.ppx_forbid # project-wide rules
src/
ui/
.ppx_forbid # UI-specific rules (can `include ../../.ppx_forbid`)
You can also pass an explicit config path:
(preprocess (pps (ppx_forbid --config .ppx_forbid.strict)))When you genuinely need a forbidden function, annotate with [@allow_forbidden "reason"]:
(* On an expression *)
let raw = (Obj.magic ptr : bytes) [@allow_forbidden "FFI boundary"]
(* On a binding *)
let[@allow_forbidden "logger writes to stderr by design"] log msg =
prerr_endline msgThe reason string is required and documents why the exception is acceptable.
This repository also ships ppx_enforce, the mirror image of ppx_forbid.
It raises a compile-time error when a source file does not contain a required
function call.
Install it with:
opam install ppx_enforceAdd it to your dune file:
(library
(name my_widgets)
(preprocess (pps ppx_enforce))
(preprocessor_deps .ppx_enforce))Create a .ppx_enforce config:
call Miaou_registry.register "Widget modules must self-register"
Each processed file must now contain a matching call such as:
let () = Miaou_registry.register ~name:"my-widget" ~mli:"..." ()If a file is intentionally outside the rule, add a file-level exemption:
[@@@enforce_exempt]or exempt one requirement:
[@@@enforce_exempt "Miaou_registry.register"]When no .ppx_forbid file is found, a single default rule applies:
| Item | Reason |
|---|---|
Obj (module) |
Obj is unsafe and breaks type safety |
Project-wide config (.ppx_forbid):
module Obj "Obj is unsafe and breaks type safety"
function Unix.open_process_in "Use Eio.Process.run or Common.run_out"
function Unix.open_process_out "Use Eio.Process.run"
function Unix.system "Use Eio.Process.run or Common.run"
function Unix.sleep "Use Eio.Time.sleep"
function Thread.create "Use Eio.Fiber.fork or Eio.Fiber.fork_daemon"
TUI-specific config (src/ui/.ppx_forbid):
include ../../.ppx_forbid
function Stdlib.print_endline "Use logging or TUI display functions"
function Stdlib.prerr_endline "Use logging or Toast notifications"
function Printf.printf "Use logging or TUI display functions"
- OCaml >= 4.14
- ppxlib >= 0.28.0
- dune >= 3.13