Skip to content

Unwrap option arguments of inlined functions directly when they can't be nested - #9504

Draft
cknitt wants to merge 3 commits into
masterfrom
option-not-nested
Draft

cknitt wants to merge 3 commits into
masterfrom
option-not-nested

Conversation

@cknitt

@cknitt cknitt commented Dec 1, 2026 •

Copy link
Copy Markdown
Member

Follow-up from #8733. An inlined function such as Option.getOr is compiled for any 'a, so its body unwraps its option with Primitive_option.valFromOption, in case the payload is itself an option. The call site knows the payload type, so the inlined copy can now read the value directly, like a switch written there.

How it works:

  • The translation of a call wraps each option argument whose payload type can't be undefined in an identity primitive, Pnot_nested_option.
  • When the call is inlined, Lam_beta_reduce rewrites valFromOption(param) in the inlined body to Pval_from_option_not_nest(param) (a plain read) for marked parameters, marks the parameter again where the body passes it to another call, and substitutes the argument without the mark.
  • A mark compiles to nothing, so calls that aren't inlined compile as before.

The fact is kept per call, not per variable. f((Obj.magic(y): option<int>)) or a coercion translates to plain y. Recording y itself as not nested would break a correct switch y elsewhere. A local prototype did that; the new test has a case for it.

// let intOr = (opt: option<int>) => opt->Option.getOr(0)
// before
return Primitive_option.valFromOption(opt);
// after
return opt;

Nested options, Nullable.t payloads and generic 'a keep valFromOption.

