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