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