Skip to content

Preserve text ranges on updated and cloned API nodes - #65649

Open
Andrew Branch (andrewbranch) wants to merge 10 commits into
microsoft:mainfrom
andrewbranch:api-clone-update-text-ranges
Open

Andrew Branch (andrewbranch) wants to merge 10 commits into
microsoft:mainfrom
andrewbranch:api-clone-update-text-ranges

Conversation

@andrewbranch

Copy link
Copy Markdown
Member

In Strada, the update* factory helpers and getSynthesizedDeepClone copy the original node's pos and end onto the new node. In TS 7, they instead delegated directly to create*, returning synthesized nodes with pos: -1, end: -1.

Because the Go printer uses node text ranges to look up trivia in the original source text, dropping ranges on updated and cloned nodes had several observable effects when printing modified ASTs:

  1. Shebangs were dropped after updateSourceFile. The printer skips shebang emission on synthesized SourceFile roots (pos < 0), so updating any statement in a file starting with #!/usr/bin/env node silently lost the shebang:

    // Source: "#!/usr/bin/env node\nconst x = 1;\n"
    const updated = updateSourceFile(sourceFile, newStatements, sourceFile.endOfFileToken);
    await api.printer.printFile(updated);
    // Before: "const y = 1;\n"
    // After:  "#!/usr/bin/env node\nconst y = 1;\n"
  2. Updated statements lost their surrounding comments. Updating a child inside a statement gave the enclosing statement pos: -1, end: -1, causing leading and trailing source comments on that statement to disappear on print:

    // Source:
    // // leading
    // foo(1); // trailing
    
    // Rename `foo` -> `bar` via visitEachChild:
    // Before: "bar(1);\n" (or leaked/misplaced comments depending on which children were untouched)
    // After:  "// leading\nbar(1); // trailing\n"

Suppressing outer comments on clones

In Strada, getSynthesizedDeepClone(node, /*includeTrivia*/ false) sets EmitFlags.NoLeadingComments / EmitFlags.NoTrailingComments down the clone's first- and last-child chains (while keeping text ranges intact, so inner comments like the one in foo(/* arg */ 1) survive).

In TS 7, emit flags live in an EmitContext rather than on nodes, so the clone function can't set them by itself. Instead of threading an EmitContext through getSynthesizedDeepClone, this PR splits the two jobs:

  • getSynthesizedDeepClone and getSynthesizedDeepClones always keep text ranges, and their includeTrivia parameter is removed.
  • The new emitContext.suppressLeadingAndTrailingComments(node) handles the comment suppression. It works on any node, not just clones.
const emitContext = api.printer.createEmitContext();
const clone = emitContext.suppressLeadingAndTrailingComments(getSynthesizedDeepClone(stmt));
await api.printer.printFile(updatedFile, { emitContext });
// Keeps `/* arg */` inside `foo(/* arg */ 1)`, strips outer `// leading` and `// trailing`

Generated update functions and updateSourceFile now copy the original
node's pos/end onto the updated node, so getSynthesizedDeepClone keeps
ranges too. This fixes shebangs being dropped when printing an updated
SourceFile. getSynthesizedDeepClone(node, false, emitContext) suppresses
leading/trailing comments via emit flags while keeping ranges.

Also visit JSDoc parameter/property tags in source order according to
isNameFirst.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
…ents

getSynthesizedDeepClone now always preserves text ranges. Comment
suppression is opted into separately via the emit context.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot AI balanced review requested due to automatic review settings November 24, 2026 01:08
@github-project-automation github-project-automation Bot moved this to Not started in PR Backlog Nov 24, 2026
@typescript-automation typescript-automation Bot added Author: Team For Uncommitted Bug PR for untriaged, rejected, closed or missing bug labels Nov 24, 2026

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 Changes recommended

Critical printer regressions can emit invalid mixed nullish/logical expressions after AST updates and discard interior comments.

2 open issues
What changed in this PR

This PR preserves source text ranges on updated and deeply cloned TypeScript API nodes, allowing the Go printer to retain shebangs and source comments when printing modified syntax trees.

Changes:

  • Preserve original ranges in generated update* helpers and deep clones.
  • Replace the clone helpers’ includeTrivia parameter with explicit outer-comment suppression through EmitContext.
  • Add range and printer regression tests, and correct JSDoc child visitation order.
File Description
tools/​scripts/​tsc/​generate-ts-ast.ts Generate range-preserving update helpers.
packages/​typescript/​test/​sync/​ast.test.ts Test preserved ranges and JSDoc visitation order.
packages/​typescript/​test/​sync/​api.test.ts Add synchronous printer regression tests.
packages/​typescript/​test/​async/​api.test.ts Add asynchronous printer regression tests.
packages/​typescript/​src/​ast/​visitor.ts Visit JSDoc names and types in source order.
packages/​typescript/​src/​ast/​factory.generated.ts Apply range preservation to generated factories.
packages/​typescript/​src/​ast/​clone.ts Preserve clone ranges and remove includeTrivia.
packages/​typescript/​src/​api/​printer.ts Add explicit outer-comment suppression.

Review effort: Balanced

Comment thread packages/typescript/src/api/printer.ts Resolved
Comment thread tools/scripts/tsc/generate-ts-ast.ts Resolved
Stop descending once a child no longer shares its parent's start/end,
so comments inside delimiters are kept.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Client factory nodes are now marked NodeFlags.Synthesized, and the printer
treats operands with that flag like range-less ones when deciding whether
mixed ?? and ||/&& need parentheses. Updated nodes keep their source ranges,
so the range alone no longer identifies factory-created operands. Parsed
code prints unchanged.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 Changes recommended

Critical comment-preservation regressions remain: outer-comment suppression removes interior function-body comments, and synthesized clones lose token-level source comments.

3 open issues
1 resolved since last review

Review effort: Balanced

Comment thread packages/typescript/src/api/printer.ts Resolved
Comment thread tools/scripts/tsc/generate-ts-ast.ts Resolved
Update and clone functions now record the node they were created from.
printNode sends the server identity of each node's parsed original so the
printer can find comments next to tokens in deep clones.

Comment suppression now only walks through nodes without source positions.
Emit flags on a positioned node already hide descendants' comments at that
position, and walking further hid comments before a function body's
closing brace.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 Changes recommended

Comment suppression crosses synthesized block boundaries and incorrectly removes comments inside emitted braces; delimiter-aware propagation and a regression test are needed.

1 open issue
3 resolved since last review

Review effort: Balanced

Comment thread packages/typescript/src/api/printer.ts Resolved
…xt-ranges

# Conflicts:
#	packages/typescript/test/async/api.test.ts
#	packages/typescript/test/sync/api.test.ts
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 Changes recommended

API printing mishandles UTF-16 ranges and replacement-list trailing commas, causing non-ASCII trailing comments to be lost and final array holes to be dropped.

2 open issues
1 resolved since last review

Review effort: Balanced

Comment thread tsc/internal/api/session.go Resolved
Comment thread tsc/internal/api/session.go Resolved
Positions from the client are UTF-16 offsets, but the printer reads comments
from the source text by UTF-8 byte offset, so comments after non-ASCII text
were missed.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔵 Needs a closer look

Human assessment is needed because findings omitted from the published review identify a critical TSX printing regression and original-node associations that cannot be cleared.

No open issues 🎉

2 resolved since last review

Review effort: Balanced

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

Author: Team For Uncommitted Bug PR for untriaged, rejected, closed or missing bug

Projects

Status: Not started

Development

Successfully merging this pull request may close these issues.

2 participants