Skip to content

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

Open
cknitt wants to merge 1 commit into
masterfrom
option-not-nested
Open

cknitt wants to merge 1 commit 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. Beta reduction substitutes through a mark, the inlining size ignores it, and the guard on inlining other modules' functions treats a marked parameter like a plain one, so the marks don't change other optimizations.

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; 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, type abbreviations of options, a variable bound to Nullable.toOption, payloads that can be undefined, the cast case). Seven existing outputs lose valFromOption calls.

Compile cost: each option argument gets a mark and the same payload check a switch on it does; type abbreviations are read from their declarations without instantiating them. Total allocated words +0.15%. The benchmarks check is red because Belt's set and map modules, which pass an option tree to nearly every call, allocate 1–2.5% more.

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.
  • Some(e) arguments and partial applications (f(a, ...)) aren't marked, so they keep valFromOption as on master.

🤖 Generated with Claude Code

https://claude.ai/code/session_01Kbf3gHZYwA1rq7zbk3dhQq

@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

1 commit · Full page

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

2bdce98 · cknitt + Claude · Dec 02, 2026, 09:44 UTC · edited

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 Pval_from_option_not_nest, a plain read, and a marked parameter the body passes to another call is marked there too. A mark compiles to nothing, so calls that aren't inlined don't change.

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 (inlined Option helpers)

let intOr = (opt: option<int>) => opt->Option.getOr(0)
let paramOr = (opt: option<int>, default) => opt->Option.getOr(default)
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 paramOr(opt, $$default) {
   if (opt !== undefined) {
-    return Primitive_option.valFromOption(opt);
+    return opt;
   } else {
     return $$default;
   }
 }
 
 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.
  • Do the marks get in the way of other optimizations? Beta reduction substitutes through a mark, the inlining size ignores it, and the guard on inlining other modules' functions treats a marked parameter like a plain one. Apart from the dropped valFromOption calls, the generated JavaScript doesn't change.
  • What does it cost to compile? Each call argument of an option type gets a mark and the payload check a switch on it does. Type abbreviations are read from their declarations first, and expanded only when that check fails or the declaration ends in a bare parameter, so arguments of other types cost almost nothing. Belt's tree modules, which pass an option to nearly every call, allocate 1–3% more words; Belt_List 0.1%.
  • 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.

@codecov

codecov Bot commented Dec 1, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 69.07216% with 30 lines in your changes missing coverage. Please review.
✅ Project coverage is 82.54%. Comparing base (69e11bf) to head (2bdce98).
⚠️ Report is 6 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/typing/translcore.ml 93.93% 2 Missing ⚠️
compiler/backend/lam_beta_reduce.ml 95.45% 1 Missing ⚠️
compiler/backend/lam_beta_reduce_util.ml 66.66% 1 Missing ⚠️
compiler/typing/lambda_effects.ml 0.00% 1 Missing ⚠️
compiler/typing/printlambda.ml 0.00% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master    #9504      +/-   ##
==========================================
+ Coverage   82.49%   82.54%   +0.04%     
==========================================
  Files         467      469       +2     
  Lines       66125    66286     +161     
==========================================
+ Hits        54553    54717     +164     
+ Misses      11572    11569       -3     
Files with missing lines Coverage Δ
compiler/backend/lam_compile_primitive.ml 81.49% <100.00%> (ø)
compiler/backend/lam_pass_remove_alias.ml 93.12% <100.00%> (+0.44%) ⬆️
compiler/backend/lam_beta_reduce.ml 81.03% <95.45%> (+3.25%) ⬆️
compiler/backend/lam_beta_reduce_util.ml 98.33% <66.66%> (+0.08%) ⬆️
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.69% <93.93%> (+0.17%) ⬆️
compiler/typing/lambda.ml 69.82% <50.00%> (+0.14%) ⬆️
compiler/backend/lam_analysis.ml 70.00% <6.25%> (ø)

... and 20 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,204,834 → 653,174,928 (+0.15%).

Generated projects: 627,042,871 → 627,058,283 (±0.00%).

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

