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