rescript-compiler
rescript-compiler copied to clipboard
Add Parsetree-level Option stdlib optimizations (forEach/map/flatMap)
This PR adds a compiler-side optimization for the most important functions from the standard library's Option module: Option.forEach/map/flatMap.
- At the Parsetree stage, we rewrite these into the same switch structure a handwritten version would yield, whenever the callback is either a literal lambda with a simple variable binder or an inlineable identifier. More complex callbacks stay as calls so evaluation order and side-effects remain untouched.
- Because the rewrite runs ahead of type checking, the existing pipeline still inserts
Primitive_option.valFromOptionexactly as before, so the generated JavaScript stays identical. The trade-off is that we can only recognize calls spelled explicitly asOption.*orStdlib_Option.*; aliases or locally opened variants aren’t rewritten. - Typedtree and Lambda remain untouched. Threading a rewrite through Typedtree would be far more invasive than we need, and once we reach Lambda the primitive-versus-boxed distinction this optimization relies on has already disappeared.
- The change is covered by the comprehensive tests in
tests/tests/src/option_stdlib_optimization_test.res. The first test in that file gives a good example of how much the compiler output for long pipe chains is simplified.
rescript
npm i https://pkg.pr.new/rescript-lang/rescript@7918
@rescript/darwin-arm64
npm i https://pkg.pr.new/rescript-lang/rescript/@rescript/darwin-arm64@7918
@rescript/darwin-x64
npm i https://pkg.pr.new/rescript-lang/rescript/@rescript/darwin-x64@7918
@rescript/linux-arm64
npm i https://pkg.pr.new/rescript-lang/rescript/@rescript/linux-arm64@7918
@rescript/linux-x64
npm i https://pkg.pr.new/rescript-lang/rescript/@rescript/linux-x64@7918
@rescript/runtime
npm i https://pkg.pr.new/rescript-lang/rescript/@rescript/runtime@7918
@rescript/win32-x64
npm i https://pkg.pr.new/rescript-lang/rescript/@rescript/win32-x64@7918
commit: 50dbc3c
@codex review