From 24423379e8f19cfde11160ececfd7a76d1e5c55d Mon Sep 17 00:00:00 2001 From: Florian Hammerschmidt Date: Wed, 27 Aug 2025 19:25:28 +0200 Subject: [PATCH 1/3] Draft: let? blog post --- _blogposts/2025-09-01-let-unwrap.mdx | 75 ++++++++++++++++++++++++++++ 1 file changed, 75 insertions(+) create mode 100644 _blogposts/2025-09-01-let-unwrap.mdx diff --git a/_blogposts/2025-09-01-let-unwrap.mdx b/_blogposts/2025-09-01-let-unwrap.mdx new file mode 100644 index 000000000..5f08e83d1 --- /dev/null +++ b/_blogposts/2025-09-01-let-unwrap.mdx @@ -0,0 +1,75 @@ +--- +author: rescript-team +date: "2025-09-01" +badge: roadmap +title: let? +description: | + A new let-unwrap syntax just landed in ReScript. +--- + +After long discussions we finally decided on an unwrap syntax for both the `option` and `result` types that we are happy with and that still matches the explicitness of ReScript we all like. + +# What is it exactly? + +`let?` or `let-unwrap` is a tiny syntax that unwraps `result`/`option` values and *early-returns* on `Error`/`None`. It’s explicitly **experimental** and **disabled by default** behind a new “experimental features” gate. + +### Example + +```rescript +let getUser = async (id) => { + let? Ok(user) = await fetchUser(id) + let? Ok(decodedUser) = decodeUser(user) + Console.log(`Got user ${decodedUser.name}!`) + let? Ok() = await ensureUserActive(decodedUser) + Ok(decodedUser) +} +``` + +This desugars to a **sequence** of `switch`/early-returns that you’d otherwise write by hand, so there’s **no extra runtime cost** and it plays nicely with `async/await`. Same idea works for `option` with `Some(...)` (and the PR also extends support so the left pattern can be `Error(...)`/`None`, not just `Ok(...)`/`Some(...)`). ([[ReScript Forum](https://forum.rescript-lang.org/t/proposing-new-syntax-for-zero-cost-unwrapping-options-results/6227)][2], [[GitHub](https://github.com/rescript-lang/rescript/pull/7582/files)][3]) + +### Where it works (and doesn’t) + +* Targets **built-ins** only: `result` and `option`. (Custom variants still need `switch`.) ([[ReScript Forum](https://forum.rescript-lang.org/t/proposing-new-syntax-for-zero-cost-unwrapping-options-results/6227)][2]) +* **Block/local bindings** only; tests show top-level usage is rejected. ([[GitHub](https://github.com/rescript-lang/rescript/pull/7582/files)][3]) +* The printed JS is the straightforward if/return form (i.e., “zero cost”). ([[ReScript Forum](https://forum.rescript-lang.org/t/proposing-new-syntax-for-zero-cost-unwrapping-options-results/6227)][2]) + +### How to enable it (experimental) + +* The PR adds an **experimental-features infrastructure** to the toolchain and **CLI support**: `-enable-experimental …`. Rewatch reads config from `rescript.json` and forwards the feature(s) to the compiler. (See `rewatch` config + compile changes and the new compiler flag.) ([[GitHub](https://github.com/rescript-lang/rescript/pull/7582/files)][3]) +* There are tests and docs stubs around the experimental toggle plus “feature not enabled” error cases. ([[GitHub](https://github.com/rescript-lang/rescript/pull/7582/files)][3]) + +> In short: add the feature in `rescript.json` via the new “experimental features” setting (per the updated `CompilerConfigurationSpec.md`), or pass `-enable-experimental` in your build; otherwise `let?` is unavailable. ([[GitHub](https://github.com/rescript-lang/rescript/pull/7582/files)][3]) + +# Dev notes (what changed under the hood) + +* **Lexer/Parser/Printer:** new token for `let?`, grammar rules, and pretty-printer support. ([[GitHub](https://github.com/rescript-lang/rescript/pull/7582/files)][3]) +* **Frontend transform:** AST handling lowers `let?` to the equivalent `switch`/early return; tailored super-errors for misuse. ([[GitHub](https://github.com/rescript-lang/rescript/pull/7582/files)][3]) +* **Feature gate:** new module(s) to register/enable experimental features, with CLI wiring and rewatch config reading. ([[GitHub](https://github.com/rescript-lang/rescript/pull/7582/files)][3]) +* **Tests:** syntax parsing, printer snapshots, super-errors (e.g., “feature not enabled”, “top-level not allowed”, “not supported variant”, and return-type mismatch). ([[GitHub](https://github.com/rescript-lang/rescript/pull/7582/files)][3]) + +# Safety analysis: can this break anything when **off**? + +**Bottom line:** extremely low risk when the flag is **off**. + +Why: + +1. **Gated by default.** The feature is unreachable unless explicitly enabled; using `let?` without the gate yields a dedicated “feature not enabled” error (there are fixtures for this). That means existing codebases remain unaffected. ([[GitHub](https://github.com/rescript-lang/rescript/pull/7582/files)][3]) +2. **New syntax, not repurposed.** `let?` didn’t previously parse; recognizing it only at a `let` binding start avoids collisions with existing `?` uses (e.g., ternary) elsewhere in expressions. Parser tests were added to lock this down. ([[GitHub](https://github.com/rescript-lang/rescript/pull/7582/files)][3]) +3. **No runtime path changes.** It’s a compile-time sugar that lowers to the same `switch`/return structure you’d hand-write. If you don’t use it, nothing in your generated JS changes. ([[ReScript Forum](https://forum.rescript-lang.org/t/proposing-new-syntax-for-zero-cost-unwrapping-options-results/6227)][2]) +4. **Confined scope.** Even when enabled, top-level `let?` is rejected; only local/block bindings are supported. This reduces any accidental global impact. ([[GitHub](https://github.com/rescript-lang/rescript/pull/7582/files)][3]) +5. **Tooling guarded.** The PR tracks TODOs for error coverage and editor support; with the gate off, current editor plugins behave as before. ([[GitHub](https://github.com/rescript-lang/rescript/pull/7582)][1]) + +**Potential edge considerations (still low risk off):** + +* **Tokenization side-effects:** The scanner learns the `let?` token, but the feature gate + grammar location prevents it from altering how existing, valid programs lex/parse when you don’t write `let?`. Tests cover “not enabled” and misuse shapes. ([[GitHub](https://github.com/rescript-lang/rescript/pull/7582/files)][3]) +* **Error text churn:** Some super-error messages were added (including a hint when code looks *eligible* for `let?`). That only triggers in error paths; it won’t change successful builds. ([[GitHub](https://github.com/rescript-lang/rescript/pull/7582/files)][3]) + +**Conclusion:** With the experimental flag **off**, there are no functional or runtime changes, and parser behavior for all previously valid code paths is preserved. It’s safe to ship behind the flag. + +--- + +If you want, I can also jot down a tiny rollout checklist (enable flag in a sample app, verify editor plugin snapshot, run the super-errors suite) next. + +[1]: https://github.com/rescript-lang/rescript/pull/7582 "PoC of let? by zth · Pull Request #7582 · rescript-lang/rescript · GitHub" +[2]: https://forum.rescript-lang.org/t/proposing-new-syntax-for-zero-cost-unwrapping-options-results/6227 "Proposing new syntax for zero-cost unwrapping options/results - Development - ReScript Forum" +[3]: https://github.com/rescript-lang/rescript/pull/7582/files "PoC of let? by zth · Pull Request #7582 · rescript-lang/rescript · GitHub" \ No newline at end of file From 27e3116fb1deba607f58ea9bbc639d897416cc56 Mon Sep 17 00:00:00 2001 From: Florian Hammerschmidt Date: Thu, 28 Aug 2025 22:41:06 +0200 Subject: [PATCH 2/3] Refine let? post --- _blogposts/2025-09-01-let-unwrap.mdx | 46 +++------------------------- 1 file changed, 5 insertions(+), 41 deletions(-) diff --git a/_blogposts/2025-09-01-let-unwrap.mdx b/_blogposts/2025-09-01-let-unwrap.mdx index 5f08e83d1..57c1edab0 100644 --- a/_blogposts/2025-09-01-let-unwrap.mdx +++ b/_blogposts/2025-09-01-let-unwrap.mdx @@ -25,51 +25,15 @@ let getUser = async (id) => { } ``` -This desugars to a **sequence** of `switch`/early-returns that you’d otherwise write by hand, so there’s **no extra runtime cost** and it plays nicely with `async/await`. Same idea works for `option` with `Some(...)` (and the PR also extends support so the left pattern can be `Error(...)`/`None`, not just `Ok(...)`/`Some(...)`). ([[ReScript Forum](https://forum.rescript-lang.org/t/proposing-new-syntax-for-zero-cost-unwrapping-options-results/6227)][2], [[GitHub](https://github.com/rescript-lang/rescript/pull/7582/files)][3]) +This desugars to a **sequence** of `switch`/early-returns that you’d otherwise write by hand, so there’s **no extra runtime cost** and it plays nicely with `async/await`. Same idea works for `option` with `Some(...)` (and the PR also extends support so the left pattern can be `Error(...)`/`None`, not just `Ok(...)`/`Some(...)`). -### Where it works (and doesn’t) - -* Targets **built-ins** only: `result` and `option`. (Custom variants still need `switch`.) ([[ReScript Forum](https://forum.rescript-lang.org/t/proposing-new-syntax-for-zero-cost-unwrapping-options-results/6227)][2]) -* **Block/local bindings** only; tests show top-level usage is rejected. ([[GitHub](https://github.com/rescript-lang/rescript/pull/7582/files)][3]) -* The printed JS is the straightforward if/return form (i.e., “zero cost”). ([[ReScript Forum](https://forum.rescript-lang.org/t/proposing-new-syntax-for-zero-cost-unwrapping-options-results/6227)][2]) +Beware it targets built-ins only: `result` and `option`. (Custom variants still need `switch`.) And it is for block or local bindings only; top-level usage is rejected. +Compiled JS code is the straightforward if/return form (i.e., “zero cost”). ### How to enable it (experimental) -* The PR adds an **experimental-features infrastructure** to the toolchain and **CLI support**: `-enable-experimental …`. Rewatch reads config from `rescript.json` and forwards the feature(s) to the compiler. (See `rewatch` config + compile changes and the new compiler flag.) ([[GitHub](https://github.com/rescript-lang/rescript/pull/7582/files)][3]) -* There are tests and docs stubs around the experimental toggle plus “feature not enabled” error cases. ([[GitHub](https://github.com/rescript-lang/rescript/pull/7582/files)][3]) - -> In short: add the feature in `rescript.json` via the new “experimental features” setting (per the updated `CompilerConfigurationSpec.md`), or pass `-enable-experimental` in your build; otherwise `let?` is unavailable. ([[GitHub](https://github.com/rescript-lang/rescript/pull/7582/files)][3]) - -# Dev notes (what changed under the hood) - -* **Lexer/Parser/Printer:** new token for `let?`, grammar rules, and pretty-printer support. ([[GitHub](https://github.com/rescript-lang/rescript/pull/7582/files)][3]) -* **Frontend transform:** AST handling lowers `let?` to the equivalent `switch`/early return; tailored super-errors for misuse. ([[GitHub](https://github.com/rescript-lang/rescript/pull/7582/files)][3]) -* **Feature gate:** new module(s) to register/enable experimental features, with CLI wiring and rewatch config reading. ([[GitHub](https://github.com/rescript-lang/rescript/pull/7582/files)][3]) -* **Tests:** syntax parsing, printer snapshots, super-errors (e.g., “feature not enabled”, “top-level not allowed”, “not supported variant”, and return-type mismatch). ([[GitHub](https://github.com/rescript-lang/rescript/pull/7582/files)][3]) - -# Safety analysis: can this break anything when **off**? - -**Bottom line:** extremely low risk when the flag is **off**. +We have added an **experimental-features infrastructure** to the toolchain. The corresponding compiler flag is `-enable-experimental`. This means you can enable `let?` in your `rescript.json`s `compiler-flags` and it forwards the feature to the compiler. -Why: - -1. **Gated by default.** The feature is unreachable unless explicitly enabled; using `let?` without the gate yields a dedicated “feature not enabled” error (there are fixtures for this). That means existing codebases remain unaffected. ([[GitHub](https://github.com/rescript-lang/rescript/pull/7582/files)][3]) -2. **New syntax, not repurposed.** `let?` didn’t previously parse; recognizing it only at a `let` binding start avoids collisions with existing `?` uses (e.g., ternary) elsewhere in expressions. Parser tests were added to lock this down. ([[GitHub](https://github.com/rescript-lang/rescript/pull/7582/files)][3]) -3. **No runtime path changes.** It’s a compile-time sugar that lowers to the same `switch`/return structure you’d hand-write. If you don’t use it, nothing in your generated JS changes. ([[ReScript Forum](https://forum.rescript-lang.org/t/proposing-new-syntax-for-zero-cost-unwrapping-options-results/6227)][2]) -4. **Confined scope.** Even when enabled, top-level `let?` is rejected; only local/block bindings are supported. This reduces any accidental global impact. ([[GitHub](https://github.com/rescript-lang/rescript/pull/7582/files)][3]) -5. **Tooling guarded.** The PR tracks TODOs for error coverage and editor support; with the gate off, current editor plugins behave as before. ([[GitHub](https://github.com/rescript-lang/rescript/pull/7582)][1]) - -**Potential edge considerations (still low risk off):** - -* **Tokenization side-effects:** The scanner learns the `let?` token, but the feature gate + grammar location prevents it from altering how existing, valid programs lex/parse when you don’t write `let?`. Tests cover “not enabled” and misuse shapes. ([[GitHub](https://github.com/rescript-lang/rescript/pull/7582/files)][3]) -* **Error text churn:** Some super-error messages were added (including a hint when code looks *eligible* for `let?`). That only triggers in error paths; it won’t change successful builds. ([[GitHub](https://github.com/rescript-lang/rescript/pull/7582/files)][3]) - -**Conclusion:** With the experimental flag **off**, there are no functional or runtime changes, and parser behavior for all previously valid code paths is preserved. It’s safe to ship behind the flag. - ---- +This is purely a syntactical change so performance is not affected. -If you want, I can also jot down a tiny rollout checklist (enable flag in a sample app, verify editor plugin snapshot, run the super-errors suite) next. -[1]: https://github.com/rescript-lang/rescript/pull/7582 "PoC of let? by zth · Pull Request #7582 · rescript-lang/rescript · GitHub" -[2]: https://forum.rescript-lang.org/t/proposing-new-syntax-for-zero-cost-unwrapping-options-results/6227 "Proposing new syntax for zero-cost unwrapping options/results - Development - ReScript Forum" -[3]: https://github.com/rescript-lang/rescript/pull/7582/files "PoC of let? by zth · Pull Request #7582 · rescript-lang/rescript · GitHub" \ No newline at end of file From 68931f92285b29294e9e14735f538ce9f9d4ff0e Mon Sep 17 00:00:00 2001 From: Florian Hammerschmidt Date: Mon, 15 Sep 2025 01:13:30 +0200 Subject: [PATCH 3/3] Better example --- _blogposts/2025-09-01-let-unwrap.mdx | 45 +++++++++++++++++++++++++++- 1 file changed, 44 insertions(+), 1 deletion(-) diff --git a/_blogposts/2025-09-01-let-unwrap.mdx b/_blogposts/2025-09-01-let-unwrap.mdx index 57c1edab0..401a8071e 100644 --- a/_blogposts/2025-09-01-let-unwrap.mdx +++ b/_blogposts/2025-09-01-let-unwrap.mdx @@ -15,15 +15,58 @@ After long discussions we finally decided on an unwrap syntax for both the `opti ### Example +Before showing off this new feauture, let's explore why it is useful. Consider a chain of `async` functions that are dependent on the result of the previous one. The naive way to write this in modern ReScript with `async`/`await` is to just `switch` on the results. + +```res +let getUser = async id => + switch await fetchUser(id) { + | Error(error) => Error(error) + | Ok(res) => + switch await decodeUser(res) { + | Error(error) => Error(error) + | Ok(decodedUser) => + switch await ensureUserActive(decodedUser) { + | Error(error) => Error(error) + | Ok() => Ok(decodedUser) + } + } + } +``` + +Two observations: + 1. with every `switch` expression, this function gets nested deeper. + 2. The `Error` branch of every `switch` is just an identity mapper (neither wrapper nor contents change) + +This means even though `async`/`await` syntax is available in ReScript for some time now, it is also understandable that people created their own `ResultPromise` libraries to handle such things with less lines of code, e.g.: + +```res +module ResultPromise = { + let flatMapOk = async (p: promise<'res>, f) => + switch await p { + | Ok(x) => await f(x) + | Error(_) as res => res + } +} + +let getUserPromises = id => + fetchUser(id) + ->ResultPromise.flatMapOk(user => Promise.resolve(user->decodeUser)) + ->ResultPromise.flatMapOk(decodedUser => ensureUserActive(decodedUser)) +``` + +While this is much shorter, it is also harder to understand because we have two wrapper types here, `promise` and `result`. And we have to wrap the non-async type in a `Promise.resolve` in order to stay on the same type level. + ```rescript let getUser = async (id) => { let? Ok(user) = await fetchUser(id) let? Ok(decodedUser) = decodeUser(user) - Console.log(`Got user ${decodedUser.name}!`) let? Ok() = await ensureUserActive(decodedUser) Ok(decodedUser) } ``` +With the new `let-unwrap` syntax, `let?` in short, we now have to follow the happy-path (in the scope of the function). And it's immediately clear that `fetchUser` is an `async` function while `decodeUser` is not. There is no nesting as the `Error` is automatically mapped. But be assured the error case is also handled as the type checker will complain when you don't handle the `Error` returned by the `getUser` function. + + This desugars to a **sequence** of `switch`/early-returns that you’d otherwise write by hand, so there’s **no extra runtime cost** and it plays nicely with `async/await`. Same idea works for `option` with `Some(...)` (and the PR also extends support so the left pattern can be `Error(...)`/`None`, not just `Ok(...)`/`Some(...)`).