Skip to content

Keep module field reads before their variable is assigned - #9534

Closed
cknitt wants to merge 4 commits into
option-result-markfrom
assigned-variable-module-field
Closed

cknitt wants to merge 4 commits into
option-result-markfrom
assigned-variable-module-field

Conversation

@cknitt

@cknitt cknitt commented Dec 5, 2026

Copy link
Copy Markdown
Member

Fixes cases 1 and 2 of #9533. Case 3 is fixed by the next PR in the stack, which no longer stores @inline bodies that update a local ref.

When the optimizer knows what a variable holds, it reads the value directly instead. That is wrong when the value reads a variable that is assigned in between. #9531 checks this for a plain variable; this extends the check to a field of a first-class module held in such a variable.

  • Alias pass: a substitution is kept only when Lam_analysis.delay_safe says the value can be read later. That covers plain variables (as in Keep a Some or tuple payload read before its variable is assigned #9531) and module fields of them.
  • Lam_util.refine_let: a module field read from an assigned variable is no longer treated as an alias it can substitute into its single use.
// Other.res
module type S = {
  let x: string
}
@inline
let viaTuple = (n: int, q: module(S), q2: module(S)) => {
  let s = ref(q)
  let t = (
    {
      let module(M) = s.contents
      M.x
    },
    1,
  )
  for _ in 0 to n {
    s := q2
  }
  let (a, _) = t
  let module(M2) = s.contents
  (a, M2.x)
}

A call with modules A (x = "a") and B (x = "b") returned ["b", "b"] instead of ["a", "b"]: t[0] became s.x, read after the loop.

These substitutions come from BuckleScript. Function bodies stored for other modules carry such variables, and since #9482 every closed @inline function stores its body. Bodies inlined while compiling to JavaScript also see the caller's own assigned variables, so the check stays needed after the next PR.

New cases in inline_assigned_payload_test: a module field in a tuple, and a module field bound once and used once.

Stacked on #9528.

🤖 Generated with Claude Code

https://claude.ai/code/session_01Kbf3gHZYwA1rq7zbk3dhQq

cknitt and others added 4 commits December 4, 2026 21:39
Why:
    The alias pass replaced the payload of a variable known to be
    `Some(x)`, and a field of one known to be `(x, _)`, with `x` itself.
    When `x` is assigned between the binding and the read, the read gets
    the new value. Since #9022 substituted `Some(x)` payloads, this is
    reachable through cross-module `@inline` bodies, which are stored
    after `Lam_pass_sroa` turned their refs into assigned variables. The
    pass now keeps the binding when the variable is assigned.

JS modified (cross-module @inline):
Example:
    // Other.res
    @inline
    let f = (n: int, q: 'a, q2: 'a) => {
      let s = ref(q)
      let o = Some(s.contents)
      for _ in 0 to n {
        s := q2
      }
      switch o {
      | Some(v) => Some((v, s.contents))
      | None => None
      }
    }
    @inline
    let g = (n: int, q: 'a, q2: 'a) => {
      let s = ref(q)
      let t = (s.contents, 1)
      for _ in 0 to n {
        s := q2
      }
      let (a, _) = t
      (a, s.contents)
    }

    // Main.res
    let viaAlias = () => Other.f(3, "a", "b")
    let viaField = () => Other.g(3, "a", "b")
Before (js): both return ["b", "b"]
    function viaAlias() {
      let s = "a";
      for (let _for = 0; _for <= 3; ++_for) {
        s = "b";
      }
      return [
        s,
        s
      ];
    }
    … viaField compiles to the same
After (js): both return ["a", "b"]
    function viaAlias() {
      let s = "a";
      let o = Primitive_option.some(s);
      for (let _for = 0; _for <= 3; ++_for) {
        s = "b";
      }
      return [
        Primitive_option.valFromOption(o),
        s
      ];
    }

    function viaField() {
      let s = "a";
      let t_0 = s;
      for (let _for = 0; _for <= 3; ++_for) {
        s = "b";
      }
      return [
        t_0,
        s
      ];
    }

Review: Why also guard `Js.Null.toOption(x)` bindings? They record `x` the
same way, and the unwrap and the `null` test read it later just like a
`Some(x)` payload; no repro was found there, the guard keeps it sound.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Kbf3gHZYwA1rq7zbk3dhQq
Signed-off-by: Christoph Knittel <ck@cca.io>
Why:
    A call to another module's function that also passes a parameter of
    the caller is inlined late, while compiling to JavaScript, after the
    alias pass has run. So the inlined body kept what that pass removes
    elsewhere: a `Some(x)` argument was bound and unwrapped again, and a
    function argument was called instead of inlined. The alias pass now
    also runs on such a body before it is compiled.

JS modified (a literal Some next to a parameter):
Example:
    let knownSome = (x: int, f) => Some(x)->Option.map(f)->Option.getOr(0)
Before (js):
    function knownSome(x, f) {
      let opt = x;
      let opt$1 = opt !== undefined ? Primitive_option.some(f(Primitive_option.valFromOption(opt))) : undefined;
      if (opt$1 !== undefined) {
        return opt$1;
      } else {
        return 0;
      }
    }
After (js):
    function knownSome(x, f) {
      let opt = Primitive_option.some(f(x));
      if (opt !== undefined) {
        return opt;
      } else {
        return 0;
      }
    }

JS modified (a function argument):
Example:
    let mapped = (opt: option<int>) => opt->Option.map(x => x + 1)
Before (js):
    function mapped(opt) {
      if (opt !== undefined) {
        return Primitive_option.some((x => x + 1 | 0)(opt));
      }
    }
After (js):
    function mapped(opt) {
      if (opt !== undefined) {
        return Primitive_option.some(opt + 1 | 0);
      }
    }

Review: Why does the late pass get a fresh `ident_tbl`? The table was
filled by `collect_info` before `simplify_alias 3`, `simplify_lets`,
`sroa` and `simplify_exits` rewrote the program, so at codegen it can
give a function body or a `Some` payload naming a variable those passes
removed or turned into an assigned one: inlining a let-bound local
function from it printed `p + k` with no `k` in scope. The body is now
simplified knowing only the parameters it binds; the caller is still
compiled with the real `meta`.

Review: Which variables count as assigned there? The pass used to take
only the ones `lam` assigns, but at codegen `lam` is just the inlined
body, so a variable of the caller assigned by a call in it looked
immutable and its read moved past that call. The pass now starts from
`meta.assignable` as well. In the other direction, the pass may inline a
further function that assigns a variable of its own, so the variables
the body assigns are collected after the pass, before it is compiled.

Review: What stays? `Option.map` still wraps its result with
`Primitive_option.some`; that needs a mark on the result of the call.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Kbf3gHZYwA1rq7zbk3dhQq
Signed-off-by: Christoph Knittel <ck@cca.io>
…n't be undefined

Why:
    An inlined function such as `Option.map` is compiled for any `'b`, so
    the `Some(v)` it returns is `Primitive_option.some(v)`, in case `v` is
    itself `None`. The caller knows the result type. A `Some(v)` written at
    the call site is just `v` when the payload can't be `undefined`; the
    inlined copy now returns it the same way.

    The translation of a full application whose own type is `option<t>`,
    where `t` can't be `undefined`, sets a new flag on the call,
    `ap_result_not_nested`. The beta reduction that inlines a call takes
    the call's flag and rewrites the callee's body for it before it
    substitutes the arguments: a `Some` in return position is built without
    wrapping, and a call in return position gets the flag, so that a
    wrapper of `Option.map` is inlined the same way. The flag is part of
    the call, so a flagged call is still a call to every other pass, and a
    self tail call stays a loop. An `@inline` body in a `.cmj` keeps its
    calls' flags, so another module inlines it the same way.

Lambda modified (result of a call):
Example:
    let mapped = (opt: option<int>, f: int => int) => opt->Option.map(f)
Before (lambda):
    (function opt/1002 f/1003
      (apply (field:map/4 global Stdlib_Option!)
        (#not_nested_option opt/1002) f/1003))
After (lambda):
    (function opt/1002 f/1003
      (apply #result_not_nested (field:map/4 global Stdlib_Option!)
        (#not_nested_option opt/1002) f/1003))

Lambda modified (body inlined at a flagged call):
Example:
    let mapped = (opt: option<int>, f: int => int) => opt->Option.map(f)
Before (lambda): Option.map's body, before its arguments are substituted
    (if (#is_not_none opt/1002)
      (some (apply f/1003 (#val_from_option_not_nest opt/1002)))
      undefined)
After (lambda):
    (if (#is_not_none opt/1002)
      (some_not_nest (apply f/1003 (#val_from_option_not_nest opt/1002)))
      undefined)

JS modified (inlined Option.map):
Example:
    let mapped = (opt: option<int>, f: int => int) => opt->Option.map(f)
    let nested = (opt: option<int>) => opt->Option.map(x => x > 0 ? Some(x) : None)
Before (js):
    function mapped(opt, f) {
      if (opt !== undefined) {
        return Primitive_option.some(f(opt));
      }
    }

    function nested(opt) {
      if (opt === undefined) {
        return;
      }
      let x = opt;
      return Primitive_option.some(x > 0 ? x : undefined);
    }
After (js):
    function mapped(opt, f) {
      if (opt !== undefined) {
        return f(opt);
      }
    }

    function nested(opt) {
      if (opt === undefined) {
        return;
      }
      let x = opt;
      return Primitive_option.some(x > 0 ? x : undefined);
    }

JS modified (a chain of Option helpers):
Example:
    let knownSome = (x: int, f) => Some(x)->Option.map(f)->Option.getOr(0)
Before (js):
    function knownSome(x, f) {
      let opt = Primitive_option.some(f(x));
      if (opt !== undefined) {
        return opt;
      } else {
        return 0;
      }
    }
After (js):
    function knownSome(x, f) {
      let opt = f(x);
      if (opt !== undefined) {
        return opt;
      } else {
        return 0;
      }
    }

Review: Why is it sound to trust the caller's type? The rewrite trusts the
type of the call itself, never the type an argument is used at, which a
cast can change. The flag has its own place on the call, so the argument
mark of #9504 is never read as one: `isSome(magic(opt->Option.map(f)))`
leaves the cast call's wrapping alone. The body is rewritten before the
arguments are substituted, so only its own `Some`s and calls are: a cast
argument that the body returns, as in `keep(magic(g(a)), true)` with
`keep = (o, _) => o`, keeps its wrapping. A `switch` at the call site on a
value of the call's type already reads the payload directly, so a body
that returned a wrapped or `undefined` payload under that type, through a
cast or an external, would already break the caller; such a body inlined
here now returns the payload as a `Some` written here would. A cast of
the called function counts the same way, since the call's type comes from
the function's type: with `callOpt = (g: int => option<int>, a) => g(a)`,
`callOpt(magic(nestedPositive), a)` inlines `nestedPositive`, of type
`int => option<option<int>>`, at the call `g(a)`, and returns its payload
unwrapped.

Review: Does the flag get in the way of other optimizations? No: a
flagged call is still a call, so no pass needs to look through a mark. The
tests' forwarding function, `let x = e; f(x)` and a tuple bound before a
call compile without a temporary, and a self tail call is still a loop.
Apart from the dropped `Primitive_option.some` calls, the generated
JavaScript of the tests, the runtime and Belt doesn't change.

Review: Why keep the flag in a `.cmj`? It is a fact about the call's
value at the types of the module that wrote it, so it holds wherever the
body is inlined. Without it, `let v = (o, f) => Inline_export.mapPair(o, f)`
in the tests returned `Primitive_option.some(f(o))`: the call to
`Option.map` in `mapPair` reads parameters, so it is inlined only after
the body is exported.

Review: Is a flagged call a marked argument? Yes: an argument whose own
call is flagged is an option whose payload can't be `undefined`, by that
call's type, so the inlined body unwraps the parameter it is bound to
directly, as for an argument marked by its type.

Review: What does it cost to compile? Each full application checks its
result type the way #9504 checks arguments: abbreviations are read from
their declarations first, and a built-in type such as `int` or `unit` is
known to be no option without a lookup, which saves the lookups #9504
made for such arguments too. Compiling the runtime and Belt allocates
0.8% fewer words in all; Belt's list and sorted array modules 2.5% fewer;
no module more than 0.15% more.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Kbf3gHZYwA1rq7zbk3dhQq
Signed-off-by: Christoph Knittel <ck@cca.io>
Why:
    Two more places moved a read of a module field past an assignment to
    the variable holding the module, reachable through cross-module
    `@inline` bodies. The alias pass substituted a tuple element recorded
    as `M.x` with `M` a variable, and the alias check that lets single-use
    bindings be inlined accepted `M.x` for any variable `M`. Both now check
    the variable like any other.

JS modified (cross-module @inline, module field):
Example:
    // Other.res
    module type S = {
      let x: string
    }
    module A = {
      let x = "a"
    }
    module B = {
      let x = "b"
    }
    let get = (m: module(S)) => {
      let module(M) = m
      M.x
    }
    @inline
    let f = (n: int, q: module(S), q2: module(S)) => {
      let s = ref(q)
      let a = get(s.contents)
      for _ in 0 to n {
        s := q2
      }
      (a, get(s.contents))
    }

    // Main.res
    let main = () => Other.f(3, module(Other.A), module(Other.B))
Before (js): returns ["b", "b"]
    function main() {
      let s = Other.A;
      for (let _for = 0; _for <= 3; ++_for) {
        s = Other.B;
      }
      return [
        s.x,
        s.x
      ];
    }
After (js): returns ["a", "b"]
    function main() {
      let s = Other.A;
      let a = s.x;
      for (let _for = 0; _for <= 3; ++_for) {
        s = Other.B;
      }
      return [
        a,
        s.x
      ];
    }

JS modified (cross-module @inline, tuple of a module field):
Example:
    // Other.res, with S, A and B as above
    @inline
    let f = (n: int, q: module(S), q2: module(S)) => {
      let s = ref(q)
      let t = (
        {
          let module(M) = s.contents
          M.x
        },
        1,
      )
      for _ in 0 to n {
        s := q2
      }
      let (a, _) = t
      let module(M2) = s.contents
      (a, M2.x)
    }

    // Main.res
    let main = () => Other.f(3, module(Other.A), module(Other.B))
Before (js): returns ["b", "b"]
    function main() {
      let s = Other.A;
      for (let _for = 0; _for <= 3; ++_for) {
        s = Other.B;
      }
      let M2 = s;
      return [
        s.x,
        M2.x
      ];
    }
After (js): returns ["a", "b"]
    function main() {
      let s = Other.A;
      let t_0 = s.x;
      for (let _for = 0; _for <= 3; ++_for) {
        s = Other.B;
      }
      let M2 = s;
      return [
        t_0,
        M2.x
      ];
    }

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Kbf3gHZYwA1rq7zbk3dhQq
Signed-off-by: Christoph Knittel <ck@cca.io>
@github-actions

github-actions Bot commented Dec 5, 2026

Copy link
Copy Markdown

Changelog

🐛 Bug fix

  • Fix a field of a first-class module held in a ref, in a function inlined from another module, being read from the module the ref is set to later.
  • Fix the payload of a Some or a tuple field, made from a variable that is assigned later, giving the variable's new value.

💅 Polish

  • Return the result of an inlined function such as Option.map without Primitive_option.some when the caller's type says the payload cannot be undefined; a cast or external inside the inlined function, or a cast of the function itself at the call site, that hides an undefined payload, as in Some(a->Array.getUnsafe(5)), now behaves as the same Some written at the call site.
  • Simplify the body of a function from another module that is inlined while compiling to JavaScript, so a Some(x) argument is read directly and a function argument applied in the body is inlined.

Semantic Diff

4 commits · Full page

Keep a Some or tuple payload read before its variable is assigned

a507341 · cknitt + Claude · Dec 04, 2026, 21:39 UTC

Why

The alias pass replaced the payload of a variable known to be Some(x), and a field of one known to be (x, _), with x itself. When x is assigned between the binding and the read, the read gets the new value. Since #9022 substituted Some(x) payloads, this is reachable through cross-module @inline bodies, which are stored after Lam_pass_sroa turned their refs into assigned variables. The pass now keeps the binding when the variable is assigned.

JS modified (cross-module @inline)

// Other.res
@inline
let f = (n: int, q: 'a, q2: 'a) => {
  let s = ref(q)
  let o = Some(s.contents)
  for _ in 0 to n {
    s := q2
  }
  switch o {
  | Some(v) => Some((v, s.contents))
  | None => None
  }
}
@inline
let g = (n: int, q: 'a, q2: 'a) => {
  let s = ref(q)
  let t = (s.contents, 1)
  for _ in 0 to n {
    s := q2
  }
  let (a, _) = t
  (a, s.contents)
}

// Main.res
let viaAlias = () => Other.f(3, "a", "b")
let viaField = () => Other.g(3, "a", "b")

js · Before: both return ["b", "b"] · After: both return ["a", "b"]

 function viaAlias() {
   let s = "a";
+  let o = Primitive_option.some(s);
   for (let _for = 0; _for <= 3; ++_for) {
     s = "b";
   }
   return [
-    s,
+    Primitive_option.valFromOption(o),
     s
   ];
 }
-… viaField compiles to the same
+
+function viaField() {
+  let s = "a";
+  let t_0 = s;
+  for (let _for = 0; _for <= 3; ++_for) {
+    s = "b";
+  }
+  return [
+    t_0,
+    s
+  ];
+}

Review

  • Why also guard Js.Null.toOption(x) bindings? They record x the same way, and the unwrap and the null test read it later just like a Some(x) payload; no repro was found there, the guard keeps it sound.
Simplify bodies inlined while compiling to JavaScript

9af8bb9 · cknitt + Claude · Dec 04, 2026, 17:58 UTC

Why

A call to another module's function that also passes a parameter of the caller is inlined late, while compiling to JavaScript, after the alias pass has run. So the inlined body kept what that pass removes elsewhere: a Some(x) argument was bound and unwrapped again, and a function argument was called instead of inlined. The alias pass now also runs on such a body before it is compiled.

JS modified (a literal Some next to a parameter)

let knownSome = (x: int, f) => Some(x)->Option.map(f)->Option.getOr(0)

js

 function knownSome(x, f) {
-  let opt = x;
-  let opt$1 = opt !== undefined ? Primitive_option.some(f(Primitive_option.valFromOption(opt))) : undefined;
-  if (opt$1 !== undefined) {
-    return opt$1;
+  let opt = Primitive_option.some(f(x));
+  if (opt !== undefined) {
+    return opt;
   } else {
     return 0;
   }
 }

JS modified (a function argument)

let mapped = (opt: option<int>) => opt->Option.map(x => x + 1)

js

 function mapped(opt) {
   if (opt !== undefined) {
-    return Primitive_option.some((x => x + 1 | 0)(opt));
+    return Primitive_option.some(opt + 1 | 0);
   }
 }

Review

  • Why does the late pass get a fresh ident_tbl? The table was filled by collect_info before simplify_alias 3, simplify_lets, sroa and simplify_exits rewrote the program, so at codegen it can give a function body or a Some payload naming a variable those passes removed or turned into an assigned one: inlining a let-bound local function from it printed p + k with no k in scope. The body is now simplified knowing only the parameters it binds; the caller is still compiled with the real meta.
  • Which variables count as assigned there? The pass used to take only the ones lam assigns, but at codegen lam is just the inlined body, so a variable of the caller assigned by a call in it looked immutable and its read moved past that call. The pass now starts from meta.assignable as well. In the other direction, the pass may inline a further function that assigns a variable of its own, so the variables the body assigns are collected after the pass, before it is compiled.
  • What stays? Option.map still wraps its result with Primitive_option.some; that needs a mark on the result of the call.
Return Some of inlined functions without wrapping when the payload can't be undefined

93beda8 · cknitt + Claude · Dec 04, 2026, 18:18 UTC

Why

An inlined function such as Option.map is compiled for any 'b, so the Some(v) it returns is Primitive_option.some(v), in case v is itself None. The caller knows the result type. A Some(v) written at the call site is just v when the payload can't be undefined; the inlined copy now returns it the same way.

The translation of a full application whose own type is option<t>, where t can't be undefined, sets a new flag on the call, ap_result_not_nested. The beta reduction that inlines a call takes the call's flag and rewrites the callee's body for it before it substitutes the arguments: a Some in return position is built without wrapping, and a call in return position gets the flag, so that a wrapper of Option.map is inlined the same way. The flag is part of the call, so a flagged call is still a call to every other pass, and a self tail call stays a loop. An @inline body in a .cmj keeps its calls' flags, so another module inlines it the same way.

Lambda modified (result of a call)

let mapped = (opt: option<int>, f: int => int) => opt->Option.map(f)

lambda

 (function opt/1002 f/1003
-  (apply (field:map/4 global Stdlib_Option!)
+  (apply #result_not_nested (field:map/4 global Stdlib_Option!)
     (#not_nested_option opt/1002) f/1003))

Lambda modified (body inlined at a flagged call)

let mapped = (opt: option<int>, f: int => int) => opt->Option.map(f)

lambda · Before: Option.map's body, before its arguments are substituted

 (if (#is_not_none opt/1002)
-  (some (apply f/1003 (#val_from_option_not_nest opt/1002)))
+  (some_not_nest (apply f/1003 (#val_from_option_not_nest opt/1002)))
   undefined)

JS modified (inlined Option.map)

let mapped = (opt: option<int>, f: int => int) => opt->Option.map(f)
let nested = (opt: option<int>) => opt->Option.map(x => x > 0 ? Some(x) : None)

js

 function mapped(opt, f) {
   if (opt !== undefined) {
-    return Primitive_option.some(f(opt));
+    return f(opt);
   }
 }
 
 function nested(opt) {
   if (opt === undefined) {
     return;
   }
   let x = opt;
   return Primitive_option.some(x > 0 ? x : undefined);
 }

JS modified (a chain of Option helpers)

let knownSome = (x: int, f) => Some(x)->Option.map(f)->Option.getOr(0)

js

 function knownSome(x, f) {
-  let opt = Primitive_option.some(f(x));
+  let opt = f(x);
   if (opt !== undefined) {
     return opt;
   } else {
     return 0;
   }
 }

Review

  • Why is it sound to trust the caller's type? The rewrite trusts the type of the call itself, never the type an argument is used at, which a cast can change. The flag has its own place on the call, so the argument mark of Unwrap option arguments of inlined functions directly when they can't be nested #9504 is never read as one: isSome(magic(opt->Option.map(f))) leaves the cast call's wrapping alone. The body is rewritten before the arguments are substituted, so only its own Somes and calls are: a cast argument that the body returns, as in keep(magic(g(a)), true) with keep = (o, _) => o, keeps its wrapping. A switch at the call site on a value of the call's type already reads the payload directly, so a body that returned a wrapped or undefined payload under that type, through a cast or an external, would already break the caller; such a body inlined here now returns the payload as a Some written here would. A cast of the called function counts the same way, since the call's type comes from the function's type: with callOpt = (g: int => option<int>, a) => g(a), callOpt(magic(nestedPositive), a) inlines nestedPositive, of type int => option<option<int>>, at the call g(a), and returns its payload unwrapped.
  • Does the flag get in the way of other optimizations? No: a flagged call is still a call, so no pass needs to look through a mark. The tests' forwarding function, let x = e; f(x) and a tuple bound before a call compile without a temporary, and a self tail call is still a loop. Apart from the dropped Primitive_option.some calls, the generated JavaScript of the tests, the runtime and Belt doesn't change.
  • Why keep the flag in a .cmj? It is a fact about the call's value at the types of the module that wrote it, so it holds wherever the body is inlined. Without it, let v = (o, f) => Inline_export.mapPair(o, f) in the tests returned Primitive_option.some(f(o)): the call to Option.map in mapPair reads parameters, so it is inlined only after the body is exported.
  • Is a flagged call a marked argument? Yes: an argument whose own call is flagged is an option whose payload can't be undefined, by that call's type, so the inlined body unwraps the parameter it is bound to directly, as for an argument marked by its type.
  • What does it cost to compile? Each full application checks its result type the way Unwrap option arguments of inlined functions directly when they can't be nested #9504 checks arguments: abbreviations are read from their declarations first, and a built-in type such as int or unit is known to be no option without a lookup, which saves the lookups Unwrap option arguments of inlined functions directly when they can't be nested #9504 made for such arguments too. Compiling the runtime and Belt allocates 0.8% fewer words in all; Belt's list and sorted array modules 2.5% fewer; no module more than 0.15% more.
Keep module field reads before their variable is assigned

a3d2b7f · cknitt + Claude · Dec 05, 2026, 07:36 UTC

Why

Two more places moved a read of a module field past an assignment to the variable holding the module, reachable through cross-module @inline bodies. The alias pass substituted a tuple element recorded as M.x with M a variable, and the alias check that lets single-use bindings be inlined accepted M.x for any variable M. Both now check the variable like any other.

JS modified (cross-module @inline, module field)

// Other.res
module type S = {
  let x: string
}
module A = {
  let x = "a"
}
module B = {
  let x = "b"
}
let get = (m: module(S)) => {
  let module(M) = m
  M.x
}
@inline
let f = (n: int, q: module(S), q2: module(S)) => {
  let s = ref(q)
  let a = get(s.contents)
  for _ in 0 to n {
    s := q2
  }
  (a, get(s.contents))
}

// Main.res
let main = () => Other.f(3, module(Other.A), module(Other.B))

js · Before: returns ["b", "b"] · After: returns ["a", "b"]

 function main() {
   let s = Other.A;
+  let a = s.x;
   for (let _for = 0; _for <= 3; ++_for) {
     s = Other.B;
   }
   return [
-    s.x,
+    a,
     s.x
   ];
 }

JS modified (cross-module @inline, tuple of a module field)

// Other.res, with S, A and B as above
@inline
let f = (n: int, q: module(S), q2: module(S)) => {
  let s = ref(q)
  let t = (
    {
      let module(M) = s.contents
      M.x
    },
    1,
  )
  for _ in 0 to n {
    s := q2
  }
  let (a, _) = t
  let module(M2) = s.contents
  (a, M2.x)
}

// Main.res
let main = () => Other.f(3, module(Other.A), module(Other.B))

js · Before: returns ["b", "b"] · After: returns ["a", "b"]

 function main() {
   let s = Other.A;
+  let t_0 = s.x;
   for (let _for = 0; _for <= 3; ++_for) {
     s = Other.B;
   }
   let M2 = s;
   return [
-    s.x,
+    t_0,
     M2.x
   ];
 }

@cknitt
cknitt changed the base branch from master to option-result-mark December 5, 2026 07:56
@cknitt
cknitt added this pull request to stack #9532 December 5, 2026 07:56
@cknitt

cknitt commented Dec 5, 2026

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Dec 5, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-12-05T07:58:26.812745Z a3d2b7f Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Delightful!

Reviewed commit: a3d2b7fc11

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@github-actions

github-actions Bot commented Dec 5, 2026

Copy link
Copy Markdown

✅ Compiler benchmarks

Allocated words

In total: 662,217,620 → 662,407,012 (+0.03%).

Generated projects: 629,143,711 → 629,189,107 (+0.01%).

Benchmark Base Head Change
packages/@rescript/belt/src/Belt_internalAVLtree.res 3,406,828 3,411,145 +0.13%
packages/@rescript/runtime/Stdlib_Result.res 1,250,269 1,251,844 +0.13%
packages/@rescript/belt/src/Belt_Set.res 838,349 839,309 +0.11%
packages/@rescript/belt/src/Belt_internalAVLset.res 2,800,755 2,803,753 +0.11%
packages/@rescript/belt/src/Belt_internalMapInt.res 1,404,697 1,406,176 +0.11%
packages/@rescript/belt/src/Belt_internalMapString.res 1,406,532 1,408,011 +0.11%
packages/@rescript/belt/src/Belt_Map.res 959,368 960,328 +0.10%

Instructions

In total: 8,978,834,591 → 8,979,187,110 (±0.00%).

None of the 33 benchmarks changed by 0.1% or more.

Output size

In total: 27,774,377 → 27,774,408 (±0.00%).

None of the 13 benchmarks changed by 0.1% or more.

Pull request a3d2b7f compared with base 93beda8 in this run.

@codecov

codecov Bot commented Dec 5, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 82.67%. Comparing base (93beda8) to head (a3d2b7f).

Additional details and impacted files
@@                  Coverage Diff                   @@
##           option-result-mark    #9534      +/-   ##
======================================================
- Coverage               82.67%   82.67%   -0.01%     
======================================================
  Files                     469      469              
  Lines                   66662    66626      -36     
======================================================
- Hits                    55115    55082      -33     
+ Misses                  11547    11544       -3     
Files with missing lines Coverage Δ
compiler/backend/lam_pass_remove_alias.ml 93.70% <100.00%> (-0.09%) ⬇️
compiler/backend/lam_util.ml 94.44% <100.00%> (+0.07%) ⬆️

... and 9 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@pkg-pr-new

pkg-pr-new Bot commented Dec 5, 2026

Copy link
Copy Markdown

Open in StackBlitz

rescript

npm i https://pkg.pr.new/rescript@9534

@rescript/belt

npm i https://pkg.pr.new/@rescript/belt@9534

@rescript/darwin-arm64

npm i https://pkg.pr.new/@rescript/darwin-arm64@9534

@rescript/linux-arm64

npm i https://pkg.pr.new/@rescript/linux-arm64@9534

@rescript/linux-x64

npm i https://pkg.pr.new/@rescript/linux-x64@9534

@rescript/runtime

npm i https://pkg.pr.new/@rescript/runtime@9534

@rescript/win32-x64

npm i https://pkg.pr.new/@rescript/win32-x64@9534

commit: a3d2b7f

@cknitt
cknitt removed this pull request from stack #9532 December 5, 2026 10:18
@cknitt
cknitt force-pushed the option-result-mark branch from 93beda8 to 1c5cac6 Compare December 5, 2026 10:18
@cknitt

cknitt commented Dec 5, 2026

Copy link
Copy Markdown
Member Author

Superseded by stack #9541. #9535 fixes #9533 at the source: bodies that update a local ref are no longer stored for other modules, so the module-field guards have nothing left to catch. The repros moved into #9535's tests. (Comment by Claude.)

@cknitt cknitt closed this Dec 5, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant