Skip to content

Commit 26fdb17

Browse files
Copilotjakebailey
andcommitted
Add test to reproduce panic in onTypeFormatting with empty file
Co-authored-by: jakebailey <[email protected]>
1 parent 9358f12 commit 26fdb17

File tree

1 file changed

+70
-0
lines changed

1 file changed

+70
-0
lines changed

internal/ls/format_test.go

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
package ls
2+
3+
import (
4+
"context"
5+
"testing"
6+
7+
"github.com/microsoft/typescript-go/internal/ast"
8+
"github.com/microsoft/typescript-go/internal/core"
9+
"github.com/microsoft/typescript-go/internal/format"
10+
"github.com/microsoft/typescript-go/internal/parser"
11+
)
12+
13+
// Test for issue: Panic Handling textDocument/onTypeFormatting
14+
// This reproduces the panic when pressing enter in an empty file
15+
func TestGetFormattingEditsAfterKeystroke_EmptyFile(t *testing.T) {
16+
// Create an empty file
17+
text := ""
18+
sourceFile := parser.ParseSourceFile(ast.SourceFileParseOptions{
19+
FileName: "/index.ts",
20+
Path: "/index.ts",
21+
}, text, core.ScriptKindTS)
22+
23+
// Create language service with nil program (we're only testing the formatting function)
24+
langService := &LanguageService{}
25+
26+
// Test formatting after keystroke with newline character at position 0
27+
ctx := context.Background()
28+
options := format.GetDefaultFormatCodeSettings("\n")
29+
30+
// This should not panic
31+
edits := langService.getFormattingEditsAfterKeystroke(
32+
ctx,
33+
sourceFile,
34+
options,
35+
0, // position
36+
"\n",
37+
)
38+
39+
// Should return nil or empty edits, not panic
40+
_ = edits
41+
}
42+
43+
// Test with a simple statement
44+
func TestGetFormattingEditsAfterKeystroke_SimpleStatement(t *testing.T) {
45+
// Create a file with a simple statement
46+
text := "const x = 1"
47+
sourceFile := parser.ParseSourceFile(ast.SourceFileParseOptions{
48+
FileName: "/index.ts",
49+
Path: "/index.ts",
50+
}, text, core.ScriptKindTS)
51+
52+
// Create language service with nil program
53+
langService := &LanguageService{}
54+
55+
// Test formatting after keystroke with newline character at end of statement
56+
ctx := context.Background()
57+
options := format.GetDefaultFormatCodeSettings("\n")
58+
59+
// This should not panic
60+
edits := langService.getFormattingEditsAfterKeystroke(
61+
ctx,
62+
sourceFile,
63+
options,
64+
len(text), // position at end of file
65+
"\n",
66+
)
67+
68+
// Should return nil or empty edits, not panic
69+
_ = edits
70+
}

0 commit comments

Comments
 (0)