Debian Codegraph @

gopls/internal/cache/parsego/resolver.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 // Code generated by resolver_gen.go. DO NOT EDIT.
6
7 package parsego
8
9 import (
10 "fmt"
11 "go/ast"
12 "go/token"
13 "strings"
14 )
15
16 const debugResolve = false
17
18 // resolveFile walks the given file to resolve identifiers within the file
19 // scope, updating ast.Ident.Obj fields with declaration information.
20 //
21 // If declErr is non-nil, it is used to report declaration errors during
22 // resolution. tok is used to format position in error messages.
23 func resolveFile(file *ast.File, handle *token.File, declErr func(token.Pos, string)) {
24 pkgScope := ast.NewScope(nil)
25 r := &resolver{
26 handle: handle,
27 declErr: declErr,
28 topScope: pkgScope,
29 pkgScope: pkgScope,
30 depth: 1,
31 }
32
33 for _, decl := range file.Decls {
34 ast.Walk(r, decl)
35 }
36
37 r.closeScope()
38 assert(r.topScope == nil, "unbalanced scopes")
39 assert(r.labelScope == nil, "unbalanced label scopes")
40
41 // resolve global identifiers within the same file
42 i := 0
43 for _, ident := range r.unresolved {
44 // i <= index for current ident
45 assert(ident.Obj == unresolved, "object already resolved")
46 ident.Obj = r.pkgScope.Lookup(ident.Name) // also removes unresolved sentinel
47 if ident.Obj == nil {
48 r.unresolved[i] = ident
49 i++
50 } else if debugResolve {
51 pos := ident.Obj.Decl.(interface{ Pos() token.Pos }).Pos()
52 r.trace("resolved %s@%v to package object %v", ident.Name, ident.Pos(), pos)
53 }
54 }
55 file.Scope = r.pkgScope
56 file.Unresolved = r.unresolved[0:i]
57 }
58
59 const maxScopeDepth int = 1e3
60
61 type resolver struct {
62 handle *token.File
63 declErr func(token.Pos, string)
64
65 // Ordinary identifier scopes
66 pkgScope *ast.Scope // pkgScope.Outer == nil
67 topScope *ast.Scope // top-most scope; may be pkgScope
68 unresolved []*ast.Ident // unresolved identifiers
69 depth int // scope depth
70
71 // Label scopes
72 // (maintained by open/close LabelScope)
73 labelScope *ast.Scope // label scope for current function
74 targetStack [][]*ast.Ident // stack of unresolved labels
75 }
76
77 func (r *resolver) trace(format string, args ...any) {
78 fmt.Println(strings.Repeat(". ", r.depth) + r.sprintf(format, args...))
79 }
80
81 func (r *resolver) sprintf(format string, args ...any) string {
82 for i, arg := range args {
83 switch arg := arg.(type) {
84 case token.Pos:
85 args[i] = r.handle.Position(arg)
86 }
87 }
88 return fmt.Sprintf(format, args...)
89 }
90
91 func (r *resolver) openScope(pos token.Pos) {
92 r.depth++
93 if r.depth > maxScopeDepth {
94 panic(bailout{pos: pos, msg: "exceeded max scope depth during object resolution"})
95 }
96 if debugResolve {
97 r.trace("opening scope @%v", pos)
98 }
99 r.topScope = ast.NewScope(r.topScope)
100 }
101
102 func (r *resolver) closeScope() {
103 r.depth--
104 if debugResolve {
105 r.trace("closing scope")
106 }
107 r.topScope = r.topScope.Outer
108 }
109
110 func (r *resolver) openLabelScope() {
111 r.labelScope = ast.NewScope(r.labelScope)
112 r.targetStack = append(r.targetStack, nil)
113 }
114
115 func (r *resolver) closeLabelScope() {
116 // resolve labels
117 n := len(r.targetStack) - 1
118 scope := r.labelScope
119 for _, ident := range r.targetStack[n] {
120 ident.Obj = scope.Lookup(ident.Name)
121 if ident.Obj == nil && r.declErr != nil {
122 r.declErr(ident.Pos(), fmt.Sprintf("label %s undefined", ident.Name))
123 }
124 }
125 // pop label scope
126 r.targetStack = r.targetStack[0:n]
127 r.labelScope = r.labelScope.Outer
128 }
129
130 func (r *resolver) declare(decl, data any, scope *ast.Scope, kind ast.ObjKind, idents ...*ast.Ident) {
131 for _, ident := range idents {
132 if ident.Obj != nil {
133 panic(fmt.Sprintf("%v: identifier %s already declared or resolved", ident.Pos(), ident.Name))
134 }
135 obj := ast.NewObj(kind, ident.Name)
136 // remember the corresponding declaration for redeclaration
137 // errors and global variable resolution/typechecking phase
138 obj.Decl = decl
139 obj.Data = data
140 // Identifiers (for receiver type parameters) are written to the scope, but
141 // never set as the resolved object. See go.dev/issue/50956.
142 if _, ok := decl.(*ast.Ident); !ok {
143 ident.Obj = obj
144 }
145 if ident.Name != "_" {
146 if debugResolve {
147 r.trace("declaring %s@%v", ident.Name, ident.Pos())
148 }
149 if alt := scope.Insert(obj); alt != nil && r.declErr != nil {
150 prevDecl := ""
151 if pos := alt.Pos(); pos.IsValid() {
152 prevDecl = r.sprintf("\n\tprevious declaration at %v", pos)
153 }
154 r.declErr(ident.Pos(), fmt.Sprintf("%s redeclared in this block%s", ident.Name, prevDecl))
155 }
156 }
157 }
158 }
159
160 func (r *resolver) shortVarDecl(decl *ast.AssignStmt) {
161 // Go spec: A short variable declaration may redeclare variables
162 // provided they were originally declared in the same block with
163 // the same type, and at least one of the non-blank variables is new.
164 n := 0 // number of new variables
165 for _, x := range decl.Lhs {
166 if ident, isIdent := x.(*ast.Ident); isIdent {
167 assert(ident.Obj == nil, "identifier already declared or resolved")
168 obj := ast.NewObj(ast.Var, ident.Name)
169 // remember corresponding assignment for other tools
170 obj.Decl = decl
171 ident.Obj = obj
172 if ident.Name != "_" {
173 if debugResolve {
174 r.trace("declaring %s@%v", ident.Name, ident.Pos())
175 }
176 if alt := r.topScope.Insert(obj); alt != nil {
177 ident.Obj = alt // redeclaration
178 } else {
179 n++ // new declaration
180 }
181 }
182 }
183 }
184 if n == 0 && r.declErr != nil {
185 r.declErr(decl.Lhs[0].Pos(), "no new variables on left side of :=")
186 }
187 }
188
189 // The unresolved object is a sentinel to mark identifiers that have been added
190 // to the list of unresolved identifiers. The sentinel is only used for verifying
191 // internal consistency.
192 var unresolved = new(ast.Object)
193
194 // If x is an identifier, resolve attempts to resolve x by looking up
195 // the object it denotes. If no object is found and collectUnresolved is
196 // set, x is marked as unresolved and collected in the list of unresolved
197 // identifiers.
198 func (r *resolver) resolve(ident *ast.Ident, collectUnresolved bool) {
199 if ident.Obj != nil {
200 panic(r.sprintf("%v: identifier %s already declared or resolved", ident.Pos(), ident.Name))
201 }
202 // '_' should never refer to existing declarations, because it has special
203 // handling in the spec.
204 if ident.Name == "_" {
205 return
206 }
207 for s := r.topScope; s != nil; s = s.Outer {
208 if obj := s.Lookup(ident.Name); obj != nil {
209 if debugResolve {
210 r.trace("resolved %v:%s to %v", ident.Pos(), ident.Name, obj)
211 }
212 assert(obj.Name != "", "obj with no name")
213 // Identifiers (for receiver type parameters) are written to the scope,
214 // but never set as the resolved object. See go.dev/issue/50956.
215 if _, ok := obj.Decl.(*ast.Ident); !ok {
216 ident.Obj = obj
217 }
218 return
219 }
220 }
221 // all local scopes are known, so any unresolved identifier
222 // must be found either in the file scope, package scope
223 // (perhaps in another file), or universe scope --- collect
224 // them so that they can be resolved later
225 if collectUnresolved {
226 ident.Obj = unresolved
227 r.unresolved = append(r.unresolved, ident)
228 }
229 }
230
231 func (r *resolver) walkExprs(list []ast.Expr) {
232 for _, node := range list {
233 ast.Walk(r, node)
234 }
235 }
236
237 func (r *resolver) walkLHS(list []ast.Expr) {
238 for _, expr := range list {
239 expr := ast.Unparen(expr)
240 if _, ok := expr.(*ast.Ident); !ok && expr != nil {
241 ast.Walk(r, expr)
242 }
243 }
244 }
245
246 func (r *resolver) walkStmts(list []ast.Stmt) {
247 for _, stmt := range list {
248 ast.Walk(r, stmt)
249 }
250 }
251
252 func (r *resolver) Visit(node ast.Node) ast.Visitor {
253 if debugResolve && node != nil {
254 r.trace("node %T@%v", node, node.Pos())
255 }
256
257 switch n := node.(type) {
258
259 // Expressions.
260 case *ast.Ident:
261 r.resolve(n, true)
262
263 case *ast.FuncLit:
264 r.openScope(n.Pos())
265 defer r.closeScope()
266 r.walkFuncType(n.Type)
267 r.walkBody(n.Body)
268
269 case *ast.SelectorExpr:
270 ast.Walk(r, n.X)
271 // Note: don't try to resolve n.Sel, as we don't support qualified
272 // resolution.
273
274 case *ast.StructType:
275 r.openScope(n.Pos())
276 defer r.closeScope()
277 r.walkFieldList(n.Fields, ast.Var)
278
279 case *ast.FuncType:
280 r.openScope(n.Pos())
281 defer r.closeScope()
282 r.walkFuncType(n)
283
284 case *ast.CompositeLit:
285 if n.Type != nil {
286 ast.Walk(r, n.Type)
287 }
288 for _, e := range n.Elts {
289 if kv, _ := e.(*ast.KeyValueExpr); kv != nil {
290 // See go.dev/issue/45160: try to resolve composite lit keys, but don't
291 // collect them as unresolved if resolution failed. This replicates
292 // existing behavior when resolving during parsing.
293 if ident, _ := kv.Key.(*ast.Ident); ident != nil {
294 r.resolve(ident, false)
295 } else {
296 ast.Walk(r, kv.Key)
297 }
298 ast.Walk(r, kv.Value)
299 } else {
300 ast.Walk(r, e)
301 }
302 }
303
304 case *ast.InterfaceType:
305 r.openScope(n.Pos())
306 defer r.closeScope()
307 r.walkFieldList(n.Methods, ast.Fun)
308
309 // Statements
310 case *ast.LabeledStmt:
311 r.declare(n, nil, r.labelScope, ast.Lbl, n.Label)
312 ast.Walk(r, n.Stmt)
313
314 case *ast.AssignStmt:
315 r.walkExprs(n.Rhs)
316 if n.Tok == token.DEFINE {
317 r.shortVarDecl(n)
318 } else {
319 r.walkExprs(n.Lhs)
320 }
321
322 case *ast.BranchStmt:
323 // add to list of unresolved targets
324 if n.Tok != token.FALLTHROUGH && n.Label != nil {
325 depth := len(r.targetStack) - 1
326 r.targetStack[depth] = append(r.targetStack[depth], n.Label)
327 }
328
329 case *ast.BlockStmt:
330 r.openScope(n.Pos())
331 defer r.closeScope()
332 r.walkStmts(n.List)
333
334 case *ast.IfStmt:
335 r.openScope(n.Pos())
336 defer r.closeScope()
337 if n.Init != nil {
338 ast.Walk(r, n.Init)
339 }
340 ast.Walk(r, n.Cond)
341 ast.Walk(r, n.Body)
342 if n.Else != nil {
343 ast.Walk(r, n.Else)
344 }
345
346 case *ast.CaseClause:
347 r.walkExprs(n.List)
348 r.openScope(n.Pos())
349 defer r.closeScope()
350 r.walkStmts(n.Body)
351
352 case *ast.SwitchStmt:
353 r.openScope(n.Pos())
354 defer r.closeScope()
355 if n.Init != nil {
356 ast.Walk(r, n.Init)
357 }
358 if n.Tag != nil {
359 // The scope below reproduces some unnecessary behavior of the parser,
360 // opening an extra scope in case this is a type switch. It's not needed
361 // for expression switches.
362 // TODO: remove this once we've matched the parser resolution exactly.
363 if n.Init != nil {
364 r.openScope(n.Tag.Pos())
365 defer r.closeScope()
366 }
367 ast.Walk(r, n.Tag)
368 }
369 if n.Body != nil {
370 r.walkStmts(n.Body.List)
371 }
372
373 case *ast.TypeSwitchStmt:
374 if n.Init != nil {
375 r.openScope(n.Pos())
376 defer r.closeScope()
377 ast.Walk(r, n.Init)
378 }
379 r.openScope(n.Assign.Pos())
380 defer r.closeScope()
381 ast.Walk(r, n.Assign)
382 // s.Body consists only of case clauses, so does not get its own
383 // scope.
384 if n.Body != nil {
385 r.walkStmts(n.Body.List)
386 }
387
388 case *ast.CommClause:
389 r.openScope(n.Pos())
390 defer r.closeScope()
391 if n.Comm != nil {
392 ast.Walk(r, n.Comm)
393 }
394 r.walkStmts(n.Body)
395
396 case *ast.SelectStmt:
397 // as for switch statements, select statement bodies don't get their own
398 // scope.
399 if n.Body != nil {
400 r.walkStmts(n.Body.List)
401 }
402
403 case *ast.ForStmt:
404 r.openScope(n.Pos())
405 defer r.closeScope()
406 if n.Init != nil {
407 ast.Walk(r, n.Init)
408 }
409 if n.Cond != nil {
410 ast.Walk(r, n.Cond)
411 }
412 if n.Post != nil {
413 ast.Walk(r, n.Post)
414 }
415 ast.Walk(r, n.Body)
416
417 case *ast.RangeStmt:
418 r.openScope(n.Pos())
419 defer r.closeScope()
420 ast.Walk(r, n.X)
421 var lhs []ast.Expr
422 if n.Key != nil {
423 lhs = append(lhs, n.Key)
424 }
425 if n.Value != nil {
426 lhs = append(lhs, n.Value)
427 }
428 if len(lhs) > 0 {
429 if n.Tok == token.DEFINE {
430 // Note: we can't exactly match the behavior of object resolution
431 // during the parsing pass here, as it uses the position of the RANGE
432 // token for the RHS OpPos. That information is not contained within
433 // the AST.
434 as := &ast.AssignStmt{
435 Lhs: lhs,
436 Tok: token.DEFINE,
437 TokPos: n.TokPos,
438 Rhs: []ast.Expr{&ast.UnaryExpr{Op: token.RANGE, X: n.X}},
439 }
440 // TODO(rFindley): this walkLHS reproduced the parser resolution, but
441 // is it necessary? By comparison, for a normal AssignStmt we don't
442 // walk the LHS in case there is an invalid identifier list.
443 r.walkLHS(lhs)
444 r.shortVarDecl(as)
445 } else {
446 r.walkExprs(lhs)
447 }
448 }
449 ast.Walk(r, n.Body)
450
451 // Declarations
452 case *ast.GenDecl:
453 switch n.Tok {
454 case token.CONST, token.VAR:
455 for i, spec := range n.Specs {
456 spec := spec.(*ast.ValueSpec)
457 kind := ast.Con
458 if n.Tok == token.VAR {
459 kind = ast.Var
460 }
461 r.walkExprs(spec.Values)
462 if spec.Type != nil {
463 ast.Walk(r, spec.Type)
464 }
465 r.declare(spec, i, r.topScope, kind, spec.Names...)
466 }
467 case token.TYPE:
468 for _, spec := range n.Specs {
469 spec := spec.(*ast.TypeSpec)
470 // Go spec: The scope of a type identifier declared inside a function begins
471 // at the identifier in the TypeSpec and ends at the end of the innermost
472 // containing block.
473 r.declare(spec, nil, r.topScope, ast.Typ, spec.Name)
474 if spec.TypeParams != nil {
475 r.openScope(spec.Pos())
476 defer r.closeScope()
477 r.walkTParams(spec.TypeParams)
478 }
479 ast.Walk(r, spec.Type)
480 }
481 }
482
483 case *ast.FuncDecl:
484 // Open the function scope.
485 r.openScope(n.Pos())
486 defer r.closeScope()
487
488 r.walkRecv(n.Recv)
489
490 // Type parameters are walked normally: they can reference each other, and
491 // can be referenced by normal parameters.
492 if n.Type.TypeParams != nil {
493 r.walkTParams(n.Type.TypeParams)
494 // TODO(rFindley): need to address receiver type parameters.
495 }
496
497 // Resolve and declare parameters in a specific order to get duplicate
498 // declaration errors in the correct location.
499 r.resolveList(n.Type.Params)
500 r.resolveList(n.Type.Results)
501 r.declareList(n.Recv, ast.Var)
502 r.declareList(n.Type.Params, ast.Var)
503 r.declareList(n.Type.Results, ast.Var)
504
505 r.walkBody(n.Body)
506 if n.Recv == nil && n.Name.Name != "init" {
507 r.declare(n, nil, r.pkgScope, ast.Fun, n.Name)
508 }
509
510 default:
511 return r
512 }
513
514 return nil
515 }
516
517 func (r *resolver) walkFuncType(typ *ast.FuncType) {
518 // typ.TypeParams must be walked separately for FuncDecls.
519 r.resolveList(typ.Params)
520 r.resolveList(typ.Results)
521 r.declareList(typ.Params, ast.Var)
522 r.declareList(typ.Results, ast.Var)
523 }
524
525 func (r *resolver) resolveList(list *ast.FieldList) {
526 if list == nil {
527 return
528 }
529 for _, f := range list.List {
530 if f.Type != nil {
531 ast.Walk(r, f.Type)
532 }
533 }
534 }
535
536 func (r *resolver) declareList(list *ast.FieldList, kind ast.ObjKind) {
537 if list == nil {
538 return
539 }
540 for _, f := range list.List {
541 r.declare(f, nil, r.topScope, kind, f.Names...)
542 }
543 }
544
545 func (r *resolver) walkRecv(recv *ast.FieldList) {
546 // If our receiver has receiver type parameters, we must declare them before
547 // trying to resolve the rest of the receiver, and avoid re-resolving the
548 // type parameter identifiers.
549 if recv == nil || len(recv.List) == 0 {
550 return // nothing to do
551 }
552 typ := recv.List[0].Type
553 if ptr, ok := typ.(*ast.StarExpr); ok {
554 typ = ptr.X
555 }
556
557 var declareExprs []ast.Expr // exprs to declare
558 var resolveExprs []ast.Expr // exprs to resolve
559 switch typ := typ.(type) {
560 case *ast.IndexExpr:
561 declareExprs = []ast.Expr{typ.Index}
562 resolveExprs = append(resolveExprs, typ.X)
563 case *ast.IndexListExpr:
564 declareExprs = typ.Indices
565 resolveExprs = append(resolveExprs, typ.X)
566 default:
567 resolveExprs = append(resolveExprs, typ)
568 }
569 for _, expr := range declareExprs {
570 if id, _ := expr.(*ast.Ident); id != nil {
571 r.declare(expr, nil, r.topScope, ast.Typ, id)
572 } else {
573 // The receiver type parameter expression is invalid, but try to resolve
574 // it anyway for consistency.
575 resolveExprs = append(resolveExprs, expr)
576 }
577 }
578 for _, expr := range resolveExprs {
579 if expr != nil {
580 ast.Walk(r, expr)
581 }
582 }
583 // The receiver is invalid, but try to resolve it anyway for consistency.
584 for _, f := range recv.List[1:] {
585 if f.Type != nil {
586 ast.Walk(r, f.Type)
587 }
588 }
589 }
590
591 func (r *resolver) walkFieldList(list *ast.FieldList, kind ast.ObjKind) {
592 if list == nil {
593 return
594 }
595 r.resolveList(list)
596 r.declareList(list, kind)
597 }
598
599 // walkTParams is like walkFieldList, but declares type parameters eagerly so
600 // that they may be resolved in the constraint expressions held in the field
601 // Type.
602 func (r *resolver) walkTParams(list *ast.FieldList) {
603 r.declareList(list, ast.Typ)
604 r.resolveList(list)
605 }
606
607 func (r *resolver) walkBody(body *ast.BlockStmt) {
608 if body == nil {
609 return
610 }
611 r.openLabelScope()
612 defer r.closeLabelScope()
613 r.walkStmts(body.List)
614 }