Skip to content

Allow parenthesized rightward sequences and frame invalid hash-pattern keys - #263

Merged
284km merged 4 commits into
mainfrom
codex-parse-parenthesized-patterns
Nov 25, 2026
Merged

284km merged 4 commits into
mainfrom
codex-parse-parenthesized-patterns

Conversation

@284km

@284km 284km commented Nov 25, 2026 •

Copy link
Copy Markdown
Owner

Continue a parenthesized statement sequence after rightward pattern matching and boolean in matching, including statement modifiers and and/or. Reject bare instance/global/class-variable hash-pattern keys and reuse Prism's framed diagnostics for invalid keys in file execution, eval, load and require. Equal-position diagnostics follow Prism's own insertion order.

The review's two Minor findings are covered by the expanded corpus 989: in followed by another statement, and if/unless/while/until/rescue after a match. Corpus 990 covers invalid keys and valid quoted-label controls. CLI checks disable optional syntax_suggest to compare core Prism output. Both modes match the independent reference.

Base main ab5a9bf. Latest runtime a518421, ordinary O2, compiler 9dec2ff687a08433247dbdb7729bc19c8522e538. Clean reference tools/ref_ruby.sh, revision a704b7cd95a42cc0cf5f307137bf3aac0285b915: 84 default/bundled specifications, zero extras, default Prism 1.8.2.

Latest review validation:

  • Corpus --both: 885/885 ON/OFF, 1188.432 s, peak family RSS 1,214,656 KiB; no resource event.
  • VM corpus: 885 VM / 0 fallback / 0 differences, 528.306 s, peak 1,109,824 KiB.
  • Eight corpus-prefix source gates, default record_hygiene and generated-C bracket gate pass (155 of 1024).
  • All six requested CRuby files are COMPLETE on both modes, with no passing case lost against main. Existing test_parse failures, test_syntax error and known skips are retained, with full per-file identities and summaries.
  • Parse-heavy mapper.rb, three alternating samples: instruction medians 171,522,878 → 170,369,625 (-0.67%); this is within the observed first-run variation, with no speedup claim.
  • Fixed seed 1 m17n_comb: all 82 tests / 248,127 assertions pass; latest RSS 977,216 KiB evaluator / 1,017,424 KiB VM. Earlier alternating main values are 975,504 / 624,032 KiB. Shared-machine variation is explicit; no stable memory improvement is claimed.

Portable review evidence: unittest/records/parse-patterns-review.json; original complete and incomplete attempts remain in parenthesized-hash-patterns.json. An earlier concurrent 3,600-second whole-corpus timeout is retained as incomplete, followed by the complete standalone run; it is not used as passing evidence.

The string forms of instance_eval/class_eval/module_eval retain their pre-existing raw-error path. Their diagnostic framing and the other pre-existing parser suggestions are tracked as separate follow-ups. No shared framework tooling changes.

@284km 284km left a comment

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

Review of head d951fb93. Event: COMMENT. Not merged.

Summary

Both parser holes are fixed for the shapes the PR names. I ran every probe below on both engines: the evaluator (MERE_RUBY_VM unset) and the VM (MERE_RUBY_VM=1). I compared each with reference Ruby 4.0.10 (Prism 1.8.2). The evaluator and the VM agreed on every probe.

Two neighbours of hole 3 are still a SyntaxError (Minor 1 and Minor 2 below). Under the merge policy, these two Minors block the merge until they are fixed or explicitly deferred.

What works (verified by running)

Hole 3: rightward match in parentheses. These now match ruby. They were a SyntaxError on main.

  • Assignment, method argument, array element, if and while conditions, endless def: x = (h => {a:}; a), foo((h => {a:}; a)), def k(h) = (h => {a: 1}; :ok).
  • Nested parentheses: ((h => {a:}; a)), (((h => {a:}; a); a + 1)).
  • Several statements, with ;, ;;; or newlines as separators. Also a trailing ; before ).
  • Inside a lambda or a block, inside (... rescue :r), and a rightward match on the value of the group.
  • A failed match still raises NoMatchingPatternError. A missing separator ((h => {a:} a)) is still a SyntaxError.
  • The same shapes work through eval, -e and a main script.
  • (a => b) in a call is still a Hash argument: p(:a => 1), foo(k => v), foo(1, k => v), foo(k => v, w: 1) give the same results as ruby.

