Skip to content

Fix index out of bounds panic in setLastNonTriviaPosition for empty strings#3375

Draft
Copilot wants to merge 2 commits intomainfrom
copilot/fix-code-action-crash
Draft

Fix index out of bounds panic in setLastNonTriviaPosition for empty strings#3375
Copilot wants to merge 2 commits intomainfrom
copilot/fix-code-action-crash

Conversation

Copy link
Copy Markdown
Contributor

Copilot AI commented Apr 9, 2026

setLastNonTriviaPosition panics when called with an empty string via WriteLiteral("") during code action JSX text emission. The trailing whitespace loop accesses s[len(s)-i-1] without a bounds check — in TypeScript, charCodeAt(-1) returns NaN which exits the loop naturally; Go panics.

Fix: Add i < len(s) guard to the loop condition:

// before
for stringutil.IsWhiteSpaceLike(rune(s[len(s)-i-1])) {

// after
for i < len(s) && stringutil.IsWhiteSpaceLike(rune(s[len(s)-i-1])) {
  • internal/printer/changetrackerwriter.go — bounds check on trailing whitespace loop
  • internal/printer/changetrackerwriter_test.go — unit tests for empty and all-whitespace strings
  • internal/fourslash/tests/importFixJsxNoCrash_test.go — fourslash test exercising import fix on JSX

Add bounds check to the trailing whitespace loop in setLastNonTriviaPosition
to prevent index out of bounds panic when called with an empty string.

In TypeScript, `s.charCodeAt(s.length - i - 1)` returns NaN for empty strings,
causing isWhiteSpaceLike to return false and the loop to exit. In Go, indexing
an empty string causes a panic, so we need an explicit bounds check.

Agent-Logs-Url: https://github.com/microsoft/typescript-go/sessions/52c89341-0a45-4f62-bb72-8145a17ef845

Co-authored-by: DanielRosenwasser <972891+DanielRosenwasser@users.noreply.github.com>
Copilot AI changed the title [WIP] Fix code action crash from setLastNonTriviaPosition Fix index out of bounds panic in setLastNonTriviaPosition for empty strings Apr 9, 2026
Copilot AI requested a review from DanielRosenwasser April 9, 2026 19:20
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.

Code action crash from setLastNonTriviaPosition

2 participants