Debian Codegraph @

gopls/internal/analysis/infertypeargs/infertypeargs.go

raw symbols SCIP
1 // Copyright 2021 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 infertypeargs
6
7 import (
8 "go/ast"
9 "go/token"
10 "go/types"
11 "slices"
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/internal/typeparams"
17 )
18
19 const Doc = `check for unnecessary type arguments in call expressions
20
21 Explicit type arguments may be omitted from call expressions if they can be
22 inferred from function arguments, or from other type arguments:
23
24 func f[T any](T) {}
25
26 func _() {
27 f[string]("foo") // string could be inferred
28 }
29 `
30
31 var Analyzer = &analysis.Analyzer{
32 Name: "infertypeargs",
33 Doc: Doc,
34 Requires: []*analysis.Analyzer{inspect.Analyzer},
35 Run: run,
36 URL: "https://pkg.go.dev/golang.org/x/tools/gopls/internal/analysis/infertypeargs",
37 }
38
39 func run(pass *analysis.Pass) (any, error) {
40 inspect := pass.ResultOf[inspect.Analyzer].(*inspector.Inspector)
41 for _, diag := range diagnose(pass.Fset, inspect, token.NoPos, token.NoPos, pass.Pkg, pass.TypesInfo) {
42 pass.Report(diag)
43 }
44 return nil, nil
45 }
46
47 // Diagnose reports diagnostics describing simplifications to type
48 // arguments overlapping with the provided start and end position.
49 //
50 // If start or end is token.NoPos, the corresponding bound is not checked
51 // (i.e. if both start and end are NoPos, all call expressions are considered).
52 func diagnose(fset *token.FileSet, inspect *inspector.Inspector, start, end token.Pos, pkg *types.Package, info *types.Info) []analysis.Diagnostic {
53 var diags []analysis.Diagnostic
54
55 nodeFilter := []ast.Node{(*ast.CallExpr)(nil)}
56 inspect.Preorder(nodeFilter, func(node ast.Node) {
57 call := node.(*ast.CallExpr)
58 x, lbrack, indices, rbrack := typeparams.UnpackIndexExpr(call.Fun)
59 ident := calledIdent(x)
60 if ident == nil || len(indices) == 0 {
61 return // no explicit args, nothing to do
62 }
63
64 if (start.IsValid() && call.End() < start) || (end.IsValid() && call.Pos() > end) {
65 return // non-overlapping
66 }
67
68 // Confirm that instantiation actually occurred at this ident.
69 idata, ok := info.Instances[ident]
70 if !ok {
71 return // something went wrong, but fail open
72 }
73 instance := idata.Type
74
75 // Start removing argument expressions from the right, and check if we can
76 // still infer the call expression.
77 required := len(indices) // number of type expressions that are required
78 for i := range slices.Backward(indices) {
79 var fun ast.Expr
80 if i == 0 {
81 // No longer an index expression: just use the parameterized operand.
82 fun = x
83 } else {
84 fun = typeparams.PackIndexExpr(x, lbrack, indices[:i], indices[i-1].End())
85 }
86 newCall := &ast.CallExpr{
87 Fun: fun,
88 Lparen: call.Lparen,
89 Args: call.Args,
90 Ellipsis: call.Ellipsis,
91 Rparen: call.Rparen,
92 }
93 info := &types.Info{
94 Instances: make(map[*ast.Ident]types.Instance),
95 FileVersions: make(map[*ast.File]string),
96 }
97 if err := types.CheckExpr(fset, pkg, call.Pos(), newCall, info); err != nil {
98 // Most likely inference failed.
99 break
100 }
101 newIData := info.Instances[ident]
102 newInstance := newIData.Type
103 if !types.Identical(instance, newInstance) {
104 // The inferred result type does not match the original result type, so
105 // this simplification is not valid.
106 break
107 }
108 required = i
109 }
110 if required < len(indices) {
111 var s, e token.Pos
112 var edit analysis.TextEdit
113 if required == 0 {
114 s, e = lbrack, rbrack+1 // erase the entire index
115 edit = analysis.TextEdit{Pos: s, End: e}
116 } else {
117 s = indices[required].Pos()
118 e = rbrack
119 // erase from end of last arg to include last comma & white-spaces
120 edit = analysis.TextEdit{Pos: indices[required-1].End(), End: e}
121 }
122 // Recheck that our (narrower) fixes overlap with the requested range.
123 if (start.IsValid() && e < start) || (end.IsValid() && s > end) {
124 return // non-overlapping
125 }
126 diags = append(diags, analysis.Diagnostic{
127 Pos: s,
128 End: e,
129 Message: "unnecessary type arguments",
130 SuggestedFixes: []analysis.SuggestedFix{{
131 Message: "Simplify type arguments",
132 TextEdits: []analysis.TextEdit{edit},
133 }},
134 })
135 }
136 })
137
138 return diags
139 }
140
141 func calledIdent(x ast.Expr) *ast.Ident {
142 switch x := x.(type) {
143 case *ast.Ident:
144 return x
145 case *ast.SelectorExpr:
146 return x.Sel
147 }
148 return nil
149 }