typescript-go icon indicating copy to clipboard operation
typescript-go copied to clipboard

lsp: prevent out-of-range panic in autoimports/completions when symbol name or position is invalid (fixes #1691)

Open arash-mosavi opened this issue 3 months ago • 2 comments

Summary

Prevent a slice out-of-range panic in the LSP when computing completions/auto-imports for edge-case positions or empty symbol names.
The change adds minimal bounds checks and early returns around string/slice indexing in the language server hot paths.

Fixes #1691.

Repro (one-liner)

Typing at boundary positions (e.g., before the first char, at len(text), or on an empty/whitespace symbol) could lead to computing invalid indices and slicing out of range, causing a panic in completions/auto-imports.

Root Cause

Helpers assumed valid non-empty symbols and in-range positions, then immediately sliced the source text or accessed s[0]. For empty names or out-of-bounds positions, indices became negative or > len, triggering a panic.

What’s changed (small & localized)

  • internal/ls/completions.go
    • Clamp indices in getWordLengthAndStart / getDotAccessor before slicing.
    • Early-return a safe default when start >= end or symbol is empty.
  • internal/ls/autoimports.go
    • Validate slice bounds when deriving node_modules subpaths; avoid constructing invalid substrings at boundaries.
  • internal/ls/autoimportsexportinfo.go
    • Skip empty symbol names before accessing the first character.

Changes are narrowly scoped to the points where invalid indices were observed; no refactors or logic rewrites.

Behavior & Compatibility

  • Only change is no more panics in these edge cases.
  • For invalid input (empty symbol / OOB position) we return a safe default so the LSP remains responsive.
  • Performance impact is negligible (constant-time checks on hot paths).

Tests

  • Manually verified with boundary positions (-1, len(text), len(text)+1) and empty/whitespace symbols.
  • Happy-path completions/auto-imports unchanged.
  • (Can follow up with regression tests for these cases if desired.)

Risk

Low. Defensive bounds checks and early returns only; no broader behavior changes.

Notes for maintainers

This PR comes from a fork; could you please Approve and run the workflows so required checks can report?
All local checks pass (go test ./..., also with -race).

arash-mosavi avatar Sep 27 '25 09:09 arash-mosavi

@microsoft-github-policy-service agree

arash-mosavi avatar Sep 27 '25 09:09 arash-mosavi

These fixes could be plausible, but need fourslash tests to verify.

jakebailey avatar Oct 09 '25 11:10 jakebailey