Skip to content

Return Some of inlined functions without wrapping when the payload can't be undefined - #9528

Open
cknitt wants to merge 1 commit into
no-late-inlinefrom
option-result-mark
Open

cknitt wants to merge 1 commit into
no-late-inlinefrom
option-result-mark

Conversation

@cknitt

@cknitt cknitt commented Dec 4, 2026 •

Copy link
Copy Markdown
Member

When an inlined function returns Some(v) and the caller's type says the payload can't be undefined, the inlined copy now returns v without Primitive_option.some.

Option.map is written once for every payload type, so its Some(f(x)) must wrap a payload that might be undefined. #9504 let inlined bodies read option arguments directly when the caller's type rules out nesting. This does the same for the result:

  • At translation, a call whose own result type is option<t>, where t can't be undefined, gets a flag on the call (ap_result_not_nested). Partial applications and externals aren't flagged.
  • The flag is kept in bodies stored for other modules, so they get the same result there.
  • When a flagged call is inlined, a Some in a return position of the body returns the value itself, and a call in a return position is flagged in turn, so wrappers around Option.map benefit too. Return positions are followed through if, switch, let bodies, sequences and try. This happens in both places that inline: the alias pass and the reduction of directly applied functions.
let mapped = (opt: option<int>, f: int => int) => opt->Option.map(f)

Before:

function mapped(opt, f) {
  if (opt !== undefined) {
    return Primitive_option.some(f(opt));
  }
}

After:

function mapped(opt, f) {
  if (opt !== undefined) {
    return f(opt);
  }
}

Soundness. The rewrite trusts only the call's own type. The caller's own switch on that call's result already reads the payload directly when t can't be undefined, so a body returning a wrapped or undefined payload under that type would already break the caller. Two things keep casts at the call site out:

  • The flag is its own field, not the argument mark from Unwrap option arguments of inlined functions directly when they can't be nested #9504. An argument mark comes from the type the argument is used at, which may be a cast, and could otherwise end up on a bare call once a block around it is simplified.
  • The body is rewritten before the arguments are substituted into it. So an argument that lands in return position, such as keep(magic(g(a))), keeps its wrapping.

A cast or an external hiding undefined inside the inlined function itself, as in Some(a->Array.getUnsafe(5)), now behaves like the same Some written at the call site. So does a cast of the function itself at the call site, as in callOpt(magic(f), a): the call's type comes from the function's type, and the cast is gone once compiled.

A flagged call is still a call, so self tail calls stay loops and no other pass needs to look through a mark.

Compile cost. Each full application checks its result type the way #9504 checks arguments, with a shortcut for built-in types such as int and unit that also saves #9504 lookups. Compiling the runtime and Belt allocates 0.2% more words in total, at most 0.8% for one module (Belt's mutable sets). The JavaScript of the runtime and Belt doesn't change.

Changed test outputs drop Primitive_option.some, in Option.map calls in the stdlib tests and in int_overflow_test, flat_make_export_test and inline_export_test. The new inline_option_result_test covers:

  • Option.map with a named function and a lambda;
  • a local @inline function returning Some through if, switch and try;
  • a wrapper around Option.map;
  • result types written as abbreviations;
  • payloads that must still wrap: nested options, Nullable and generic payloads;
  • casts at the call site that must keep the wrapping: a cast held in a block-bound variable, and cast arguments flowing to the result;
  • calls that still compile without temporaries: a forwarding function's arguments, let x = e; f(x), and a tuple bound before a call;
  • tail-recursive functions returning an option.

Stacked on #9537. Follow-up of #9504 (#8733).

🤖 Generated with Claude Code

https://claude.ai/code/session_01Kbf3gHZYwA1rq7zbk3dhQq

@cknitt
cknitt changed the base branch from master to late-inline-alias-pass December 4, 2026 18:37
@cknitt
cknitt added this pull request to stack #9529 December 4, 2026 18:37
@github-actions

github-actions Bot commented Dec 4, 2026 •

Copy link
Copy Markdown

Changelog

💅 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.

Semantic Diff

1 commit · Full page

Return Some of inlined functions without wrapping when the payload can't be undefined

