github.com/go-asm/go@v1.21.1-0.20240213172139-40c5ead50c48/cmd/compile/types2/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 types2 6 7 import ( 8 "fmt" 9 "go/constant" 10 "sort" 11 "strconv" 12 "strings" 13 "unicode" 14 15 "github.com/go-asm/go/cmd/compile/syntax" 16 . "github.com/go-asm/go/types/errors" 17 ) 18 19 // A declInfo describes a package-level const, type, var, or func declaration. 20 type declInfo struct { 21 file *Scope // scope of file containing this declaration 22 lhs []*Var // lhs of n:1 variable declarations, or nil 23 vtyp syntax.Expr // type, or nil (for const and var declarations only) 24 init syntax.Expr // init/orig expression, or nil (for const and var declarations only) 25 inherited bool // if set, the init expression is inherited from a previous constant declaration 26 tdecl *syntax.TypeDecl // type declaration, or nil 27 fdecl *syntax.FuncDecl // func declaration, or nil 28 29 // The deps field tracks initialization expression dependencies. 30 deps map[Object]bool // lazily initialized 31 } 32 33 // hasInitializer reports whether the declared object has an initialization 34 // expression or function body. 35 func (d *declInfo) hasInitializer() bool { 36 return d.init != nil || d.fdecl != nil && d.fdecl.Body != nil 37 } 38 39 // addDep adds obj to the set of objects d's init expression depends on. 40 func (d *declInfo) addDep(obj Object) { 41 m := d.deps 42 if m == nil { 43 m = make(map[Object]bool) 44 d.deps = m 45 } 46 m[obj] = true 47 } 48 49 // arity checks that the lhs and rhs of a const or var decl 50 // have a matching number of names and initialization values. 51 // If inherited is set, the initialization values are from 52 // another (constant) declaration. 53 func (check *Checker) arity(pos syntax.Pos, names []*syntax.Name, inits []syntax.Expr, constDecl, inherited bool) { 54 l := len(names) 55 r := len(inits) 56 57 const code = WrongAssignCount 58 switch { 59 case l < r: 60 n := inits[l] 61 if inherited { 62 check.errorf(pos, code, "extra init expr at %s", n.Pos()) 63 } else { 64 check.errorf(n, code, "extra init expr %s", n) 65 } 66 case l > r && (constDecl || r != 1): // if r == 1 it may be a multi-valued function and we can't say anything yet 67 n := names[r] 68 check.errorf(n, code, "missing init expr for %s", n.Value) 69 } 70 } 71 72 func validatedImportPath(path string) (string, error) { 73 s, err := strconv.Unquote(path) 74 if err != nil { 75 return "", err 76 } 77 if s == "" { 78 return "", fmt.Errorf("empty string") 79 } 80 const illegalChars = `!"#$%&'()*,:;<=>?[\]^{|}` + "`\uFFFD" 81 for _, r := range s { 82 if !unicode.IsGraphic(r) || unicode.IsSpace(r) || strings.ContainsRune(illegalChars, r) { 83 return s, fmt.Errorf("invalid character %#U", r) 84 } 85 } 86 return s, nil 87 } 88 89 // declarePkgObj declares obj in the package scope, records its ident -> obj mapping, 90 // and updates check.objMap. The object must not be a function or method. 91 func (check *Checker) declarePkgObj(ident *syntax.Name, obj Object, d *declInfo) { 92 assert(ident.Value == obj.Name()) 93 94 // spec: "A package-scope or file-scope identifier with name init 95 // may only be declared to be a function with this (func()) signature." 96 if ident.Value == "init" { 97 check.error(ident, InvalidInitDecl, "cannot declare init - must be func") 98 return 99 } 100 101 // spec: "The main package must have package name main and declare 102 // a function main that takes no arguments and returns no value." 103 if ident.Value == "main" && check.pkg.name == "main" { 104 check.error(ident, InvalidMainDecl, "cannot declare main - must be func") 105 return 106 } 107 108 check.declare(check.pkg.scope, ident, obj, nopos) 109 check.objMap[obj] = d 110 obj.setOrder(uint32(len(check.objMap))) 111 } 112 113 // filename returns a filename suitable for debugging output. 114 func (check *Checker) filename(fileNo int) string { 115 file := check.files[fileNo] 116 if pos := file.Pos(); pos.IsKnown() { 117 // return check.fset.File(pos).Name() 118 // TODO(gri) do we need the actual file name here? 119 return pos.RelFilename() 120 } 121 return fmt.Sprintf("file[%d]", fileNo) 122 } 123 124 func (check *Checker) importPackage(pos syntax.Pos, path, dir string) *Package { 125 // If we already have a package for the given (path, dir) 126 // pair, use it instead of doing a full import. 127 // Checker.impMap only caches packages that are marked Complete 128 // or fake (dummy packages for failed imports). Incomplete but 129 // non-fake packages do require an import to complete them. 130 key := importKey{path, dir} 131 imp := check.impMap[key] 132 if imp != nil { 133 return imp 134 } 135 136 // no package yet => import it 137 if path == "C" && (check.conf.FakeImportC || check.conf.go115UsesCgo) { 138 imp = NewPackage("C", "C") 139 imp.fake = true // package scope is not populated 140 imp.cgo = check.conf.go115UsesCgo 141 } else { 142 // ordinary import 143 var err error 144 if importer := check.conf.Importer; importer == nil { 145 err = fmt.Errorf("Config.Importer not installed") 146 } else if importerFrom, ok := importer.(ImporterFrom); ok { 147 imp, err = importerFrom.ImportFrom(path, dir, 0) 148 if imp == nil && err == nil { 149 err = fmt.Errorf("Config.Importer.ImportFrom(%s, %s, 0) returned nil but no error", path, dir) 150 } 151 } else { 152 imp, err = importer.Import(path) 153 if imp == nil && err == nil { 154 err = fmt.Errorf("Config.Importer.Import(%s) returned nil but no error", path) 155 } 156 } 157 // make sure we have a valid package name 158 // (errors here can only happen through manipulation of packages after creation) 159 if err == nil && imp != nil && (imp.name == "_" || imp.name == "") { 160 err = fmt.Errorf("invalid package name: %q", imp.name) 161 imp = nil // create fake package below 162 } 163 if err != nil { 164 check.errorf(pos, BrokenImport, "could not import %s (%s)", path, err) 165 if imp == nil { 166 // create a new fake package 167 // come up with a sensible package name (heuristic) 168 name := path 169 if i := len(name); i > 0 && name[i-1] == '/' { 170 name = name[:i-1] 171 } 172 if i := strings.LastIndex(name, "/"); i >= 0 { 173 name = name[i+1:] 174 } 175 imp = NewPackage(path, name) 176 } 177 // continue to use the package as best as we can 178 imp.fake = true // avoid follow-up lookup failures 179 } 180 } 181 182 // package should be complete or marked fake, but be cautious 183 if imp.complete || imp.fake { 184 check.impMap[key] = imp 185 // Once we've formatted an error message, keep the pkgPathMap 186 // up-to-date on subsequent imports. It is used for package 187 // qualification in error messages. 188 if check.pkgPathMap != nil { 189 check.markImports(imp) 190 } 191 return imp 192 } 193 194 // something went wrong (importer may have returned incomplete package without error) 195 return nil 196 } 197 198 // collectObjects collects all file and package objects and inserts them 199 // into their respective scopes. It also performs imports and associates 200 // methods with receiver base type names. 201 func (check *Checker) collectObjects() { 202 pkg := check.pkg 203 204 // pkgImports is the set of packages already imported by any package file seen 205 // so far. Used to avoid duplicate entries in pkg.imports. Allocate and populate 206 // it (pkg.imports may not be empty if we are checking test files incrementally). 207 // Note that pkgImports is keyed by package (and thus package path), not by an 208 // importKey value. Two different importKey values may map to the same package 209 // which is why we cannot use the check.impMap here. 210 var pkgImports = make(map[*Package]bool) 211 for _, imp := range pkg.imports { 212 pkgImports[imp] = true 213 } 214 215 type methodInfo struct { 216 obj *Func // method 217 ptr bool // true if pointer receiver 218 recv *syntax.Name // receiver type name 219 } 220 var methods []methodInfo // collected methods with valid receivers and non-blank _ names 221 var fileScopes []*Scope 222 for fileNo, file := range check.files { 223 // The package identifier denotes the current package, 224 // but there is no corresponding package object. 225 check.recordDef(file.PkgName, nil) 226 227 fileScope := NewScope(pkg.scope, syntax.StartPos(file), syntax.EndPos(file), check.filename(fileNo)) 228 fileScopes = append(fileScopes, fileScope) 229 check.recordScope(file, fileScope) 230 231 // determine file directory, necessary to resolve imports 232 // FileName may be "" (typically for tests) in which case 233 // we get "." as the directory which is what we would want. 234 fileDir := dir(file.PkgName.Pos().RelFilename()) // TODO(gri) should this be filename? 235 236 first := -1 // index of first ConstDecl in the current group, or -1 237 var last *syntax.ConstDecl // last ConstDecl with init expressions, or nil 238 for index, decl := range file.DeclList { 239 if _, ok := decl.(*syntax.ConstDecl); !ok { 240 first = -1 // we're not in a constant declaration 241 } 242 243 switch s := decl.(type) { 244 case *syntax.ImportDecl: 245 // import package 246 if s.Path == nil || s.Path.Bad { 247 continue // error reported during parsing 248 } 249 path, err := validatedImportPath(s.Path.Value) 250 if err != nil { 251 check.errorf(s.Path, BadImportPath, "invalid import path (%s)", err) 252 continue 253 } 254 255 imp := check.importPackage(s.Path.Pos(), path, fileDir) 256 if imp == nil { 257 continue 258 } 259 260 // local name overrides imported package name 261 name := imp.name 262 if s.LocalPkgName != nil { 263 name = s.LocalPkgName.Value 264 if path == "C" { 265 // match 1.17 cmd/compile (not prescribed by spec) 266 check.error(s.LocalPkgName, ImportCRenamed, `cannot rename import "C"`) 267 continue 268 } 269 } 270 271 if name == "init" { 272 check.error(s, InvalidInitDecl, "cannot import package as init - init must be a func") 273 continue 274 } 275 276 // add package to list of explicit imports 277 // (this functionality is provided as a convenience 278 // for clients; it is not needed for type-checking) 279 if !pkgImports[imp] { 280 pkgImports[imp] = true 281 pkg.imports = append(pkg.imports, imp) 282 } 283 284 pkgName := NewPkgName(s.Pos(), pkg, name, imp) 285 if s.LocalPkgName != nil { 286 // in a dot-import, the dot represents the package 287 check.recordDef(s.LocalPkgName, pkgName) 288 } else { 289 check.recordImplicit(s, pkgName) 290 } 291 292 if imp.fake { 293 // match 1.17 cmd/compile (not prescribed by spec) 294 pkgName.used = true 295 } 296 297 // add import to file scope 298 check.imports = append(check.imports, pkgName) 299 if name == "." { 300 // dot-import 301 if check.dotImportMap == nil { 302 check.dotImportMap = make(map[dotImportKey]*PkgName) 303 } 304 // merge imported scope with file scope 305 for name, obj := range imp.scope.elems { 306 // Note: Avoid eager resolve(name, obj) here, so we only 307 // resolve dot-imported objects as needed. 308 309 // A package scope may contain non-exported objects, 310 // do not import them! 311 if isExported(name) { 312 // declare dot-imported object 313 // (Do not use check.declare because it modifies the object 314 // via Object.setScopePos, which leads to a race condition; 315 // the object may be imported into more than one file scope 316 // concurrently. See go.dev/issue/32154.) 317 if alt := fileScope.Lookup(name); alt != nil { 318 var err error_ 319 err.code = DuplicateDecl 320 err.errorf(s.LocalPkgName, "%s redeclared in this block", alt.Name()) 321 err.recordAltDecl(alt) 322 check.report(&err) 323 } else { 324 fileScope.insert(name, obj) 325 check.dotImportMap[dotImportKey{fileScope, name}] = pkgName 326 } 327 } 328 } 329 } else { 330 // declare imported package object in file scope 331 // (no need to provide s.LocalPkgName since we called check.recordDef earlier) 332 check.declare(fileScope, nil, pkgName, nopos) 333 } 334 335 case *syntax.ConstDecl: 336 // iota is the index of the current constDecl within the group 337 if first < 0 || s.Group == nil || file.DeclList[index-1].(*syntax.ConstDecl).Group != s.Group { 338 first = index 339 last = nil 340 } 341 iota := constant.MakeInt64(int64(index - first)) 342 343 // determine which initialization expressions to use 344 inherited := true 345 switch { 346 case s.Type != nil || s.Values != nil: 347 last = s 348 inherited = false 349 case last == nil: 350 last = new(syntax.ConstDecl) // make sure last exists 351 inherited = false 352 } 353 354 // declare all constants 355 values := syntax.UnpackListExpr(last.Values) 356 for i, name := range s.NameList { 357 obj := NewConst(name.Pos(), pkg, name.Value, nil, iota) 358 359 var init syntax.Expr 360 if i < len(values) { 361 init = values[i] 362 } 363 364 d := &declInfo{file: fileScope, vtyp: last.Type, init: init, inherited: inherited} 365 check.declarePkgObj(name, obj, d) 366 } 367 368 // Constants must always have init values. 369 check.arity(s.Pos(), s.NameList, values, true, inherited) 370 371 case *syntax.VarDecl: 372 lhs := make([]*Var, len(s.NameList)) 373 // If there's exactly one rhs initializer, use 374 // the same declInfo d1 for all lhs variables 375 // so that each lhs variable depends on the same 376 // rhs initializer (n:1 var declaration). 377 var d1 *declInfo 378 if _, ok := s.Values.(*syntax.ListExpr); !ok { 379 // The lhs elements are only set up after the for loop below, 380 // but that's ok because declarePkgObj only collects the declInfo 381 // for a later phase. 382 d1 = &declInfo{file: fileScope, lhs: lhs, vtyp: s.Type, init: s.Values} 383 } 384 385 // declare all variables 386 values := syntax.UnpackListExpr(s.Values) 387 for i, name := range s.NameList { 388 obj := NewVar(name.Pos(), pkg, name.Value, nil) 389 lhs[i] = obj 390 391 d := d1 392 if d == nil { 393 // individual assignments 394 var init syntax.Expr 395 if i < len(values) { 396 init = values[i] 397 } 398 d = &declInfo{file: fileScope, vtyp: s.Type, init: init} 399 } 400 401 check.declarePkgObj(name, obj, d) 402 } 403 404 // If we have no type, we must have values. 405 if s.Type == nil || values != nil { 406 check.arity(s.Pos(), s.NameList, values, false, false) 407 } 408 409 case *syntax.TypeDecl: 410 _ = len(s.TParamList) != 0 && check.verifyVersionf(s.TParamList[0], go1_18, "type parameter") 411 obj := NewTypeName(s.Name.Pos(), pkg, s.Name.Value, nil) 412 check.declarePkgObj(s.Name, obj, &declInfo{file: fileScope, tdecl: s}) 413 414 case *syntax.FuncDecl: 415 name := s.Name.Value 416 obj := NewFunc(s.Name.Pos(), pkg, name, nil) 417 hasTParamError := false // avoid duplicate type parameter errors 418 if s.Recv == nil { 419 // regular function 420 if name == "init" || name == "main" && pkg.name == "main" { 421 code := InvalidInitDecl 422 if name == "main" { 423 code = InvalidMainDecl 424 } 425 if len(s.TParamList) != 0 { 426 check.softErrorf(s.TParamList[0], code, "func %s must have no type parameters", name) 427 hasTParamError = true 428 } 429 if t := s.Type; len(t.ParamList) != 0 || len(t.ResultList) != 0 { 430 check.softErrorf(s.Name, code, "func %s must have no arguments and no return values", name) 431 } 432 } 433 // don't declare init functions in the package scope - they are invisible 434 if name == "init" { 435 obj.parent = pkg.scope 436 check.recordDef(s.Name, obj) 437 // init functions must have a body 438 if s.Body == nil { 439 // TODO(gri) make this error message consistent with the others above 440 check.softErrorf(obj.pos, MissingInitBody, "missing function body") 441 } 442 } else { 443 check.declare(pkg.scope, s.Name, obj, nopos) 444 } 445 } else { 446 // method 447 // d.Recv != nil 448 ptr, recv, _ := check.unpackRecv(s.Recv.Type, false) 449 // Methods with invalid receiver cannot be associated to a type, and 450 // methods with blank _ names are never found; no need to collect any 451 // of them. They will still be type-checked with all the other functions. 452 if recv != nil && name != "_" { 453 methods = append(methods, methodInfo{obj, ptr, recv}) 454 } 455 check.recordDef(s.Name, obj) 456 } 457 _ = len(s.TParamList) != 0 && !hasTParamError && check.verifyVersionf(s.TParamList[0], go1_18, "type parameter") 458 info := &declInfo{file: fileScope, fdecl: s} 459 // Methods are not package-level objects but we still track them in the 460 // object map so that we can handle them like regular functions (if the 461 // receiver is invalid); also we need their fdecl info when associating 462 // them with their receiver base type, below. 463 check.objMap[obj] = info 464 obj.setOrder(uint32(len(check.objMap))) 465 466 default: 467 check.errorf(s, InvalidSyntaxTree, "unknown syntax.Decl node %T", s) 468 } 469 } 470 } 471 472 // verify that objects in package and file scopes have different names 473 for _, scope := range fileScopes { 474 for name, obj := range scope.elems { 475 if alt := pkg.scope.Lookup(name); alt != nil { 476 obj = resolve(name, obj) 477 var err error_ 478 err.code = DuplicateDecl 479 if pkg, ok := obj.(*PkgName); ok { 480 err.errorf(alt, "%s already declared through import of %s", alt.Name(), pkg.Imported()) 481 err.recordAltDecl(pkg) 482 } else { 483 err.errorf(alt, "%s already declared through dot-import of %s", alt.Name(), obj.Pkg()) 484 // TODO(gri) dot-imported objects don't have a position; recordAltDecl won't print anything 485 err.recordAltDecl(obj) 486 } 487 check.report(&err) 488 } 489 } 490 } 491 492 // Now that we have all package scope objects and all methods, 493 // associate methods with receiver base type name where possible. 494 // Ignore methods that have an invalid receiver. They will be 495 // type-checked later, with regular functions. 496 if methods != nil { 497 check.methods = make(map[*TypeName][]*Func) 498 for i := range methods { 499 m := &methods[i] 500 // Determine the receiver base type and associate m with it. 501 ptr, base := check.resolveBaseTypeName(m.ptr, m.recv, fileScopes) 502 if base != nil { 503 m.obj.hasPtrRecv_ = ptr 504 check.methods[base] = append(check.methods[base], m.obj) 505 } 506 } 507 } 508 } 509 510 // unpackRecv unpacks a receiver type and returns its components: ptr indicates whether 511 // rtyp is a pointer receiver, rname is the receiver type name, and tparams are its 512 // type parameters, if any. The type parameters are only unpacked if unpackParams is 513 // set. If rname is nil, the receiver is unusable (i.e., the source has a bug which we 514 // cannot easily work around). 515 func (check *Checker) unpackRecv(rtyp syntax.Expr, unpackParams bool) (ptr bool, rname *syntax.Name, tparams []*syntax.Name) { 516 L: // unpack receiver type 517 // This accepts invalid receivers such as ***T and does not 518 // work for other invalid receivers, but we don't care. The 519 // validity of receiver expressions is checked elsewhere. 520 for { 521 switch t := rtyp.(type) { 522 case *syntax.ParenExpr: 523 rtyp = t.X 524 // case *ast.StarExpr: 525 // ptr = true 526 // rtyp = t.X 527 case *syntax.Operation: 528 if t.Op != syntax.Mul || t.Y != nil { 529 break 530 } 531 ptr = true 532 rtyp = t.X 533 default: 534 break L 535 } 536 } 537 538 // unpack type parameters, if any 539 if ptyp, _ := rtyp.(*syntax.IndexExpr); ptyp != nil { 540 rtyp = ptyp.X 541 if unpackParams { 542 for _, arg := range syntax.UnpackListExpr(ptyp.Index) { 543 var par *syntax.Name 544 switch arg := arg.(type) { 545 case *syntax.Name: 546 par = arg 547 case *syntax.BadExpr: 548 // ignore - error already reported by parser 549 case nil: 550 check.error(ptyp, InvalidSyntaxTree, "parameterized receiver contains nil parameters") 551 default: 552 check.errorf(arg, BadDecl, "receiver type parameter %s must be an identifier", arg) 553 } 554 if par == nil { 555 par = syntax.NewName(arg.Pos(), "_") 556 } 557 tparams = append(tparams, par) 558 } 559 560 } 561 } 562 563 // unpack receiver name 564 if name, _ := rtyp.(*syntax.Name); name != nil { 565 rname = name 566 } 567 568 return 569 } 570 571 // resolveBaseTypeName returns the non-alias base type name for typ, and whether 572 // there was a pointer indirection to get to it. The base type name must be declared 573 // in package scope, and there can be at most one pointer indirection. If no such type 574 // name exists, the returned base is nil. 575 func (check *Checker) resolveBaseTypeName(seenPtr bool, typ syntax.Expr, fileScopes []*Scope) (ptr bool, base *TypeName) { 576 // Algorithm: Starting from a type expression, which may be a name, 577 // we follow that type through alias declarations until we reach a 578 // non-alias type name. If we encounter anything but pointer types or 579 // parentheses we're done. If we encounter more than one pointer type 580 // we're done. 581 ptr = seenPtr 582 var seen map[*TypeName]bool 583 for { 584 // check if we have a pointer type 585 // if pexpr, _ := typ.(*ast.StarExpr); pexpr != nil { 586 if pexpr, _ := typ.(*syntax.Operation); pexpr != nil && pexpr.Op == syntax.Mul && pexpr.Y == nil { 587 // if we've already seen a pointer, we're done 588 if ptr { 589 return false, nil 590 } 591 ptr = true 592 typ = syntax.Unparen(pexpr.X) // continue with pointer base type 593 } 594 595 // typ must be a name, or a C.name cgo selector. 596 var name string 597 switch typ := typ.(type) { 598 case *syntax.Name: 599 name = typ.Value 600 case *syntax.SelectorExpr: 601 // C.struct_foo is a valid type name for packages using cgo. 602 // 603 // Detect this case, and adjust name so that the correct TypeName is 604 // resolved below. 605 if ident, _ := typ.X.(*syntax.Name); ident != nil && ident.Value == "C" { 606 // Check whether "C" actually resolves to an import of "C", by looking 607 // in the appropriate file scope. 608 var obj Object 609 for _, scope := range fileScopes { 610 if scope.Contains(ident.Pos()) { 611 obj = scope.Lookup(ident.Value) 612 } 613 } 614 // If Config.go115UsesCgo is set, the typechecker will resolve Cgo 615 // selectors to their cgo name. We must do the same here. 616 if pname, _ := obj.(*PkgName); pname != nil { 617 if pname.imported.cgo { // only set if Config.go115UsesCgo is set 618 name = "_Ctype_" + typ.Sel.Value 619 } 620 } 621 } 622 if name == "" { 623 return false, nil 624 } 625 default: 626 return false, nil 627 } 628 629 // name must denote an object found in the current package scope 630 // (note that dot-imported objects are not in the package scope!) 631 obj := check.pkg.scope.Lookup(name) 632 if obj == nil { 633 return false, nil 634 } 635 636 // the object must be a type name... 637 tname, _ := obj.(*TypeName) 638 if tname == nil { 639 return false, nil 640 } 641 642 // ... which we have not seen before 643 if seen[tname] { 644 return false, nil 645 } 646 647 // we're done if tdecl defined tname as a new type 648 // (rather than an alias) 649 tdecl := check.objMap[tname].tdecl // must exist for objects in package scope 650 if !tdecl.Alias { 651 return ptr, tname 652 } 653 654 // otherwise, continue resolving 655 typ = tdecl.Type 656 if seen == nil { 657 seen = make(map[*TypeName]bool) 658 } 659 seen[tname] = true 660 } 661 } 662 663 // packageObjects typechecks all package objects, but not function bodies. 664 func (check *Checker) packageObjects() { 665 // process package objects in source order for reproducible results 666 objList := make([]Object, len(check.objMap)) 667 i := 0 668 for obj := range check.objMap { 669 objList[i] = obj 670 i++ 671 } 672 sort.Sort(inSourceOrder(objList)) 673 674 // add new methods to already type-checked types (from a prior Checker.Files call) 675 for _, obj := range objList { 676 if obj, _ := obj.(*TypeName); obj != nil && obj.typ != nil { 677 check.collectMethods(obj) 678 } 679 } 680 681 if check.enableAlias { 682 // With Alias nodes we can process declarations in any order. 683 for _, obj := range objList { 684 check.objDecl(obj, nil) 685 } 686 } else { 687 // Without Alias nodes, we process non-alias type declarations first, followed by 688 // alias declarations, and then everything else. This appears to avoid most situations 689 // where the type of an alias is needed before it is available. 690 // There may still be cases where this is not good enough (see also go.dev/issue/25838). 691 // In those cases Checker.ident will report an error ("invalid use of type alias"). 692 var aliasList []*TypeName 693 var othersList []Object // everything that's not a type 694 // phase 1: non-alias type declarations 695 for _, obj := range objList { 696 if tname, _ := obj.(*TypeName); tname != nil { 697 if check.objMap[tname].tdecl.Alias { 698 aliasList = append(aliasList, tname) 699 } else { 700 check.objDecl(obj, nil) 701 } 702 } else { 703 othersList = append(othersList, obj) 704 } 705 } 706 // phase 2: alias type declarations 707 for _, obj := range aliasList { 708 check.objDecl(obj, nil) 709 } 710 // phase 3: all other declarations 711 for _, obj := range othersList { 712 check.objDecl(obj, nil) 713 } 714 } 715 716 // At this point we may have a non-empty check.methods map; this means that not all 717 // entries were deleted at the end of typeDecl because the respective receiver base 718 // types were not found. In that case, an error was reported when declaring those 719 // methods. We can now safely discard this map. 720 check.methods = nil 721 } 722 723 // inSourceOrder implements the sort.Sort interface. 724 type inSourceOrder []Object 725 726 func (a inSourceOrder) Len() int { return len(a) } 727 func (a inSourceOrder) Less(i, j int) bool { return a[i].order() < a[j].order() } 728 func (a inSourceOrder) Swap(i, j int) { a[i], a[j] = a[j], a[i] } 729 730 // unusedImports checks for unused imports. 731 func (check *Checker) unusedImports() { 732 // If function bodies are not checked, packages' uses are likely missing - don't check. 733 if check.conf.IgnoreFuncBodies { 734 return 735 } 736 737 // spec: "It is illegal (...) to directly import a package without referring to 738 // any of its exported identifiers. To import a package solely for its side-effects 739 // (initialization), use the blank identifier as explicit package name." 740 741 for _, obj := range check.imports { 742 if !obj.used && obj.name != "_" { 743 check.errorUnusedPkg(obj) 744 } 745 } 746 } 747 748 func (check *Checker) errorUnusedPkg(obj *PkgName) { 749 // If the package was imported with a name other than the final 750 // import path element, show it explicitly in the error message. 751 // Note that this handles both renamed imports and imports of 752 // packages containing unconventional package declarations. 753 // Note that this uses / always, even on Windows, because Go import 754 // paths always use forward slashes. 755 path := obj.imported.path 756 elem := path 757 if i := strings.LastIndex(elem, "/"); i >= 0 { 758 elem = elem[i+1:] 759 } 760 if obj.name == "" || obj.name == "." || obj.name == elem { 761 check.softErrorf(obj, UnusedImport, "%q imported and not used", path) 762 } else { 763 check.softErrorf(obj, UnusedImport, "%q imported as %s and not used", path, obj.name) 764 } 765 } 766 767 // dir makes a good-faith attempt to return the directory 768 // portion of path. If path is empty, the result is ".". 769 // (Per the go/build package dependency tests, we cannot import 770 // path/filepath and simply use filepath.Dir.) 771 func dir(path string) string { 772 if i := strings.LastIndexAny(path, `/\`); i > 0 { 773 return path[:i] 774 } 775 // i <= 0 776 return "." 777 }