Hole 4: invalid hash-pattern keys. I tried 27 keys through eval(src, binding, "pat.rb", 7). The output matched ruby byte for byte on both engines. The keys included @iv, $g, @@cv, $1, $~, +, -, [], !, a=, "a#{x}", %s(a), :a, 9, and a b. Valid keys also matched: "str", 'q', "@iv", a?, a!, A, Foo, _, if, nil, self and __FILE__.

  • The framed report also matched ruby for a main script, -e, stdin, load (with and without wrap), require, require_relative, Binding#eval with a file and line, and eval with no file name.
  • I also checked framing edge cases: a multibyte line, a long previous line, two error lines in one file, and a bad key inside an array pattern. The shorthand keys {@iv:} and {$g:} and the brace-less in @iv: 1 / in a: 1, $g: 2 match too. On main, most of these keys were accepted and failed later with NoMatchingPatternKeyError.
  • The tie order in prism_report (a <= b) matches pm_parse_errors_format_sort in Ruby's prism_compile.c. That code inserts a new error before an equal position. Five regexp-frame probes (files and eval) are unchanged from main and match ruby.

Corpus. 989 and 990 pass on both engines. Both fail on main.

Parser speed. I parsed a generated file of 1.16 MB, with 3,000 never-called methods full of hashes, calls, parenthesized groups and patterns. I compared against a clean build of the PR base ab5a9bfd, counting instructions retired.

  • Evaluator, median of 5 alternating runs: 4,370,056,307 → 4,370,614,561 (+0.01%).
  • VM, median of 3: 13,500,522,774 → 13,541,724,038 (+0.31%).
  • Both are within noise. This agrees with the PR's +0.40% on mapper.rb.

Merge state. git merge-tree is clean against current origin/main (d03cbb83), which already contains the merged #239. It is also clean against open #247 (1fa3c3b3) and open #245 (bc3d6042). None of their m_parse.mere or main.mere hunks touch the lines this PR changes. #239 is not in the PR base (ab5a9bfd). A rebuild on top of current main has not been tested.

Size. About 1,650 of the 1,784 added lines are the JSON record in unittest/records/. 50 are the loop note, 61 are the two corpus programs, and about 29 are code. I found no local absolute paths and no personal data in the changed files. The PR description does contain a local absolute path to the reference Ruby. Consider replacing it with tools/ref_ruby.sh.

Findings

Minor 1: in inside parentheses still refuses a following statement. The => branch now continues the statement sequence. The in branch about 17 lines below still ends with expect (skip_nls r3) ")". Ruby accepts all of these; this head (and main) raise SyntaxError on both engines:

h = {a: 7}
x = (h in {a:}; a)            # ruby: 7
def k3(h) = (h in {a: 1}; :ok) # ruby: :ok
(h in {a:}
 a)                            # ruby: 7
(h in {a:} and true; a)        # ruby: 7

This is the same hole as the => case, one token over. It is not worse than main, but it is a direct neighbour of hole 3. A likely fix is paren_expr_end (EMatchTest (e, pat)) r3.

Minor 2: a modifier after a rightward match inside parentheses is still a SyntaxError. Ruby accepts all of these; this head (and main) raise SyntaxError on both engines. The same forms work without the parentheses.

h = {a: 5}
(h => [x] rescue :r)            # ruby: :r
(h => {a:} if true)             # ruby: nil
(h => {a:} unless false; a)     # ruby: 5
(h in {a:} if true; a)          # ruby: 5

After parse_pattern_top, paren_expr_end only knows newline/; and ). The in / while / if / unless / rescue modifier branch of paren_expr_body handles this for a plain expression. The rightward match does not reach it.

Suggestion 1: the string forms of instance_eval / class_eval / module_eval. For an invalid key these raise StandardError with the internal text mere-ruby: syntax: expected a label as the key in the hash pattern. Ruby raises a framed SyntaxError. On main, @iv: and $g: were accepted there and failed later with NoMatchingPatternKeyError. So the case moves from one wrong result to another. Main already does this for every refused syntax in these methods ({+: 1}, {a}, def (1).x; end), so I do not count it as a regression of this PR.

