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