github.com/gmemcc/yaegi@v0.12.1-0.20221128122509-aa99124c5d16/internal/cmd/extract/types/resolver.go (about) 1 // Copyright 2013 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 types 6 7 import ( 8 "fmt" 9 "go/ast" 10 "go/constant" 11 "go/token" 12 "sort" 13 "strconv" 14 "strings" 15 "unicode" 16 ) 17 18 // A declInfo describes a package-level const, type, var, or func declaration. 19 type declInfo struct { 20 file *Scope // scope of file containing this declaration 21 lhs []*Var // lhs of n:1 variable declarations, or nil 22 typ ast.Expr // type, or nil 23 init ast.Expr // init/orig expression, or nil 24 inherited bool // if set, the init expression is inherited from a previous constant declaration 25 fdecl *ast.FuncDecl // func declaration, or nil 26 alias bool // type alias declaration 27 28 // The deps field tracks initialization expression dependencies. 29 deps map[Object]bool // lazily initialized 30 } 31 32 // hasInitializer reports whether the declared object has an initialization 33 // expression or function body. 34 func (d *declInfo) hasInitializer() bool { 35 return d.init != nil || d.fdecl != nil && d.fdecl.Body != nil 36 } 37 38 // addDep adds obj to the set of objects d's init expression depends on. 39 func (d *declInfo) addDep(obj Object) { 40 m := d.deps 41 if m == nil { 42 m = make(map[Object]bool) 43 d.deps = m 44 } 45 m[obj] = true 46 } 47 48 // arityMatch checks that the lhs and rhs of a const or var decl 49 // have the appropriate number of names and init exprs. For const 50 // decls, init is the value spec providing the init exprs; for 51 // var decls, init is nil (the init exprs are in s in this case). 52 func (check *Checker) arityMatch(s, init *ast.ValueSpec) { 53 l := len(s.Names) 54 r := len(s.Values) 55 if init != nil { 56 r = len(init.Values) 57 } 58 59 const code = _WrongAssignCount 60 switch { 61 case init == nil && r == 0: 62 // var decl w/o init expr 63 if s.Type == nil { 64 check.errorf(s, code, "missing type or init expr") 65 } 66 case l < r: 67 if l < len(s.Values) { 68 // init exprs from s 69 n := s.Values[l] 70 check.errorf(n, code, "extra init expr %s", n) 71 // TODO(gri) avoid declared but not used error here 72 } else { 73 // init exprs "inherited" 74 check.errorf(s, code, "extra init expr at %s", check.fset.Position(init.Pos())) 75 // TODO(gri) avoid declared but not used error here 76 } 77 case l > r && (init != nil || r != 1): 78 n := s.Names[r] 79 check.errorf(n, code, "missing init expr for %s", n) 80 } 81 } 82 83 func validatedImportPath(path string) (string, error) { 84 s, err := strconv.Unquote(path) 85 if err != nil { 86 return "", err 87 } 88 if s == "" { 89 return "", fmt.Errorf("empty string") 90 } 91 const illegalChars = `!"#$%&'()*,:;<=>?[\]^{|}` + "`\uFFFD" 92 for _, r := range s { 93 if !unicode.IsGraphic(r) || unicode.IsSpace(r) || strings.ContainsRune(illegalChars, r) { 94 return s, fmt.Errorf("invalid character %#U", r) 95 } 96 } 97 return s, nil 98 } 99 100 // declarePkgObj declares obj in the package scope, records its ident -> obj mapping, 101 // and updates check.objMap. The object must not be a function or method. 102 func (check *Checker) declarePkgObj(ident *ast.Ident, obj Object, d *declInfo) { 103 assert(ident.Name == obj.Name()) 104 105 // spec: "A package-scope or file-scope identifier with name init 106 // may only be declared to be a function with this (func()) signature." 107 if ident.Name == "init" { 108 check.errorf(ident, _InvalidInitDecl, "cannot declare init - must be func") 109 return 110 } 111 112 // spec: "The main package must have package name main and declare 113 // a function main that takes no arguments and returns no value." 114 if ident.Name == "main" && check.pkg.name == "main" { 115 check.errorf(ident, _InvalidMainDecl, "cannot declare main - must be func") 116 return 117 } 118 119 check.declare(check.pkg.scope, ident, obj, token.NoPos) 120 check.objMap[obj] = d 121 obj.setOrder(uint32(len(check.objMap))) 122 } 123 124 // filename returns a filename suitable for debugging output. 125 func (check *Checker) filename(fileNo int) string { 126 file := check.files[fileNo] 127 if pos := file.Pos(); pos.IsValid() { 128 return check.fset.File(pos).Name() 129 } 130 return fmt.Sprintf("file[%d]", fileNo) 131 } 132 133 func (check *Checker) importPackage(pos token.Pos, path, dir string, depth int) *Package { 134 // If we already have a package for the given (path, dir) 135 // pair, use it instead of doing a full import. 136 // Checker.impMap only caches packages that are marked Complete 137 // or fake (dummy packages for failed imports). Incomplete but 138 // non-fake packages do require an import to complete them. 139 key := importKey{path, dir} 140 imp := check.impMap[key] 141 if imp != nil { 142 return imp 143 } 144 145 // no package yet => import it 146 if path == "C" && (check.conf.FakeImportC || check.conf.go115UsesCgo) { 147 imp = NewPackage("C", "C") 148 imp.fake = true // package scope is not populated 149 imp.cgo = check.conf.go115UsesCgo 150 } else { 151 // ordinary import 152 var err error 153 if importer := check.conf.Importer; importer == nil { 154 err = fmt.Errorf("Config.Importer not installed") 155 } else if importerFrom, ok := importer.(ImporterFrom); ok { 156 imp, err = importerFrom.ImportFrom(path, dir, 0, depth) 157 if imp == nil && err == nil { 158 err = fmt.Errorf("Config.Importer.ImportFrom(%s, %s, 0) returned nil but no error", path, dir) 159 } 160 } else { 161 imp, err = importer.Import(path, depth) 162 if imp == nil && err == nil { 163 err = fmt.Errorf("Config.Importer.Import(%s) returned nil but no error", path) 164 } 165 } 166 // make sure we have a valid package name 167 // (errors here can only happen through manipulation of packages after creation) 168 if err == nil && imp != nil && (imp.name == "_" || imp.name == "") { 169 err = fmt.Errorf("invalid package name: %q", imp.name) 170 imp = nil // create fake package below 171 } 172 if err != nil { 173 check.errorf(atPos(pos), _BrokenImport, "could not import %s (%s)", path, err) 174 if imp == nil { 175 // create a new fake package 176 // come up with a sensible package name (heuristic) 177 name := path 178 if i := len(name); i > 0 && name[i-1] == '/' { 179 name = name[:i-1] 180 } 181 if i := strings.LastIndex(name, "/"); i >= 0 { 182 name = name[i+1:] 183 } 184 imp = NewPackage(path, name) 185 } 186 // continue to use the package as best as we can 187 imp.fake = true // avoid follow-up lookup failures 188 } 189 } 190 191 // package should be complete or marked fake, but be cautious 192 if imp.complete || imp.fake { 193 check.impMap[key] = imp 194 check.pkgCnt[imp.name]++ 195 return imp 196 } 197 198 // something went wrong (importer may have returned incomplete package without error) 199 return nil 200 } 201 202 // collectObjects collects all file and package objects and inserts them 203 // into their respective scopes. It also performs imports and associates 204 // methods with receiver base type names. 205 func (check *Checker) collectObjects(depth int) { 206 pkg := check.pkg 207 208 // pkgImports is the set of packages already imported by any package file seen 209 // so far. Used to avoid duplicate entries in pkg.imports. Allocate and populate 210 // it (pkg.imports may not be empty if we are checking test files incrementally). 211 // Note that pkgImports is keyed by package (and thus package path), not by an 212 // importKey value. Two different importKey values may map to the same package 213 // which is why we cannot use the check.impMap here. 214 var pkgImports = make(map[*Package]bool) 215 for _, imp := range pkg.imports { 216 pkgImports[imp] = true 217 } 218 219 var methods []*Func // list of methods with non-blank _ names 220 for fileNo, file := range check.files { 221 // The package identifier denotes the current package, 222 // but there is no corresponding package object. 223 check.recordDef(file.Name, nil) 224 225 // Use the actual source file extent rather than *ast.File extent since the 226 // latter doesn't include comments which appear at the start or end of the file. 227 // Be conservative and use the *ast.File extent if we don't have a *token.File. 228 pos, end := file.Pos(), file.End() 229 if f := check.fset.File(file.Pos()); f != nil { 230 pos, end = token.Pos(f.Base()), token.Pos(f.Base()+f.Size()) 231 } 232 fileScope := NewScope(check.pkg.scope, pos, end, check.filename(fileNo)) 233 check.recordScope(file, fileScope) 234 235 // determine file directory, necessary to resolve imports 236 // FileName may be "" (typically for tests) in which case 237 // we get "." as the directory which is what we would want. 238 fileDir := dir(check.fset.Position(file.Name.Pos()).Filename) 239 240 check.walkDecls(file.Decls, func(d decl) { 241 switch d := d.(type) { 242 case importDecl: 243 if depth >= 1 { 244 return 245 } 246 // import package 247 path, err := validatedImportPath(d.spec.Path.Value) 248 if err != nil { 249 check.errorf(d.spec.Path, _BadImportPath, "invalid import path (%s)", err) 250 return 251 } 252 253 imp := check.importPackage(d.spec.Path.Pos(), path, fileDir, depth+1) 254 if imp == nil { 255 return 256 } 257 258 // add package to list of explicit imports 259 // (this functionality is provided as a convenience 260 // for clients; it is not needed for type-checking) 261 if !pkgImports[imp] { 262 pkgImports[imp] = true 263 pkg.imports = append(pkg.imports, imp) 264 } 265 266 // local name overrides imported package name 267 name := imp.name 268 if d.spec.Name != nil { 269 name = d.spec.Name.Name 270 if path == "C" { 271 // match cmd/compile (not prescribed by spec) 272 check.errorf(d.spec.Name, _ImportCRenamed, `cannot rename import "C"`) 273 return 274 } 275 if name == "init" { 276 check.errorf(d.spec.Name, _InvalidInitDecl, "cannot declare init - must be func") 277 return 278 } 279 } 280 281 obj := NewPkgName(d.spec.Pos(), pkg, name, imp) 282 if d.spec.Name != nil { 283 // in a dot-import, the dot represents the package 284 check.recordDef(d.spec.Name, obj) 285 } else { 286 check.recordImplicit(d.spec, obj) 287 } 288 289 if path == "C" { 290 // match cmd/compile (not prescribed by spec) 291 obj.used = true 292 } 293 294 // add import to file scope 295 if name == "." { 296 // merge imported scope with file scope 297 for _, obj := range imp.scope.elems { 298 // A package scope may contain non-exported objects, 299 // do not import them! 300 if obj.Exported() { 301 // declare dot-imported object 302 // (Do not use check.declare because it modifies the object 303 // via Object.setScopePos, which leads to a race condition; 304 // the object may be imported into more than one file scope 305 // concurrently. See issue #32154.) 306 if alt := fileScope.Insert(obj); alt != nil { 307 check.errorf(d.spec.Name, _DuplicateDecl, "%s redeclared in this block", obj.Name()) 308 check.reportAltDecl(alt) 309 } 310 } 311 } 312 // add position to set of dot-import positions for this file 313 // (this is only needed for "imported but not used" errors) 314 check.addUnusedDotImport(fileScope, imp, d.spec) 315 } else { 316 // declare imported package object in file scope 317 // (no need to provide s.Name since we called check.recordDef earlier) 318 check.declare(fileScope, nil, obj, token.NoPos) 319 } 320 case constDecl: 321 // declare all constants 322 for i, name := range d.spec.Names { 323 obj := NewConst(name.Pos(), pkg, name.Name, nil, constant.MakeInt64(int64(d.iota))) 324 325 var init ast.Expr 326 if i < len(d.init) { 327 init = d.init[i] 328 } 329 330 d := &declInfo{file: fileScope, typ: d.typ, init: init, inherited: d.inherited} 331 check.declarePkgObj(name, obj, d) 332 } 333 334 case varDecl: 335 lhs := make([]*Var, len(d.spec.Names)) 336 // If there's exactly one rhs initializer, use 337 // the same declInfo d1 for all lhs variables 338 // so that each lhs variable depends on the same 339 // rhs initializer (n:1 var declaration). 340 var d1 *declInfo 341 if len(d.spec.Values) == 1 { 342 // The lhs elements are only set up after the for loop below, 343 // but that's ok because declareVar only collects the declInfo 344 // for a later phase. 345 d1 = &declInfo{file: fileScope, lhs: lhs, typ: d.spec.Type, init: d.spec.Values[0]} 346 } 347 348 // declare all variables 349 for i, name := range d.spec.Names { 350 obj := NewVar(name.Pos(), pkg, name.Name, nil) 351 lhs[i] = obj 352 353 di := d1 354 if di == nil { 355 // individual assignments 356 var init ast.Expr 357 if i < len(d.spec.Values) { 358 init = d.spec.Values[i] 359 } 360 di = &declInfo{file: fileScope, typ: d.spec.Type, init: init} 361 } 362 363 check.declarePkgObj(name, obj, di) 364 } 365 case typeDecl: 366 obj := NewTypeName(d.spec.Name.Pos(), pkg, d.spec.Name.Name, nil) 367 check.declarePkgObj(d.spec.Name, obj, &declInfo{file: fileScope, typ: d.spec.Type, alias: d.spec.Assign.IsValid()}) 368 case funcDecl: 369 info := &declInfo{file: fileScope, fdecl: d.decl} 370 name := d.decl.Name.Name 371 obj := NewFunc(d.decl.Name.Pos(), pkg, name, nil) 372 if d.decl.Recv == nil { 373 // regular function 374 if name == "init" { 375 // don't declare init functions in the package scope - they are invisible 376 obj.parent = pkg.scope 377 check.recordDef(d.decl.Name, obj) 378 // init functions must have a body 379 if d.decl.Body == nil { 380 check.softErrorf(obj, _MissingInitBody, "missing function body") 381 } 382 } else { 383 check.declare(pkg.scope, d.decl.Name, obj, token.NoPos) 384 } 385 } else { 386 // method 387 // (Methods with blank _ names are never found; no need to collect 388 // them for later type association. They will still be type-checked 389 // with all the other functions.) 390 if name != "_" { 391 methods = append(methods, obj) 392 } 393 check.recordDef(d.decl.Name, obj) 394 } 395 // Methods are not package-level objects but we still track them in the 396 // object map so that we can handle them like regular functions (if the 397 // receiver is invalid); also we need their fdecl info when associating 398 // them with their receiver base type, below. 399 check.objMap[obj] = info 400 obj.setOrder(uint32(len(check.objMap))) 401 } 402 }) 403 } 404 405 // verify that objects in package and file scopes have different names 406 for _, scope := range check.pkg.scope.children /* file scopes */ { 407 for _, obj := range scope.elems { 408 if alt := pkg.scope.Lookup(obj.Name()); alt != nil { 409 if pkg, ok := obj.(*PkgName); ok { 410 check.errorf(alt, _DuplicateDecl, "%s already declared through import of %s", alt.Name(), pkg.Imported()) 411 check.reportAltDecl(pkg) 412 } else { 413 check.errorf(alt, _DuplicateDecl, "%s already declared through dot-import of %s", alt.Name(), obj.Pkg()) 414 // TODO(gri) dot-imported objects don't have a position; reportAltDecl won't print anything 415 check.reportAltDecl(obj) 416 } 417 } 418 } 419 } 420 421 // Now that we have all package scope objects and all methods, 422 // associate methods with receiver base type name where possible. 423 // Ignore methods that have an invalid receiver. They will be 424 // type-checked later, with regular functions. 425 if methods == nil { 426 return // nothing to do 427 } 428 check.methods = make(map[*TypeName][]*Func) 429 for _, f := range methods { 430 fdecl := check.objMap[f].fdecl 431 if list := fdecl.Recv.List; len(list) > 0 { 432 // f is a method. 433 // Determine the receiver base type and associate f with it. 434 ptr, base := check.resolveBaseTypeName(list[0].Type) 435 if base != nil { 436 f.hasPtrRecv = ptr 437 check.methods[base] = append(check.methods[base], f) 438 } 439 } 440 } 441 } 442 443 // resolveBaseTypeName returns the non-alias base type name for typ, and whether 444 // there was a pointer indirection to get to it. The base type name must be declared 445 // in package scope, and there can be at most one pointer indirection. If no such type 446 // name exists, the returned base is nil. 447 func (check *Checker) resolveBaseTypeName(typ ast.Expr) (ptr bool, base *TypeName) { 448 // Algorithm: Starting from a type expression, which may be a name, 449 // we follow that type through alias declarations until we reach a 450 // non-alias type name. If we encounter anything but pointer types or 451 // parentheses we're done. If we encounter more than one pointer type 452 // we're done. 453 var seen map[*TypeName]bool 454 for { 455 typ = unparen(typ) 456 457 // check if we have a pointer type 458 if pexpr, _ := typ.(*ast.StarExpr); pexpr != nil { 459 // if we've already seen a pointer, we're done 460 if ptr { 461 return false, nil 462 } 463 ptr = true 464 typ = unparen(pexpr.X) // continue with pointer base type 465 } 466 467 // typ must be a name 468 name, _ := typ.(*ast.Ident) 469 if name == nil { 470 return false, nil 471 } 472 473 // name must denote an object found in the current package scope 474 // (note that dot-imported objects are not in the package scope!) 475 obj := check.pkg.scope.Lookup(name.Name) 476 if obj == nil { 477 return false, nil 478 } 479 480 // the object must be a type name... 481 tname, _ := obj.(*TypeName) 482 if tname == nil { 483 return false, nil 484 } 485 486 // ... which we have not seen before 487 if seen[tname] { 488 return false, nil 489 } 490 491 // we're done if tdecl defined tname as a new type 492 // (rather than an alias) 493 tdecl := check.objMap[tname] // must exist for objects in package scope 494 if !tdecl.alias { 495 return ptr, tname 496 } 497 498 // otherwise, continue resolving 499 typ = tdecl.typ 500 if seen == nil { 501 seen = make(map[*TypeName]bool) 502 } 503 seen[tname] = true 504 } 505 } 506 507 // packageObjects typechecks all package objects, but not function bodies. 508 func (check *Checker) packageObjects() { 509 // process package objects in source order for reproducible results 510 objList := make([]Object, len(check.objMap)) 511 i := 0 512 for obj := range check.objMap { 513 objList[i] = obj 514 i++ 515 } 516 sort.Sort(inSourceOrder(objList)) 517 518 // add new methods to already type-checked types (from a prior Checker.Files call) 519 for _, obj := range objList { 520 if obj, _ := obj.(*TypeName); obj != nil && obj.typ != nil { 521 check.addMethodDecls(obj) 522 } 523 } 524 525 // We process non-alias declarations first, in order to avoid situations where 526 // the type of an alias declaration is needed before it is available. In general 527 // this is still not enough, as it is possible to create sufficiently convoluted 528 // recursive type definitions that will cause a type alias to be needed before it 529 // is available (see issue #25838 for examples). 530 // As an aside, the cmd/compiler suffers from the same problem (#25838). 531 var aliasList []*TypeName 532 // phase 1 533 for _, obj := range objList { 534 // If we have a type alias, collect it for the 2nd phase. 535 if tname, _ := obj.(*TypeName); tname != nil && check.objMap[tname].alias { 536 aliasList = append(aliasList, tname) 537 continue 538 } 539 540 check.objDecl(obj, nil) 541 } 542 // phase 2 543 for _, obj := range aliasList { 544 check.objDecl(obj, nil) 545 } 546 547 // At this point we may have a non-empty check.methods map; this means that not all 548 // entries were deleted at the end of typeDecl because the respective receiver base 549 // types were not found. In that case, an error was reported when declaring those 550 // methods. We can now safely discard this map. 551 check.methods = nil 552 } 553 554 // inSourceOrder implements the sort.Sort interface. 555 type inSourceOrder []Object 556 557 func (a inSourceOrder) Len() int { return len(a) } 558 func (a inSourceOrder) Less(i, j int) bool { return a[i].order() < a[j].order() } 559 func (a inSourceOrder) Swap(i, j int) { a[i], a[j] = a[j], a[i] } 560 561 // unusedImports checks for unused imports. 562 func (check *Checker) unusedImports() { 563 // if function bodies are not checked, packages' uses are likely missing - don't check 564 if check.conf.IgnoreFuncBodies { 565 return 566 } 567 568 // spec: "It is illegal (...) to directly import a package without referring to 569 // any of its exported identifiers. To import a package solely for its side-effects 570 // (initialization), use the blank identifier as explicit package name." 571 572 // check use of regular imported packages 573 for _, scope := range check.pkg.scope.children /* file scopes */ { 574 for _, obj := range scope.elems { 575 if obj, ok := obj.(*PkgName); ok { 576 // Unused "blank imports" are automatically ignored 577 // since _ identifiers are not entered into scopes. 578 if !obj.used { 579 path := obj.imported.path 580 base := pkgName(path) 581 if obj.name == base { 582 check.softErrorf(obj, _UnusedImport, "%q imported but not used", path) 583 } else { 584 check.softErrorf(obj, _UnusedImport, "%q imported but not used as %s", path, obj.name) 585 } 586 } 587 } 588 } 589 } 590 591 // check use of dot-imported packages 592 for _, unusedDotImports := range check.unusedDotImports { 593 for pkg, pos := range unusedDotImports { 594 check.softErrorf(pos, _UnusedImport, "%q imported but not used", pkg.path) 595 } 596 } 597 } 598 599 // pkgName returns the package name (last element) of an import path. 600 func pkgName(path string) string { 601 if i := strings.LastIndex(path, "/"); i >= 0 { 602 path = path[i+1:] 603 } 604 return path 605 } 606 607 // dir makes a good-faith attempt to return the directory 608 // portion of path. If path is empty, the result is ".". 609 // (Per the go/build package dependency tests, we cannot import 610 // path/filepath and simply use filepath.Dir.) 611 func dir(path string) string { 612 if i := strings.LastIndexAny(path, `/\`); i > 0 { 613 return path[:i] 614 } 615 // i <= 0 616 return "." 617 }