|
| 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 | + t.Parallel() |
| 17 | + // Create an empty file |
| 18 | + text := "" |
| 19 | + sourceFile := parser.ParseSourceFile(ast.SourceFileParseOptions{ |
| 20 | + FileName: "/index.ts", |
| 21 | + Path: "/index.ts", |
| 22 | + }, text, core.ScriptKindTS) |
| 23 | + |
| 24 | + // Create language service with nil program (we're only testing the formatting function) |
| 25 | + langService := &LanguageService{} |
| 26 | + |
| 27 | + // Test formatting after keystroke with newline character at position 0 |
| 28 | + ctx := context.Background() |
| 29 | + options := format.GetDefaultFormatCodeSettings("\n") |
| 30 | + |
| 31 | + // This should not panic |
| 32 | + edits := langService.getFormattingEditsAfterKeystroke( |
| 33 | + ctx, |
| 34 | + sourceFile, |
| 35 | + options, |
| 36 | + 0, // position |
| 37 | + "\n", |
| 38 | + ) |
| 39 | + |
| 40 | + // Should return nil or empty edits, not panic |
| 41 | + _ = edits |
| 42 | +} |
| 43 | + |
| 44 | +// Test with a simple statement |
| 45 | +func TestGetFormattingEditsAfterKeystroke_SimpleStatement(t *testing.T) { |
| 46 | + t.Parallel() |
| 47 | + // Create a file with a simple statement |
| 48 | + text := "const x = 1" |
| 49 | + sourceFile := parser.ParseSourceFile(ast.SourceFileParseOptions{ |
| 50 | + FileName: "/index.ts", |
| 51 | + Path: "/index.ts", |
| 52 | + }, text, core.ScriptKindTS) |
| 53 | + |
| 54 | + // Create language service with nil program |
| 55 | + langService := &LanguageService{} |
| 56 | + |
| 57 | + // Test formatting after keystroke with newline character at end of statement |
| 58 | + ctx := context.Background() |
| 59 | + options := format.GetDefaultFormatCodeSettings("\n") |
| 60 | + |
| 61 | + // This should not panic |
| 62 | + edits := langService.getFormattingEditsAfterKeystroke( |
| 63 | + ctx, |
| 64 | + sourceFile, |
| 65 | + options, |
| 66 | + len(text), // position at end of file |
| 67 | + "\n", |
| 68 | + ) |
| 69 | + |
| 70 | + // Should return nil or empty edits, not panic |
| 71 | + _ = edits |
| 72 | +} |
0 commit comments