Debian Codegraph @

go/ast/inspector/cursor_test.go

raw symbols SCIP
1 // Copyright 2025 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 inspector_test
6
7 import (
8 "fmt"
9 "go/ast"
10 "go/parser"
11 "go/token"
12 "iter"
13 "math/rand"
14 "reflect"
15 "slices"
16 "strings"
17 "testing"
18
19 "golang.org/x/tools/go/ast/edge"
20 "golang.org/x/tools/go/ast/inspector"
21 )
22
23 func TestCursor_Preorder(t *testing.T) {
24 inspect := netInspect
25
26 nodeFilter := []ast.Node{(*ast.FuncDecl)(nil), (*ast.FuncLit)(nil)}
27
28 // reference implementation
29 var want []ast.Node
30 for cur := range inspect.Root().Preorder(nodeFilter...) {
31 want = append(want, cur.Node())
32 }
33
34 // Check entire sequence.
35 got := slices.Collect(inspect.PreorderSeq(nodeFilter...))
36 compare(t, got, want)
37
38 // Check that break works.
39 got = got[:0]
40 for _, c := range firstN(10, inspect.Root().Preorder(nodeFilter...)) {
41 got = append(got, c.Node())
42 }
43 compare(t, got, want[:10])
44 }
45
46 func TestCursor_nestedTraversal(t *testing.T) {
47 const src = `package a
48 func f() {
49 print("hello")
50 }
51 func g() {
52 print("goodbye")
53 panic("oops")
54 }
55 `
56 fset := token.NewFileSet()
57 f, _ := parser.ParseFile(fset, "a.go", src, 0)
58 inspect := inspector.New([]*ast.File{f})
59
60 var (
61 funcDecls = []ast.Node{(*ast.FuncDecl)(nil)}
62 callExprs = []ast.Node{(*ast.CallExpr)(nil)}
63 nfuncs = 0
64 ncalls = 0
65 )
66
67 for curFunc := range inspect.Root().Preorder(funcDecls...) {
68 _ = curFunc.Node().(*ast.FuncDecl)
69
70 // Check edge and index.
71 if k, idx := curFunc.ParentEdge(); k != edge.File_Decls || idx != nfuncs {
72 t.Errorf("%v.ParentEdge() = (%v, %d), want edge.File_Decls, %d", curFunc, k, idx, nfuncs)
73 }
74
75 nfuncs++
76 stack := slices.Collect(curFunc.Enclosing())
77
78 // Stacks are convenient to print!
79 if got, want := fmt.Sprint(stack), "[*ast.FuncDecl *ast.File]"; got != want {
80 t.Errorf("curFunc.Enclosing() = %q, want %q", got, want)
81 }
82
83 // Parent, iterated, is Enclosing stack.
84 i := 0
85 for c := curFunc; c.Node() != nil; c = c.Parent() {
86 if got, want := stack[i], c; got != want {
87 t.Errorf("Enclosing[%d] = %v; Parent()^%d = %v", i, got, i, want)
88 }
89 i++
90 }
91
92 wantStack := "[*ast.CallExpr *ast.ExprStmt *ast.BlockStmt *ast.FuncDecl *ast.File]"
93
94 // nested Preorder traversal
95 preorderCount := 0
96 for curCall := range curFunc.Preorder(callExprs...) {
97 _ = curCall.Node().(*ast.CallExpr)
98 preorderCount++
99 stack := slices.Collect(curCall.Enclosing())
100 if got := fmt.Sprint(stack); got != wantStack {
101 t.Errorf("curCall.Enclosing() = %q, want %q", got, wantStack)
102 }
103 }
104
105 // nested Inspect traversal
106 inspectCount := 0
107 curFunc.Inspect(callExprs, func(curCall inspector.Cursor) (proceed bool) {
108 _ = curCall.Node().(*ast.CallExpr)
109 inspectCount++
110 stack := slices.Collect(curCall.Enclosing())
111 if got := fmt.Sprint(stack); got != wantStack {
112 t.Errorf("curCall.Enclosing() = %q, want %q", got, wantStack)
113 }
114 return true
115 })
116
117 if inspectCount != preorderCount {
118 t.Errorf("Inspect (%d) and Preorder (%d) events are not consistent", inspectCount, preorderCount)
119 }
120
121 ncalls += preorderCount
122 }
123
124 if nfuncs != 2 {
125 t.Errorf("Found %d FuncDecls, want 2", nfuncs)
126 }
127 if ncalls != 3 {
128 t.Errorf("Found %d CallExprs, want 3", ncalls)
129 }
130 }
131
132 func TestCursor_Children(t *testing.T) {
133 inspect := netInspect
134
135 // Assert that Cursor.Children agrees with
136 // reference implementation for every node.
137 var want, got []ast.Node
138 for c := range inspect.Root().Preorder() {
139
140 // reference implementation
141 want = want[:0]
142 {
143 parent := c.Node()
144 ast.Inspect(parent, func(n ast.Node) bool {
145 if n != nil && n != parent {
146 want = append(want, n)
147 }
148 return n == parent // descend only into parent
149 })
150 }
151
152 // Check cursor-based implementation
153 // (uses FirstChild+NextSibling).
154 got = got[:0]
155 for child := range c.Children() {
156 got = append(got, child.Node())
157 }
158
159 if !slices.Equal(got, want) {
160 t.Errorf("For %v\n"+
161 "Using FirstChild+NextSibling: %v\n"+
162 "Using ast.Inspect: %v",
163 c, sliceTypes(got), sliceTypes(want))
164 }
165
166 // Second cursor-based implementation
167 // using LastChild+PrevSibling+reverse.
168 got = got[:0]
169 for c, ok := c.LastChild(); ok; c, ok = c.PrevSibling() {
170 got = append(got, c.Node())
171 }
172 slices.Reverse(got)
173
174 if !slices.Equal(got, want) {
175 t.Errorf("For %v\n"+
176 "Using LastChild+PrevSibling: %v\n"+
177 "Using ast.Inspect: %v",
178 c, sliceTypes(got), sliceTypes(want))
179 }
180 }
181 }
182
183 func TestCursor_Inspect(t *testing.T) {
184 inspect := netInspect
185
186 // In all three loops, we'll gather both kinds of type switches,
187 // but we'll prune the traversal from descending into (value) switches.
188 switches := []ast.Node{(*ast.SwitchStmt)(nil), (*ast.TypeSwitchStmt)(nil)}
189
190 // reference implementation (ast.Inspect)
191 var nodesA []ast.Node
192 for _, f := range netFiles {
193 ast.Inspect(f, func(n ast.Node) (proceed bool) {
194 switch n.(type) {
195 case *ast.SwitchStmt, *ast.TypeSwitchStmt:
196 nodesA = append(nodesA, n)
197 return !is[*ast.SwitchStmt](n) // descend only into TypeSwitchStmt
198 }
199 return true
200 })
201 }
202
203 // Test Cursor.Inspect implementation.
204 var nodesB []ast.Node
205 inspect.Root().Inspect(switches, func(c inspector.Cursor) (proceed bool) {
206 n := c.Node()
207 nodesB = append(nodesB, n)
208 return !is[*ast.SwitchStmt](n) // descend only into TypeSwitchStmt
209 })
210 compare(t, nodesA, nodesB)
211
212 // Test WithStack implementation.
213 var nodesC []ast.Node
214 inspect.WithStack(switches, func(n ast.Node, push bool, stack []ast.Node) (proceed bool) {
215 if push {
216 nodesC = append(nodesC, n)
217 return !is[*ast.SwitchStmt](n) // descend only into TypeSwitchStmt
218 }
219 return false
220 })
221 compare(t, nodesA, nodesC)
222 }
223
224 func TestCursor_FindNode(t *testing.T) {
225 inspect := netInspect
226
227 // Enumerate all nodes of a particular type,
228 // then check that FindByPos can find them,
229 // starting at the root.
230 //
231 // (We use BasicLit because they are numerous.)
232 root := inspect.Root()
233 for c := range root.Preorder((*ast.BasicLit)(nil)) {
234 node := c.Node()
235 got, ok := root.FindNode(node)
236 if !ok {
237 t.Errorf("root.FindNode failed")
238 } else if got != c {
239 t.Errorf("root.FindNode returned %v, want %v", got, c)
240 }
241 }
242
243 // Same thing, but searching only within subtrees (each FuncDecl).
244 for funcDecl := range root.Preorder((*ast.FuncDecl)(nil)) {
245 for c := range funcDecl.Preorder((*ast.BasicLit)(nil)) {
246 node := c.Node()
247 got, ok := funcDecl.FindNode(node)
248 if !ok {
249 t.Errorf("funcDecl.FindNode failed")
250 } else if got != c {
251 t.Errorf("funcDecl.FindNode returned %v, want %v", got, c)
252 }
253
254 // Also, check that we cannot find the BasicLit
255 // beneath a different FuncDecl.
256 if prevFunc, ok := funcDecl.PrevSibling(); ok {
257 got, ok := prevFunc.FindNode(node)
258 if ok {
259 t.Errorf("prevFunc.FindNode succeeded unexpectedly: %v", got)
260 }
261 }
262 }
263 }
264 }
265
266 // TestCursor_FindByPos_order ensures that FindByPos does not assume files are in Pos order.
267 func TestCursor_FindByPos_order(t *testing.T) {
268 // Pick an arbitrary decl.
269 target := netFiles[7].Decls[0]
270
271 // Find the target decl by its position.
272 cur, ok := netInspect.Root().FindByPos(target.Pos(), target.End())
273 if !ok || cur.Node() != target {
274 t.Fatalf("unshuffled: FindByPos(%T) = (%v, %t)", target, cur, ok)
275 }
276
277 // Shuffle the files out of Pos order.
278 files := slices.Clone(netFiles)
279 rand.Shuffle(len(files), func(i, j int) {
280 files[i], files[j] = files[j], files[i]
281 })
282
283 // Find it again.
284 inspect := inspector.New(files)
285 cur, ok = inspect.Root().FindByPos(target.Pos(), target.End())
286 if !ok || cur.Node() != target {
287 t.Fatalf("shuffled: FindByPos(%T) = (%v, %t)", target, cur, ok)
288 }
289 }
290
291 func TestCursor_Edge(t *testing.T) {
292 root := netInspect.Root()
293 for cur := range root.Preorder() {
294 if cur == root {
295 continue // root node
296 }
297
298 var (
299 parent = cur.Parent()
300 e, idx = cur.ParentEdge()
301 )
302
303 // ast.File, child of root?
304 if parent.Node() == nil {
305 if e != edge.Invalid || idx != -1 {
306 t.Errorf("%v.Edge = (%v, %d), want (Invalid, -1)", cur, e, idx)
307 }
308 continue
309 }
310
311 // Check Edge.NodeType matches type of Parent.Node.
312 if e.NodeType() != reflect.TypeOf(parent.Node()) {
313 t.Errorf("Edge.NodeType = %v, Parent.Node has type %T",
314 e.NodeType(), parent.Node())
315 }
316
317 // Check c.Edge.Get(c.Parent.Node) == c.Node.
318 if got := e.Get(parent.Node(), idx); got != cur.Node() {
319 t.Errorf("cur=%v@%s: %s.Get(cur.Parent().Node(), %d) = %T@%s, want cur.Node()",
320 cur, netFset.Position(cur.Node().Pos()), e, idx, got, netFset.Position(got.Pos()))
321 }
322
323 // Check c.Parent.ChildAt(c.ParentEdge()) == c.
324 if got := parent.ChildAt(e, idx); got != cur {
325 t.Errorf("cur=%v@%s: cur.Parent().ChildAt(%v, %d) = %T@%s, want cur",
326 cur, netFset.Position(cur.Node().Pos()), e, idx, got.Node(), netFset.Position(got.Node().Pos()))
327 }
328
329 // Check that reflection on the parent finds the current node.
330 fv := reflect.ValueOf(parent.Node()).Elem().FieldByName(e.FieldName())
331 if idx >= 0 {
332 fv = fv.Index(idx) // element of []ast.Node
333 }
334 if fv.Kind() == reflect.Interface {
335 fv = fv.Elem() // e.g. ast.Expr -> *ast.Ident
336 }
337 got := fv.Interface().(ast.Node)
338 if got != cur.Node() {
339 t.Errorf("%v.Edge = (%v, %d); FieldName/Index reflection gave %T@%s, not original node",
340 cur, e, idx, got, netFset.Position(got.Pos()))
341 }
342
343 // Check that Cursor.Child is the reverse of Parent.
344 if cur.Parent().Child(cur.Node()) != cur {
345 t.Errorf("Cursor.Parent.Child = %v, want %v", cur.Parent().Child(cur.Node()), cur)
346 }
347
348 // Check invariants of Contains:
349
350 // A cursor contains itself.
351 if !cur.Contains(cur) {
352 t.Errorf("!cur.Contains(cur): %v", cur)
353 }
354 // A parent contains its child, but not the inverse.
355 if !parent.Contains(cur) {
356 t.Errorf("!cur.Parent().Contains(cur): %v", cur)
357 }
358 if cur.Contains(parent) {
359 t.Errorf("cur.Contains(cur.Parent()): %v", cur)
360 }
361 // A grandparent contains its grandchild, but not the inverse.
362 if grandparent := cur.Parent(); grandparent.Node() != nil {
363 if !grandparent.Contains(cur) {
364 t.Errorf("!cur.Parent().Parent().Contains(cur): %v", cur)
365 }
366 if cur.Contains(grandparent) {
367 t.Errorf("cur.Contains(cur.Parent().Parent()): %v", cur)
368 }
369 }
370 // A cursor and its uncle/aunt do not contain each other.
371 if uncle, ok := parent.NextSibling(); ok {
372 if uncle.Contains(cur) {
373 t.Errorf("cur.Parent().NextSibling().Contains(cur): %v", cur)
374 }
375 if cur.Contains(uncle) {
376 t.Errorf("cur.Contains(cur.Parent().NextSibling()): %v", cur)
377 }
378 }
379 }
380 }
381
382 // Regression test for multiple matching nodes in FindByPos (#76872).
383 func TestCursor_FindByPos_Boundary(t *testing.T) {
384 // This test verifies that when a cursor position is on the boundary of two
385 // adjacent nodes (e.g. "foo|("), FindByPos returns the first node
386 // encountered in traversal order (which is usually the node "to the left").
387 //
388 // Note: The source is intentionally unformatted (no space between ')' and
389 // '{') to ensure the nodes are strictly adjacent at the boundary.
390 const src = `package p; func foo(a int){}`
391 var (
392 fset = token.NewFileSet()
393 f, _ = parser.ParseFile(fset, "p.go", src, 0)
394 tokFile = fset.File(f.FileStart)
395 inspect = inspector.New([]*ast.File{f})
396 )
397
398 d := f.Decls[0].(*ast.FuncDecl)
399
400 format := func(pos token.Pos) string {
401 off := tokFile.Offset(pos)
402 return fmt.Sprintf("...%s<<>>%s...", src[off-1:off], src[off:off+1])
403 }
404
405 for _, test := range []struct {
406 name string
407 pos token.Pos
408 want ast.Node
409 }{
410 {
411 // "foo|(" Ident
412 pos: d.Type.Params.Opening,
413 want: d.Name,
414 },
415 {
416 // ")|{" FieldList
417 pos: d.Body.Pos(),
418 want: d.Type.Params,
419 },
420 } {
421 cur, ok := inspect.Root().FindByPos(test.pos, test.pos)
422 if !ok {
423 t.Fatalf("FindByPos(%d) %s found nothing", test.pos, format(test.pos))
424 }
425
426 if cur.Node() != test.want {
427 t.Errorf("FindByPos(%d) %s:\ngot %T (%v)\nwant %T (%v)",
428 test.pos, format(test.pos),
429 cur.Node(), cur.Node(),
430 test.want, test.want)
431 }
432 }
433 }
434
435 // Regression test for FuncDecl.Type irregularity in FindByPos (#75997).
436 func TestCursor_FindByPos(t *testing.T) {
437 // Observe that the range of FuncType has a hole between
438 // the "func" token and the start of Type.Params.
439 // The hole contains FuncDecl.{Recv,Name}.
440 //
441 // ~~~~~~~~~~~~FuncDecl~~~~~~~~~~~~~~~~~~~~~~~~~
442 // ~Recv~ ~Name~
443 // ~~~~--------------~~~~FuncType~~~~~~
444 // ~Params~ ~Results~
445 const src = `package a; func (recv) method(params) (results) { body }`
446 var (
447 fset = token.NewFileSet()
448 f, _ = parser.ParseFile(fset, "a.go", src, 0) // ignore parse errors
449 tokFile = fset.File(f.FileStart)
450 inspect = inspector.New([]*ast.File{f})
451 )
452 format := func(start, end token.Pos) string {
453 var (
454 startOffset = tokFile.Offset(start)
455 endOffset = tokFile.Offset(end)
456 )
457 return fmt.Sprintf("%s<<%s>>%s", src[:startOffset], src[startOffset:endOffset], src[endOffset:])
458 }
459
460 d := f.Decls[0].(*ast.FuncDecl)
461
462 // Each test case specifies a [pos-end) range for
463 // FindByPos and the syntax node it should find.
464 for _, test := range []struct {
465 start, end token.Pos
466 want ast.Node
467 }{
468 // pure subtrees
469 {d.Pos(), d.End(), d}, // decl
470 {d.Recv.Pos(), d.Recv.End(), d.Recv}, // recv
471 {d.Name.Pos(), d.Name.End(), d.Name}, // name
472 // (A FuncDecl can't have both Recv and TypeParams, so skip this one.)
473 // {d.Type.TypeParams.Pos(), d.Type.TypeParams.End(), d.Type.TypeParams},
474 {d.Type.Params.Pos(), d.Type.Params.End(), d.Type.Params}, // params
475 {d.Type.Results.Pos(), d.Type.Results.End(), d.Type.Results}, // results
476 {d.Body.Pos(), d.Body.End(), d.Body}, // body
477
478 // single tokens
479 {
480 // "func"
481 d.Type.Func, d.Type.Func + 4,
482 d, // arguably this should be d.Type
483 },
484 {
485 // "(" FieldList
486 d.Recv.Pos(), d.Recv.Pos() + 1,
487 d.Recv,
488 },
489 {
490 // "recv" Ident
491 d.Recv.List[0].Pos(), d.Recv.List[0].Pos() + 1,
492 d.Recv.List[0].Type,
493 },
494 {
495 // "name" Ident
496 d.Name.Pos(), d.Name.Pos() + 1,
497 d.Name,
498 },
499 {
500 // "(" FieldList
501 d.Type.Params.Pos(), d.Type.Params.Pos() + 1,
502 d.Type.Params,
503 },
504 {
505 // "params" Ident
506 d.Type.Params.List[0].Pos(), d.Type.Params.List[0].Pos() + 1,
507 d.Type.Params.List[0].Type,
508 },
509 {
510 // "(" FieldList
511 d.Type.Results.Pos(), d.Type.Results.Pos() + 1,
512 d.Type.Results,
513 },
514 {
515 // "results" Ident
516 d.Type.Results.List[0].Pos(), d.Type.Results.List[0].Pos() + 1,
517 d.Type.Results.List[0].Type,
518 },
519 {
520 // "{" BlockStmt
521 d.Body.Pos(), d.Body.Pos() + 1,
522 d.Body,
523 },
524 {
525 // "body" Ident
526 d.Body.List[0].Pos(), d.Body.List[0].Pos() + 1,
527 d.Body.List[0].(*ast.ExprStmt).X,
528 },
529 } {
530 cur, ok := inspect.Root().FindByPos(test.start, test.end)
531 if !ok || cur.Node() == nil {
532 t.Errorf("%s: FindByPos failed", format(test.start, test.end))
533 continue
534 }
535 got := cur.Node()
536 if got != test.want {
537 t.Errorf("FindByPos:\ninput:\t%s\ngot:\t%s (%T)\nwant:\t%s (%T)",
538 format(test.start, test.end),
539 format(got.Pos(), got.End()), got,
540 format(test.want.Pos(), test.want.End()), test.want)
541 }
542 }
543 }
544
545 func is[T any](x any) bool {
546 _, ok := x.(T)
547 return ok
548 }
549
550 // sliceTypes is a debugging helper that formats each slice element with %T.
551 func sliceTypes[T any](slice []T) string {
552 var buf strings.Builder
553 buf.WriteByte('[')
554 for i, elem := range slice {
555 if i > 0 {
556 buf.WriteByte(' ')
557 }
558 fmt.Fprintf(&buf, "%T", elem)
559 }
560 buf.WriteByte(']')
561 return buf.String()
562 }
563
564 func BenchmarkInspectCalls(b *testing.B) {
565 inspect := netInspect
566
567 // Measure marginal cost of traversal.
568
569 callExprs := []ast.Node{(*ast.CallExpr)(nil)}
570
571 b.Run("Preorder", func(b *testing.B) {
572 var ncalls int
573 for b.Loop() {
574 inspect.Preorder(callExprs, func(n ast.Node) {
575 _ = n.(*ast.CallExpr)
576 ncalls++
577 })
578 }
579 })
580
581 b.Run("WithStack", func(b *testing.B) {
582 var ncalls int
583 for b.Loop() {
584 inspect.WithStack(callExprs, func(n ast.Node, push bool, stack []ast.Node) (proceed bool) {
585 _ = n.(*ast.CallExpr)
586 if push {
587 ncalls++
588 }
589 return true
590 })
591 }
592 })
593
594 b.Run("Cursor", func(b *testing.B) {
595 var ncalls int
596 for b.Loop() {
597 for cur := range inspect.Root().Preorder(callExprs...) {
598 _ = cur.Node().(*ast.CallExpr)
599 ncalls++
600 }
601 }
602 })
603
604 b.Run("CursorEnclosing", func(b *testing.B) {
605 var ncalls int
606 for b.Loop() {
607 for cur := range inspect.Root().Preorder(callExprs...) {
608 _ = cur.Node().(*ast.CallExpr)
609 for range cur.Enclosing() {
610 }
611 ncalls++
612 }
613 }
614 })
615 }
616
617 // This benchmark compares methods for finding a known node in a tree.
618 func BenchmarkCursor_FindNode(b *testing.B) {
619 root := netInspect.Root()
620
621 callExprs := []ast.Node{(*ast.CallExpr)(nil)}
622
623 // Choose a needle in the haystack to use as the search target:
624 // a CallExpr not too near the start nor at too shallow a depth.
625 var needle inspector.Cursor
626 {
627 count := 0
628 found := false
629 for c := range root.Preorder(callExprs...) {
630 count++
631 if count >= 1000 && iterlen(c.Enclosing()) >= 6 {
632 needle = c
633 found = true
634 break
635 }
636 }
637 if !found {
638 b.Fatal("can't choose needle")
639 }
640 }
641
642 b.ResetTimer()
643
644 b.Run("Cursor.Preorder", func(b *testing.B) {
645 needleNode := needle.Node()
646 for b.Loop() {
647 var found inspector.Cursor
648 for c := range root.Preorder(callExprs...) {
649 if c.Node() == needleNode {
650 found = c
651 break
652 }
653 }
654 if found != needle {
655 b.Errorf("Preorder search failed: got %v, want %v", found, needle)
656 }
657 }
658 })
659
660 // This method is about 10-15% faster than Cursor.Preorder.
661 b.Run("Cursor.FindNode", func(b *testing.B) {
662 for b.Loop() {
663 found, ok := root.FindNode(needle.Node())
664 if !ok || found != needle {
665 b.Errorf("FindNode search failed: got %v, want %v", found, needle)
666 }
667 }
668 })
669
670 // This method is about 100x (!) faster than Cursor.Preorder.
671 b.Run("Cursor.FindByPos", func(b *testing.B) {
672 needleNode := needle.Node()
673 for b.Loop() {
674 found, ok := root.FindByPos(needleNode.Pos(), needleNode.End())
675 if !ok || found != needle {
676 b.Errorf("FindByPos search failed: got %v, want %v", found, needle)
677 }
678 }
679 })
680 }
681
682 func iterlen[T any](seq iter.Seq[T]) (len int) {
683 for range seq {
684 len++
685 }
686 return
687 }