Skip to content

Accept reserved words as field names, labels, variant tags and JSX names - #9435

Open
jfrolich wants to merge 3 commits into
masterfrom
syntax-keywords-as-names
Open

jfrolich wants to merge 3 commits into
masterfrom
syntax-keywords-as-names

Conversation

@jfrolich

@jfrolich jfrolich commented Nov 26, 2026 •

Copy link
Copy Markdown
Collaborator

Recreated from jfrolich/rescript-rust#341 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.

Reserved words can now name record fields, argument labels, JSX props, polymorphic variant tags and lowercase JSX elements without an escape:

type input = {type: string, mutable open: bool, @as("data-for") for: string}
let kind = r.type
let r = {...r, type: "text", in: 1}
let f = (~type as kind, ~for=?) => kind
let el = <input type="text" data-type="a" />
let tag = #type
let el = <switch />

Today each of these is a syntax error and needs \"type", #"type" or a type_ field mapped back with @as("type"). This is the first part of the RFC in docs/rfcs/reserved-words-as-labels.md.

What changes

Only the parser and the printers change. Each of these positions is entered on a token that is not a keyword (., ~, #, <, {, ,), so a reserved word there can only be a name. The parse tree is the one the escaped spelling already gives, so type checking and the generated JavaScript are unchanged.

  • A record expression or pattern {type: ...} is told apart from a block by the token after the word (:, ?, ,, }), with one token of lookahead.
  • After the . of a field access or the ~ of a label, a reserved word is taken only on the same line. So user. or f(~ at the end of a line that is still being written doesn't swallow the next let, and editor completion still sees the unfinished argument.
  • Shorthands ({type}, ~type, <input type />) still need a variable named type, so they stay errors, with messages that show the long form. A missing comma before such a field ({a type: x}) is reported as before.
  • let? is a single token. Where a name is expected it is split into let and ? ({let?: int}, x == #let? a : b).
  • The existing "Cannot use keyword type as a record field name" recovery is removed, because that input now parses.
  • The formatter prints these names bare. A punned field or argument keeps its escape, because it also names a variable. 15 runtime and test sources are reformatted (escapes dropped), and they compile to the same JavaScript.

Two existing parser bugs, found by the fuzzing below, are fixed in separate commits:

  • type t = int as ' at the end of a file crashed the parser with an assertion.
  • A ' directly followed by a line break shifted every later syntax error one line down, and crashed the error printer at the end of a file.

Tests

  • New grammar, error and printer fixtures under tests/syntax_tests/data, plus a Mocha test (tests/tests/src/keyword_labels_test.res) that checks fields, patterns, labels, tags and JSX props at runtime.
  • tests/syntax_tests/res_keyword_name_test.ml is a seeded property test. It writes 2,000 random programs in both spellings (bare and escaped) and checks that both parse, give the same tree, format identically and idempotently, re-parse to the same tree, and that formatting adds no escape. It also checks that every shorthand, and every missing comma before a keyword field, is rejected for each of the 28 words. Breaking the printer's escaping, the let? split or the missing-comma check makes it fail.
  • Differential fuzzing against master, run out of tree:
    • All 2,948 .res/.resi files in the repository that master accepts give an identical -print ml tree.
    • 199,692 corpus mutants: keywords inserted, removed, escaped and unescaped, and line breaks added. All 33,367 that master accepts give an identical tree.
    • Every mutant this branch accepts is also formatted and parsed again. The few that don't round-trip fail the same way on master, with an ordinary name in place of the keyword. These are existing formatter bugs, such as a bare identifier as a JSX child.
    • No crashes or hangs, with or without -recover, except in the debug -print ml printer and the JSX transform's error reporting, which master reaches the same way.
  • Parsing the benchmark sources (tests/compiler_benchmarks/data) allocates within 0.03% of master, and formatting them within 0.04%.

make test-syntax and its roundtrip mode, dune build @fmt, the Mocha suite, the editor analysis tests, super_errors, the build tests, make dead-code, the changelog check, and the rescript-syntax build with OCaml 4.14 all pass. Hover and completion snapshots change only where they now print tags bare (#switch, [#and | #or]).

Not included: making keywords usable as variables (#9436, stacked on this one), un-reserving type, and renaming JsxDOM's @as("type") type_ fields, which is a standard library change.


Started by Jaap Frolich in this Assistant session

open-session-submodule Bot and others added 3 commits November 25, 2026 21:51
Why:
    A record field, argument label or JSX prop named like a keyword (type,
    open, in, for) has to be renamed and mapped back with @as, or escaped
    as \"type". Keys such as type are common in JavaScript objects; the
    standard library itself declares `@as("type") type_` in JsxDOM.

Where the grammar expects a name that no variable is bound to, a reserved
word is now that name: a record field (in a type, an expression, a pattern
and after the `.` of a field access), an argument label after `~`, a JSX
prop, a polymorphic variant tag after `#` and a lowercase JSX tag name.
Each of these positions is entered on a token that is not a keyword, so
the reading is unambiguous; the one choice, `{` starting a record or a
block, is made by a reserved word followed by `:`, which no block item
starts with. The parse tree is the one the escaped spelling gives, so type
checking and the generated JavaScript do not change.

A shorthand (`{type}`, `~type`, `<input type />`) stands for a variable of
the same name, and a reserved word still can't be one. After the `.` of a
field access or the `~` of a label a reserved word is taken only on the
same line, so `user.` or `f(~` at the end of a line being written does not
swallow the next `let`, and editor completion still sees the unfinished
argument.
`let?`, one token, is split into the name `let` and `?` where a name is
expected (`{let?: int}`, `x == #let? a : b`).

Format modified (escaped names):
Example:
    type t = {\"type": string, mutable \"open": bool}
    let get = r => r.\"type"
    let call = f(~\"for"="a")
    let tag = #"true"
    let el = <\"switch" />
Before (rescript):
    type t = {\"type": string, mutable \"open": bool}
    let get = r => r.\"type"
    let call = f(~\"for"="a")
    let tag = #"true"
    let el = <\"switch" />
After (rescript):
    type t = {type: string, mutable open: bool}
    let get = r => r.type
    let call = f(~for="a")
    let tag = #true
    let el = <switch />

Diagnostic removed (keyword as a field name):
Example:
    let r = {type: 1}
Before (diagnostic):
    Cannot use keyword `type` as a record field name. Suggestion: rename it (e.g. `type_`)
After (diagnostic): none, `type` is the field's name

Diagnostic added (shorthand with a reserved word):
Example:
    let {type} = r
After (diagnostic):
    `type` is a reserved keyword, so it can't be a variable name and this shorthand can't be used.
    Write it out instead: `{type: pattern}`

Review: Can a program that parses today change meaning? Every accepted form
was a syntax error before. All 2,948 .res/.resi files in the repository
that the previous parser accepts give the same parse tree (-print ml), and
so do the 33,367 of 199,692 corpus mutants (keywords inserted, removed,
escaped and unescaped, line breaks added) that it accepts. None crashes or
hangs, with or without -recover, beyond the debug -print ml printer and
the JSX transform's errors, which the previous parser reaches the same way.
Formatting every accepted mutant gives the same tree again; the few that
don't fail the same way with an ordinary name in place of the keyword.
Review: Why do runtime and test sources change? They used escaped labels
and tags (`\"type": ...`, `#"true"`), which the formatter now prints bare.
The runtime and tests/tests compile to the same JavaScript.
Review: Why do analysis snapshots change? Hover and completion print the
types with bare tags (`[#and | #or]`, `#switch`).
Review: Does parsing allocate more? The benchmark sources
(tests/compiler_benchmarks/data) allocate within 0.03% of the previous
parser: the new checks use one-token lookahead, no backtracking, and no
closures on the field, label and JSX prop paths.
Review: What checks the two spellings agree? tests/syntax_tests generates
2,000 seeded programs in both spellings and checks that they parse, give
the same tree, format identically and idempotently, and that formatting
adds no escape; every shorthand with each of the 28 words, and every
record row with one of them after a missing comma (`{a type: x}`), must be
rejected.

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>
Why:
    `type t = int as '` at the end of a file stopped the parser with an
    assertion instead of a syntax error, in the compiler and the editor.

`parse_ident` reported the missing name and then skipped the token in its
place with `Parser.next`, which asserts at the end of the file. It now
uses `Parser.next_unsafe`, as the other error paths do.

Diagnostic added (missing type variable name at the end of a file):
Example:
    type t = int as '
Before (diagnostic): none, the parser stops with an assertion
After (diagnostic):
    A type param consists of a singlequote followed by a name like `'a` or `'A`

Review: How was it found? Mutation fuzzing of the parser; the input
crashes the parser before this branch too.

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>
Why:
    A `'` directly followed by a line break moved every later location one
    line down, so syntax errors pointed at the wrong line; at the end of a
    file, printing the error crashed.

The scanner reads `'` as a codepoint literal when a character and a closing
`'` follow. When they don't, it went back to the character after the quote,
restoring the offset but not the line: the line break it had stepped over
stayed counted. It now restores the line number and the line's start too.

Diagnostic modified (location after a lone quote):
Example:
    let x = y '
    let z = 1
    let w = )
Before (diagnostic):
    ln.res:4:8-9  This let-binding misses an expression
After (diagnostic):
    ln.res:3:8-9  This let-binding misses an expression

Review: Why does aliasAtEndOfFile.res.txt change? Its error was reported on
line 3 of a two-line file; it is now on line 2.

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

  • Reserved words can name record fields, argument labels, JSX props, polymorphic variant tags and lowercase JSX elements without an escape: type t = {type: string}, r.type, f(~type="a"), <input type="text" />, #type, <switch>. A shorthand such as {type} or ~type is still an error, since it would need a variable named type. The formatter prints these names bare.

🐛 Bug fix

  • Fix a parser crash when a name is missing at the end of a file, as in type t = int as '.
  • Fix syntax error locations after a ' that is directly followed by a line break: every later line was reported one line too low, and at the end of a file the parser crashed.

Semantic Diff

3 commits · Full page

Accept reserved words as field names, labels, variant tags and JSX names

b0ac12f · open-session-submodule[bot] + Jaap Frolich · Nov 16, 2026, 20:50 UTC

Why

A record field, argument label or JSX prop named like a keyword (type, open, in, for) has to be renamed and mapped back with @as, or escaped as \"type". Keys such as type are common in JavaScript objects; the standard library itself declares @as("type") type_ in JsxDOM.

Where the grammar expects a name that no variable is bound to, a reserved word is now that name: a record field (in a type, an expression, a pattern and after the . of a field access), an argument label after ~, a JSX prop, a polymorphic variant tag after # and a lowercase JSX tag name. Each of these positions is entered on a token that is not a keyword, so the reading is unambiguous; the one choice, { starting a record or a block, is made by a reserved word followed by :, which no block item starts with. The parse tree is the one the escaped spelling gives, so type checking and the generated JavaScript do not change.

A shorthand ({type}, ~type, <input type />) stands for a variable of the same name, and a reserved word still can't be one. After the . of a field access or the ~ of a label a reserved word is taken only on the same line, so user. or f(~ at the end of a line being written does not swallow the next let, and editor completion still sees the unfinished argument. let?, one token, is split into the name let and ? where a name is expected ({let?: int}, x == #let? a : b).

Format modified (escaped names)

type t = {\"type": string, mutable \"open": bool}
let get = r => r.\"type"
let call = f(~\"for"="a")
let tag = #"true"
let el = <\"switch" />

rescript

-type t = {\"type": string, mutable \"open": bool}
-let get = r => r.\"type"
-let call = f(~\"for"="a")
-let tag = #"true"
-let el = <\"switch" />
+type t = {type: string, mutable open: bool}
+let get = r => r.type
+let call = f(~for="a")
+let tag = #true
+let el = <switch />

Diagnostic removed (keyword as a field name)

let r = {type: 1}

diagnostic

-Cannot use keyword `type` as a record field name. Suggestion: rename it (e.g. `type_`)
+none, `type` is the field's name

Diagnostic added (shorthand with a reserved word)

let {type} = r

diagnostic · After

`type` is a reserved keyword, so it can't be a variable name and this shorthand can't be used.
Write it out instead: `{type: pattern}`

Review

  • Can a program that parses today change meaning? Every accepted form was a syntax error before. All 2,948 .res/.resi files in the repository that the previous parser accepts give the same parse tree (-print ml), and so do the 33,367 of 199,692 corpus mutants (keywords inserted, removed, escaped and unescaped, line breaks added) that it accepts. None crashes or hangs, with or without -recover, beyond the debug -print ml printer and the JSX transform's errors, which the previous parser reaches the same way. Formatting every accepted mutant gives the same tree again; the few that don't fail the same way with an ordinary name in place of the keyword.
  • Why do runtime and test sources change? They used escaped labels and tags (\"type": ..., #"true"), which the formatter now prints bare. The runtime and tests/tests compile to the same JavaScript.
  • Why do analysis snapshots change? Hover and completion print the types with bare tags ([#and | #or], #switch).
  • Does parsing allocate more? The benchmark sources (tests/compiler_benchmarks/data) allocate within 0.03% of the previous parser: the new checks use one-token lookahead, no backtracking, and no closures on the field, label and JSX prop paths.
  • What checks the two spellings agree? tests/syntax_tests generates 2,000 seeded programs in both spellings and checks that they parse, give the same tree, format identically and idempotently, and that formatting adds no escape; every shorthand with each of the 28 words, and every record row with one of them after a missing comma ({a type: x}), must be rejected.
Don't crash on a name missing at the end of a file

412e65b · open-session-submodule[bot] + Jaap Frolich · Nov 25, 2026, 20:46 UTC

Why

type t = int as ' at the end of a file stopped the parser with an assertion instead of a syntax error, in the compiler and the editor.

parse_ident reported the missing name and then skipped the token in its place with Parser.next, which asserts at the end of the file. It now uses Parser.next_unsafe, as the other error paths do.

Diagnostic added (missing type variable name at the end of a file)

type t = int as '

diagnostic

-none, the parser stops with an assertion
+A type param consists of a singlequote followed by a name like `'a` or `'A`

Review

  • How was it found? Mutation fuzzing of the parser; the input crashes the parser before this branch too.
Keep line numbers right after a quote before a line break

6af6ecd · open-session-submodule[bot] + Jaap Frolich · Nov 25, 2026, 20:47 UTC

Why

A ' directly followed by a line break moved every later location one line down, so syntax errors pointed at the wrong line; at the end of a file, printing the error crashed.

The scanner reads ' as a codepoint literal when a character and a closing ' follow. When they don't, it went back to the character after the quote, restoring the offset but not the line: the line break it had stepped over stayed counted. It now restores the line number and the line's start too.

Diagnostic modified (location after a lone quote)

let x = y '
let z = 1
let w = )

diagnostic

-ln.res:4:8-9  This let-binding misses an expression
+ln.res:3:8-9  This let-binding misses an expression

Review

  • Why does aliasAtEndOfFile.res.txt change? Its error was reported on line 3 of a two-line file; it is now on line 2.

@github-actions

Copy link
Copy Markdown

✅ Compiler benchmarks

Allocated words

In total: 638,386,285 → 638,418,973 (+0.01%).

Generated projects: 629,069,606 → 629,087,678 (±0.00%).

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

Instructions

In total: 9,221,423,192 → 9,225,687,141 (+0.05%).

Benchmark Base Head Change
packages/@rescript/runtime/Stdlib_Math.resi (inputs changed) 21,298,462 21,401,849 +0.49%
parse/RedBlackTreeNoComments.res 14,490,889 14,553,908 +0.43%
parse/HeroGraphic.res 70,400,219 70,700,144 +0.43%
packages/@rescript/runtime/Stdlib_List.resi (inputs changed) 24,525,839 24,625,859 +0.41%
packages/@rescript/runtime/Stdlib_Temporal_PlainDate.res (inputs changed) 24,087,316 24,184,986 +0.41%
packages/@rescript/runtime/Stdlib_Temporal_PlainDateTime.res (inputs changed) 25,530,153 25,627,689 +0.38%
packages/@rescript/runtime/Stdlib_String.resi (inputs changed) 29,450,597 29,552,755 +0.35%
format/RedBlackTreeNoComments.res 24,075,111 24,155,329 +0.33%
packages/@rescript/runtime/Stdlib_Temporal_ZonedDateTime.res (inputs changed) 31,204,066 31,306,774 +0.33%
format/RedBlackTree.res 24,420,069 24,500,151 +0.33%
8 more changes
Benchmark Base Head Change
format/HeroGraphic.res 211,538,313 212,214,452 +0.32%
packages/@rescript/belt/src/Belt_Array.resi (inputs changed) 33,710,607 33,816,256 +0.31%
parse/RedBlackTree.res 14,917,559 14,963,996 +0.31%
packages/@rescript/runtime/Stdlib_Date.resi (inputs changed) 34,285,292 34,388,599 +0.30%
packages/@rescript/belt/src/Belt_List.resi (inputs changed) 38,971,131 39,079,721 +0.28%
packages/@rescript/runtime/Stdlib_Array.resi (inputs changed) 40,108,765 40,210,049 +0.25%
packages/@rescript/runtime/Stdlib_TypedArray.res (inputs changed) 41,327,641 41,415,050 +0.21%
format/Napkinscript.res 603,280,748 603,935,909 +0.11%

(inputs changed): this pull request changes runtime or Belt sources, so these benchmarks compile different code than on the base, and their changes don't count as regressions.

Output size

In total: 26,070,038 → 26,074,057 (+0.02%).

Benchmark Base Head Change
output/playground/compiler.js 1,889,271 1,893,637 +0.23%

Pull request 6af6ecd compared with base 17874c0 in this run.

@codecov

codecov Bot commented Nov 26, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 91.08280% with 28 lines in your changes missing coverage. Please review.
✅ Project coverage is 82.25%. Comparing base (895cf4c) to head (6af6ecd).
⚠️ Report is 2 commits behind head on master.

Files with missing lines Patch % Lines
syntax/parser/res_core.ml 89.32% 27 Missing ⚠️
syntax/parser/res_parser.ml 83.33% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master    #9435      +/-   ##
==========================================
+ Coverage   82.22%   82.25%   +0.03%     
==========================================
  Files         461      462       +1     
  Lines       65574    65766     +192     
==========================================
+ Hits        53916    54098     +182     
- Misses      11658    11668      +10     
Files with missing lines Coverage Δ
compiler/typing/res_outcome_printer.ml 83.73% <100.00%> (ø)
syntax/parser/res_scanner.ml 91.80% <ø> (ø)
syntax/printer/res_printer.ml 95.54% <100.00%> (+0.01%) ⬆️
syntax/printer/res_token.ml 77.55% <100.00%> (+5.59%) ⬆️
syntax/parser/res_parser.ml 95.41% <83.33%> (-0.59%) ⬇️
syntax/parser/res_core.ml 91.98% <89.32%> (-0.10%) ⬇️

... and 6 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@9435

@rescript/belt

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

@rescript/darwin-arm64

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

@rescript/linux-arm64

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

@rescript/linux-x64

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

@rescript/runtime

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

@rescript/win32-x64

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

commit: 6af6ecd

@github-actions

Copy link
Copy Markdown

@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:40:12.218079Z 6af6ecd 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. What shall we delve into next?

Reviewed commit: 6af6ecd79f

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

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