6883faf · cknitt + Claude · Dec 05, 2026, 10:05 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 Primitive_option.some(opt > 0 ? opt : 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) {
-  return Primitive_option.some(f(x));
+  return f(x);
 }

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.
  • What about a flagged call passed as an argument? It gets the argument mark of Unwrap option arguments of inlined functions directly when they can't be nested #9504 from its type like any other argument, so the body it is passed to unwraps it directly. The two marks stay separate: the flag says what an inlined body may return, the argument mark what a parameter holds.
  • 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. Most calls in a stored body are inlined before it is stored, as Option.map in mapPair of the tests is, so the flag is rarely needed there, but keeping it costs nothing.
  • 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.2% more words in all, at most 0.8% more for one module (Belt's mutable sets).

@codecov

codecov Bot commented Dec 4, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 76.34409% with 22 lines in your changes missing coverage. Please review.
✅ Project coverage is 82.63%. Comparing base (de87d9a) to head (6883faf).

Files with missing lines Patch % Lines
compiler/backend/lam_beta_reduce.ml 56.25% 21 Missing ⚠️
compiler/typing/printlambda.ml 0.00% 1 Missing ⚠️
Additional details and impacted files
@@                Coverage Diff                 @@
##           no-late-inline    #9528      +/-   ##
==================================================
- Coverage           82.65%   82.63%   -0.02%     
==================================================
  Files                 469      469              
  Lines               66577    66638      +61     
==================================================
+ Hits                55028    55069      +41     
- Misses              11549    11569      +20     
Files with missing lines Coverage Δ
compiler/backend/lam_beta_reduce_util.ml 98.33% <100.00%> (ø)
compiler/backend/lam_bounded_vars.ml 75.86% <100.00%> (ø)
compiler/backend/lam_pass_remove_alias.ml 93.07% <100.00%> (+0.21%) ⬆️
compiler/backend/lam_util.ml 94.36% <100.00%> (ø)
compiler/typing/lambda.ml 69.88% <100.00%> (+0.05%) ⬆️
compiler/typing/lambda_traverse.ml 94.41% <100.00%> (+0.06%) ⬆️
compiler/typing/translcore.ml 88.98% <100.00%> (+0.24%) ⬆️
tests/ounit_tests/ounit_constant_argument_tests.ml 90.69% <100.00%> (ø)
compiler/typing/printlambda.ml 8.71% <0.00%> (-0.04%) ⬇️
compiler/backend/lam_beta_reduce.ml 76.87% <56.25%> (-8.47%) ⬇️
🚀 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 4, 2026 •

Copy link
Copy Markdown

✅ Compiler benchmarks

Allocated words

In total: 658,250,716 → 658,663,785 (+0.06%).

Generated projects: 628,525,972 → 628,539,777 (±0.00%).

Benchmark Base Head Change
packages/@rescript/belt/src/Belt_MutableSetInt.res 1,620,996 1,632,786 +0.73%
packages/@rescript/belt/src/Belt_MutableSetString.res 1,622,239 1,634,029 +0.73%
packages/@rescript/belt/src/Belt_MapDict.res 1,620,795 1,631,895 +0.68%
packages/@rescript/belt/src/Belt_SetInt.res 1,297,013 1,305,698 +0.67%
packages/@rescript/belt/src/Belt_SetString.res 1,297,741 1,306,426 +0.67%
packages/@rescript/belt/src/Belt_MapInt.res 1,175,674 1,183,539 +0.67%
packages/@rescript/belt/src/Belt_MapString.res 1,176,205 1,184,070 +0.67%
packages/@rescript/belt/src/Belt_MutableMapInt.res 1,139,692 1,146,876 +0.63%
packages/@rescript/belt/src/Belt_MutableMapString.res 1,139,971 1,147,155 +0.63%
packages/@rescript/belt/src/Belt_MutableSet.res 1,849,380 1,860,330 +0.59%
11 more changes
Benchmark Base Head Change
packages/@rescript/belt/src/Belt_internalMapInt.res 1,397,639 1,405,526 +0.56%
packages/@rescript/belt/src/Belt_internalMapString.res 1,399,483 1,407,370 +0.56%
packages/@rescript/belt/src/Belt_SetDict.res 1,447,359 1,455,481 +0.56%
packages/@rescript/belt/src/Belt_MutableMap.res 1,282,254 1,289,342 +0.55%
packages/@rescript/belt/src/Belt_internalSetInt.res 728,464 730,824 +0.32%
packages/@rescript/belt/src/Belt_internalSetString.res 729,653 732,013 +0.32%
packages/@rescript/belt/src/Belt_internalAVLset.res 2,794,814 2,802,300 +0.27%
packages/@rescript/belt/src/Belt_internalAVLtree.res 3,398,987 3,407,479 +0.25%
stress/InlineChain.res 3,406,271 3,410,461 +0.12%
packages/@rescript/runtime/Primitive_object.res 1,106,224 1,107,482 +0.11%
build/shared-edit 86,252,387 86,342,210 +0.10%

Instructions

In total: 8,976,466,510 → 8,976,822,585 (±0.00%).

Benchmark Base Head Change
packages/@rescript/belt/src/Belt_internalAVLtree.res 136,075,276 136,513,332 +0.32%

Output size

In total: 27,660,834 → 27,662,405 (+0.01%).

Benchmark Base Head Change
output/runtime/*.cmj 20,606 20,646 +0.19%

Pull request 6883faf compared with base 12d3ffc in this run.

@pkg-pr-new

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

Copy link
Copy Markdown

Open in StackBlitz

rescript

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

@rescript/belt

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

@rescript/darwin-arm64

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

@rescript/linux-arm64

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

@rescript/linux-x64

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

@rescript/runtime

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

@rescript/win32-x64

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

commit: 6883faf

@cknitt
cknitt removed this pull request from stack #9529 December 4, 2026 22:20
@cknitt
cknitt added this pull request to stack #9532 December 4, 2026 22:20
@cknitt
cknitt force-pushed the option-result-mark branch from 08cc41a to d99531b Compare December 5, 2026 00:02
@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-05T10:51:57.781181Z 848634f 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. You're on a roll.

Reviewed commit: d99531b28a

ℹ️ 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 commented Dec 5, 2026

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 93beda8c1b

ℹ️ 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 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 changed the base branch from late-inline-alias-pass to master December 5, 2026 10:20
@cknitt
cknitt changed the base branch from master to no-late-inline December 5, 2026 10:20
@cknitt
cknitt added this pull request to stack #9541 December 5, 2026 10:20
@cknitt

cknitt commented Dec 5, 2026

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. You're on a roll.

Reviewed commit: 1c5cac6d1b

ℹ️ 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-result-mark branch from 1c5cac6 to 5b18c3e Compare December 5, 2026 10:23
@cknitt
cknitt force-pushed the option-result-mark branch from 5b18c3e to 848634f Compare December 5, 2026 10:49
@cknitt

cknitt commented Dec 5, 2026

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Chef's kiss.

Reviewed commit: 848634f8d1

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

…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 Primitive_option.some(opt > 0 ? opt : undefined);
      }
    }
After (js):
    function mapped(opt, f) {
      if (opt !== undefined) {
        return f(opt);
      }
    }

    function nested(opt) {
      if (opt !== undefined) {
        return Primitive_option.some(opt > 0 ? opt : 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) {
      return Primitive_option.some(f(x));
    }
After (js):
    function knownSome(x, f) {
      return f(x);
    }

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: What about a flagged call passed as an argument? It gets the
argument mark of #9504 from its type like any other argument, so the body
it is passed to unwraps it directly. The two marks stay separate: the
flag says what an inlined body may return, the argument mark what a
parameter holds.

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. Most calls in a stored body are inlined before it is
stored, as `Option.map` in `mapPair` of the tests is, so the flag is rarely
needed there, but keeping it costs nothing.

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.2% more words in all, at most 0.8% more for one module (Belt's mutable
sets).

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-result-mark branch from 848634f to 6883faf Compare December 5, 2026 11:50
@cknitt
cknitt marked this pull request as ready for review December 5, 2026 13:11
@cknitt
cknitt requested a review from cristianoc December 5, 2026 13:11

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