Skip to content

Add try..finally syntax - #7903

Closed
cknitt wants to merge 5 commits into
masterfrom
try-finally
Closed

cknitt wants to merge 5 commits into
masterfrom
try-finally

Conversation

@cknitt

@cknitt cknitt commented Sep 18, 2025 •

Copy link
Copy Markdown
Member

Adds support for try..finally and try..catch..finally syntax to ReScript.
No breaking changes / full backwards compatibility.

Resolves #6974.

@pkg-pr-new

pkg-pr-new Bot commented Sep 18, 2025

Copy link
Copy Markdown

Open in StackBlitz

rescript

npm i https://pkg.pr.new/rescript-lang/rescript@7903

@rescript/darwin-arm64

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

@rescript/darwin-x64

npm i https://pkg.pr.new/rescript-lang/rescript/@rescript/darwin-x64@7903

@rescript/linux-arm64

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

@rescript/linux-x64

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

@rescript/runtime

npm i https://pkg.pr.new/rescript-lang/rescript/@rescript/runtime@7903

@rescript/win32-x64

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

commit: 4eb58f6

@cknitt cknitt changed the title [PoC] try..finally Add try..finally syntax Sep 18, 2025
@cknitt
cknitt marked this pull request as ready for review September 18, 2025 17:54
@cknitt
cknitt requested review from cristianoc and zth September 18, 2025 17:54
@fhammerschmidt

Copy link
Copy Markdown
Member

Maybe add a try await example to the tests.

attach t.trailing expr.pexp_loc after_expr;
walk_list (cases |> List.map (fun case -> Case case)) t rest
(* unary expression: todo use parsetreeviewer *)
| Pexp_try (expr, cases, finally_expr) -> (

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why was this case not handled at all before?
I would expect a change that only deals with finally, here

else if
Parser.lookahead p (fun state ->
match state.Parser.token with
| Lident "finally" -> true

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

what's finally in the grammar? just an identified?
Not a keyword I guess

} catch {
| InnerError => Console.log("Inner caught")
}
} catch {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this the indentation we want? Does TS look like this when formatted?

Comment thread compiler/ml/typecore.ml
let finally_typed =
type_expect ~context:None env expr Predef.type_unit
in
(* Finally blocks must return unit *)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why?

Comment thread compiler/ml/typedtree.mli
*)
| Texp_try of expression * case list
(** try E with P1 -> E1 | ... | PN -> EN *)
| Texp_try of expression * case list * expression option

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: get assistant to use a record in a hypothetical follow-up PR, if this goes ahead

Sexp.list (map_empty ~f:case cases);
]
| Pexp_try (expr, cases) ->
| Pexp_try (expr, cases, finally_expr) ->

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I keep on forgetting why we have this debugger file. Gives maintenance burden but can't remember why we need it.

Comment thread compiler/core/lam.mli
| Lstaticraise of int * t list
| Lstaticcatch of t * (int * ident list) * t
| Ltrywith of t * ident * t
| Ltrywith of t * ident * t option * t option

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

opportunity: this file is entirely uncommented
a separate PR could assist in adding some explanation

More bigger / longer term assistance opportunity: why do we have both lambda and lam? Is that a historical artefact for what used to be backwards compatibility, or can they possibly be merged now?

Comment thread compiler/core/js_dump.ml
P.string f L.finally;
P.space f;
brace_block cxt f b))
P.space f;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

curious why fin was already here

@cristianoc cristianoc left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The PR should have a good amount of text in the description explaining what this PR does at high level.

@cknitt
cknitt marked this pull request as draft September 20, 2025 06:30
@github-actions

Copy link
Copy Markdown

This pull request has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

@github-actions github-actions Bot added the stale Old issues that went stale label Sep 16, 2026
@github-actions github-actions Bot closed this Sep 24, 2026
@github-actions
github-actions Bot deleted the try-finally branch September 25, 2026 00:23
@cknitt cknitt mentioned this pull request Oct 20, 2026
cknitt added a commit that referenced this pull request Oct 24, 2026
Why:
    JavaScript code cleans up with finally blocks: after an await, around
    break and continue, and in generators, where cancellation is only seen
    by finally. ReScript had no way to express them.

`try` takes `finally { ... }` after its body or after its catch. `finally`
stays an identifier: after a catch it only starts a finally block when a
brace follows. The block is a statement and must not break or continue out
of it. Supersedes #7903.

AST modified (Pexp_try):
Example:
    let f = g =>
      try g() catch {
      | Not_found => 0
      } finally {
        Console.log("done")
      }
Before (diagnostic): `finally` was not valid after a catch.
After (parse):
    expression
      Pexp_try
      expression
        Pexp_apply
        expression
          Pexp_ident "g"
        …
      [
        <case>
          pattern
            Ppat_construct "Not_found"
          expression
            Pexp_constant PConst_int (0,None)
      ]
      Some
        expression
          Pexp_apply
          expression
            Pexp_ident "Console.log"
          …

Lambda added (Ltryfinally):
After (lambda):
    (try
      (try (apply g/1002 unit) with raw_exn/1062
        …)
     finally (seq (js_call[console.log] "done") unit))

JS added (try..catch..finally):
After (js):
    function f(g) {
      try {
        return g();
      } catch (raw_exn) {
        let exn = Primitive_exceptions.internalToException(raw_exn);
        if (exn.RE_EXN_ID === "Not_found") {
          return 0;
        }
        throw exn;
      } finally {
        console.log("done");
      }
    }

Diagnostic added (break out of finally):
Example:
    while true {
      try {
        ()
      } finally {
        break
      }
    }
After (diagnostic):
    `break` cannot leave a `finally` block. Only a loop inside the block can be broken out of.

Review: Why a separate Ltryfinally instead of an optional finally on
Ltrywith? Ltrywith keeps its meaning in every pass, a try without catch
needs no exception ident, and try..catch..finally is an Ltryfinally around
an Ltrywith that the JS backend prints as one statement.
Review: Why is the catch handler no longer in tail position? With a
finally, a self tail call in the handler would become a loop `continue`
that runs the finally before the recursive call instead of after it.
Review: Why reject break and continue in finally? JavaScript allows them,
but they silently drop a pending exception or return value.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Fc7LEuyEfynjaKCVEBPmTF
Signed-off-by: Christoph Knittel <ck@cca.io>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

stale Old issues that went stale

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Support try...finally

3 participants