| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
package golang |
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
import ( |
| 10 |
"context" |
| 11 |
"fmt" |
| 12 |
"go/ast" |
| 13 |
"go/token" |
| 14 |
"go/types" |
| 15 |
|
| 16 |
"golang.org/x/tools/go/analysis" |
| 17 |
goastutil "golang.org/x/tools/go/ast/astutil" |
| 18 |
"golang.org/x/tools/go/ast/edge" |
| 19 |
"golang.org/x/tools/go/ast/inspector" |
| 20 |
"golang.org/x/tools/go/types/typeutil" |
| 21 |
"golang.org/x/tools/gopls/internal/cache" |
| 22 |
"golang.org/x/tools/gopls/internal/cache/parsego" |
| 23 |
"golang.org/x/tools/gopls/internal/util/safetoken" |
| 24 |
"golang.org/x/tools/internal/astutil" |
| 25 |
"golang.org/x/tools/internal/event" |
| 26 |
"golang.org/x/tools/internal/refactor/inline" |
| 27 |
) |
| 28 |
|
| 29 |
|
| 30 |
|
| 31 |
func enclosingStaticCall(pkg *cache.Package, pgf *parsego.File, start, end token.Pos) (*ast.CallExpr, *types.Func, error) { |
| 32 |
|
| 33 |
path, _ := goastutil.PathEnclosingInterval(pgf.File, start, end) |
| 34 |
|
| 35 |
var call *ast.CallExpr |
| 36 |
loop: |
| 37 |
for _, n := range path { |
| 38 |
switch n := n.(type) { |
| 39 |
case *ast.FuncLit: |
| 40 |
break loop |
| 41 |
case *ast.CallExpr: |
| 42 |
call = n |
| 43 |
break loop |
| 44 |
} |
| 45 |
} |
| 46 |
if call == nil { |
| 47 |
return nil, nil, fmt.Errorf("no enclosing call") |
| 48 |
} |
| 49 |
if safetoken.Line(pgf.Tok, call.Lparen) != safetoken.Line(pgf.Tok, start) { |
| 50 |
return nil, nil, fmt.Errorf("enclosing call is not on this line") |
| 51 |
} |
| 52 |
fn := typeutil.StaticCallee(pkg.TypesInfo(), call) |
| 53 |
if fn == nil { |
| 54 |
return nil, nil, fmt.Errorf("not a static call to a Go function") |
| 55 |
} |
| 56 |
return call, fn, nil |
| 57 |
} |
| 58 |
|
| 59 |
func inlineCall(ctx context.Context, snapshot *cache.Snapshot, callerPkg *cache.Package, callerPGF *parsego.File, start, end token.Pos) (_ *token.FileSet, _ *analysis.SuggestedFix, err error) { |
| 60 |
countInlineCall.Inc() |
| 61 |
|
| 62 |
call, fn, err := enclosingStaticCall(callerPkg, callerPGF, start, end) |
| 63 |
if err != nil { |
| 64 |
return nil, nil, err |
| 65 |
} |
| 66 |
|
| 67 |
calleePkg, calleePGF, calleePos, err := NarrowestDeclaringPackage(ctx, snapshot, callerPkg, fn) |
| 68 |
if err != nil { |
| 69 |
return nil, nil, err |
| 70 |
} |
| 71 |
|
| 72 |
var calleeDecl *ast.FuncDecl |
| 73 |
for _, decl := range calleePGF.File.Decls { |
| 74 |
funcDecl, ok := decl.(*ast.FuncDecl) |
| 75 |
if !ok { |
| 76 |
continue |
| 77 |
} |
| 78 |
if funcDecl.Name.Pos() == calleePos { |
| 79 |
calleeDecl = funcDecl |
| 80 |
break |
| 81 |
} |
| 82 |
} |
| 83 |
if calleeDecl == nil { |
| 84 |
return nil, nil, fmt.Errorf("can't find callee") |
| 85 |
} |
| 86 |
|
| 87 |
|
| 88 |
|
| 89 |
|
| 90 |
|
| 91 |
bad := func(p *cache.Package) bool { return len(p.ParseErrors())+len(p.TypeErrors()) > 0 } |
| 92 |
if bad(calleePkg) || bad(callerPkg) { |
| 93 |
defer func() { |
| 94 |
if x := recover(); x != nil { |
| 95 |
err = fmt.Errorf("inlining failed (%q), likely because inputs were ill-typed", x) |
| 96 |
} |
| 97 |
}() |
| 98 |
} |
| 99 |
|
| 100 |
|
| 101 |
|
| 102 |
logf := logger(ctx, "inliner", snapshot.Options().VerboseOutput) |
| 103 |
|
| 104 |
callee, err := inline.AnalyzeCallee(logf, calleePkg.FileSet(), calleePkg.Types(), calleePkg.TypesInfo(), calleeDecl, calleePGF.Src) |
| 105 |
if err != nil { |
| 106 |
return nil, nil, err |
| 107 |
} |
| 108 |
|
| 109 |
|
| 110 |
caller := &inline.Caller{ |
| 111 |
Fset: callerPkg.FileSet(), |
| 112 |
Types: callerPkg.Types(), |
| 113 |
Info: callerPkg.TypesInfo(), |
| 114 |
File: callerPGF.File, |
| 115 |
Call: call, |
| 116 |
CountUses: nil, |
| 117 |
} |
| 118 |
|
| 119 |
res, err := inline.Inline(caller, callee, &inline.Options{Logf: logf}) |
| 120 |
if err != nil { |
| 121 |
return nil, nil, err |
| 122 |
} |
| 123 |
|
| 124 |
return callerPkg.FileSet(), &analysis.SuggestedFix{ |
| 125 |
Message: fmt.Sprintf("inline call of %v", callee), |
| 126 |
TextEdits: res.Edits, |
| 127 |
}, nil |
| 128 |
} |
| 129 |
|
| 130 |
|
| 131 |
func logger(ctx context.Context, name string, verbose bool) func(format string, args ...any) { |
| 132 |
if verbose { |
| 133 |
return func(format string, args ...any) { |
| 134 |
event.Log(ctx, name+": "+fmt.Sprintf(format, args...)) |
| 135 |
} |
| 136 |
} else { |
| 137 |
return func(string, ...any) {} |
| 138 |
} |
| 139 |
} |
| 140 |
|
| 141 |
|
| 142 |
|
| 143 |
|
| 144 |
|
| 145 |
func canInlineVariable(info *types.Info, curFile inspector.Cursor, start, end token.Pos) (_, _ inspector.Cursor, ok bool) { |
| 146 |
if curUse, ok := curFile.FindByPos(start, end); ok { |
| 147 |
if id, ok := curUse.Node().(*ast.Ident); ok && !isLvalueUse(curUse, info) { |
| 148 |
if v, ok := info.Uses[id].(*types.Var); ok && v.Kind() == types.LocalVar { |
| 149 |
if curIdent, ok := curFile.FindByPos(v.Pos(), v.Pos()); ok { |
| 150 |
curParent := curIdent.Parent() |
| 151 |
kind, index := curIdent.ParentEdge() |
| 152 |
switch kind { |
| 153 |
case edge.ValueSpec_Names: |
| 154 |
|
| 155 |
spec := curParent.Node().(*ast.ValueSpec) |
| 156 |
if len(spec.Names) == len(spec.Values) { |
| 157 |
return curUse, curParent.ChildAt(edge.ValueSpec_Values, index), true |
| 158 |
} |
| 159 |
case edge.AssignStmt_Lhs: |
| 160 |
|
| 161 |
stmt := curParent.Node().(*ast.AssignStmt) |
| 162 |
if len(stmt.Lhs) == len(stmt.Rhs) { |
| 163 |
return curUse, curParent.ChildAt(edge.AssignStmt_Rhs, index), true |
| 164 |
} |
| 165 |
} |
| 166 |
} |
| 167 |
} |
| 168 |
} |
| 169 |
} |
| 170 |
return |
| 171 |
} |
| 172 |
|
| 173 |
|
| 174 |
|
| 175 |
|
| 176 |
|
| 177 |
|
| 178 |
|
| 179 |
|
| 180 |
func isLvalueUse(cur inspector.Cursor, info *types.Info) bool { |
| 181 |
cur = unparenEnclosing(cur) |
| 182 |
|
| 183 |
switch cur.ParentEdgeKind() { |
| 184 |
case edge.AssignStmt_Lhs, edge.IncDecStmt_X: |
| 185 |
return true |
| 186 |
|
| 187 |
case edge.UnaryExpr_X: |
| 188 |
return cur.Parent().Node().(*ast.UnaryExpr).Op == token.AND |
| 189 |
|
| 190 |
case edge.SelectorExpr_X: |
| 191 |
sel := cur.Parent().Node().(*ast.SelectorExpr) |
| 192 |
isPointer := func(t types.Type) bool { |
| 193 |
return is[*types.Pointer](t) |
| 194 |
} |
| 195 |
if seln, ok := info.Selections[sel]; ok && seln.Kind() == types.MethodVal { |
| 196 |
|
| 197 |
methodRecv := seln.Obj().(*types.Func).Signature().Recv().Type() |
| 198 |
return !seln.Indirect() && isPointer(methodRecv) && !isPointer(info.TypeOf(sel.X)) |
| 199 |
} |
| 200 |
} |
| 201 |
|
| 202 |
return false |
| 203 |
} |
| 204 |
|
| 205 |
|
| 206 |
|
| 207 |
func unparenEnclosing(cur inspector.Cursor) inspector.Cursor { |
| 208 |
for cur.ParentEdgeKind() == edge.ParenExpr_X { |
| 209 |
cur = cur.Parent() |
| 210 |
} |
| 211 |
return cur |
| 212 |
} |
| 213 |
|
| 214 |
|
| 215 |
|
| 216 |
func inlineVariableOne(pkg *cache.Package, pgf *parsego.File, start, end token.Pos) (*token.FileSet, *analysis.SuggestedFix, error) { |
| 217 |
countInlineVariable.Inc() |
| 218 |
info := pkg.TypesInfo() |
| 219 |
curUse, curRHS, ok := canInlineVariable(info, pgf.Cursor(), start, end) |
| 220 |
if !ok { |
| 221 |
return nil, nil, fmt.Errorf("cannot inline variable here") |
| 222 |
} |
| 223 |
|
| 224 |
|
| 225 |
var ( |
| 226 |
use = curUse.Node().(*ast.Ident) |
| 227 |
rhs = curRHS.Node().(ast.Expr) |
| 228 |
pos = use.Pos() |
| 229 |
scope = info.Scopes[pgf.File].Innermost(pos) |
| 230 |
) |
| 231 |
for curIdent := range curRHS.Preorder((*ast.Ident)(nil)) { |
| 232 |
if curIdent.ParentEdgeKind() == edge.SelectorExpr_Sel { |
| 233 |
continue |
| 234 |
} |
| 235 |
id := curIdent.Node().(*ast.Ident) |
| 236 |
obj1 := info.Uses[id] |
| 237 |
if obj1 == nil { |
| 238 |
continue |
| 239 |
} |
| 240 |
if v, ok := obj1.(*types.Var); ok && v.IsField() { |
| 241 |
continue |
| 242 |
} |
| 243 |
if astutil.NodeContainsPos(rhs, obj1.Pos()) { |
| 244 |
continue |
| 245 |
} |
| 246 |
_, obj2 := scope.LookupParent(id.Name, pos) |
| 247 |
|
| 248 |
if obj1 != obj2 { |
| 249 |
return nil, nil, fmt.Errorf("cannot inline variable: its initializer expression refers to %q, which is shadowed by the declaration at line %d", id.Name, safetoken.Position(pgf.Tok, obj2.Pos()).Line) |
| 250 |
} |
| 251 |
} |
| 252 |
|
| 253 |
|
| 254 |
|
| 255 |
|
| 256 |
rhs = astutil.MaybeParenthesize(curUse.Parent().Node(), use, rhs) |
| 257 |
|
| 258 |
return pkg.FileSet(), &analysis.SuggestedFix{ |
| 259 |
Message: fmt.Sprintf("Replace variable %q by its initializer expression", use.Name), |
| 260 |
TextEdits: []analysis.TextEdit{ |
| 261 |
{ |
| 262 |
Pos: use.Pos(), |
| 263 |
End: use.End(), |
| 264 |
NewText: []byte(FormatNode(pkg.FileSet(), rhs)), |
| 265 |
}, |
| 266 |
}, |
| 267 |
}, nil |
| 268 |
} |