Repository navigation
Fix parser parity: idempotency, JSX, regex, and Unicode - #8239
Merged
Merged
Conversation
Added table showing test status by category: - printer: 187/187 (100%) - complete - ast-mapping: 3/3 (100%) - complete - ppx/react: 28/31 (90%) - conversion: 26/27 (96%) - parsing categories need more work Syntax tests: 323/506 passed (63%) Co-Authored-By: Claude <noreply@anthropic.com>
1. Recursive component transformation (v4.res):
- Generate nested let structure for recursive components matching OCaml
- let rec make = { let "make$Internal" = ... in let make = ... in make }
- make_props_wrapper_expr_with_ref now calls fn$Internal for recursive
2. Ref type preservation (interfaceWithRef.res):
- When ref parameter has explicit type annotation, preserve it
- Only use Js.Nullable.t<'ref> when pattern is just Ppat_var
3. @as attributes on labeled function parameters:
- Parser now correctly places @as attrs on pattern's ppat_attributes
- FundefTermParam.attrs is empty when attrs are on pattern (no double)
- print_record_pattern now prints attrs for punned fields
Syntax tests: 326/506 passed (64%)
ppx/react: 31/31 passed (100%)
Co-Authored-By: Claude <noreply@anthropic.com>
- Fix Pmty_signature to use proper HV boxes with break hints between items, allowing short signatures to stay on one line - Fix Pmod_structure similarly with proper HV boxes - Fix Pstr_modtype/Psig_modtype to use HOV boxes and proper spacing (two spaces before =, break hint after =) - Fix Pmty_with to wrap in parens when there are constraints - Fix with type constraint spacing to match OCaml's double spaces Progress: 332/506 tests passing (65%), parsing/grammar up from 58 to 64 Co-Authored-By: Claude <noreply@anthropic.com>
… formatting - Add print_item_attributes call for Psig_modtype to print [@@...] attributes - Fix Pcstr_record (inline records in constructors) to use proper indented newlines instead of raw \n characters Progress: 333/506 tests passing (65%), parsing/grammar up to 65 Co-Authored-By: Claude <noreply@anthropic.com>
- Fix type extension printing (Pstr_typext/Psig_typext):
- Add type params like ('a,'b) when present
- Print private flag
- Format constructors on separate lines with | prefix
- Use proper "+= " spacing
- Fix exception declaration (Pstr_exception/Psig_exception):
- Wrap in HOV2 box matching OCaml's exception_declaration
- This gives inline records correct +2 indentation
- Remove extra indentation in Pcstr_record (now context-dependent
via the enclosing box)
Progress: 334/506 tests passing (66%), parsing/grammar at 66
Co-Authored-By: Claude <noreply@anthropic.com>
- Fix Psig_type to put "and" declarations on separate lines (like Pstr_type) - Add attributes printing for Psig_module - Fix empty functors to print "functor () ->" instead of "functor (*) ->" Progress: 336/506 tests passing (66%), parsing/grammar at 50% Co-Authored-By: Claude <noreply@anthropic.com>
- Fix print_signature_ml to use newlines between items instead of spaces - Remove unnecessary trailing newline from signature output Progress: 337/506 tests passing (66%), parsing/grammar at 51% Co-Authored-By: Claude <noreply@anthropic.com>
When Psig_module has pmd_type that is Pmty_alias with no attributes, print as "module Name = Alias" instead of "module Name : (module Alias)" to match OCaml's pprintast output. Progress: 338/506 tests passing (66%), parsing/grammar at 51% Co-Authored-By: Claude <noreply@anthropic.com>
Wrap Psig_value printing in a HOV2 box with break hints so long declarations can wrap after ":" like OCaml's output. Progress: 339/506 tests passing (66%), parsing/grammar at 52% Co-Authored-By: Claude <noreply@anthropic.com>
Add space before closing brace in inline record fields to match OCaml output. Co-Authored-By: Claude <noreply@anthropic.com>
Print type params, private flag, and constraints for Pwith_type and
Pwith_typesubst constraints. This fixes cases like:
- `with type 'a t = string`
- `with type ('a,'b) t = string`
- `with type t = 'st constraint 'st = int`
- `with type t = private string`
Co-Authored-By: Claude <noreply@anthropic.com>
- Print optional field marker `?` in expression records (e.g., `x = ?value`) - Print optional field marker `?` in pattern records (e.g., `name?`) - Print optional field marker `?` in type record fields (e.g., `y?: string`) - Print field attributes on label declarations - Fix spacing: no space before `}` when last field has attributes Co-Authored-By: Claude <noreply@anthropic.com>
Handle Pexp_newtype in value bindings to print `let f (type t) x = ...` instead of `let f = fun (type t) -> fun x -> ...`. Also print arity annotation correctly after type params. Co-Authored-By: Claude <noreply@anthropic.com>
Print attributes like [@attr] on labeled and unlabeled arrow type arguments. Co-Authored-By: Claude <noreply@anthropic.com>
Fixed several ML printer issues: - with type constraint printing (params, private, constraints) - Optional record field printing (?, field attributes) - Locally abstract types inline printing - Arrow type argument attributes ppx/react is now at 100%. Most remaining parsing/grammar failures are line-wrapping cosmetic differences (80-column). Co-Authored-By: Claude <noreply@anthropic.com>
In uncurried-by-default mode, functions can have multiple arity markers at different positions (e.g., `[arity:3]a b c [arity:3]d e f`). Changed to print the arity for each Pexp_fun that has an explicit arity, not just the first one. Co-Authored-By: Claude <noreply@anthropic.com>
OCaml's core_type1 wraps arrow types in parens, so when an arrow type appears as an argument to another arrow type, it needs parens: `(string -> unit (a:1)) -> unit (a:1)` not `string -> unit (a:1) -> unit (a:1)` Co-Authored-By: Claude <noreply@anthropic.com>
When a module binding has a Pmod_constraint with an ident or signature type and no attributes, print it as `module X : mt = me` instead of `module X = (me : mt)`. Also add trailing space to match OCaml's @; break hint. Co-Authored-By: Claude <noreply@anthropic.com>
Print covariant (+) and contravariant (-) variance prefixes on type parameters in type declarations. Co-Authored-By: Claude <noreply@anthropic.com>
Open types can also be private: `type t = private ..` Co-Authored-By: Claude <noreply@anthropic.com>
The print_extension_at_module_level function was duplicating payload
printing logic without proper soft_line handling. Now it reuses the
print_payload function which correctly handles line breaks and
indentation for structure payloads.
This fixes the conversion/reason/ppx.res test where
module Form = %form(type input = {...
was being printed on one line instead of:
module Form = %form(
type input = {...
Syntax tests: 345/506 passed (68%)
- conversion: 27/27 (100%)
Co-Authored-By: Claude <noreply@anthropic.com>
Add syntax_tests/data/parsing to the main parity test, excluding errors/ and recovery/ subdirectories which contain intentionally invalid syntax. This catches parser bugs like the nonrec keyword being incorrectly parsed as a type name. Co-Authored-By: Claude <noreply@anthropic.com>
OCaml attaches attributes to the inner module type BEFORE parsing the 'with' constraints. So `@attr Foo with type t = int` should produce `Pmty_with(Foo[@attr], constraints)`, not `Pmty_with(Foo, constraints)[@attr]`. This fixes the AST structure for attributed module types with 'with' clauses. Syntax tests: 345/506 passed (68%) Co-Authored-By: Claude <noreply@anthropic.com>
…traints Multiple with-constraints in package types should be joined with 'and' instead of 'with': `with type key = string and type value = int` Co-Authored-By: Claude <noreply@anthropic.com>
Exclude infiniteLoops/ directory (stress tests), ffi/export.res, and parsing/other/gentype.res since both OCaml and Rust parsers fail on these - they're not parity issues. Co-Authored-By: Claude <noreply@anthropic.com>
- Psig_recmodule: Use proper box formatting with breaks between decls, add attributes for each declaration - Psig_type: Open HOV box with indent 2 for each declaration so variant constructors get proper indentation when line breaking The variant constructors (| Leaf, | Node, etc.) now align correctly with 2-space extra indent inside the type declaration. Syntax tests: 345/506 passed (68%) Co-Authored-By: Claude <noreply@anthropic.com>
Type declarations can have constraints like `constraint 'a = int` that were being dropped. Now properly printed. Co-Authored-By: Claude <noreply@anthropic.com>
- Status now: 347/506 tests passing (68%) - conversion now at 100% (27/27) - Documented root causes of remaining failures: - parsing/grammar: 80-column line wrapping in ML printer - parsing/errors: Missing "consecutive statements" error checks - parsing/recovery: Error recovery output differences - parsing/infiniteLoops: Error messages and AST format differ Co-Authored-By: Claude <noreply@anthropic.com>
- Document consecutive statement error checking as critical missing feature - Add OCaml references for Grammar.is_block_expr_start, parse_newline_or_semicolon_* - Update parsing/grammar section with 80-column line wrapping root cause - Mark conversion, ast-mapping, ppx/react as 100% passing Co-Authored-By: Claude <noreply@anthropic.com>
When { lident: ... } appears in a type expression context
(not in a type declaration), emit the OCaml error message about
inline record types only being allowed in variant constructors
or nested inside record type declarations.
Co-Authored-By: Claude <noreply@anthropic.com>
This enables the diagnostic system to produce "I'm missing a type here" messages when a type expression is expected but a closing brace or comma is found in object type fields. Co-Authored-By: Claude <noreply@anthropic.com>
…int/arrow overparse Implements OCaml's over_parse_constrained_or_coerced_or_arrow_expression: - Handles expr :> type (coercion) - Handles expr : type with proper error message using ResPrinter - Handles expr : type => body with ambiguous arrow error showing both interpretations - Placed in parse_block_body for innermost expression and in let binding value parsing - Fix ML printer to only print arity when explicitly set (matching OCaml's pprintast) Co-Authored-By: Claude <noreply@anthropic.com>
Implements OCaml's parse_if_let_expr: when the parser sees `if let`, it parses the pattern, `=`, condition, then/else branches, and produces a Pexp_match with @res.iflet and @warning "-4" attributes. Emits the "If-let is currently highly experimental" error with a suggested switch replacement rendered via ResPrinter. Co-Authored-By: Claude <noreply@anthropic.com>
Matches OCaml pprintast's ctxt record {pipe, semi, ifthenelse} for
context-dependent paren wrapping. Also fixes arity printing to only
print when explicitly Full(n), matching OCaml behavior.
Fixes equalAfterBinaryExpr and other formatting parity tests.
Co-Authored-By: Claude <noreply@anthropic.com>
Match OCaml's pprintast behavior where simple_expr ctxt inherits the parent context. This ensures context-dependent parenthesization (pipe, semi, ifthenelse) is applied when simple_expr falls through to expression ctxt. Added ctx-aware variants: - print_expression_simple_ctx - print_expression2_ctx - print_expression_simple_under_semi_ctx - print_arg_with_label_ctx Updated all calls within print_expression_inner to use these ctx-aware variants, matching OCaml's semantics: - Infix binary: lhs uses reset_ctxt, rhs uses ctxt - Normal apply: function uses expression2 ctxt, args use reset_ctxt - Record fields, construct args, field/setfield, tuple, variant, array, send, assert, prefix ops: all use simple_expr ctxt - Array elements: use simple_expr (under_semi ctxt) Existing context-free wrappers kept for callers outside print_expression_inner (JSX, etc.) that don't have context. Co-Authored-By: Claude <noreply@anthropic.com>
When encountering DotDotDot (spread) in constructor arguments like
Foo({...a, u: int}), scan past the spread to check for string fields
before classifying as object type. Only treat as object if string
keys are found, otherwise treat as inline record.
Fixes objectSpread.res parity test.
Co-Authored-By: Claude <noreply@anthropic.com>
- "Did you forget a `</` here?" for missing closing tag - "Missing </TagName>" for mismatched closing tag names - "JSX identifier cannot end with a hyphen" for trailing hyphens - "expected identifier after '.' in JSX tag name" for trailing dots - "Spreading JSX children is no longer supported." for spread children - Helper functions for comparing JSX tag names Co-Authored-By: Claude <noreply@anthropic.com>
OCaml wraps Pexp_send in @[<hov2>...@] which allows the Format engine to break long lines inside parenthesized expressions like style=(obj#field). Co-Authored-By: Claude <noreply@anthropic.com>
OCaml's parser never does JSX disambiguation in the binary expression loop. The is_jsx_start_after_less_than check was causing `list<i>` and similar expressions to be incorrectly parsed as JSX instead of as comparison operators. The existing newline+whitespace check already handles the case where `<` on a new line should start a new JSX expression. Co-Authored-By: Claude <noreply@anthropic.com>
OCaml distinguishes three cases when looking for a JSX closing tag: 1. `<` followed by `/` -> proper closing tag 2. Structure item start (let, type, etc.) -> emit "Missing </Tag>" 3. Other tokens -> emit "Did you forget a `</` here?" Previously Rust only had cases 1 and 3. Adding case 2 fixes jsxChildren.res parity by correctly handling unclosed JSX elements that are followed by new structure items. Also removes synthetic </error> closing tags when no proper closing tag is found, matching OCaml's behavior of setting closing_tag to None. Co-Authored-By: Claude <noreply@anthropic.com>
- Add Grammar::Jsx breadcrumb to parse_jsx with eat_breadcrumb at all exits - Add Grammar::JsxAttribute breadcrumb to parse_jsx_props with parse_region-style recovery - Fix trailing hyphen error position (advance past '-' before emitting error) - Add three-way check for self-closing/container/unexpected token in JSX - Preserve trailing dot in invalid JSX tag names (JsxTagName::Invalid) - Fixes jsx.res parity test (493/506) Co-Authored-By: Claude <noreply@anthropic.com>
…r_start - Add scan_regex() to scanner for rescanning / as regex literal - Add next_regex_token() to parser state (matches OCaml's next_regex_token) - Add Forwardslash/ForwardslashDot cases in parse_atomic_expr to rescan as regex - Add Forwardslash/ForwardslashDot to is_atomic_expr_start and is_expr_start - Fixes regexCharacterClasses.res parity test (494/506) Co-Authored-By: Claude <noreply@anthropic.com>
- Change err_multiple to err_at for old-style type parameter errors so the region is properly silenced after the first error, matching OCaml's behavior where only one error per region is reported. - Fixes extra "Type parameters require angle brackets" errors in nonRecTypes Co-Authored-By: Claude <noreply@anthropic.com>
When parse_single_row_field_with_attrs returns None in the bar-prefixed path, call parse_typ_expr to match OCaml's parse_tag_spec behavior. This produces a typehole ([%rescript.typehole]) via error recovery for unknown tokens like backtick, instead of silently discarding the field. Co-Authored-By: Claude <noreply@anthropic.com>
Files with syntax errors (like export.res) legitimately exit non-zero. The test script was treating all non-zero exits as failures without comparing the actual output. Now it captures the exit code safely (avoiding set -e) and only skips comparison on actual timeouts (124). This properly counts 2 previously miscategorized tests as passing. Co-Authored-By: Claude <noreply@anthropic.com>
OCaml pushes Grammar.ExprBlock breadcrumb in parse_expr_block and in brace-expression parsing in parse_atomic_expr. This is critical for error recovery: should_abort_list_parse checks (ExprBlock, Rbrace) as a list terminator, so when parsing fails inside a block, recovery knows to stop at }. Without this breadcrumb, recovery like setField.res (missing expression after field mutation =) would not produce an exprhole and instead continue parsing past the }. Fixes setField.res parity (497 -> 498/506). Co-Authored-By: Claude <noreply@anthropic.com>
… in constrained types Two related changes to match OCaml's pattern parsing behavior: 1. Switch case patterns: Use parse_pattern instead of parse_constrained_pattern. OCaml's parse_pattern_match_case calls parse_pattern for the case LHS, not parse_constrained_pattern. Type constraints in switch cases are only valid inside delimiters like parentheses: | (x: int) => body. 2. Constrained pattern types: Use parse_typ_expr (with es6_arrow) instead of parse_typ_expr_no_arrow. Since switch cases no longer use constrained pattern parsing, the => token won't be ambiguous. This allows proper recovery for cases like | (a : int => () where int => () is parsed as the arrow type int -> unit. Fixes constrained.res parity (498 -> 499/506). Co-Authored-By: Claude <noreply@anthropic.com>
Push ExprOperand breadcrumb before emitting error in parse_switch_case_block, matching OCaml's parse_expr_block -> parse_expr -> parse_atomic_expr path. This produces the correct "Looks like there might be an expression missing here" message for empty switch case bodies (| Empty => | Next => ...). Co-Authored-By: Claude <noreply@anthropic.com>
- List patterns: parse all items with spread flags using parse_comma_delimited_reversed_list approach, validate spreads after (last spread becomes tail, others emit list_pattern_spread error) - Record patterns: parse spread fields as regular fields with has_spread flag, include them in output, emit record_pattern_spread error after - Fixes parenthesized.res and record.res parity (499→501/506) Co-Authored-By: Claude <noreply@anthropic.com>
Process record pattern fields in reversed order (matching OCaml's fold_left on reversed list) so the LAST spread field's error is emitted first. Region silencing then suppresses earlier spreads, matching OCaml's behavior. Fixes spread.res parity (501→502/506) Co-Authored-By: Claude <noreply@anthropic.com>
Match OCaml's parse_comma_delimited_region which checks if token can start an argument before parsing. When encountering } inside loop(, this produces 'Did you forget a )?' (from expect Rparen) instead of 'Missing expression' (from parse_atomic_expr attempting to parse }). Fixes block.res parity (502→503/506) Co-Authored-By: Claude <noreply@anthropic.com>
Add parse_type_constructor_arg_region which silently skips < tokens before parsing type arguments, matching OCaml's behavior. Rewrite parse_type_args to use parse_comma_delimited_region pattern with TypExprList breadcrumb for proper error recovery. This fixes option(<node<int>>) parsing where the < before node was being treated as an error instead of being skipped. Fixes typeConstructorArgs.res parity (503→504/506) Co-Authored-By: Claude <noreply@anthropic.com>
OCaml's parse_atomic_typ_expr does NOT handle Token::Typ - locally abstract types (type a. T) are handled at let-binding sites. Move the handling to parse_locally_abstract_type called from expr.rs and module.rs let-binding contexts. This fixes type state = followed by type on next line being misinterpreted as locally abstract type syntax. Co-Authored-By: Claude <noreply@anthropic.com>
When a type declaration name starts with Uident (e.g. `type T1 = D1`), OCaml's parse_value_path has a quirk where its internal `aux` function consumes tokens differently: it always calls Parser.next, then Parser.next_unsafe consumes one additional token. This means the `=` or `+=` operator can get consumed, fundamentally changing the parse result to an abstract type declaration instead of a type equation. Add parse_value_path_for_type that replicates this behavior, only activating for paths that end with Uident (error cases). Valid type extensions like Foo.Bar.t that end with lident continue using the original lookahead-based approach. Co-Authored-By: Claude <noreply@anthropic.com>
…rity!)
Add inline_types_found, current_type_name_path, and inline_types_params
fields to the Parser struct to enable nested inline record extraction
within type constructor arguments. When parsing a type like
`result<{first: bool}, {second: bool}>` inside a record field with
active inline context, the `{...}` blocks are now extracted as separate
inline record type declarations, matching OCaml's behavior.
This fixes nestedRecord.res and achieves 506/506 (100%) syntax parity.
Co-Authored-By: Claude <noreply@anthropic.com>
…ing) - Add Token::Regex to is_expr_start/is_atomic_expr_start/is_block_expr_start so pre-scanned regex tokens are recognized as valid expressions - Fix try_scan_regex_literal: only treat ']' as closing char class when in_char_class is true (matching scan_regex behavior) - Fix is_jsx_close_slash to use char-based lookup instead of byte array (correct for Latin-1 encoded source) - Fix is_binary_op to use char-based indexing instead of src.as_bytes() since cnum values are char indices, not UTF-8 byte offsets - Switch bsc.rs, driver.rs, benchmark.rs from from_utf8_lossy to Latin-1 encoding (bytes→chars) to match res_parser.rs and OCaml's byte handling Co-Authored-By: Claude <noreply@anthropic.com>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Fixes 12 idempotency test parse failures and improves parser parity with OCaml by addressing regex rescanning, JSX error recovery, Unicode handling, and type parsing quirks. Includes fixes for inline record extraction (reaching 100% parity), pattern spread handling, switch case error recovery, and various OCaml parse behavior matching.
Key improvements: proper regex forwardslash rescanning, improved JSX closing tag and prop handling, correct Uident type name parsing, locally abstract type parsing restructuring, and region-aware error suppression.
This work continues the OCaml-to-Rust parser rewrite by systematically addressing edge cases and parse failures to achieve byte-identical parity in AST generation.