Repository navigation
Description
"Inlining" in the compiler covers four different features that share one attribute name (@inline). They move through the pipeline in different ways and are stored in different build files. This issue describes how each works today, lists the problems found, and proposes what to change, as context for #8689 and the @inline item in #8624.
Updated 2026-11-28 after a review by Claude (Fable model) against master e51ee46 and #9467: new problems 2.8–2.11 and repro 4 in 2.1, a single meaning for @inline (proposal 3), and an ordered PR plan (section 6). Paths now point at compiler/backend, compiler/typing and build_system/.
TL;DR
| # | Feature | How it's written | What it means | Stored in | The build system notices a change? |
|---|---|---|---|---|---|
| A | Inline constants | @inline let x = 1 / @inline(1) let x: int |
Changes the interface: the value is part of the signature | .cmi |
✅ (the .cmi changes) |
| B | Externals | external f: … = "…" |
The FFI call is emitted directly at each call site | .cmi |
✅ |
| C | Function inlining inside one module | Automatic, or @inline / @inline(never) on a function |
Optimization hint | Nowhere; happens during compilation | n/a |
| D | Cross-module value and function inlining | Automatic (true/false/null/undefined); functions only with -bs-cross-module-opt |
Optimization | .cmj |
❌ can go stale: inlined values, and whether the module has side effects |
Feature A was handled by a frontend rewrite; #9467 moves it into the type checker. Feature D has a correctness bug in incremental builds (2.1) and two bugs in what it exports (2.8, 2.9). #8689 extends D with an explicit opt-in. The proposed model (proposal 3) drops that opt-in: @inline on an exported function exports its body.
1. How the pipeline works today
A. Inline constants (@inline let / @inline(lit) let)
-
Parser:
@inlineis kept as a plain attribute. In an implementation the value is the right-hand side (@inline let x = 1). In an interface it's the attribute payload (@inline(1) let x: int). -
Type checker (with Type @inline constants in the type checker, keep their attributes and allow annotations #9467):
Typedecl.transl_value_declreads@inline(<literal>)on a value in a signature, and thePstr_valuecase inTypemodreads@inline let x = <literal>, also with a type annotation that is the literal's type, possibly through an alias. Both buildVal_prim {prim_kind = Kind_inline_const c}and keep the value's other attributes.On master, the frontend (
bs_builtin_ppx.ml) still rewrites such a binding into a fake external with a reserved primitive name, drops its other attributes, and the type checker decodes it again. Type @inline constants in the type checker, keep their attributes and allow annotations #9467 removes that rewrite and the reserved name. -
Annotated bindings (
@inline let x: int = 3) are inline constants with Type @inline constants in the type checker, keep their attributes and allow annotations #9467. On master they are ordinary values with warning 53. -
Translation:
translcore(transl_external_application) replaces each use withLconst (lambda_of_inline_const c). -
Build files:
.cmi: the constant itself, inside the value'sVal_primprimitive description. Any change to the value changes the.cmi, so dependents are rebuilt correctly.- JS: nothing. A primitive doesn't produce a JS binding, so
@inlineconstants are not exported from the generated module (for example,tests/tests/src/inline_const.mjsdoesn't exportf,f1,f5,f6). JS or genType consumers can't import them.
-
Interface matching:
Primitive.coerciblerequires the same kind. An interface@inline(1) let x: intcan only be satisfied by an@inlineimplementation with the same value. A plainlet x = 1doesn't match it, while an@inlineimplementation can be hidden behind a plainlet x: int. It then gets a normal JS binding, and dependents useA.xinstead of the constant: for A, the.residecides what is inlined.
B. Externals
These follow the same path as A, with Prim_ffi → Kind_external spec. The full FFI spec is stored in the .cmi, so every call site emits the JS call directly.
Exception: when an external's module path is package-relative (@module("./foo")), Ast_external_process sets no_inline_cross_module. The interface then gets a plain val, and the implementation is wrapped in include (… : sig val … end). Other modules call through an ordinary exported binding, because the relative path only works from the declaring file.
C. Function inlining inside one module
- Attributes:
Translattributereads@inline/@inline(always)/@inline(never)on a function expression or binding and stores it asLfunction.attr.inline(Always_inline | Never_inline | Default_inline).@inlineon anything that isn't a function gives warning 53 ("misplaced attribute"). - Optimizer:
Lam_pass_remove_aliasdoes the beta reduction (substituting the arguments into the function body).Lam_analysis.ok_to_inline_fun_when_appdecides when:Always_inline→ always inline;Never_inline→ never.Default_inline→ inline when the body size is under 5 (small_inline_size), when the call can be resolved statically viadestruct_pattern, or when all arguments are constants, the size is under 10, and the body has no side effects.- Async functions and functions with a directive are never inlined (
lfunction_can_be_inlined).
D. Cross-module inlining via .cmj
Export (Lam_stats_export.values_of_export). For each exported value, the .cmj stores {name; arity; persistent_closed_lambda}, where the last field is a Lambda term (the compiler's intermediate representation) that callers can copy:
-
true/false/null/undefinedconstants are always exported, whatever the flags. -
Everything else is only exported when
-bs-cross-module-optis set (off by default; can be set throughcompiler-flags). Even then, only values that passsafe_to_inlineare exported:- functions;
- constant constructors and polymorphic variants, booleans,
undefined.
Ints and strings are never exported. Functions qualify under one of two rules:
@inlinefunctions and functors: exported only when closed (Lam_closure.is_closed), i.e. they don't capture any surrounding local values.- Other functions: exported when the size is under 5 and there are no free variables.
-
Js_cmj_format.get_resultfilters again when the.cmjis read: unless the flag is set, everything except the four constants is dropped. -
None of this depends on the interface. With an
A.resideclaringlet flag: bool, dependents still gettruecopied in. The.resionly decides which values are exported; their stored bodies come from the implementation. The same holds for functions under-bs-cross-module-opt.
Use. Lam_compile_env.query_external_id_info looks up the other module's .cmj entry:
Lam_pass_remove_aliasbeta-reducesA.f(args)with the stored body.Lam_compile.compile_external_fieldemits stored non-function constants directly.compile_external_field_applyinlines stored functions during code generation.
Format. The .cmj is a 16-byte digest header followed by the marshalled data. to_file ~check_exists skips rewriting the file when its content is unchanged.
Observed with a two-module project (B uses A's values):
- With no flags,
let flag = truein A is copied into B aslet f = true.let num = 1and all functions are referenced asA.num/A.g(3), even@inline let g = …. - With
-bs-cross-module-opt, both@inline let g = x => x + 1and the unannotatedlet h = x => x * 2were inlined (let a = 4; let b = 6).
Summary: what each build file stores
| File | Inlining-related contents | The build system rebuilds dependents when it changes? |
|---|---|---|
.cmi |
Types, plus Val_prim descriptions: the full FFI spec for externals (B) and the literal for @inline constants (A). Also declaration locations. |
Yes. This is the only signal the build system uses today: publish_compiler_artifacts in build_system/compiler_process.ml reports Cmi_changed, and Build_state.record_published_cmi marks dependents dirty. |
.cmj |
Per exported value: arity, plus an optional persistent_closed_lambda (D: always-exported bool/null/undefined constants, plus small or @inline closed functions under the flag). Also effect information and hoisted exports. |
No on master; publish_compiler_artifacts only checks that it exists. #8689 adds this. |
.js |
The generated code. @inline constants and externals produce no binding. |
n/a |
2. Problems
2.1 Stale JS after incremental builds (bug on master)
A dependent reads A's .cmj (copied values, arity, and whether A has side effects), but the build system only checks A's .cmi.
Repro 1 (no flags):
// A.res
let flag = true // two spaces, so the edit below keeps every location
let num = 2
// B.res
let f = A.flagBuild, then change A to let flag = false and build again. Only A is recompiled. A's .cmi is byte-identical, A.mjs has let flag = false, but B.mjs still has let f = true.
Repro 2 ("compiler-flags": ["-bs-cross-module-opt"]):
// A.res
let h = x => x * 2
// B.res
let b = A.h(3)Build, then change the body to x * 3. Only A is recompiled, and B.mjs still has let b = 6.
Repro 3 (any module with a .resi, no flags):
// A.resi
let flag: bool
// A.res
let flag = true
// B.res
let f = A.flagBuild, then change A.res to let flag = false. A.cmi is built from the .resi alone, so it stays byte-identical even when every line of A.res moves. B is never rebuilt and keeps let f = true.
For modules without an interface, the bug is mostly hidden in practice because the .cmi stores declaration locations, so most edits shift something and trigger the rebuild by accident. Modules with a .resi don't have this safety net: every change of such a value leaves dependents stale. #8689's .cmj digest check fixes this as a side effect.
Repro 4 (no flags, not about inlining): with the A.resi and B.res of repro 3, add Console.log("effect") to A.res. Only A is compiled. B.mjs keeps /* No side effect */ and still has no import of A.mjs, so the effect never runs when B is A's only importer. Dependents read the "pure" bit from the .cmj (Lam_compile_env.is_pure_module), and B's own bit is then stale too. So the whole .cmj is an input of every dependent, not only its inlinable part.
2.2 @inline means three things
@inline is a signature-level constant (A), an optimization hint (C), and with #8689 an opt-in for cross-module inlining (D). Which one applies depends on whether the right-hand side is a literal, which is easy to get wrong. For example, @inline let x: int = 3 silently became an ordinary value with warning 53 (fixed in #9467).
2.3 Inline constants are a frontend rewrite, not part of the AST
Also tracked in #8624. Status of each problem:
- ✅ Implementations and interfaces disagreed on bigint (
@inline(12n) let x: bigintin an interface couldn't be implemented). Fixed in Resolve FFI externals during type checking #8728. - ✅ A type annotation disabled inlining:
@inline let x: int = 3was an ordinary value with warning 53. Fixed in Type @inline constants in the type checker, keep their attributes and allow annotations #9467: it's inlined, and the annotation must be the literal's type, possibly through an alias. Like other@inlineconstants it's no longer exported to JS (see 2.4 and proposal 5). - ✅ Other attributes on the binding were dropped, so
@deprecatednever warned and doc comments were lost. Fixed in Type @inline constants in the type checker, keep their attributes and allow annotations #9467. - ✅ The frontend made up a type annotation. With Type @inline constants in the type checker, keep their attributes and allow annotations #9467 the type checker builds the declaration itself, giving it the literal's built-in type.
- ✅
Prim_inline_constlived in the parsetree only to carry the result of the rewrite. Removed in Resolve FFI externals during type checking #8728. - ✅ The inverted bigint sign in this encoding was fixed in Fix the sign of @inline bigint constants #8732.
2.4 @inline constants are missing from the JS output
That's expected for externals, but surprising for something written as let, and it limits interop. Two consequences:
@genType @inline let x = 42is silently left out of the.gen.tsx, with no warning; so is@genType @inline(42) let x: intin a.resi.- Type @inline constants in the type checker, keep their attributes and allow annotations #9467 inlines annotated constants (
@inline let x: int = 3), which until now were ordinary exported values. Their JS export goes away.
2.5 @inline on a function does nothing across modules by default
Without the global flag nothing is exported to .cmj. The global flag, meanwhile, inlines every small closed function, opted-in or not.
2.6 The global -bs-cross-module-opt flag isn't a clear contract
It applies per compiler invocation, its export rules are an internal heuristic (size < 5), and nothing documents it. #8689 makes cross-module inlining an explicit per-function choice, which would make the global flag largely redundant.
2.7 The .cmj is not governed by the interface
true/false/null/undefined values are copied into dependents even when the .resi only promises a type. Arity and purity also come from the implementation, whatever the .resi says. This is safe once 2.1 is fixed: every package is compiled from source by its consumer, so a .resi is a typing boundary, not a binary one. No change proposed. Dropping the four constants would quietly turn if A.debug in dependents from dead code into a runtime check.
2.8 Exported bodies can contain relative-path externals
With -bs-cross-module-opt, a body that calls a @module("./helper.js") external is inlined into a module in another directory, which then imports ./helper.js relative to itself. Example: src/ffi/Hidden.res with @module("./helper.js") external raw: int => int = "raw" and @inline let wrapped = x => raw(x) + 1; src/app/B.res calling Hidden.raw(1) and Hidden.wrapped(1) gets import * as HelperJs from "./helper.js". The type checker's guard (Primitive.no_cross_module_inline and the include wrapper in typemod.ml) is undone by the backend, because the wrapper is a small closed function and is exported. #8689 has no check for this either.
2.9 Exported bodies can name modules the caller cannot load
If an exported body refers to a module C that the caller cannot see (for example a module of a package the caller does not depend on), inlining it fails with "C not found, it means either the module does not exist or it is a namespace". Reproduced by hiding C from the include path; the two-package case has not been built yet.
2.10 Stored bodies carry locations
Stored Lambda bodies keep Location.t (lfunction.loc, ap_loc, prim_info.loc), and -no-keep-locs does not cover them. So a line shift changes the .cmj, and the runtime's lib/rescript/*.cmj, which are published (lib is in the package's files), contain absolute build paths. The runtime is built with -bs-cross-module-opt. With default flags the .cmj holds no bodies: it is about 100 bytes and keeps its digest across line shifts and body edits.
2.11 Payloads on constants are ignored
@inline(3) let x = 4 is the constant 4, and @inline(never) let x = 5 is an inlined constant, both without a warning. module type S = { @inline(never) let q: int } is accepted silently. Separately, an @inline constant in a signature isn't checked against its type (#9468).
3. Related work
- Add opt-in cross-module inlining for Option helpers #8689 (open): adds
@inline(crossModule)→Cross_module_inline. Under proposal 3 its build-system part becomes PR 2 and its compiler part is replaced by plain@inline(PR 5).- The body is exported to
.cmjregardless of the flag (it must be closed, not async, and have no directive) and is always inlined at call sites. - The build system also rebuilds dependents when the
.cmjdigest changes. - Applied to
Option.map,flatMap,getOr, etc. in the stdlib.
- The body is exported to
- Stamp parsetree v1: what remains before the AST can be frozen for PPXs #8624 (parsetree v1): lists "
@inlineconstants: give them a structural form". - Fix the sign of @inline bigint constants #8732 (merged): fixed the inverted bigint sign in inline constants.
- Resolve FFI externals during type checking #8728 (merged): removed
Prim_inline_constfrom the parsetree by resolving externals during type checking. Inline constants became fake externals with a reserved primitive name, which Type @inline constants in the type checker, keep their attributes and allow annotations #9467 removes. - @inline constants in signatures are not checked against their type #9468 (open):
@inlineconstants in signatures are not checked against their type. - Type @inline constants in the type checker, keep their attributes and allow annotations #9467 (draft): the type checker handles
@inlineconstants directly, so the frontend rewrite and the reserved primitive name go away, other attributes are kept, and annotated constants are inlined. This is proposal 2, done differently.
4. Proposals
- Rebuild dependents when a module's
.cmjchanges, independently of Add opt-in cross-module inlining for Option helpers #8689 (its build-system part). The whole.cmjis the right unit: dependents read almost every field (2.1, repro 4), so a separate digest of only the inlinable data buys nothing. With default flags the.cmjchanges only when an exported arity, the purity, one of the four constants or the package spec changes, and each of those changes dependents' JS. A rebuild stops at the first dependent whose own.cmiand.cmjare unchanged. Stripping locations from stored bodies (2.10) keeps a line shift from rebuilding the direct dependents of a module with a.resi. - Give inline constants a structural form (feature A). Done differently in Type @inline constants in the type checker, keep their attributes and allow annotations #9467. The original plan was a
Prim_inlineconstructor inprimitive_repr, produced by the parser. Resolve FFI externals during type checking #8728 madepval_prima plain string again and kept FFI attributes as attributes that the type checker reads. Type @inline constants in the type checker, keep their attributes and allow annotations #9467 does the same for@inline: no parsetree change, and PPXs keep seeing the attribute as written (the rewrite always ran after them). Type @inline constants in the type checker, keep their attributes and allow annotations #9467 also inlines annotated constants, so nothing from 2.3 is left. - One meaning for
@inline: uses are replaced by the definition, in this module and in others.- On a literal
let: a signature constant (A), as Type @inline constants in the type checker, keep their attributes and allow annotations #9467 implements it. - On a function or functor: every saturated call is inlined (C). If the value is exported and exportable, its body is stored in the
.cmjand inlined in other modules too (D), with or without a flag. @inline(never): never inlined and never exported.- No
@inline(crossModule). A fourth payload would make 2.2 worse, and the flag already gives@inlinethis meaning for functions and functors. - Exportable means closed, not async, no directive, and no call to a relative-path external (2.8). A non-exportable
@inlinefunction is inlined only in its own module, without a warning, so existing code keeps compiling. - At the use site, a stored body is inlined only when every module it names can be loaded; otherwise the call stays a normal call (2.9).
- The
.resicontrols types and@inlineconstants (they areVal_primin the.cmi), not bodies, the four constants, arity or purity (2.7). - Cost: existing
@inlinefunctions start exporting bodies, which changes the JS of their dependents. Fine for a major version.
- On a literal
- Remove
-bs-cross-module-optonce the stdlib helpers that rely on it are annotated with@inline. Keep the four always-exported constants (2.7). For one release, accept the flag and ignore it with a warning. - Export
@inlineconstants to JS by making them ordinary values whose literal is also known in their value description. Coercing one to a plainletis then the identity, module objects contain the field, and genType needs no special case (2.4). Ideally in the same release as Type @inline constants in the type checker, keep their attributes and allow annotations #9467, so the lost exports of annotated constants never ship.
5. Open questions
- Should a non-exportable
@inlinefunction on an exported binding warn? - Is losing source-map positions inside inlined bodies acceptable, in exchange for stable
.cmjfiles (2.10)? - Should the "pure" bit, arity and the four constants keep coming from the implementation when a
.resiexists (2.7)? Proposed: yes.
6. PR plan
- Strip locations from stored bodies (2.10; Leave source locations out of bodies stored in .cmj files #9470). First, so that PR 2 doesn't rebuild the direct dependents of a module with a
.resion every line shift when bodies are stored. Breaks source-map positions inside inlined bodies. Tests: the.cmjdigest survives a line shift; no absolute paths in the runtime's.cmjfiles. - Rebuild dependents when the
.cmjchanges (build_system/only; proposal 1). Tests: integration tests (tests/build_tests/integration) for repros 3 and 4, a unit test intests/build_tests/unit/compiler_process_tests.ml, and the allocation benchmarks for edits in generated projects. - Never export a body that calls a relative-path external (
lam_stats_export.ml; 2.8). Test: the 2.8 layout with the flag. - Fall back to a normal call when a stored body names a module that cannot be loaded (
lam_pass_remove_alias.ml,lam_compile.ml; 2.9). Test: a two-package build test with an undeclared transitive dependency. @inlineon an exported function or functor exports its body, flag or not, and the Option helpers are annotated (proposal 3; replaces the compiler part of Add opt-in cross-module inlining for Option helpers #8689). Breaks: the JS output of dependents of existing@inlinefunctions. Tests: Add opt-in cross-module inlining for Option helpers #8689's tests with@inline.- Diagnostics: warn on a payload on an
@inlineconstant (2.11), warn on@genTypeon an@inlineconstant until proposal 5 lands, and check signature constants against their type (@inline constants in signatures are not checked against their type #9468). - Remove
-bs-cross-module-opt(proposal 4): first drop it from the runtime and Beltrescript.jsonand review thelib/es6diff, annotate what regresses, then remove the flag, the read-side filter inJs_cmj_format.get_resultand the size heuristic inLam_stats_export. - Export
@inlineconstants to JS (proposal 5).
Optional and cosmetic: accept a local @inline let inside a function, and stop parsing @inlined only to warn about it.
Activity
Remove the call-site @inlined attribute (#8734)
Remove the call-site @inlined attribute (rescript-lang#8734)