Object.new.instance_eval("case {}\nin {$g: 1}\nend")
# ruby: SyntaxError "(eval at ...):2: syntax errors found ..."
# head: StandardError "mere-ruby: syntax: expected a label ... unexpected local variable or method; ..."

Also, the raw second line says "unexpected local variable or method" for @iv, $g and @@cv. Prism says "unexpected instance variable", "global variable" or "class variable". Only these paths show the raw line.

Suggestion 2 (outside the scope of this PR, unchanged from main): in {a: 1, **@r} is accepted (ruby: SyntaxError). x = (k => v) and [(k => v)] are accepted and return nil (ruby: "void value expression" SyntaxError). foo (k => v) with a space is accepted (ruby: SyntaxError). The framed report for load/require is chosen by matching the message text "expected a label as the key in the hash pattern". Other refusals in a loaded file stay one line.

What I ran vs. read

  • Ran: every probe named above, on the PR head build, a clean main build (e8788681, contains the PR base) and the reference Ruby. The speed runs used a clean build of ab5a9bfd. I also ran corpus 989/990 and the git merge-tree checks.
  • Read only: the full code diff, prism_report, and Prism's sort routine.
  • Not run: the full corpus, the gates, or the CRuby unit files. The PR body reports those: corpus --both 885/885, VM 885 / 0 fallback / 0 differences, nine gates plus record_hygiene, and six related CRuby files with no lost passes. I did not reproduce them.

CI

At review time, every required job for d951fb93 is still queued or pending. Only reactor, runtime-load-path (ubuntu-24.04) and NKF Wasm engine have finished, and they passed.

Comment thread m_parse.mere
| Cons (TP c0, r2b) ->
if str_eq c0 "=>" then
let (pat, r3) = parse_pattern_top r2b in (EMatchBind (e, pat), expect (skip_nls r3) ")")
let (pat, r3) = parse_pattern_top r2b in paren_expr_end (EMatchBind (e, pat)) r3

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

Minor 1: the in branch about 17 lines below ((EMatchTest (e, pat), expect (skip_nls r3) ")")) still refuses a following statement. h = {a: 7}; x = (h in {a:}; a) and def k3(h) = (h in {a: 1}; :ok) are SyntaxError here; ruby gives 7 and :ok. Routing it through paren_expr_end (EMatchTest (e, pat)) r3 would cover it.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

Fixed in a518421. The in branch now uses paren_expr_end, and that continuation accepts the existing and/or and modifier parser as well as separators. Corpus 989 adds direct and eval sequence/endless-method controls, including the newline and and/or forms. Full validation passes: 885/885 ON/OFF, 885 VM / 0 fallback / 0 differences, nine source gates plus hygiene, and no lost passing case across the six requested CRuby files.

Portable evidence: https://github.com/284km/mere-ruby/blob/codex-parse-parenthesized-patterns/unittest/records/parse-patterns-review.json

Comment thread m_parse.mere

// `; more` after an expression or rightward match begins the rest of the
// statement sequence. A missing separator still goes through expect.
and paren_expr_end = fn (e: Expr) -> fn r2 ->

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

Minor 2: after a rightward match, only newline/; and ) are accepted here, so a statement modifier is still refused inside parentheses. (h => [x] rescue :r), (h => {a:} if true) and (h => {a:} unless false; a) are SyntaxError; ruby gives :r, nil and 5. The same forms work without the parentheses.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

Fixed in a518421. Parenthesized match continuations now route if/unless/while/until/rescue and and/or through the existing statement-modifier handling. Corpus 989 covers both rightward and boolean in matching, failed matches rescued inside the parentheses, inactive modifiers, and bounded loop modifiers. All match the reference on evaluator and VM.

Comment thread m_parse.mere
if str_eq colon ":" && str_len nm > 0
&& (if str_eq (char_at nm 0) "@" || str_eq (char_at nm 0) "$" then false else true)
then (nm, r0)
else (let _ = syn_refuse "expected a label as the key in the hash pattern\nunexpected local variable or method; expected a key in the hash pattern" in ("", Nil))

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

