| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
package golang |
| 6 |
|
| 7 |
import ( |
| 8 |
"bytes" |
| 9 |
"fmt" |
| 10 |
"go/ast" |
| 11 |
"go/format" |
| 12 |
"go/token" |
| 13 |
"go/types" |
| 14 |
"strings" |
| 15 |
"unicode" |
| 16 |
|
| 17 |
"golang.org/x/tools/go/analysis" |
| 18 |
"golang.org/x/tools/go/ast/edge" |
| 19 |
"golang.org/x/tools/go/ast/inspector" |
| 20 |
"golang.org/x/tools/gopls/internal/cache" |
| 21 |
"golang.org/x/tools/gopls/internal/cache/parsego" |
| 22 |
"golang.org/x/tools/gopls/internal/util/cursorutil" |
| 23 |
"golang.org/x/tools/gopls/internal/util/typesutil" |
| 24 |
"golang.org/x/tools/internal/typesinternal" |
| 25 |
) |
| 26 |
|
| 27 |
|
| 28 |
var undeclaredNamePrefixes = []string{"undeclared name: ", "undefined: "} |
| 29 |
|
| 30 |
|
| 31 |
|
| 32 |
func undeclaredFixTitle(curId inspector.Cursor, errMsg string) string { |
| 33 |
|
| 34 |
var name string |
| 35 |
for _, prefix := range undeclaredNamePrefixes { |
| 36 |
if !strings.HasPrefix(errMsg, prefix) { |
| 37 |
continue |
| 38 |
} |
| 39 |
name = strings.TrimPrefix(errMsg, prefix) |
| 40 |
} |
| 41 |
ident, ok := curId.Node().(*ast.Ident) |
| 42 |
if !ok || ident.Name != name { |
| 43 |
return "" |
| 44 |
} |
| 45 |
|
| 46 |
if _, ok := curId.Parent().Node().(*ast.SelectorExpr); ok { |
| 47 |
return "" |
| 48 |
} |
| 49 |
|
| 50 |
|
| 51 |
block, _ := cursorutil.FirstEnclosing[*ast.BlockStmt](curId) |
| 52 |
if block == nil { |
| 53 |
return "" |
| 54 |
} |
| 55 |
|
| 56 |
|
| 57 |
noun := cond(curId.ParentEdgeKind() == edge.CallExpr_Fun, "function", "variable") |
| 58 |
return fmt.Sprintf("Create %s %s", noun, name) |
| 59 |
} |
| 60 |
|
| 61 |
|
| 62 |
func createUndeclared(pkg *cache.Package, pgf *parsego.File, start, end token.Pos) (*token.FileSet, *analysis.SuggestedFix, error) { |
| 63 |
var ( |
| 64 |
fset = pkg.FileSet() |
| 65 |
info = pkg.TypesInfo() |
| 66 |
file = pgf.File |
| 67 |
pos = start |
| 68 |
) |
| 69 |
curId, _ := pgf.Cursor().FindByPos(pos, pos) |
| 70 |
ident, ok := curId.Node().(*ast.Ident) |
| 71 |
if !ok { |
| 72 |
return nil, nil, fmt.Errorf("no identifier found") |
| 73 |
} |
| 74 |
|
| 75 |
|
| 76 |
|
| 77 |
if curId.ParentEdgeKind() == edge.CallExpr_Fun { |
| 78 |
return newFunctionDeclaration(curId, file, pkg.Types(), info, fset) |
| 79 |
} |
| 80 |
|
| 81 |
|
| 82 |
var curFirstRef inspector.Cursor |
| 83 |
|
| 84 |
|
| 85 |
|
| 86 |
|
| 87 |
|
| 88 |
|
| 89 |
|
| 90 |
|
| 91 |
|
| 92 |
_, curFuncDecl := cursorutil.FirstEnclosing[*ast.FuncDecl](curId) |
| 93 |
for curRef := range curFuncDecl.Preorder((*ast.Ident)(nil)) { |
| 94 |
n := curRef.Node().(*ast.Ident) |
| 95 |
if n.Name == ident.Name && info.ObjectOf(n) == nil { |
| 96 |
if curRef.ParentEdgeKind() == edge.AssignStmt_Lhs { |
| 97 |
assign := curRef.Parent().Node().(*ast.AssignStmt) |
| 98 |
if assign.Tok == token.ASSIGN && !referencesIdent(info, assign, ident) { |
| 99 |
|
| 100 |
return fset, &analysis.SuggestedFix{ |
| 101 |
TextEdits: []analysis.TextEdit{{ |
| 102 |
Pos: assign.TokPos, |
| 103 |
End: assign.TokPos, |
| 104 |
NewText: []byte(":"), |
| 105 |
}}, |
| 106 |
}, nil |
| 107 |
} |
| 108 |
} |
| 109 |
curFirstRef = curRef |
| 110 |
break |
| 111 |
} |
| 112 |
} |
| 113 |
|
| 114 |
|
| 115 |
|
| 116 |
if !curFirstRef.Valid() { |
| 117 |
return nil, nil, fmt.Errorf("no identifier found") |
| 118 |
} |
| 119 |
insertPos, err := stmtToInsertVarBefore(curFirstRef, nil) |
| 120 |
if err != nil { |
| 121 |
return nil, nil, fmt.Errorf("could not locate insertion point: %v", err) |
| 122 |
} |
| 123 |
indent, err := pgf.Indentation(insertPos) |
| 124 |
if err != nil { |
| 125 |
return nil, nil, err |
| 126 |
} |
| 127 |
typs := typesutil.TypesFromContext(info, curId) |
| 128 |
if typs == nil { |
| 129 |
|
| 130 |
typs = []types.Type{types.Typ[types.Int]} |
| 131 |
} |
| 132 |
expr, _ := typesinternal.ZeroExpr(typs[0], typesinternal.FileQualifier(file, pkg.Types())) |
| 133 |
assignStmt := &ast.AssignStmt{ |
| 134 |
Lhs: []ast.Expr{ast.NewIdent(ident.Name)}, |
| 135 |
Tok: token.DEFINE, |
| 136 |
Rhs: []ast.Expr{expr}, |
| 137 |
} |
| 138 |
var buf bytes.Buffer |
| 139 |
if err := format.Node(&buf, fset, assignStmt); err != nil { |
| 140 |
return nil, nil, err |
| 141 |
} |
| 142 |
newLineIndent := "\n" + indent |
| 143 |
assignment := strings.ReplaceAll(buf.String(), "\n", newLineIndent) + newLineIndent |
| 144 |
|
| 145 |
return fset, &analysis.SuggestedFix{ |
| 146 |
TextEdits: []analysis.TextEdit{ |
| 147 |
{ |
| 148 |
Pos: insertPos, |
| 149 |
End: insertPos, |
| 150 |
NewText: []byte(assignment), |
| 151 |
}, |
| 152 |
}, |
| 153 |
}, nil |
| 154 |
} |
| 155 |
|
| 156 |
|
| 157 |
|
| 158 |
func referencesIdent(info *types.Info, assign *ast.AssignStmt, ident *ast.Ident) bool { |
| 159 |
for _, rhs := range assign.Rhs { |
| 160 |
for n := range ast.Preorder(rhs) { |
| 161 |
if id, ok := n.(*ast.Ident); ok && |
| 162 |
id.Name == ident.Name && info.Uses[id] == nil { |
| 163 |
return true |
| 164 |
} |
| 165 |
} |
| 166 |
} |
| 167 |
return false |
| 168 |
} |
| 169 |
|
| 170 |
|
| 171 |
|
| 172 |
func newFunctionDeclaration(curId inspector.Cursor, file *ast.File, pkg *types.Package, info *types.Info, fset *token.FileSet) (*token.FileSet, *analysis.SuggestedFix, error) { |
| 173 |
|
| 174 |
id := curId.Node().(*ast.Ident) |
| 175 |
call := curId.Parent().Node().(*ast.CallExpr) |
| 176 |
|
| 177 |
|
| 178 |
|
| 179 |
funcdecl, _ := cursorutil.FirstEnclosing[*ast.FuncDecl](curId) |
| 180 |
if funcdecl == nil { |
| 181 |
|
| 182 |
|
| 183 |
return nil, nil, fmt.Errorf("no enclosing function found: %v", curId) |
| 184 |
} |
| 185 |
|
| 186 |
pos := funcdecl.End() |
| 187 |
|
| 188 |
var paramNames []string |
| 189 |
var paramTypes []types.Type |
| 190 |
|
| 191 |
nameCounts := map[string]int{} |
| 192 |
for _, arg := range call.Args { |
| 193 |
typ := info.TypeOf(arg) |
| 194 |
if typ == nil { |
| 195 |
return nil, nil, fmt.Errorf("unable to determine type for %s", arg) |
| 196 |
} |
| 197 |
|
| 198 |
switch t := typ.(type) { |
| 199 |
|
| 200 |
|
| 201 |
case *types.Tuple: |
| 202 |
n := t.Len() |
| 203 |
for i := range n { |
| 204 |
name := typeToArgName(t.At(i).Type()) |
| 205 |
nameCounts[name]++ |
| 206 |
|
| 207 |
paramNames = append(paramNames, name) |
| 208 |
paramTypes = append(paramTypes, types.Default(t.At(i).Type())) |
| 209 |
} |
| 210 |
|
| 211 |
default: |
| 212 |
|
| 213 |
|
| 214 |
var name string |
| 215 |
if ident, ok := arg.(*ast.Ident); ok { |
| 216 |
name = ident.Name |
| 217 |
} |
| 218 |
|
| 219 |
if name == "" { |
| 220 |
name = typeToArgName(typ) |
| 221 |
} |
| 222 |
|
| 223 |
nameCounts[name]++ |
| 224 |
|
| 225 |
paramNames = append(paramNames, name) |
| 226 |
paramTypes = append(paramTypes, types.Default(typ)) |
| 227 |
} |
| 228 |
} |
| 229 |
|
| 230 |
for n, c := range nameCounts { |
| 231 |
|
| 232 |
|
| 233 |
|
| 234 |
if c >= 2 { |
| 235 |
nameCounts[n] = 1 |
| 236 |
} else { |
| 237 |
delete(nameCounts, n) |
| 238 |
} |
| 239 |
} |
| 240 |
|
| 241 |
params := &ast.FieldList{} |
| 242 |
qual := typesinternal.FileQualifier(file, pkg) |
| 243 |
for i, name := range paramNames { |
| 244 |
if suffix, repeats := nameCounts[name]; repeats { |
| 245 |
nameCounts[name]++ |
| 246 |
name = fmt.Sprintf("%s%d", name, suffix) |
| 247 |
} |
| 248 |
|
| 249 |
|
| 250 |
if i > 0 { |
| 251 |
|
| 252 |
|
| 253 |
|
| 254 |
|
| 255 |
|
| 256 |
if paramTypes[i] == paramTypes[i-1] { |
| 257 |
params.List[len(params.List)-1].Names = append(params.List[len(params.List)-1].Names, ast.NewIdent(name)) |
| 258 |
continue |
| 259 |
} |
| 260 |
} |
| 261 |
|
| 262 |
params.List = append(params.List, &ast.Field{ |
| 263 |
Names: []*ast.Ident{ |
| 264 |
ast.NewIdent(name), |
| 265 |
}, |
| 266 |
Type: typesinternal.TypeExpr(paramTypes[i], qual), |
| 267 |
}) |
| 268 |
} |
| 269 |
|
| 270 |
rets := &ast.FieldList{} |
| 271 |
retTypes := typesutil.TypesFromContext(info, curId.Parent()) |
| 272 |
for _, rt := range retTypes { |
| 273 |
rets.List = append(rets.List, &ast.Field{ |
| 274 |
Type: typesinternal.TypeExpr(rt, qual), |
| 275 |
}) |
| 276 |
} |
| 277 |
|
| 278 |
decl := &ast.FuncDecl{ |
| 279 |
Name: ast.NewIdent(id.Name), |
| 280 |
Type: &ast.FuncType{ |
| 281 |
Params: params, |
| 282 |
Results: rets, |
| 283 |
}, |
| 284 |
Body: &ast.BlockStmt{ |
| 285 |
List: []ast.Stmt{ |
| 286 |
&ast.ExprStmt{ |
| 287 |
X: &ast.CallExpr{ |
| 288 |
Fun: ast.NewIdent("panic"), |
| 289 |
Args: []ast.Expr{ |
| 290 |
&ast.BasicLit{ |
| 291 |
Value: `"unimplemented"`, |
| 292 |
}, |
| 293 |
}, |
| 294 |
}, |
| 295 |
}, |
| 296 |
}, |
| 297 |
}, |
| 298 |
} |
| 299 |
|
| 300 |
b := bytes.NewBufferString("\n\n") |
| 301 |
if err := format.Node(b, fset, decl); err != nil { |
| 302 |
return nil, nil, err |
| 303 |
} |
| 304 |
return fset, &analysis.SuggestedFix{ |
| 305 |
TextEdits: []analysis.TextEdit{{ |
| 306 |
Pos: pos, |
| 307 |
End: pos, |
| 308 |
NewText: b.Bytes(), |
| 309 |
}}, |
| 310 |
}, nil |
| 311 |
} |
| 312 |
|
| 313 |
func typeToArgName(ty types.Type) string { |
| 314 |
s := types.Default(ty).String() |
| 315 |
|
| 316 |
switch t := types.Unalias(ty).(type) { |
| 317 |
case *types.Basic: |
| 318 |
|
| 319 |
return s[0:1] |
| 320 |
case *types.Slice: |
| 321 |
|
| 322 |
return typeToArgName(t.Elem()) |
| 323 |
case *types.Array: |
| 324 |
|
| 325 |
return typeToArgName(t.Elem()) |
| 326 |
case *types.Chan: |
| 327 |
return "ch" |
| 328 |
} |
| 329 |
|
| 330 |
s = strings.TrimFunc(s, func(r rune) bool { |
| 331 |
return !unicode.IsLetter(r) |
| 332 |
}) |
| 333 |
|
| 334 |
if s == "error" { |
| 335 |
return "err" |
| 336 |
} |
| 337 |
|
| 338 |
|
| 339 |
|
| 340 |
a := []rune(s[strings.LastIndexByte(s, '.')+1:]) |
| 341 |
a[0] = unicode.ToLower(a[0]) |
| 342 |
return string(a) |
| 343 |
} |