Fix panic in textDocument/formatting with slice bounds out of range #1931
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.
Problem
The formatter was panicking when handling certain code patterns, specifically when formatting code with trailing semicolons and comments. The panic manifested as:
Example code that triggered the panic:
Root Causes
After cross-comparing with the TypeScript reference implementation in
_submodules/TypeScript/src/services/formatting/formatting.ts, two related issues were identified:1. Negative indentation handling
When processing comments, the formatter can receive an indentation value of
-1(representingConstants.Unknownin TypeScript). Go'sstrings.Repeatpanics on negative counts, while TypeScript's customrepeatStringfunction gracefully handles this by using a for loop that simply returns an empty string when the count is negative.2. Slice bounds checking
The
indentationIsDifferentfunction attempted to slice the source text without verifying the slice wouldn't exceed the text length, causing a bounds panic.Solution
In
internal/format/span.go:getIndentationStringto return an empty string for negative indentation values, matching TypeScript's behaviorindentationIsDifferentbefore slicing to prevent out-of-range panicsIn
internal/format/comment_test.go:TestSliceBoundsPanicthat reproduces the original panic scenario and verifies the fixTesting
Fixes the panic reported in the issue while maintaining compatibility with all existing formatting behavior.
Original prompt
Fixes #1925
✨ Let Copilot coding agent set things up for you — coding agent works faster and does higher quality work when set up for your repo.