Suggestion: for @iv, $g and @@cv the second line says "unexpected local variable or method". Prism says "unexpected instance variable" / "global variable" / "class variable". The framed eval/load paths replace this text. The string forms of instance_eval / class_eval / module_eval do not: they raise StandardError with this raw text.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

Recorded as a separate pre-existing follow-up in the loop and updated description. The string forms of instance_eval/class_eval/module_eval still use their existing raw-error path; this update preserves the framed file/eval/load/require behavior and fixes the two blocking Minor findings. The raw variable-kind wording should be addressed together with that entry-point framing rather than reported as fixed here.

@284km 284km left a comment

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

Re-review of head 869ef3c9. Our previous review was on d951fb93. Event: COMMENT. Not merged.

Earlier findings

  • Minor 1 (in inside parentheses refused a following statement): resolved. Verified by running. The in branch now goes through paren_expr_end, the same path as =>.
  • Minor 2 (a modifier after a rightward match inside parentheses): resolved. Verified by running. paren_expr_end now sends if / unless / while / until / rescue / and / or to paren_after_stmt, which uses the existing statement modifier parser.
  • Suggestion 1 (string forms of instance_eval / class_eval / module_eval): deferred by the author as a follow-up. That is fine. Behaviour there is unchanged.

How I checked

I ran a build of this head. The build's tree is clean and on 869ef3c9. The binary is newer than every .mere source. 869ef3c9 only adds a loop note and a JSON record, so the code is the code of a5184219. I ran each probe on both engines: the evaluator (MERE_RUBY_VM unset) and the VM (MERE_RUBY_VM=1). I compared each with reference Ruby 4.0.10. I also ran a build of d951fb93 as the "before" side.

The earlier failing probes. All of these were a SyntaxError at d951fb93. All now print the same as ruby on both engines:

x = (h in {a:}; a)                     # 7
def k3(h) = (h in {a: 1}; :ok)         # :ok
(h in {a:}
 a)                                    # 7
(h in {a:} and true; a)                # 7
(h => [x] rescue :r)                   # :r
(h => {a:} if true)                    # nil
(h => {a:} unless false; a)            # 5
(h in {a:} if true; a)                 # 5

I also ran these neighbours. All match ruby on both engines: (h => {a:} if false; a) (nil, the variable is still declared), (h in {b:} or :no), (h => {a:} while (c += 1) < 3; [a, c]), (h => {a: 0} rescue $!.class), (h => {a:} rescue nil if true; a), (h => {a:} if true and false), (1 in Integer and 2 in Integer or 3), (h in {a:} if + newline + true), def f(h) = (h in {a:} and a), a lambda body, and ((h in {a:} and a) + 1).

Regressions from the new routing. paren_expr_end has three callers, all in paren_expr_body: the => branch, the in branch, and the fall-through arm. The fall-through arm never sees an identifier, because the TId arm above it takes every identifier first. So the new and / or / modifier arm fires only after a one-line pattern match. A plain expression still takes its old path. I confirmed this by running. These match ruby on both engines:

  • (a and b), (nil or b), (not a), (x = 1 if c), (foo rescue nil), (foo rescue :r; 3), (a or b; :c), (1 while false), (1 until true).
  • A multi-line group, (1 + newline + and 2), (nil or + newline + 2).
  • (...) as call arguments (m((1 if true), (2 rescue 3), (4 and 5))), as hash values ({k: (1 if false), j: (2 and 3)}), and pattern groups in both places.
  • p(:a => 1), foo(1, :k => 2), foo(:k => 2, w: 1), while (v = q.next rescue nil), (a, b = 1, 2 if true), and a case/in guard with (a in Integer and true).

Corpus. 989 and 990 pass on both engines. So do the other pattern and paren programs I picked (70, 97, 136, 364, 365, 376, 377, 666, 821, 850, 899) and 980–986.

Merge state. git merge-tree against current origin/main (a63e47c3) is clean. A rebuild on top of current main has not been tested.

New findings

Suggestion 1: a leading and / or on the next line after a pattern match inside parentheses is still a SyntaxError. Ruby 4.0 lets a line that begins with and / or continue the statement before it.

