Debian Codegraph @

refactor/eg/eg.go

raw symbols SCIP
1 // Copyright 2014 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 eg implements the example-based refactoring tool whose
6 // command-line is defined in golang.org/x/tools/cmd/eg.
7 package eg // import "golang.org/x/tools/refactor/eg"
8
9 import (
10 "bytes"
11 "errors"
12 "fmt"
13 "go/ast"
14 "go/format"
15 "go/printer"
16 "go/token"
17 "go/types"
18 "maps"
19 "os"
20 )
21
22 const Help = `
23 This tool implements example-based refactoring of expressions.
24
25 The transformation is specified as a Go file defining two functions,
26 'before' and 'after', of identical types. Each function body consists
27 of a single statement: either a return statement with a single
28 (possibly multi-valued) expression, or an expression statement. The
29 'before' expression specifies a pattern and the 'after' expression its
30 replacement.
31
32 package P
33 import ( "errors"; "fmt" )
34 func before(s string) error { return fmt.Errorf("%s", s) }
35 func after(s string) error { return errors.New(s) }
36
37 The expression statement form is useful when the expression has no
38 result, for example:
39
40 func before(msg string) { log.Fatalf("%s", msg) }
41 func after(msg string) { log.Fatal(msg) }
42
43 The parameters of both functions are wildcards that may match any
44 expression assignable to that type. If the pattern contains multiple
45 occurrences of the same parameter, each must match the same expression
46 in the input for the pattern to match. If the replacement contains
47 multiple occurrences of the same parameter, the expression will be
48 duplicated, possibly changing the side-effects.
49
50 The tool analyses all Go code in the packages specified by the
51 arguments, replacing all occurrences of the pattern with the
52 substitution.
53
54 So, the transform above would change this input:
55 err := fmt.Errorf("%s", "error: " + msg)
56 to this output:
57 err := errors.New("error: " + msg)
58
59 Identifiers, including qualified identifiers (p.X) are considered to
60 match only if they denote the same object. This allows correct
61 matching even in the presence of dot imports, named imports and
62 locally shadowed package names in the input program.
63
64 Matching of type syntax is semantic, not syntactic: type syntax in the
65 pattern matches type syntax in the input if the types are identical.
66 Thus, func(x int) matches func(y int).
67
68 This tool was inspired by other example-based refactoring tools,
69 'gofmt -r' for Go and Refaster for Java.
70
71
72 LIMITATIONS
73 ===========
74
75 EXPRESSIVENESS
76
77 Only refactorings that replace one expression with another, regardless
78 of the expression's context, may be expressed. Refactoring arbitrary
79 statements (or sequences of statements) is a less well-defined problem
80 and is less amenable to this approach.
81
82 A pattern that contains a function literal (and hence statements)
83 never matches.
84
85 There is no way to generalize over related types, e.g. to express that
86 a wildcard may have any integer type, for example.
87
88 It is not possible to replace an expression by one of a different
89 type, even in contexts where this is legal, such as x in fmt.Print(x).
90
91 The struct literals T{x} and T{K: x} cannot both be matched by a single
92 template.
93
94
95 SAFETY
96
97 Verifying that a transformation does not introduce type errors is very
98 complex in the general case. An innocuous-looking replacement of one
99 constant by another (e.g. 1 to 2) may cause type errors relating to
100 array types and indices, for example. The tool performs only very
101 superficial checks of type preservation.
102
103
104 IMPORTS
105
106 Although the matching algorithm is fully aware of scoping rules, the
107 replacement algorithm is not, so the replacement code may contain
108 incorrect identifier syntax for imported objects if there are dot
109 imports, named imports or locally shadowed package names in the input
110 program.
111
112 Imports are added as needed, but they are not removed as needed.
113 Run 'goimports' on the modified file for now.
114
115 Dot imports are forbidden in the template.
116
117
118 TIPS
119 ====
120
121 Sometimes a little creativity is required to implement the desired
122 migration. This section lists a few tips and tricks.
123
124 To remove the final parameter from a function, temporarily change the
125 function signature so that the final parameter is variadic, as this
126 allows legal calls both with and without the argument. Then use eg to
127 remove the final argument from all callers, and remove the variadic
128 parameter by hand. The reverse process can be used to add a final
129 parameter.
130
131 To add or remove parameters other than the final one, you must do it in
132 stages: (1) declare a variant function f' with a different name and the
133 desired parameters; (2) use eg to transform calls to f into calls to f',
134 changing the arguments as needed; (3) change the declaration of f to
135 match f'; (4) use eg to rename f' to f in all calls; (5) delete f'.
136 `
137
138 // TODO(adonovan): expand upon the above documentation as an HTML page.
139
140 // A Transformer represents a single example-based transformation.
141 type Transformer struct {
142 fset *token.FileSet
143 verbose bool
144 info *types.Info // combined type info for template/input/output ASTs
145 seenInfos map[*types.Info]bool
146 wildcards map[*types.Var]bool // set of parameters in func before()
147 env map[string]ast.Expr // maps parameter name to wildcard binding
148 importedObjs map[types.Object]*ast.SelectorExpr // objects imported by after().
149 before, after ast.Expr
150 afterStmts []ast.Stmt
151 allowWildcards bool
152
153 // Working state of Transform():
154 nsubsts int // number of substitutions made
155 currentPkg *types.Package // package of current call
156 }
157
158 // NewTransformer returns a transformer based on the specified template,
159 // a single-file package containing "before" and "after" functions as
160 // described in the package documentation.
161 // tmplInfo is the type information for tmplFile.
162 func NewTransformer(fset *token.FileSet, tmplPkg *types.Package, tmplFile *ast.File, tmplInfo *types.Info, verbose bool) (*Transformer, error) {
163 // These maps are required by types.Info.TypeOf.
164 if tmplInfo.Types == nil || tmplInfo.Defs == nil || tmplInfo.Uses == nil {
165 return nil, errors.New("eg.NewTransformer: types.Info argument missing one of Types, Defs or Uses")
166 }
167 // Check the template.
168 beforeSig := funcSig(tmplPkg, "before")
169 if beforeSig == nil {
170 return nil, fmt.Errorf("no 'before' func found in template")
171 }
172 afterSig := funcSig(tmplPkg, "after")
173 if afterSig == nil {
174 return nil, fmt.Errorf("no 'after' func found in template")
175 }
176
177 // TODO(adonovan): should we also check the names of the params match?
178 if !types.Identical(afterSig, beforeSig) {
179 return nil, fmt.Errorf("before %s and after %s functions have different signatures",
180 beforeSig, afterSig)
181 }
182
183 for _, imp := range tmplFile.Imports {
184 if imp.Name != nil && imp.Name.Name == "." {
185 // Dot imports are currently forbidden. We
186 // make the simplifying assumption that all
187 // imports are regular, without local renames.
188 return nil, fmt.Errorf("dot-import (of %s) in template", imp.Path.Value)
189 }
190 }
191 var beforeDecl, afterDecl *ast.FuncDecl
192 for _, decl := range tmplFile.Decls {
193 if decl, ok := decl.(*ast.FuncDecl); ok {
194 switch decl.Name.Name {
195 case "before":
196 beforeDecl = decl
197 case "after":
198 afterDecl = decl
199 }
200 }
201 }
202
203 before, err := soleExpr(beforeDecl)
204 if err != nil {
205 return nil, fmt.Errorf("before: %s", err)
206 }
207 afterStmts, after, err := stmtAndExpr(afterDecl)
208 if err != nil {
209 return nil, fmt.Errorf("after: %s", err)
210 }
211
212 wildcards := make(map[*types.Var]bool)
213 for v := range beforeSig.Params().Variables() {
214 wildcards[v] = true
215 }
216
217 // checkExprTypes returns an error if Tb (type of before()) is not
218 // safe to replace with Ta (type of after()).
219 //
220 // Only superficial checks are performed, and they may result in both
221 // false positives and negatives.
222 //
223 // Ideally, we would only require that the replacement be assignable
224 // to the context of a specific pattern occurrence, but the type
225 // checker doesn't record that information and it's complex to deduce.
226 // A Go type cannot capture all the constraints of a given expression
227 // context, which may include the size, constness, signedness,
228 // namedness or constructor of its type, and even the specific value
229 // of the replacement. (Consider the rule that array literal keys
230 // must be unique.) So we cannot hope to prove the safety of a
231 // transformation in general.
232 Tb := tmplInfo.TypeOf(before)
233 Ta := tmplInfo.TypeOf(after)
234 if types.AssignableTo(Tb, Ta) {
235 // safe: replacement is assignable to pattern.
236 } else if tuple, ok := Tb.(*types.Tuple); ok && tuple.Len() == 0 {
237 // safe: pattern has void type (must appear in an ExprStmt).
238 } else {
239 return nil, fmt.Errorf("%s is not a safe replacement for %s", Ta, Tb)
240 }
241
242 tr := &Transformer{
243 fset: fset,
244 verbose: verbose,
245 wildcards: wildcards,
246 allowWildcards: true,
247 seenInfos: make(map[*types.Info]bool),
248 importedObjs: make(map[types.Object]*ast.SelectorExpr),
249 before: before,
250 after: after,
251 afterStmts: afterStmts,
252 }
253
254 // Combine type info from the template and input packages, and
255 // type info for the synthesized ASTs too. This saves us
256 // having to book-keep where each ast.Node originated as we
257 // construct the resulting hybrid AST.
258 tr.info = &types.Info{
259 Types: make(map[ast.Expr]types.TypeAndValue),
260 Defs: make(map[*ast.Ident]types.Object),
261 Uses: make(map[*ast.Ident]types.Object),
262 Selections: make(map[*ast.SelectorExpr]*types.Selection),
263 }
264 mergeTypeInfo(tr.info, tmplInfo)
265
266 // Compute set of imported objects required by after().
267 // TODO(adonovan): reject dot-imports in pattern
268 ast.Inspect(after, func(n ast.Node) bool {
269 if n, ok := n.(*ast.SelectorExpr); ok {
270 if _, ok := tr.info.Selections[n]; !ok {
271 // qualified ident
272 obj := tr.info.Uses[n.Sel]
273 tr.importedObjs[obj] = n
274 return false // prune
275 }
276 }
277 return true // recur
278 })
279
280 return tr, nil
281 }
282
283 // WriteAST is a convenience function that writes AST f to the specified file.
284 func WriteAST(fset *token.FileSet, filename string, f *ast.File) (err error) {
285 fh, err := os.Create(filename)
286 if err != nil {
287 return err
288 }
289
290 defer func() {
291 if err2 := fh.Close(); err != nil {
292 err = err2 // prefer earlier error
293 }
294 }()
295 return format.Node(fh, fset, f)
296 }
297
298 // -- utilities --------------------------------------------------------
299
300 // funcSig returns the signature of the specified package-level function.
301 func funcSig(pkg *types.Package, name string) *types.Signature {
302 if f, ok := pkg.Scope().Lookup(name).(*types.Func); ok {
303 return f.Type().(*types.Signature)
304 }
305 return nil
306 }
307
308 // soleExpr returns the sole expression in the before/after template function.
309 func soleExpr(fn *ast.FuncDecl) (ast.Expr, error) {
310 if fn.Body == nil {
311 return nil, fmt.Errorf("no body")
312 }
313 if len(fn.Body.List) != 1 {
314 return nil, fmt.Errorf("must contain a single statement")
315 }
316 switch stmt := fn.Body.List[0].(type) {
317 case *ast.ReturnStmt:
318 if len(stmt.Results) != 1 {
319 return nil, fmt.Errorf("return statement must have a single operand")
320 }
321 return stmt.Results[0], nil
322
323 case *ast.ExprStmt:
324 return stmt.X, nil
325 }
326
327 return nil, fmt.Errorf("must contain a single return or expression statement")
328 }
329
330 // stmtAndExpr returns the expression in the last return statement as well as the preceding lines.
331 func stmtAndExpr(fn *ast.FuncDecl) ([]ast.Stmt, ast.Expr, error) {
332 if fn.Body == nil {
333 return nil, nil, fmt.Errorf("no body")
334 }
335
336 n := len(fn.Body.List)
337 if n == 0 {
338 return nil, nil, fmt.Errorf("must contain at least one statement")
339 }
340
341 stmts, last := fn.Body.List[:n-1], fn.Body.List[n-1]
342
343 switch last := last.(type) {
344 case *ast.ReturnStmt:
345 if len(last.Results) != 1 {
346 return nil, nil, fmt.Errorf("return statement must have a single operand")
347 }
348 return stmts, last.Results[0], nil
349
350 case *ast.ExprStmt:
351 return stmts, last.X, nil
352 }
353
354 return nil, nil, fmt.Errorf("must end with a single return or expression statement")
355 }
356
357 // mergeTypeInfo adds type info from src to dst.
358 func mergeTypeInfo(dst, src *types.Info) {
359 maps.Copy(dst.Types, src.Types)
360 maps.Copy(dst.Defs, src.Defs)
361 maps.Copy(dst.Uses, src.Uses)
362 maps.Copy(dst.Selections, src.Selections)
363 }
364
365 // (debugging only)
366 func astString(fset *token.FileSet, n ast.Node) string {
367 var buf bytes.Buffer
368 printer.Fprint(&buf, fset, n)
369 return buf.String()
370 }