Debian Codegraph @

gopls/internal/cache/parsego/parse_test.go

raw symbols SCIP
1 // Copyright 2023 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package parsego_test
6
7 import (
8 "context"
9 "fmt"
10 "go/ast"
11 "go/parser"
12 "go/token"
13 "reflect"
14 "slices"
15 "testing"
16
17 "golang.org/x/tools/gopls/internal/cache/parsego"
18 "golang.org/x/tools/gopls/internal/util/safetoken"
19 "golang.org/x/tools/gopls/internal/util/tokeninternal"
20 "golang.org/x/tools/internal/astutil"
21 )
22
23 // TODO(golang/go#64335): we should have many more tests for fixed syntax.
24
25 func TestFixPosition_Issue64488(t *testing.T) {
26 // This test reproduces the conditions of golang/go#64488, where a type error
27 // on fixed syntax overflows the token.File.
28 const src = `
29 package foo
30
31 func _() {
32 type myThing struct{}
33 var foo []myThing
34 for ${1:}, ${2:} := range foo {
35 $0
36 }
37 }
38 `
39
40 pgf, _ := parsego.Parse(context.Background(), token.NewFileSet(), "file://foo.go", []byte(src), parsego.Full, false)
41 fset := tokeninternal.FileSetFor(pgf.Tok)
42 ast.Inspect(pgf.File, func(n ast.Node) bool {
43 if n != nil {
44 posn := safetoken.StartPosition(fset, n.Pos())
45 if !posn.IsValid() {
46 t.Fatalf("invalid position for %T (%v): %v not in [%d, %d]", n, n, n.Pos(), pgf.Tok.Base(), pgf.Tok.Base()+pgf.Tok.Size())
47 }
48 }
49 return true
50 })
51 }
52
53 func TestFixGoAndDefer(t *testing.T) {
54 var testCases = []struct {
55 source string
56 fixes []parsego.FixType
57 wantFix string
58 }{
59 {source: "", fixes: nil}, // keyword alone
60 {source: "a.b(", fixes: nil},
61 {source: "a.b()", fixes: nil},
62 {source: "func {", fixes: nil},
63 {
64 source: "f",
65 fixes: []parsego.FixType{parsego.FixedDeferOrGo},
66 wantFix: "f()",
67 },
68 {
69 source: "func",
70 fixes: []parsego.FixType{parsego.FixedDeferOrGo},
71 wantFix: "(func())()",
72 },
73 {
74 source: "func {}",
75 fixes: []parsego.FixType{parsego.FixedDeferOrGo},
76 wantFix: "(func())()",
77 },
78 {
79 source: "func {}(",
80 fixes: []parsego.FixType{parsego.FixedDeferOrGo},
81 wantFix: "(func())()",
82 },
83 {
84 source: "func {}()",
85 fixes: []parsego.FixType{parsego.FixedDeferOrGo},
86 wantFix: "(func())()",
87 },
88 {
89 source: "a.",
90 fixes: []parsego.FixType{parsego.FixedDeferOrGo, parsego.FixedDanglingSelector, parsego.FixedDeferOrGo},
91 wantFix: "a._()",
92 },
93 {
94 source: "a.b",
95 fixes: []parsego.FixType{parsego.FixedDeferOrGo},
96 wantFix: "a.b()",
97 },
98 }
99
100 for _, keyword := range []string{"go", "defer"} {
101 for _, tc := range testCases {
102 source := fmt.Sprintf("%s %s", keyword, tc.source)
103 t.Run(source, func(t *testing.T) {
104 src := filesrc(source)
105 pgf, fixes := parsego.Parse(context.Background(), token.NewFileSet(), "file://foo.go", src, parsego.Full, false)
106 if !slices.Equal(fixes, tc.fixes) {
107 t.Fatalf("got %v want %v", fixes, tc.fixes)
108 }
109 if tc.fixes == nil {
110 return
111 }
112
113 fset := tokeninternal.FileSetFor(pgf.Tok)
114 inspect(t, pgf, func(stmt ast.Stmt) {
115 var call *ast.CallExpr
116 switch stmt := stmt.(type) {
117 case *ast.DeferStmt:
118 call = stmt.Call
119 case *ast.GoStmt:
120 call = stmt.Call
121 default:
122 return
123 }
124
125 if got := astutil.Format(fset, call); got != tc.wantFix {
126 t.Fatalf("got %v want %v", got, tc.wantFix)
127 }
128 })
129 })
130 }
131 }
132 }
133
134 // TestFixInit tests the init stmt after if/for/switch which is put under cond after parsing
135 // will be fixed and moved to Init.
136 func TestFixInit(t *testing.T) {
137 var testCases = []struct {
138 name string
139 source string
140 fixes []parsego.FixType
141 wantInitFix string
142 }{
143 {
144 name: "simple define",
145 source: "i := 0",
146 fixes: []parsego.FixType{parsego.FixedInit},
147 wantInitFix: "i := 0",
148 },
149 {
150 name: "simple assign",
151 source: "i = 0",
152 fixes: []parsego.FixType{parsego.FixedInit},
153 wantInitFix: "i = 0",
154 },
155 {
156 name: "define with function call",
157 source: "i := f()",
158 fixes: []parsego.FixType{parsego.FixedInit},
159 wantInitFix: "i := f()",
160 },
161 {
162 name: "assign with function call",
163 source: "i = f()",
164 fixes: []parsego.FixType{parsego.FixedInit},
165 wantInitFix: "i = f()",
166 },
167 {
168 name: "assign with receiving chan",
169 source: "i = <-ch",
170 fixes: []parsego.FixType{parsego.FixedInit},
171 wantInitFix: "i = <-ch",
172 },
173
174 // fixInitStmt won't fix the following cases.
175 {
176 name: "call in if",
177 source: `fmt.Println("helloworld")`,
178 fixes: nil,
179 },
180 {
181 name: "receive chan",
182 source: `<- ch`,
183 fixes: nil,
184 },
185 }
186
187 // currently, switch will leave its Tag empty after fix because it allows empty,
188 // and if and for will leave an underscore in Cond.
189 getWantCond := func(keyword string) string {
190 if keyword == "switch" {
191 return ""
192 }
193 return "_"
194 }
195
196 for _, keyword := range []string{"if", "for", "switch"} {
197 for _, tc := range testCases {
198 caseName := fmt.Sprintf("%s %s", keyword, tc.name)
199 t.Run(caseName, func(t *testing.T) {
200 // the init stmt is treated as a cond.
201 src := filesrc(fmt.Sprintf("%s %s {}", keyword, tc.source))
202 pgf, fixes := parsego.Parse(context.Background(), token.NewFileSet(), "file://foo.go", src, parsego.Full, false)
203 if !slices.Equal(fixes, tc.fixes) {
204 t.Fatalf("TestFixArrayType(): got %v want %v", fixes, tc.fixes)
205 }
206 if tc.fixes == nil {
207 return
208 }
209
210 // ensure the init stmt is parsed to a BadExpr.
211 ensureSource(t, src, func(bad *ast.BadExpr) {})
212
213 info := func(n ast.Node, wantStmt string) (init ast.Stmt, cond ast.Expr, has bool) {
214 switch wantStmt {
215 case "if":
216 if e, ok := n.(*ast.IfStmt); ok {
217 return e.Init, e.Cond, true
218 }
219 case "switch":
220 if e, ok := n.(*ast.SwitchStmt); ok {
221 return e.Init, e.Tag, true
222 }
223 case "for":
224 if e, ok := n.(*ast.ForStmt); ok {
225 return e.Init, e.Cond, true
226 }
227 }
228 return nil, nil, false
229 }
230 fset := tokeninternal.FileSetFor(pgf.Tok)
231 inspect(t, pgf, func(n ast.Stmt) {
232 if init, cond, ok := info(n, keyword); ok {
233 if got := astutil.Format(fset, init); got != tc.wantInitFix {
234 t.Fatalf("%s: Init got %v want %v", tc.source, got, tc.wantInitFix)
235 }
236
237 wantCond := getWantCond(keyword)
238 if got := astutil.Format(fset, cond); got != wantCond {
239 t.Fatalf("%s: Cond got %v want %v", tc.source, got, wantCond)
240 }
241 }
242 })
243 })
244 }
245 }
246 }
247
248 func TestFixPhantomSelector(t *testing.T) {
249 wantFixes := []parsego.FixType{parsego.FixedPhantomSelector}
250 var testCases = []struct {
251 source string
252 fixes []parsego.FixType
253 }{
254 {source: "a.break", fixes: wantFixes},
255 {source: "_.break", fixes: wantFixes},
256 {source: "a.case", fixes: wantFixes},
257 {source: "a.chan", fixes: wantFixes},
258 {source: "a.const", fixes: wantFixes},
259 {source: "a.continue", fixes: wantFixes},
260 {source: "a.default", fixes: wantFixes},
261 {source: "a.defer", fixes: wantFixes},
262 {source: "a.else", fixes: wantFixes},
263 {source: "a.fallthrough", fixes: wantFixes},
264 {source: "a.for", fixes: wantFixes},
265 {source: "a.func", fixes: wantFixes},
266 {source: "a.go", fixes: wantFixes},
267 {source: "a.goto", fixes: wantFixes},
268 {source: "a.if", fixes: wantFixes},
269 {source: "a.import", fixes: wantFixes},
270 {source: "a.interface", fixes: wantFixes},
271 {source: "a.map", fixes: wantFixes},
272 {source: "a.package", fixes: wantFixes},
273 {source: "a.range", fixes: wantFixes},
274 {source: "a.return", fixes: wantFixes},
275 {source: "a.select", fixes: wantFixes},
276 {source: "a.struct", fixes: wantFixes},
277 {source: "a.switch", fixes: wantFixes},
278 {source: "a.type", fixes: wantFixes},
279 {source: "a.var", fixes: wantFixes},
280
281 {source: "break.break"},
282 {source: "a.BREAK"},
283 {source: "a.break_"},
284 {source: "a.breaka"},
285 }
286
287 for _, tc := range testCases {
288 t.Run(tc.source, func(t *testing.T) {
289 src := filesrc(tc.source)
290 pgf, fixes := parsego.Parse(context.Background(), token.NewFileSet(), "file://foo.go", src, parsego.Full, false)
291 if !slices.Equal(fixes, tc.fixes) {
292 t.Fatalf("got %v want %v", fixes, tc.fixes)
293 }
294
295 // some fixes don't fit the fix scenario, but we want to confirm it.
296 if fixes == nil {
297 return
298 }
299
300 // ensure the selector has been converted to underscore by parser.
301 ensureSource(t, src, func(sel *ast.SelectorExpr) {
302 if sel.Sel.Name != "_" {
303 t.Errorf("%s: selector name is %q, want _", tc.source, sel.Sel.Name)
304 }
305 })
306
307 fset := tokeninternal.FileSetFor(pgf.Tok)
308 inspect(t, pgf, func(sel *ast.SelectorExpr) {
309 // the fix should restore the selector as is.
310 if got, want := astutil.Format(fset, sel), tc.source; got != want {
311 t.Fatalf("got %v want %v", got, want)
312 }
313 })
314 })
315 }
316 }
317
318 // inspect helps to go through each node of pgf and trigger checkFn if the type matches T.
319 func inspect[T ast.Node](t *testing.T, pgf *parsego.File, checkFn func(n T)) {
320 fset := tokeninternal.FileSetFor(pgf.Tok)
321 var visited bool
322 ast.Inspect(pgf.File, func(node ast.Node) bool {
323 if node != nil {
324 posn := safetoken.StartPosition(fset, node.Pos())
325 if !posn.IsValid() {
326 t.Fatalf("invalid position for %T (%v): %v not in [%d, %d]", node, node, node.Pos(), pgf.Tok.Base(), pgf.Tok.Base()+pgf.Tok.Size())
327 }
328 if n, ok := node.(T); ok {
329 visited = true
330 checkFn(n)
331 }
332 }
333 return true
334 })
335 if !visited {
336 var n T
337 t.Fatalf("got no %s node but want at least one", reflect.TypeOf(n))
338 }
339 }
340
341 // ensureSource helps to parse src into an ast.File by go/parser and trigger checkFn if the type matches T.
342 func ensureSource[T ast.Node](t *testing.T, src []byte, checkFn func(n T)) {
343 // tolerate error as usually the src is problematic.
344 originFile, _ := parser.ParseFile(token.NewFileSet(), "file://foo.go", src, parsego.Full)
345 var visited bool
346 ast.Inspect(originFile, func(node ast.Node) bool {
347 if n, ok := node.(T); ok {
348 visited = true
349 checkFn(n)
350 }
351 return true
352 })
353
354 if !visited {
355 var n T
356 t.Fatalf("got no %s node but want at least one", reflect.TypeOf(n))
357 }
358 }
359
360 func filesrc(expressions string) []byte {
361 const srcTmpl = `package foo
362
363 func _() {
364 %s
365 }`
366 return fmt.Appendf(nil, srcTmpl, expressions)
367 }