Skip to content

Make as, open, private and seven other keywords contextual - #9436

Open
jfrolich wants to merge 1 commit into
syntax-keywords-as-namesfrom
syntax-contextual-keywords
Open

jfrolich wants to merge 1 commit into
syntax-keywords-as-namesfrom
syntax-contextual-keywords

Conversation

@jfrolich

@jfrolich jfrolich commented Nov 26, 2026 •

Copy link
Copy Markdown
Collaborator

Recreated from jfrolich/rescript-rust#342 with unchanged commits, on a branch in this repository so CI and benchmark reporting can run here. The validation results below are carried over from the original PR; fresh CI will validate this stack.

Stacked on #9435.

as, constraint, exception, external, mutable, of, open, private, rec and when become contextual keywords. Each is a keyword only in the position where the grammar uses it, and only when the next token is what the keyword takes. Everywhere else it is a name, so these work without an escape:

let open = dialog.open
let next = {...dialog, open}
let render = (~as, ~open=false) => <Dialog as open />
let onError = exception => log(exception)

open Belt still opens a module, and open(file) calls a function. This is the second part of the RFC in docs/rfcs/reserved-words-as-labels.md.

What changes

  • The scanner returns the ten words as identifiers. Their token constructors are removed.
  • One token of lookahead decides each word, because what follows the keyword can't follow a variable:
    • open takes a module name or !.
    • external takes an identifier.
    • exception takes a constructor or a pattern.
    • private takes a type.
    • mutable takes a field name.
    • constraint and type as take a type variable.
    • let rec and type rec take a binding.
  • A signature has no expressions, so open, external and exception are always keywords there.
  • Existing code keeps its meaning. An escaped word such as \"open" stays a name everywhere. The scanner gives it the same token as open, so the parser checks whether the token was written escaped before reading it as a keyword.
  • Error messages stay helpful. open, exception or external followed on the same line by an identifier, a string or a number is treated as a misspelled declaration, so open belt keeps its error about the module name.
  • Incomplete code recovers as before. A line starting with open M, exception E or external f, after an unfinished x., x->, f(~ or {a: on the line before, is read as the declaration. Error recovery and editor completion therefore still see the unfinished expression.
  • The formatter prints the ten words bare, except in four places where the bare name would read as the keyword:
    • A statement that is only open, exception or external is printed escaped (\"open"). Parentheses would not work: after type t = Foo, (open) on the next line is read as Foo's arguments, the same way (x) is today.
    • let (rec as x) = ...
    • exception (as), exception (when) and exception (of) in a pattern.
    • type t = (private)
  • Behaviour change: a bare open, exception, external or mutable with nothing after it is now a variable or a punned field. The error for it now comes from type checking instead of the parser. parsing/errors/typeDef/recordMutable.res keeps its parser error by using mutable 1.

Tests

  • Fixtures: grammar, printer and error fixtures for each keyword in both its keyword and name readings, including escaped spellings (contextualKeywords*.res, errors/structure/contextualKeywordDeclarations.res). Mocha cases are in keyword_labels_test.res.
  • Property test: res_keyword_name_test.ml now writes the ten words as variables next to each keyword position, bare in one spelling and escaped in the other. It also checks that each escaped word means what an ordinary name means in 31 keyword positions. Removing any of the four printer rules, or the escaped-name check, makes it fail.
  • Differential fuzzing compared this branch with both master and Accept reserved words as field names, labels, variant tags and JSX names #9435, run out of tree:
    • Repository files: all 2,948 .res/.resi files in the repository that master accepts give an identical -print ml tree.
    • Mutants: 199,671 mutants of those files, with keywords inserted, removed, escaped and unescaped, and line breaks added. All 33,587 that master accepts give an identical tree. The same holds for a second run of 199,646 mutants against Accept reserved words as field names, labels, variant tags and JSX names #9435.
    • Mutants this branch rejects: 8 mutants that master accepts are now errors. In each, master silently drops a word (private private A, ${x as}, a stray of after a variant spread), and its formatter deletes it.
    • Formatting: every accepted mutant is also formatted and parsed again. Every one that fails to round-trip also fails on master with an ordinary name in place of the keyword, so these are existing formatter bugs.
    • Crashes: no crashes or hangs, with or without -recover, except in the debug -print ml printer and the JSX transform's error reporting. master reaches both the same way.
  • Allocation: parsing the benchmark sources allocates within 0.03% of master, and formatting them within 0.07%.

These all pass on this branch: make test-syntax and its roundtrip mode, dune build @fmt, Mocha, the editor analysis tests (unchanged snapshots), super_errors, the build tests, make dead-code, the changelog check, and the rescript-syntax build with OCaml 4.14.

Not included: making type contextual, which is a follow-up.


Started by Jaap Frolich in this Assistant session

Why:
    `open`, `private`, `as`, `exception` and `of` are common JavaScript
    names (a dialog's `open`, a component's `as` prop, an `exception`
    callback parameter), but as reserved words they can't be variables, so
    `{...dialog, open}`, `(~as) => as` and `exception => log(exception)`
    need an escape or a rename.

`as`, `constraint`, `exception`, `external`, `mutable`, `of`, `open`,
`private`, `rec` and `when` are now scanned as identifiers. Each is a
keyword only in the position where the grammar uses it, and there only
when what follows is what the keyword takes: `open Belt` opens a module,
`open(file)` calls a function. One token of lookahead decides, because
what follows the keyword can't follow a variable: `open` takes a module
name or `!`, `external` an identifier, `exception` a constructor or a
pattern, `private` a type, `mutable` a field name, `constraint` and type
`as` a type variable, `let rec`/`type rec` a binding. Everywhere else the
word is a name, so it can be a variable, a type name, a type variable and
a shorthand. A signature has no expressions, so `open`, `external` and
`exception` are always keywords there.

An escaped word, such as `\"open"`, stays a name everywhere. The scanner
gives it the same token as `open`, so the parser checks the token's first
source character before reading the word as a keyword; every program that
parses today keeps its meaning. `open`, `exception` or `external` followed
on the same line by an identifier, a string or a number is a misspelled
declaration, since no variable is followed by one, so `open belt` keeps
its error about the module name.

Incomplete code recovers as before: `open M`, `exception E` or
`external f` starting a line, after an unfinished `x.`, `x->`, `f(~` or
`{a:` on the line before, is the declaration, as it was when the word was
reserved, so error recovery and editor completion still see the
unfinished expression. A variable at the start of a line followed by a
module name on the same line is never valid code, so this changes nothing
that parses.

Format modified (escaped names):
Example:
    let \"open" = dialog.\"open"
    let render = (~\"as", ~\"open"=false) => <Dialog \"as" \"open" />
Before (rescript):
    let \"open" = dialog.\"open"
    let render = (~\"as", ~\"open"=false) => <Dialog \"as" \"open" />
After (rescript):
    let open = dialog.open
    let render = (~as, ~open=false) => <Dialog as open />

Format added (where the bare name reads as the keyword):
Example:
    \"open"
    Belt.x
    let (rec as x) = 1
    let f = x => switch x { | exception (as) => 1 }
    type t = (private)
After (rescript):
    \"open"
    Belt.x
    let (rec as x) = 1
    let f = x =>
      switch x {
      | exception (as) => 1
      }
    type t = (private)

Diagnostic removed (contextual keyword as a variable):
Example:
    let open = 1
Before (diagnostic):
    `open` is a reserved keyword. Keywords need to be escaped: \"open"
After (diagnostic): none, `open` is the variable's name

Review: Can a program that parses today change meaning? No. All 2,948
.res/.resi files in the repository that the parser before this branch
accepts give the same parse tree (-print ml), and so do the 33,587 of
199,671 corpus mutants (keywords inserted, removed, escaped and unescaped,
line breaks added) that it accepts. The property test checks that each of
the ten words, escaped, means what an ordinary name means in 31 keyword
positions. Part 2 rejects 8 mutants the previous parser accepted; each
drops a keyword without an error there (`private private A`, `${x as}`),
and its formatter deleted the word.
Review: Why is a statement `open` printed escaped and not in parentheses?
After a variant declaration, `(open)` on the next line is read as the
constructor's arguments, as `(x)` is today: `type t = Foo` then `(open)` is
`Foo(open)`.
Review: How was the recovery checked? The editor analysis tests complete
inside unfinished expressions followed by `open M`; their snapshots are
unchanged.
Review: What checks the printer? The seeded property test now writes the
ten words as variables (bare in one spelling, escaped in the other) next
to each keyword position, and checks every shorthand. Removing any one of
the four rules makes it fail. Formatting every mutant this branch accepts
gives the same tree again; the few that don't fail the same way with an
ordinary name in place of the keyword, before this branch too.
Review: Why does recordMutable.res change? `{foo: string, mutable}` is now
a punned field named `mutable`, like any other name; the fixture keeps the
error with `mutable 1`.

Co-authored-by: Jaap Frolich <jfrolich@gmail.com>
Session: https://os.submodule.nl/session/os-01a1cf02-c45e-7b38-9d7d-9bb237c29854
Signed-off-by: open-session-submodule[bot] <341020755+open-session-submodule[bot]@users.noreply.github.com>
@jfrolich
jfrolich added this pull request to stack #9437 November 26, 2026 09:17
@github-actions

Copy link
Copy Markdown

Changelog

🚀 New Feature

  • as, constraint, exception, external, mutable, of, open, private, rec and when are contextual keywords: each is a keyword only where the grammar uses it and a name everywhere else, so let open = dialog.open, {...dialog, open}, (~as) => as and exception => log(exception) need no escape. An escaped spelling such as \"open" stays a name everywhere, so existing code keeps its meaning. The formatter prints these names bare, and escapes or parenthesizes them where the bare name would read as the keyword.

Semantic Diff

1 commit · Full page

Make as, open, private and seven other keywords contextual

377f429 · open-session-submodule[bot] + Jaap Frolich · Nov 16, 2026, 21:16 UTC

Why

open, private, as, exception and of are common JavaScript names (a dialog's open, a component's as prop, an exception callback parameter), but as reserved words they can't be variables, so {...dialog, open}, (~as) => as and exception => log(exception) need an escape or a rename.

as, constraint, exception, external, mutable, of, open, private, rec and when are now scanned as identifiers. Each is a keyword only in the position where the grammar uses it, and there only when what follows is what the keyword takes: open Belt opens a module, open(file) calls a function. One token of lookahead decides, because what follows the keyword can't follow a variable: open takes a module name or !, external an identifier, exception a constructor or a pattern, private a type, mutable a field name, constraint and type as a type variable, let rec/type rec a binding. Everywhere else the word is a name, so it can be a variable, a type name, a type variable and a shorthand. A signature has no expressions, so open, external and exception are always keywords there.

An escaped word, such as \"open", stays a name everywhere. The scanner gives it the same token as open, so the parser checks the token's first source character before reading the word as a keyword; every program that parses today keeps its meaning. open, exception or external followed on the same line by an identifier, a string or a number is a misspelled declaration, since no variable is followed by one, so open belt keeps its error about the module name.

Incomplete code recovers as before: open M, exception E or external f starting a line, after an unfinished x., x->, f(~ or {a: on the line before, is the declaration, as it was when the word was reserved, so error recovery and editor completion still see the unfinished expression. A variable at the start of a line followed by a module name on the same line is never valid code, so this changes nothing that parses.

Format modified (escaped names)

let \"open" = dialog.\"open"
let render = (~\"as", ~\"open"=false) => <Dialog \"as" \"open" />

rescript

-let \"open" = dialog.\"open"
-let render = (~\"as", ~\"open"=false) => <Dialog \"as" \"open" />
+let open = dialog.open
+let render = (~as, ~open=false) => <Dialog as open />

Format added (where the bare name reads as the keyword)

\"open"
Belt.x
let (rec as x) = 1
let f = x => switch x { | exception (as) => 1 }
type t = (private)

rescript · After

\"open"
Belt.x
let (rec as x) = 1
let f = x =>
  switch x {
  | exception (as) => 1
  }
type t = (private)

Diagnostic removed (contextual keyword as a variable)

let open = 1

diagnostic

-`open` is a reserved keyword. Keywords need to be escaped: \"open"
+none, `open` is the variable's name

Review

  • Can a program that parses today change meaning? No. All 2,948 .res/.resi files in the repository that the parser before this branch accepts give the same parse tree (-print ml), and so do the 33,587 of 199,671 corpus mutants (keywords inserted, removed, escaped and unescaped, line breaks added) that it accepts. The property test checks that each of the ten words, escaped, means what an ordinary name means in 31 keyword positions. Part 2 rejects 8 mutants the previous parser accepted; each drops a keyword without an error there (private private A, ${x as}), and its formatter deleted the word.
  • Why is a statement open printed escaped and not in parentheses? After a variant declaration, (open) on the next line is read as the constructor's arguments, as (x) is today: type t = Foo then (open) is Foo(open).
  • How was the recovery checked? The editor analysis tests complete inside unfinished expressions followed by open M; their snapshots are unchanged.
  • What checks the printer? The seeded property test now writes the ten words as variables (bare in one spelling, escaped in the other) next to each keyword position, and checks every shorthand. Removing any one of the four rules makes it fail. Formatting every mutant this branch accepts gives the same tree again; the few that don't fail the same way with an ordinary name in place of the keyword, before this branch too.
  • Why does recordMutable.res change? {foo: string, mutable} is now a punned field named mutable, like any other name; the fixture keeps the error with mutable 1.

@github-actions

Copy link
Copy Markdown

✅ Compiler benchmarks

Allocated words

In total: 639,071,350 → 639,062,931 (±0.00%).

Generated projects: 629,051,704 → 628,990,934 (-0.01%).

Benchmark Base Head Change
packages/@rescript/runtime/Dom.res 1,071,720 1,069,130 -0.24%

Instructions

In total: 9,225,559,445 → 9,225,880,331 (±0.00%).

None of the 33 benchmarks changed by 0.1% or more.

Output size

In total: 26,041,952 → 26,045,011 (+0.01%).

Benchmark Base Head Change
output/playground/compiler.js 1,893,425 1,896,451 +0.16%

Pull request 377f429 compared with base 6af6ecd in this run.

@codecov

codecov Bot commented Nov 26, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 91.80328% with 15 lines in your changes missing coverage. Please review.
✅ Project coverage is 82.33%. Comparing base (6af6ecd) to head (377f429).

Files with missing lines Patch % Lines
syntax/parser/res_grammar.ml 45.45% 6 Missing ⚠️
syntax/parser/res_core.ml 96.92% 4 Missing ⚠️
syntax/printer/res_printer.ml 90.32% 3 Missing ⚠️
syntax/printer/res_token.ml 33.33% 2 Missing ⚠️
Additional details and impacted files
@@                     Coverage Diff                      @@
##           syntax-keywords-as-names    #9436      +/-   ##
============================================================
+ Coverage                     82.25%   82.33%   +0.07%     
============================================================
  Files                           462      461       -1     
  Lines                         65766    65849      +83     
============================================================
+ Hits                          54098    54214     +116     
+ Misses                        11668    11635      -33     
Files with missing lines Coverage Δ
compiler/syntax_cli/res_token_debugger.ml 0.00% <ø> (ø)
syntax/printer/res_parsetree_viewer.ml 94.77% <100.00%> (+0.16%) ⬆️
syntax/printer/res_token.ml 76.96% <33.33%> (-0.59%) ⬇️
syntax/printer/res_printer.ml 95.48% <90.32%> (-0.06%) ⬇️
syntax/parser/res_core.ml 92.51% <96.92%> (+0.53%) ⬆️
syntax/parser/res_grammar.ml 42.48% <45.45%> (-0.67%) ⬇️

... and 5 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.

@pkg-pr-new

pkg-pr-new Bot commented Nov 26, 2026

Copy link
Copy Markdown

Open in StackBlitz

rescript

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

@rescript/belt

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

@rescript/darwin-arm64

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

@rescript/linux-arm64

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

@rescript/linux-x64

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

@rescript/runtime

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

@rescript/win32-x64

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

commit: 377f429

@cknitt

cknitt commented Nov 26, 2026

Copy link
Copy Markdown
Member

Two things I found while probing this against master:

  1. An unfinished line followed by a declaration on the next line now pulls the declaration into the unfinished expression. f(~, f(x,, [1, 2,, (1,, list{1,, <div> or cond ? followed by open Belt (or exception E, external f: …) parses as f(hole) open Belt, [1; 2; open; Belt] or cond ? open : Belt. On master open Belt stays its own item. Inside a function body, a local open or exception disappears while you type g(x, above it. The description lists f(~ as recovering as before; the fixture only covers f(~ followed by let. Comma lists seem to read open as the next element after a missing comma, so starts_declaration_on_new_line may need to end those lists, the ternary branch and JSX children too.
  2. external F: int = "f" used to say "Did you mean f instead of F?" and now says "Consecutive statements on a line…". The same goes for external @attr f and type rec @attr t. Maybe the misspelled-declaration check could also accept a capitalised name after external.

This review was done by Claude.

@cknitt

cknitt commented Nov 26, 2026

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 26, 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-11-26T16:41:05.332527Z 377f429 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 chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 377f429cb4

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

Comment on lines +1527 to +1530
let typ_doc =
if Parsetree_viewer.typ_starts_with_lident "private" typ then
add_parens typ_doc
else typ_doc

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Protect private manifests in type re-exports too

When a record or variant re-export has a manifest alias starting with the type name private, formatting produces invalid syntax. For example, type t = (private as 'a) = {x: int} is accepted, but the formatter emits type t = private as 'a = {x: int}: starts_private_type then interprets private as the visibility keyword because it is followed by as. This protection currently applies only to Ptype_abstract; the Ptype_record and Ptype_variant branches still print their manifests directly. Apply the same protection to those manifests so formatting preserves valid programs.

Useful? React with 👍 / 👎.

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.

2 participants