Debian Codegraph @

gopls/internal/analysis/recursiveiter/recursiveiter.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 recursiveiter
6
7 import (
8 _ "embed"
9 "fmt"
10 "go/ast"
11 "go/types"
12
13 "golang.org/x/tools/go/analysis"
14 "golang.org/x/tools/go/analysis/passes/inspect"
15 "golang.org/x/tools/go/ast/inspector"
16 "golang.org/x/tools/go/types/typeutil"
17 "golang.org/x/tools/internal/analysis/analyzerutil"
18 typeindexanalyzer "golang.org/x/tools/internal/analysis/typeindex"
19 "golang.org/x/tools/internal/typesinternal/typeindex"
20 )
21
22 //go:embed doc.go
23 var doc string
24
25 var Analyzer = &analysis.Analyzer{
26 Name: "recursiveiter",
27 Doc: analyzerutil.MustExtractDoc(doc, "recursiveiter"),
28 Requires: []*analysis.Analyzer{inspect.Analyzer, typeindexanalyzer.Analyzer},
29 Run: run,
30 URL: "https://pkg.go.dev/golang.org/x/tools/gopls/internal/analysis/recursiveiter",
31 }
32
33 func run(pass *analysis.Pass) (any, error) {
34 var (
35 inspector = pass.ResultOf[inspect.Analyzer].(*inspector.Inspector)
36 index = pass.ResultOf[typeindexanalyzer.Analyzer].(*typeindex.Index)
37 info = pass.TypesInfo
38 iterSeq = index.Object("iter", "Seq")
39 iterSeq2 = index.Object("iter", "Seq2")
40 )
41 if iterSeq == nil || iterSeq2 == nil {
42 return nil, nil // fast path: no iterators
43 }
44
45 // Search for a function or method f that returns an iter.Seq
46 // or Seq2 and calls itself recursively within a range stmt:
47 //
48 // func f(...) iter.Seq[E] {
49 // return func(yield func(E) bool) {
50 // ...
51 // for range f(...) { ... }
52 // }
53 // }
54 for curDecl := range inspector.Root().Preorder((*ast.FuncDecl)(nil)) {
55 decl := curDecl.Node().(*ast.FuncDecl)
56 fn := info.Defs[decl.Name].(*types.Func)
57 results := fn.Signature().Results()
58 if results.Len() != 1 {
59 continue // result not a singleton
60 }
61 retType, ok := results.At(0).Type().(*types.Named)
62 if !ok {
63 continue // result not a named type
64 }
65 switch retType.Origin().Obj() {
66 case iterSeq, iterSeq2:
67 default:
68 continue // result not iter.Seq{,2}
69 }
70 // Have: a FuncDecl that returns an iterator.
71 for curRet := range curDecl.Preorder((*ast.ReturnStmt)(nil)) {
72 ret := curRet.Node().(*ast.ReturnStmt)
73 if len(ret.Results) != 1 || !is[*ast.FuncLit](ret.Results[0]) {
74 continue // not "return func(){...}"
75 }
76 for curRange := range curRet.Preorder((*ast.RangeStmt)(nil)) {
77 rng := curRange.Node().(*ast.RangeStmt)
78 call, ok := rng.X.(*ast.CallExpr)
79 if !ok {
80 continue
81 }
82 if typeutil.StaticCallee(info, call) == fn {
83 pass.Report(analysis.Diagnostic{
84 Pos: rng.Range,
85 End: rng.X.End(),
86 Message: fmt.Sprintf("inefficient recursion in iterator %s", fn.Name()),
87 })
88 }
89 }
90 }
91 }
92
93 return nil, nil
94 }
95
96 func is[T any](x any) bool {
97 _, ok := x.(T)
98 return ok
99 }