Benchmark Base Head Change
packages/@rescript/belt/src/Belt_SetInt.res 1,263,715 1,295,289 +2.50%
packages/@rescript/belt/src/Belt_SetString.res 1,264,444 1,296,018 +2.50%
packages/@rescript/belt/src/Belt_SetDict.res 1,415,624 1,445,679 +2.12%
packages/@rescript/belt/src/Belt_internalSetInt.res 711,866 726,912 +2.11%
packages/@rescript/belt/src/Belt_internalSetString.res 713,057 728,103 +2.11%
packages/@rescript/belt/src/Belt_internalMapInt.res 1,368,904 1,395,865 +1.97%
packages/@rescript/belt/src/Belt_internalMapString.res 1,370,748 1,397,709 +1.97%
packages/@rescript/belt/src/Belt_MapDict.res 1,593,620 1,618,628 +1.57%
packages/@rescript/belt/src/Belt_MutableMapInt.res 1,123,097 1,137,930 +1.32%
packages/@rescript/belt/src/Belt_MutableMapString.res 1,123,376 1,138,209 +1.32%
29 more changes
Benchmark Base Head Change
packages/@rescript/belt/src/Belt_MutableMap.res 1,264,085 1,280,105 +1.27%
packages/@rescript/belt/src/Belt_internalAVLset.res 2,757,592 2,791,221 +1.22%
packages/@rescript/belt/src/Belt_MapInt.res 1,160,313 1,173,742 +1.16%
packages/@rescript/belt/src/Belt_MapString.res 1,160,856 1,174,285 +1.16%
packages/@rescript/belt/src/Belt_MutableSetInt.res 1,602,682 1,619,112 +1.03%
packages/@rescript/belt/src/Belt_MutableSetString.res 1,603,930 1,620,360 +1.02%
packages/@rescript/belt/src/Belt_internalAVLtree.res 3,361,329 3,394,602 +0.99%
packages/@rescript/belt/src/Belt_MutableSet.res 1,830,069 1,847,002 +0.93%
stress/InlineChain.res 3,385,050 3,401,227 +0.48%
packages/@rescript/runtime/Primitive_object.res 1,107,436 1,111,354 +0.35%
packages/@rescript/belt/src/Belt_SortArray.res 1,367,562 1,372,302 +0.35%
packages/@rescript/belt/src/Belt_MutableQueue.res 763,526 766,137 +0.34%
packages/@rescript/belt/src/Belt_SortArrayInt.res 1,269,988 1,273,758 +0.30%
packages/@rescript/belt/src/Belt_SortArrayString.res 1,271,783 1,275,553 +0.30%
build/shared-edit 84,457,627 84,635,474 +0.21%
packages/@rescript/runtime/Stdlib_List.res 2,580,481 2,585,655 +0.20%
packages/@rescript/belt/src/Belt_List.res 3,059,994 3,065,877 +0.19%
build/leaf-edit 11,634,643 11,655,272 +0.18%
build/no-op 9,003,895 9,019,732 +0.18%
packages/@rescript/belt/src/Belt_Range.res 279,644 280,102 +0.16%
packages/@rescript/belt/src/Belt_Map.res 953,461 954,960 +0.16%
packages/@rescript/belt/src/Belt_Set.res 833,330 834,599 +0.15%
packages/@rescript/belt/src/Belt_internalBuckets.res 934,912 936,247 +0.14%
stress/LetRec.res 26,331,044 26,367,075 +0.14%
packages/@rescript/belt/src/Belt_HashSet.res 946,444 947,739 +0.14%
packages/@rescript/belt/src/Belt_MutableStack.res 378,462 378,970 +0.13%
packages/@rescript/belt/src/Belt_HashMap.res 1,161,005 1,162,547 +0.13%
packages/@rescript/belt/src/Belt_internalSetBuckets.res 679,996 680,721 +0.11%
build/clean 254,373,917 254,636,643 +0.10%

Instructions

In total: 8,963,849,954 → 8,969,079,624 (+0.06%).

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

