Skip to content

fix: stabilize with statement formatting with comments#788

Open
todor-a wants to merge 1 commit into
dprint:mainfrom
todor-a:fix-with-stmt-comment-stability
Open

fix: stabilize with statement formatting with comments#788
todor-a wants to merge 1 commit into
dprint:mainfrom
todor-a:fix-with-stmt-comment-stability

Conversation

@todor-a

@todor-a todor-a commented May 28, 2026

Copy link
Copy Markdown
Contributor

Fixes #787.


Transparency note: This PR was prepared with AI assistance (Claude).


Problem

with (a) { //
}

emits Error formatting repro.ts. Message: Formatting not stable. Bailed after 5 tries.

Root cause

Node::WithStmt had no IR generator. It fell into the gen_node_inner fallback at the bottom of the dispatch (Class | Function | Invalid | WithStmt | TsModuleBlock), which calls gen_from_raw_string(node.text_fast(...)) — i.e. emits the original source bytes verbatim without walking children.

That bypasses the comment tracker. The inner // is never marked consumed, so on the next pass it's re-emitted as a trailing comment after the closing brace. Each format pass appends another //:

with (a) { //   →   with (a) { //   →   with (a) { //
}                   } //                } //
                                        //

Stability check bails after 5 attempts.

Fix

Add a real gen_with_stmt mirroring gen_while_stmt. with (obj) body has the same shape as while (test) body (keyword + parenthesized expression + body statement), so the new function reuses the existing while_statement_* configuration rather than introducing new config keys (with is deprecated and forbidden in strict mode, so dedicated config seems unwarranted).

Removed WithStmt from the "should never be matched" fallback list.

Tests

Added tests for this specific case, plus extra tests from https://github.com/prettier/prettier/tree/main/tests/format/json/with-comment.

`WithStmt` had no IR generator and fell into the raw-text fallback,
which dumps node source verbatim without consuming child comments. The
comment tracker then re-emitted the inner line comment after the node,
duplicating it on every pass:

    with (a) { //
    }

    -> with (a) { //
       } //

    -> with (a) { //
       } //
       //
    ...

Causing "Formatting not stable. Bailed after 5 tries."

Add a proper `gen_with_stmt` that mirrors `gen_while_stmt` (identical
shape: keyword + parenthesized expression + body statement) and reuses
the existing `while_statement_*` configuration.
@todor-a todor-a changed the title fix: stabilize with statement formatting with comments (#787) fix: stabilize with statement formatting with comments May 28, 2026
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.

Formatting instability with 'with' statement and trailing line comment

1 participant