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