Debian Codegraph @

gopls/internal/analysis/simplifycompositelit/simplifycompositelit.go

raw symbols SCIP
1 // Copyright 2020 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 simplifycompositelit defines an Analyzer that simplifies composite literals.
6 // https://github.com/golang/go/blob/master/src/cmd/gofmt/simplify.go
7 // https://golang.org/cmd/gofmt/#hdr-The_simplify_command
8 package simplifycompositelit
9
10 import (
11 "bytes"
12 _ "embed"
13 "fmt"
14 "go/ast"
15 "go/printer"
16 "go/token"
17 "reflect"
18
19 "golang.org/x/tools/go/analysis"
20 "golang.org/x/tools/go/analysis/passes/inspect"
21 "golang.org/x/tools/go/ast/inspector"
22 "golang.org/x/tools/internal/analysis/analyzerutil"
23 )
24
25 //go:embed doc.go
26 var doc string
27
28 var Analyzer = &analysis.Analyzer{
29 Name: "simplifycompositelit",
30 Doc: analyzerutil.MustExtractDoc(doc, "simplifycompositelit"),
31 Requires: []*analysis.Analyzer{inspect.Analyzer},
32 Run: run,
33 URL: "https://pkg.go.dev/golang.org/x/tools/gopls/internal/analysis/simplifycompositelit",
34 }
35
36 func run(pass *analysis.Pass) (any, error) {
37 // Gather information whether file is generated or not
38 generated := make(map[*token.File]bool)
39 for _, file := range pass.Files {
40 if ast.IsGenerated(file) {
41 generated[pass.Fset.File(file.FileStart)] = true
42 }
43 }
44
45 inspect := pass.ResultOf[inspect.Analyzer].(*inspector.Inspector)
46 nodeFilter := []ast.Node{(*ast.CompositeLit)(nil)}
47 inspect.Preorder(nodeFilter, func(n ast.Node) {
48 if _, ok := generated[pass.Fset.File(n.Pos())]; ok {
49 return // skip checking if it's generated code
50 }
51
52 expr := n.(*ast.CompositeLit)
53
54 outer := expr
55 var keyType, eltType ast.Expr
56 switch typ := outer.Type.(type) {
57 case *ast.ArrayType:
58 eltType = typ.Elt
59 case *ast.MapType:
60 keyType = typ.Key
61 eltType = typ.Value
62 }
63
64 if eltType == nil {
65 return
66 }
67 var ktyp reflect.Value
68 if keyType != nil {
69 ktyp = reflect.ValueOf(keyType)
70 }
71 typ := reflect.ValueOf(eltType)
72 for _, x := range outer.Elts {
73 // look at value of indexed/named elements
74 if t, ok := x.(*ast.KeyValueExpr); ok {
75 if keyType != nil {
76 simplifyLiteral(pass, ktyp, keyType, t.Key)
77 }
78 x = t.Value
79 }
80 simplifyLiteral(pass, typ, eltType, x)
81 }
82 })
83 return nil, nil
84 }
85
86 func simplifyLiteral(pass *analysis.Pass, typ reflect.Value, astType, x ast.Expr) {
87 // if the element is a composite literal and its literal type
88 // matches the outer literal's element type exactly, the inner
89 // literal type may be omitted
90 if inner, ok := x.(*ast.CompositeLit); ok && match(typ, reflect.ValueOf(inner.Type)) {
91 var b bytes.Buffer
92 printer.Fprint(&b, pass.Fset, inner.Type) // ignore error
93 createDiagnostic(pass, inner.Type.Pos(), inner.Type.End(), b.String())
94 }
95 // if the outer literal's element type is a pointer type *T
96 // and the element is & of a composite literal of type T,
97 // the inner &T may be omitted.
98 if ptr, ok := astType.(*ast.StarExpr); ok {
99 if addr, ok := x.(*ast.UnaryExpr); ok && addr.Op == token.AND {
100 if inner, ok := addr.X.(*ast.CompositeLit); ok {
101 if match(reflect.ValueOf(ptr.X), reflect.ValueOf(inner.Type)) {
102 var b bytes.Buffer
103 printer.Fprint(&b, pass.Fset, inner.Type) // ignore error
104 // Account for the & by subtracting 1 from typ.Pos().
105 createDiagnostic(pass, inner.Type.Pos()-1, inner.Type.End(), "&"+b.String())
106 }
107 }
108 }
109 }
110 }
111
112 func createDiagnostic(pass *analysis.Pass, start, end token.Pos, typ string) {
113 pass.Report(analysis.Diagnostic{
114 Pos: start,
115 End: end,
116 Message: "redundant type from array, slice, or map composite literal",
117 SuggestedFixes: []analysis.SuggestedFix{{
118 Message: fmt.Sprintf("Remove '%s'", typ),
119 TextEdits: []analysis.TextEdit{{
120 Pos: start,
121 End: end,
122 NewText: []byte{},
123 }},
124 }},
125 })
126 }
127
128 // match reports whether pattern matches val,
129 // recording wildcard submatches in m.
130 // If m == nil, match checks whether pattern == val.
131 // from https://github.com/golang/go/blob/26154f31ad6c801d8bad5ef58df1e9263c6beec7/src/cmd/gofmt/rewrite.go#L160
132 func match(pattern, val reflect.Value) bool {
133 // Otherwise, pattern and val must match recursively.
134 if !pattern.IsValid() || !val.IsValid() {
135 return !pattern.IsValid() && !val.IsValid()
136 }
137 if pattern.Type() != val.Type() {
138 return false
139 }
140
141 // Special cases.
142 switch pattern.Type() {
143 case identType:
144 // For identifiers, only the names need to match
145 // (and none of the other *ast.Object information).
146 // This is a common case, handle it all here instead
147 // of recursing down any further via reflection.
148 p := pattern.Interface().(*ast.Ident)
149 v := val.Interface().(*ast.Ident)
150 return p == nil && v == nil || p != nil && v != nil && p.Name == v.Name
151 case objectPtrType, positionType:
152 // object pointers and token positions always match
153 return true
154 case callExprType:
155 // For calls, the Ellipsis fields (token.Position) must
156 // match since that is how f(x) and f(x...) are different.
157 // Check them here but fall through for the remaining fields.
158 p := pattern.Interface().(*ast.CallExpr)
159 v := val.Interface().(*ast.CallExpr)
160 if p.Ellipsis.IsValid() != v.Ellipsis.IsValid() {
161 return false
162 }
163 }
164
165 p := reflect.Indirect(pattern)
166 v := reflect.Indirect(val)
167 if !p.IsValid() || !v.IsValid() {
168 return !p.IsValid() && !v.IsValid()
169 }
170
171 switch p.Kind() {
172 case reflect.Slice:
173 if p.Len() != v.Len() {
174 return false
175 }
176 for i := 0; i < p.Len(); i++ {
177 if !match(p.Index(i), v.Index(i)) {
178 return false
179 }
180 }
181 return true
182
183 case reflect.Struct:
184 for i := 0; i < p.NumField(); i++ {
185 if !match(p.Field(i), v.Field(i)) {
186 return false
187 }
188 }
189 return true
190
191 case reflect.Interface:
192 return match(p.Elem(), v.Elem())
193 }
194
195 // Handle token integers, etc.
196 return p.Interface() == v.Interface()
197 }
198
199 // Values/types for special cases.
200 var (
201 identType = reflect.TypeFor[*ast.Ident]()
202 objectPtrType = reflect.TypeFor[*ast.Object]()
203 positionType = reflect.TypeFor[token.Pos]()
204 callExprType = reflect.TypeFor[*ast.CallExpr]()
205 )