Benchmark Base Head Change
packages/@rescript/belt/src/Belt_internalAVLtree.res 134,553,704 136,054,219 +1.12%
packages/@rescript/runtime/Stdlib_Math.resi 21,255,510 21,322,582 +0.32%
stress/InlineChain.res 136,791,191 137,201,730 +0.30%
packages/@rescript/runtime/Stdlib_Temporal_PlainDate.res 24,089,535 24,160,426 +0.29%
packages/@rescript/runtime/Stdlib_List.resi 24,448,642 24,515,444 +0.27%
packages/@rescript/runtime/Stdlib_Temporal_PlainDateTime.res 25,528,981 25,598,593 +0.27%
packages/@rescript/belt/src/Belt_List.res 116,691,816 116,977,936 +0.25%
parse/RedBlackTree.res 14,929,511 14,965,054 +0.24%
parse/RedBlackTreeNoComments.res 14,521,355 14,555,021 +0.23%
packages/@rescript/runtime/Stdlib_String.resi 29,396,382 29,463,984 +0.23%
9 more changes
Benchmark Base Head Change
packages/@rescript/runtime/Stdlib_Temporal_ZonedDateTime.res 31,220,357 31,288,799 +0.22%
packages/@rescript/belt/src/Belt_Array.resi 33,591,787 33,659,960 +0.20%
packages/@rescript/belt/src/Belt_List.resi 38,781,223 38,848,601 +0.17%
packages/@rescript/runtime/Stdlib_Array.resi 39,963,603 40,030,768 +0.17%
packages/@rescript/runtime/Stdlib_TypedArray.res 41,314,030 41,381,874 +0.16%
packages/@rescript/runtime/Stdlib_Date.resi 34,206,008 34,260,578 +0.16%
format/RedBlackTreeNoComments.res 24,095,450 24,129,251 +0.14%
format/RedBlackTree.res 24,440,318 24,474,119 +0.14%
stress/LetRec.res 1,222,845,051 1,224,443,481 +0.13%

Output size

In total: 27,405,620 → 27,408,046 (+0.01%).

Benchmark Base Head Change
output/playground/compiler.js 1,900,643 1,903,069 +0.13%

Pull request 2bdce98 compared with base 653cfc0 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: 2bdce98

@cknitt
cknitt force-pushed the option-not-nested branch 2 times, most recently from cfe78d2 to 06215dc Compare December 2, 2026 10:13
@cknitt

cknitt commented Dec 2, 2026

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Dec 2, 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-02T18:18:57.306595Z 2bdce98 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. Bravo.

Reviewed commit: 06215dcdb2

ℹ️ 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".

@cknitt
cknitt force-pushed the option-not-nested branch from 06215dc to bf01388 Compare December 2, 2026 15:40
@cknitt

cknitt commented Dec 2, 2026

Copy link
Copy Markdown
Member Author

@codex review

… 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 `Pval_from_option_not_nest`, a plain read, and
    a marked parameter the body passes to another call is marked there too.
    A mark compiles to nothing, so calls that aren't inlined don't change.

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 (inlined Option helpers):
Example:
    let intOr = (opt: option<int>) => opt->Option.getOr(0)
    let paramOr = (opt: option<int>, default) => opt->Option.getOr(default)
    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 paramOr(opt, $$default) {
      if (opt !== undefined) {
        return Primitive_option.valFromOption(opt);
      } else {
        return $$default;
      }
    }

    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 paramOr(opt, $$default) {
      if (opt !== undefined) {
        return opt;
      } else {
        return $$default;
      }
    }

    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: Do the marks get in the way of other optimizations? Beta
reduction substitutes through a mark, the inlining size ignores it, and
the guard on inlining other modules' functions treats a marked parameter
like a plain one. Apart from the dropped `valFromOption` calls, the
generated JavaScript doesn't change.

Review: What does it cost to compile? Each call argument of an option
type gets a mark and the payload check a `switch` on it does. Type
abbreviations are read from their declarations first, and expanded only
when that check fails or the declaration ends in a bare parameter, so
arguments of other types cost almost nothing. Belt's tree modules, which
pass an option to nearly every call, allocate 1–3% more words;
`Belt_List` 0.1%.

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>
@cknitt
cknitt force-pushed the option-not-nested branch from bf01388 to 2bdce98 Compare December 2, 2026 17:58
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Another round soon, please!

Reviewed commit: 2bdce98658

ℹ️ 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".

@cknitt
cknitt marked this pull request as ready for review December 2, 2026 18:19
@cknitt
cknitt requested a review from cristianoc December 2, 2026 18:19

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