Tests: new inline_option_unwrap_test (direct reads, other modules' functions with parameter arguments, a generic wrapper, a variable bound to Nullable.toOption, payloads that can be undefined, the cast case). Seven existing outputs lose valFromOption calls.

Left for later: Option.map still wraps its result with Primitive_option.some, because the body doesn't know the result type either. That needs a second mark, on the result.

🤖 Generated with Claude Code

https://claude.ai/code/session_01Kbf3gHZYwA1rq7zbk3dhQq

… be nested

Why:
    An inlined function such as `Option.getOr` is compiled for any `'a`, so
    its body unwraps its option with `Primitive_option.valFromOption`, in
    case the payload is itself an option. The caller knows the payload type.
    A `switch` written at the call site reads the value directly when the
    payload can't be `undefined`; the inlined copy now does the same.

    The translation of a call marks each option argument whose payload type
    can't be `undefined` with an identity primitive, `Pnot_nested_option`.
    When the call is inlined, the body is rewritten for that call: unwrapping
    a marked parameter becomes a plain read. The marks are dropped after the
    last inlining pass.

Lambda added (Pnot_nested_option):
Example:
    let intOr = (opt: option<int>) => opt->Option.getOr(0)
Before (lambda):
    (function opt/1002
      (apply (field:getOr/6 global Stdlib_Option!) opt/1002 0))
After (lambda):
    (function opt/1002
      (apply (field:getOr/6 global Stdlib_Option!)
        (#not_nested_option opt/1002) 0))

JS modified (an inlined Option helper):
Example:
    let intOr = (opt: option<int>) => opt->Option.getOr(0)
    let nestedOr = (opt: option<option<int>>) => opt->Option.getOr(Some(0))
Before (js):
    function intOr(opt) {
      if (opt !== undefined) {
        return Primitive_option.valFromOption(opt);
      } else {
        return 0;
      }
    }

    function nestedOr(opt) {
      if (opt !== undefined) {
        return Primitive_option.valFromOption(opt);
      } else {
        return 0;
      }
    }
After (js):
    function intOr(opt) {
      if (opt !== undefined) {
        return opt;
      } else {
        return 0;
      }
    }

    function nestedOr(opt) {
      if (opt !== undefined) {
        return Primitive_option.valFromOption(opt);
      } else {
        return 0;
      }
    }

Review: Why is the fact kept per call and not per variable? A variable
can reach a call with a type of its own: `f((Obj.magic(y): option<int>))`
or a coercion translates to plain `y`. Recording `y` as not nested would
also turn a correct `switch y` elsewhere into a plain read. So only the
inlined body is rewritten, and `y` keeps `valFromOption` everywhere else.

Review: What stays? `Option.map` still wraps its result with
`Primitive_option.some`, since the body doesn't know the result type
either. That needs a second mark, on the result, and is left for later.

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 1, 2026 •

Copy link
Copy Markdown

Changelog

💅 Polish

  • Inlined functions such as Option.getOr and Option.map no longer call
    Primitive_option.valFromOption on an argument whose payload cannot be undefined.

Semantic Diff

3 commits · Full page

Unwrap option arguments of inlined functions directly when they can't be nested

a717faf · cknitt + Claude · Dec 01, 2026, 21:29 UTC

Why

An inlined function such as Option.getOr is compiled for any 'a, so its body unwraps its option with Primitive_option.valFromOption, in case the payload is itself an option. The caller knows the payload type. A switch written at the call site reads the value directly when the payload can't be undefined; the inlined copy now does the same.

The translation of a call marks each option argument whose payload type can't be undefined with an identity primitive, Pnot_nested_option. When the call is inlined, the body is rewritten for that call: unwrapping a marked parameter becomes a plain read. The marks are dropped after the last inlining pass.

Lambda added (Pnot_nested_option)

let intOr = (opt: option<int>) => opt->Option.getOr(0)

lambda

 (function opt/1002
-  (apply (field:getOr/6 global Stdlib_Option!) opt/1002 0))
+  (apply (field:getOr/6 global Stdlib_Option!)
+    (#not_nested_option opt/1002) 0))

JS modified (an inlined Option helper)

let intOr = (opt: option<int>) => opt->Option.getOr(0)
let nestedOr = (opt: option<option<int>>) => opt->Option.getOr(Some(0))

js

 function intOr(opt) {
   if (opt !== undefined) {
-    return Primitive_option.valFromOption(opt);
+    return opt;
   } else {
     return 0;
   }
 }
 
 function nestedOr(opt) {
   if (opt !== undefined) {
     return Primitive_option.valFromOption(opt);
   } else {
     return 0;
   }
 }

Review

  • Why is the fact kept per call and not per variable? A variable can reach a call with a type of its own: f((Obj.magic(y): option<int>)) or a coercion translates to plain y. Recording y as not nested would also turn a correct switch y elsewhere into a plain read. So only the inlined body is rewritten, and y keeps valFromOption everywhere else.
  • What stays? Option.map still wraps its result with Primitive_option.some, since the body doesn't know the result type either. That needs a second mark, on the result, and is left for later.
Keep known option values and cross-module inlining with marked arguments

88fa108 · cknitt + Claude · Dec 02, 2026, 06:28 UTC

Why

A review found three gaps in the first commit. Rewriting the unwrap to the bare parameter skipped the rule that reads the value a known option was built from, so let opt = Nullable.toOption(x) kept a wrapper variable. Each mark counted toward the inlining size, so small wrappers stopped being inlined. And calls to another module's function with a parameter as an argument are inlined only during JavaScript compilation, after the marks were gone, so opt->Option.getOr(default) kept valFromOption.

Now the unwrap becomes Pval_from_option_not_nest for a variable bound to a known option, the size ignores the mark, the marks stay on the arguments of calls to other modules' functions, and the inlining guard treats a marked parameter like a plain one.

JS modified (another module's function with a parameter argument)

let paramOr = (opt: option<int>, default) => opt->Option.getOr(default)

js

 function paramOr(opt, $$default) {
   if (opt !== undefined) {
-    return Primitive_option.valFromOption(opt);
+    return opt;
   } else {
     return $$default;
   }
 }

JS modified (a variable bound to a nullable conversion)

type r = {input: string}
@send external exec: (string, string) => Nullable.t<r> = "exec"
let r1 = (s: string) => {
  let result = exec(s, s)->Nullable.toOption
  (result->Option.map(x => x.input), result->Option.map(x => x.input ++ "a"))
}

js

 function r1(s) {
   let result = s.exec(s);
-  let result$1 = result == null ? undefined : Primitive_option.some(result);
   return [
-    !(result == null) ? Primitive_option.some(result$1.input) : undefined,
-    !(result == null) ? Primitive_option.some(result$1.input + "a") : undefined
+    !(result == null) ? Primitive_option.some(result.input) : undefined,
+    !(result == null) ? Primitive_option.some(result.input + "a") : undefined
   ];
 }
✨ Keep option marks to the end and pass them through forwarding calls

ae67fff · cknitt + Claude · Dec 02, 2026, 07:36 UTC · new

Why

A second review found a simpler design and a regression. The marks no longer need removing: a mark compiles to nothing, and the passes after inlining don't look at the shape of call arguments. So the strip pass goes, and the unwrap always becomes Pval_from_option_not_nest, which the alias pass still resolves for a variable bound to a known option.

The regression: simple_beta_reduce refused a body whose call arguments were marked, so a small forwarding wrapper got temporaries for its arguments. It now substitutes through a mark. And an inlined body that passes a marked parameter on to another call marks it there too, so a generic wrapper of getOr reads the value directly as well.

JS modified (a forwarding wrapper)

@val external h: unit => option<int> = "h"
@val external k: unit => int = "k"
let w2 = (f, o: option<int>, d: int): int => f(o, d)
let useW2 = f => w2(f, h(), k())

js

 function useW2(f) {
-  let o = h();
-  let d = k();
-  return f(o, d);
+  return f(h(), k());
 }

JS modified (a generic wrapper)

@inline
let getOr = (opt, default) =>
  switch opt {
  | Some(v) => v
  | None => default
  }
let wrapOr = (opt, default) => getOr(opt, default)
let viaWrapper = (opt: option<int>) => wrapOr(opt, 0)

js

 function viaWrapper(opt) {
   if (opt !== undefined) {
-    return Primitive_option.valFromOption(opt);
+    return opt;
   } else {
     return 0;
   }
 }

@codecov

codecov Bot commented Dec 1, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 62.82051% with 29 lines in your changes missing coverage. Please review.
✅ Project coverage is 82.54%. Comparing base (69e11bf) to head (ae67fff).
⚠️ Report is 5 commits behind head on master.

Files with missing lines Patch % Lines
compiler/backend/lam_analysis.ml 6.25% 15 Missing ⚠️
compiler/typing/lambda.ml 50.00% 9 Missing ⚠️
compiler/backend/lam_beta_reduce_util.ml 60.00% 2 Missing ⚠️
compiler/typing/lambda_effects.ml 0.00% 1 Missing ⚠️
compiler/typing/printlambda.ml 0.00% 1 Missing ⚠️
compiler/typing/translcore.ml 92.85% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master    #9504      +/-   ##
==========================================
+ Coverage   82.49%   82.54%   +0.04%     
==========================================
  Files         467      469       +2     
  Lines       66125    66266     +141     
==========================================
+ Hits        54553    54696     +143     
+ Misses      11572    11570       -2     
Files with missing lines Coverage Δ
compiler/backend/lam_beta_reduce.ml 81.57% <100.00%> (+3.80%) ⬆️
compiler/backend/lam_compile_primitive.ml 81.49% <100.00%> (ø)
compiler/backend/lam_pass_remove_alias.ml 93.12% <100.00%> (+0.44%) ⬆️
compiler/typing/lambda_effects.ml 68.11% <0.00%> (-1.45%) ⬇️
compiler/typing/printlambda.ml 8.74% <0.00%> (-0.04%) ⬇️
compiler/typing/translcore.ml 88.54% <92.85%> (+0.03%) ⬆️
compiler/backend/lam_beta_reduce_util.ml 96.77% <60.00%> (-1.48%) ⬇️
compiler/typing/lambda.ml 69.82% <50.00%> (+0.14%) ⬆️
compiler/backend/lam_analysis.ml 70.00% <6.25%> (ø)

... and 18 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.

@github-actions

github-actions Bot commented Dec 1, 2026 •

Copy link
Copy Markdown

⚠️ Compiler benchmarks

Allocated words

In total: 652,201,961 → 653,531,691 (+0.20%).

Generated projects: 627,034,667 → 627,049,925 (±0.00%).

⚠️ Regression: 20 benchmarks allocate more than 1% more.

Benchmark Base Head Change
packages/@rescript/belt/src/Belt_SetInt.res 1,263,715 1,311,227 +3.76%
packages/@rescript/belt/src/Belt_SetString.res 1,264,444 1,311,956 +3.76%
packages/@rescript/belt/src/Belt_internalMapInt.res 1,368,904 1,414,315 +3.32%
packages/@rescript/belt/src/Belt_internalMapString.res 1,370,748 1,416,159 +3.31%
packages/@rescript/belt/src/Belt_internalSetInt.res 711,866 734,786 +3.22%
packages/@rescript/belt/src/Belt_internalSetString.res 713,057 735,977 +3.21%
packages/@rescript/belt/src/Belt_SetDict.res 1,415,624 1,457,385 +2.95%
packages/@rescript/belt/src/Belt_MutableMapInt.res 1,123,097 1,153,015 +2.66%
packages/@rescript/belt/src/Belt_MutableMapString.res 1,123,376 1,153,294 +2.66%
packages/@rescript/belt/src/Belt_MutableMap.res 1,264,085 1,294,034 +2.37%
38 more changes
Benchmark Base Head Change
packages/@rescript/belt/src/Belt_MapDict.res 1,593,620 1,630,944 +2.34%
packages/@rescript/belt/src/Belt_MutableSetInt.res 1,602,682 1,636,430 +2.11%
packages/@rescript/belt/src/Belt_MutableSetString.res 1,603,930 1,637,678 +2.10%
packages/@rescript/belt/src/Belt_internalAVLset.res 2,757,592 2,812,556 +1.99%
packages/@rescript/belt/src/Belt_MapInt.res 1,160,313 1,182,871 +1.94%
packages/@rescript/belt/src/Belt_MapString.res 1,160,856 1,183,414 +1.94%
packages/@rescript/belt/src/Belt_internalAVLtree.res 3,361,329 3,421,835 +1.80%
packages/@rescript/belt/src/Belt_MutableSet.res 1,830,069 1,862,688 +1.78%
packages/@rescript/belt/src/Belt_Map.res 953,461 968,507 +1.58%
packages/@rescript/belt/src/Belt_Set.res 833,330 844,610 +1.35%
packages/@rescript/belt/src/Belt_MutableQueue.res 763,526 768,361 +0.63%
packages/@rescript/belt/src/Belt_HashSetInt.res 823,291 828,501 +0.63%
packages/@rescript/belt/src/Belt_HashSetString.res 823,606 828,816 +0.63%
packages/@rescript/belt/src/Belt_internalBuckets.res 934,912 940,718 +0.62%
packages/@rescript/belt/src/Belt_SortArrayInt.res 1,269,988 1,277,829 +0.62%
packages/@rescript/belt/src/Belt_SortArrayString.res 1,271,783 1,279,624 +0.62%
packages/@rescript/runtime/Primitive_object.res 1,107,436 1,114,009 +0.59%
packages/@rescript/belt/src/Belt_SortArray.res 1,367,562 1,375,469 +0.58%
packages/@rescript/belt/src/Belt_HashMapInt.res 1,027,416 1,032,802 +0.52%
packages/@rescript/belt/src/Belt_HashMapString.res 1,028,128 1,033,514 +0.52%
packages/@rescript/belt/src/Belt_HashSet.res 946,444 951,165 +0.50%
packages/@rescript/belt/src/Belt_internalSetBuckets.res 679,996 683,228 +0.48%
packages/@rescript/belt/src/Belt_List.res 3,059,994 3,073,814 +0.45%
stress/InlineChain.res 3,385,050 3,400,027 +0.44%
packages/@rescript/belt/src/Belt_HashMap.res 1,161,005 1,165,913 +0.42%
packages/@rescript/belt/src/Belt_Array.res 2,034,549 2,039,362 +0.24%
packages/@rescript/belt/src/Belt_MutableStack.res 378,462 379,326 +0.23%
build/shared-edit 84,456,844 84,640,910 +0.22%
packages/@rescript/runtime/Primitive_module.res 326,801 327,462 +0.20%
build/leaf-edit 11,634,503 11,654,832 +0.17%
packages/@rescript/runtime/Primitive_option.res 288,355 288,853 +0.17%
packages/@rescript/runtime/Stdlib_AsyncIterableIterator.res 225,502 225,888 +0.17%
packages/@rescript/runtime/Primitive_hash.res 922,131 923,662 +0.17%
build/no-op 9,003,784 9,018,319 +0.16%
packages/@rescript/runtime/Stdlib_List.res 2,580,481 2,584,511 +0.16%
packages/@rescript/belt/src/Belt_Range.res 279,644 279,994 +0.13%
build/clean 254,372,078 254,646,426 +0.11%
stress/LetRec.res 26,331,044 26,359,071 +0.11%

Instructions

In total: 8,963,853,314 → 8,972,231,420 (+0.09%).

⚠️ Regression: 1 benchmark executes more than 1% more instructions.

Benchmark Base Head Change
packages/@rescript/belt/src/Belt_internalAVLtree.res 134,553,844 137,404,482 +2.12%
packages/@rescript/belt/src/Belt_List.res 116,691,956 117,492,152 +0.69%
stress/InlineChain.res 136,791,261 137,448,043 +0.48%
stress/LetRec.res 1,222,845,121 1,226,147,835 +0.27%
packages/@rescript/runtime/Stdlib_Math.resi 21,255,650 21,297,262 +0.20%
packages/@rescript/runtime/Stdlib_Temporal_PlainDate.res 24,089,675 24,131,866 +0.18%
packages/@rescript/runtime/Stdlib_Temporal_PlainDateTime.res 25,529,121 25,571,443 +0.17%
packages/@rescript/runtime/Stdlib_List.resi 24,448,782 24,481,355 +0.13%
packages/@rescript/runtime/Stdlib_Temporal_ZonedDateTime.res 31,220,497 31,260,929 +0.13%
parse/RedBlackTree.res 14,929,581 14,947,201 +0.12%
3 more changes
Benchmark Base Head Change
packages/@rescript/runtime/Stdlib_String.resi 29,396,522 29,430,718 +0.12%
parse/RedBlackTreeNoComments.res 14,521,425 14,537,799 +0.11%
packages/@rescript/belt/src/Belt_Array.resi 33,591,927 33,625,606 +0.10%

Output size

In total: 27,405,552 → 27,407,604 (+0.01%).

Benchmark Base Head Change
output/playground/compiler.js 1,900,575 1,902,627 +0.11%

Pull request ae67fff compared with base f570bfb in this run.

@pkg-pr-new

pkg-pr-new Bot commented Dec 1, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

rescript

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

@rescript/belt

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

@rescript/darwin-arm64

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

@rescript/linux-arm64

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

@rescript/linux-x64

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

@rescript/runtime

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

@rescript/win32-x64

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

commit: 88fa108

cknitt and others added 2 commits December 2, 2026 06:28
Why:
    A review found three gaps in the first commit. Rewriting the unwrap to
    the bare parameter skipped the rule that reads the value a known option
    was built from, so `let opt = Nullable.toOption(x)` kept a wrapper
    variable. Each mark counted toward the inlining size, so small wrappers
    stopped being inlined. And calls to another module's function with a
    parameter as an argument are inlined only during JavaScript compilation,
    after the marks were gone, so `opt->Option.getOr(default)` kept
    `valFromOption`.

    Now the unwrap becomes `Pval_from_option_not_nest` for a variable bound
    to a known option, the size ignores the mark, the marks stay on the
    arguments of calls to other modules' functions, and the inlining guard
    treats a marked parameter like a plain one.

JS modified (another module's function with a parameter argument):
Example:
    let paramOr = (opt: option<int>, default) => opt->Option.getOr(default)
Before (js):
    function paramOr(opt, $$default) {
      if (opt !== undefined) {
        return Primitive_option.valFromOption(opt);
      } else {
        return $$default;
      }
    }
After (js):
    function paramOr(opt, $$default) {
      if (opt !== undefined) {
        return opt;
      } else {
        return $$default;
      }
    }

JS modified (a variable bound to a nullable conversion):
Example:
    type r = {input: string}
    @send external exec: (string, string) => Nullable.t<r> = "exec"
    let r1 = (s: string) => {
      let result = exec(s, s)->Nullable.toOption
      (result->Option.map(x => x.input), result->Option.map(x => x.input ++ "a"))
    }
Before (js):
    function r1(s) {
      let result = s.exec(s);
      let result$1 = result == null ? undefined : Primitive_option.some(result);
      return [
        !(result == null) ? Primitive_option.some(result$1.input) : undefined,
        !(result == null) ? Primitive_option.some(result$1.input + "a") : undefined
      ];
    }
After (js):
    function r1(s) {
      let result = s.exec(s);
      return [
        !(result == null) ? Primitive_option.some(result.input) : undefined,
        !(result == null) ? Primitive_option.some(result.input + "a") : undefined
      ];
    }

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 second review found a simpler design and a regression. The marks no
    longer need removing: a mark compiles to nothing, and the passes after
    inlining don't look at the shape of call arguments. So the strip pass
    goes, and the unwrap always becomes `Pval_from_option_not_nest`, which
    the alias pass still resolves for a variable bound to a known option.

    The regression: `simple_beta_reduce` refused a body whose call arguments
    were marked, so a small forwarding wrapper got temporaries for its
    arguments. It now substitutes through a mark. And an inlined body that
    passes a marked parameter on to another call marks it there too, so a
    generic wrapper of `getOr` reads the value directly as well.

JS modified (a forwarding wrapper):
Example:
    @Val external h: unit => option<int> = "h"
    @Val external k: unit => int = "k"
    let w2 = (f, o: option<int>, d: int): int => f(o, d)
    let useW2 = f => w2(f, h(), k())
Before (js):
    function useW2(f) {
      let o = h();
      let d = k();
      return f(o, d);
    }
After (js):
    function useW2(f) {
      return f(h(), k());
    }

JS modified (a generic wrapper):
Example:
    @inline
    let getOr = (opt, default) =>
      switch opt {
      | Some(v) => v
      | None => default
      }
    let wrapOr = (opt, default) => getOr(opt, default)
    let viaWrapper = (opt: option<int>) => wrapOr(opt, 0)
Before (js):
    function viaWrapper(opt) {
      if (opt !== undefined) {
        return Primitive_option.valFromOption(opt);
      } else {
        return 0;
      }
    }
After (js):
    function viaWrapper(opt) {
      if (opt !== undefined) {
        return opt;
      } else {
        return 0;
      }
    }

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>

This branch has not been deployed

No deployments
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