Fix: second sweep of Rails-idiom formatting bugs#104
Merged
sorafujitani merged 1 commit intomainfrom Apr 24, 2026
Merged
Conversation
Follow-up to PR #102. A second pass over common Ruby/Rails patterns (operator methods, begin/else/ensure, heredocs in unusual positions, inline comments in headers, block-nested chains, etc.) turned up seven additional latent bugs, three of which produced code that stopped parsing as Ruby. This change fixes all of them in one shot. Critical — formatter output no longer parses - else/ensure overshoot in `begin…end` (bugs #4/#5) `ElseNode.location` extends through the following clause's keyword (`ensure`, or the begin's `end`). Emitting that slice through the fallback rule therefore duplicated whichever keyword came next: `else/ensure/end` became `else…\nensure\nensure\n…\nend`, and `else/end` became `else…\nend\nend`. Fixed by handling ElseNode explicitly in `format_explicit_begin` / `format_implicit_begin_body` so we emit just `else\n body` and defer the following keyword to its own rule. - heredoc argument + postfix `if`/`unless` (bug #3) `foo(<<~SQL, …) if cond\n …\nSQL` used to be rewritten as `foo(…) if cond\n …\nSQL if cond` — which makes Ruby treat `SQL` as part of the heredoc body and silently merges into the next heredoc, or fails to parse entirely. The bridge extends a heredoc-carrying statement's end_offset past the terminator, so the source slice already contains the modifier in the right place; emit the slice verbatim in `format_postfix` when it looks like a heredoc tail (line 1 contains `<<`, and later lines contain non-chain content). - multi-line def header with inline comments (bug #2) `def demo(a, # c1\n b, # c2\n c) # c3` lost the trailing paren's comment, duplicated the opener's, and moved the rest into the body; worse, each format pass duplicated them again, so the file was non-idempotent. When `parameters_text` spans multiple lines, emit the header verbatim from source (def_start → end of the line before the body begins) and mark every comment in that range as emitted. High — wrong indent, not a parse error - chain continuations inside a block/lambda body (bug #9) `scope :x, -> { where(...)\n .where(...) }` had its inner `.where(...)` collapsed to the outer base indent because `reformat_chain_lines` didn't distinguish top-level chain continuations from continuations inside a nested scope. Skip the reformat when the opening line ends with `{`, ` do`, or `|` (the marker of a `do |params|` opener). - heredoc inside `if` predicate (bug #10) `if (sql = <<~SQL)\n …\nSQL\n body` inserted a blank line between the terminator and the body, because the predicate slice kept the trailing newline past the heredoc terminator. Strip one trailing newline from the predicate source in `format_normal`. Style preservation - `x = begin…end` inline (bug #6) The assignment `x = begin\n …\nend` was rewritten to `x =\n begin\n …\nend`. Detect "value starts on the same line as the assignment" in `format_variable_write` and keep the opener on the assignment line. - `def !@` → `def !` (operator method) `extract_node_name` returned Prism's canonical name (`:!`), silently rewriting `def !@` to `def !`. Prefer `name_loc.slice` for DefNode so explicit `@` suffixes survive. Shared plumbing - `format_body_end` factors body + `end` emission into `push_body_and_end` so the single-line, multi-line-header, and standard paths share the logic. - `begin.rs` introduces `format_begin_clause`, a clause emitter shared by explicit and implicit begin paths. - `if_unless.rs` adds `statement_contains_heredoc_tail` for the postfix-with-heredoc detection. - New helper `line_end_offset` in `body_end.rs` locates the newline that terminates a given 1-based line. Tests - spec/rails_idioms_round2_spec.rb: 9 round-trip + idempotence + Prism parse-check tests covering every fix above. - All 128 rspec examples (119 existing + 9 new) and 127 cargo unit tests pass. `cargo clippy -D warnings`, `cargo fmt --check`, and `rubocop` are clean.
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.
Re-opens #103 now that #102 has landed and its base branch was deleted. This PR now targets
maindirectly; no content changes from #103.Summary
Seven more formatter bugs surfaced by a systematic walk through Rails-flavoured Ruby patterns that weren't covered by #102. Three of them caused the formatter to emit code that no longer parses; the rest silently reshape user style.
Bugs fixed
begin/rescue/else/ensure/end→else...\nensure\nensure\n...\nend;begin/rescue/else/end→else...\nend\nendElseNode.locationextends through the next clause keyword. The fallback rule's source-slice emission therefore re-prints whatever comes after — duplicatingensureorend.foo(<<~SQL, …) if cond\n …\nSQL→foo(…) if cond\n …\nSQL if cond— theifmodifier sticks to the terminator line, so Ruby never closes the heredoc.end_offsetpast the terminator, and the extended slice already contains the modifier text, butformat_postfixstill appendedif condafter it.def demo(a, # c1\n b, # c2\n c) # c3duplicated the first comment, ejected the rest into the body, and each format pass duplicated them again.build_def_headerrebuilds the signature fromparameters_text, and laterformat_trailing_comment/format_leading_commentscalls re-collect comments already embedded in the slice.scope :x, -> { where(...)\n .where(...) }) were re-indented to the outerbase_indent, erasing the nested scope.reformat_chain_linestreats any.xxxline as chain continuation regardless of nesting.if (sql = <<~SQL)\n …\nSQL\n execute(sql)gained a blank line between the terminator andexecute.\npast the heredoc terminator, which compounded withformat_normal's ownhardline.x = begin\n …\nendrewritten asx =\n begin\n …\nend.format_variable_writeunconditionally split block-valued assignments across two lines.!@def !@silently rewritten todef !.extract_node_namereturns Prism's canonicalname(:!), discarding the@suffix; the original slice lives onname_loc.Before / after highlights
Changes
ext/rfmt/src/format/rule.rs—reformat_chain_linesnow skips lines that open a block ({,do,|).ext/rfmt/src/format/rules/begin.rs—format_begin_clauseemitter handlesElseNodeexplicitly; used from bothformat_explicit_beginandformat_implicit_begin_body.ext/rfmt/src/format/rules/body_end.rs— multi-line header detection with verbatim source emission + comment-mass-mark-emitted; sharedpush_body_and_endbody/end emitter;line_end_offsethelper.ext/rfmt/src/format/rules/if_unless.rs—format_postfixemits heredoc-containing statements verbatim;format_normalstrips one trailing newline from the predicate slice; newstatement_contains_heredoc_taildetector.ext/rfmt/src/format/rules/variable_write.rs— inline preservation when the block-valued RHS starts on the assignment's own line.lib/rfmt/prism_bridge.rb—DefNodename usesname_loc.sliceto keep operator@suffixes.spec/rails_idioms_round2_spec.rb— 9 round-trip + idempotence + Prism parse-check tests, one per bug.Test plan
cargo test --manifest-path ext/rfmt/Cargo.toml --lib— 127 passedbundle exec rspec— 128 passed (119 existing + 9 new)cargo clippy -- -D warnings— cleancargo fmt --check— cleanbundle exec rubocop— cleanSupersedes #103 (closed when its base branch was deleted alongside the #102 merge).