h = {a: 1}
x = (h in {a:}
  and 2)     # ruby: 2; this head: SyntaxError on both engines
x = (h in {a:}
  or 2)      # ruby: true; this head: SyntaxError

This is not a regression. d951fb93 refuses it too. The same shape works at top level, in begin ... end, and for a plain expression in parentheses ((1 + newline + and 2)). Here the newline arm of paren_expr_end sends the next line to paren_seq as a new statement. A likely fix: in that arm, if the first token after the newlines is and / or, call paren_after_stmt (SExpr e) r2. apply_modifier already handles a newline followed by and / or. I call it a Suggestion because the shape is rare and the PR's stated cases all work.

Suggestion 2: and / or after a rightward match => inside parentheses is now accepted. Ruby refuses it.

h = {a: 1}
p((h => {a:} and false))   # ruby: SyntaxError "unexpected void value expression"; this head: nil
p [(h => {a:} or :n)]      # ruby: the same SyntaxError; this head: [:n]

A rightward match has no value, so ruby refuses it as the left side of and / or. d951fb93 refused these shapes (with a different message). But the same gap already exists without parentheses on main: h => {a:} and false and h => {a:} or p(:n) both run. Only programs that ruby refuses change. So I do not count it as a blocking regression. A fix could refuse and / or after an EMatchBind in apply_modifier, which would cover both places. (in is different: h in {a:} and true is valid and works.)

Not changed (outside the scope of this PR)

  • defined?(h in {a:} and 1) is still a SyntaxError. Ruby gives "expression". It goes through defined_paren_rest, which this PR does not touch.
  • The PR description still contains a local absolute path to the reference Ruby. Consider replacing it with tools/ref_ruby.sh.

What I ran vs. read

  • Ran: every probe above, corpus programs listed above, and git merge-tree.
  • Read only: the diff of a5184219 and 869ef3c9, paren_expr_body, paren_expr_end, paren_after_stmt, paren_seq and apply_modifier at the head.
  • Not run: the full corpus, the gates, or the CRuby unit files. The PR body and the loop note report them for a5184219: corpus --both 885/885, VM 885 / 0 fallback / 0 differences, eight corpus-prefix source gates plus record_hygiene and the generated-C bracket gate, and all six related CRuby files COMPLETE on both engines with no lost passes. I did not reproduce them.

Merge criteria

Both earlier Minors are resolved. Suggestion 1 from the earlier review is deferred, which is allowed. The two new findings are Suggestions. The author's local results are posted. So the merge criteria are met.

CI

At review time, for 869ef3c9 only NKF Wasm engine has finished (success). CI is pending. The gem suites, runtime load path controls, Linux build dependency controls and Rake suite jobs are queued.

Merge waits for the pending manual main CI run to start.

Comment thread m_parse.mere
| Cons (TId w, _) when str_eq w "if" || str_eq w "unless" || str_eq w "while"
|| str_eq w "until" || str_eq w "rescue" || str_eq w "and" || str_eq w "or" ->
paren_after_stmt (SExpr e) r2
| Cons (TNL _, _) ->

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

Suggestion 1: after a pattern match, a next line that begins with and / or goes to paren_seq as a new statement and is refused. x = (h in {a:} + newline + and 2) gives 2 in ruby and a SyntaxError here. Checking for and / or after skip_nls r2 and calling paren_after_stmt (SExpr e) r2 would cover it, since apply_modifier already handles a newline followed by and / or.

Comment thread m_parse.mere
// statement sequence. A missing separator still goes through expect.
and paren_expr_end = fn (e: Expr) -> fn r2 ->
match r2 with
| Cons (TId w, _) when str_eq w "if" || str_eq w "unless" || str_eq w "while"

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

Suggestion 2: this arm also accepts and / or after a rightward match. Ruby refuses (h => {a:} and false) with "unexpected void value expression"; this head returns nil. The same gap exists without parentheses on main (h => {a:} and false runs), so it is not blocking. A check in apply_modifier for and / or after an EMatchBind would cover both places.

@284km
284km merged commit f371c46 into main Nov 25, 2026
9 of 19 checks passed
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.

1 participant