]> Cypherpunks.ru repositories - gostls13.git/blob - src/go/types/resolver.go
go/types, types2: no "imported but not used" error for unimported packages
[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                                 path, err := validatedImportPath(d.spec.Path.Value)
258                                 if err != nil {
259                                         check.errorf(d.spec.Path, _BadImportPath, "invalid import path (%s)", err)
260                                         return
261                                 }
262
263                                 imp := check.importPackage(d.spec.Path, path, fileDir)
264                                 if imp == nil {
265                                         return
266                                 }
267
268                                 // local name overrides imported package name
269                                 name := imp.name
270                                 if d.spec.Name != nil {
271                                         name = d.spec.Name.Name
272                                         if path == "C" {
273                                                 // match 1.17 cmd/compile (not prescribed by spec)
274                                                 check.errorf(d.spec.Name, _ImportCRenamed, `cannot rename import "C"`)
275                                                 return
276                                         }
277                                 }
278
279                                 if name == "init" {
280                                         check.errorf(d.spec, _InvalidInitDecl, "cannot import package as init - init must be a func")
281                                         return
282                                 }
283
284                                 // add package to list of explicit imports
285                                 // (this functionality is provided as a convenience
286                                 // for clients; it is not needed for type-checking)
287                                 if !pkgImports[imp] {
288                                         pkgImports[imp] = true
289                                         pkg.imports = append(pkg.imports, imp)
290                                 }
291
292                                 pkgName := NewPkgName(d.spec.Pos(), pkg, name, imp)
293                                 if d.spec.Name != nil {
294                                         // in a dot-import, the dot represents the package
295                                         check.recordDef(d.spec.Name, pkgName)
296                                 } else {
297                                         check.recordImplicit(d.spec, pkgName)
298                                 }
299
300                                 if imp.fake {
301                                         // match 1.17 cmd/compile (not prescribed by spec)
302                                         pkgName.used = true
303                                 }
304
305                                 // add import to file scope
306                                 check.imports = append(check.imports, pkgName)
307                                 if name == "." {
308                                         // dot-import
309                                         if check.dotImportMap == nil {
310                                                 check.dotImportMap = make(map[dotImportKey]*PkgName)
311                                         }
312                                         // merge imported scope with file scope
313                                         for name, obj := range imp.scope.elems {
314                                                 // Note: Avoid eager resolve(name, obj) here, so we only
315                                                 // resolve dot-imported objects as needed.
316
317                                                 // A package scope may contain non-exported objects,
318                                                 // do not import them!
319                                                 if token.IsExported(name) {
320                                                         // declare dot-imported object
321                                                         // (Do not use check.declare because it modifies the object
322                                                         // via Object.setScopePos, which leads to a race condition;
323                                                         // the object may be imported into more than one file scope
324                                                         // concurrently. See issue #32154.)
325                                                         if alt := fileScope.Lookup(name); alt != nil {
326                                                                 check.errorf(d.spec.Name, _DuplicateDecl, "%s redeclared in this block", alt.Name())
327                                                                 check.reportAltDecl(alt)
328                                                         } else {
329                                                                 fileScope.insert(name, obj)
330                                                                 check.dotImportMap[dotImportKey{fileScope, name}] = pkgName
331                                                         }
332                                                 }
333                                         }
334                                 } else {
335                                         // declare imported package object in file scope
336                                         // (no need to provide s.Name since we called check.recordDef earlier)
337                                         check.declare(fileScope, nil, pkgName, token.NoPos)
338                                 }
339                         case constDecl:
340                                 // declare all constants
341                                 for i, name := range d.spec.Names {
342                                         obj := NewConst(name.Pos(), pkg, name.Name, nil, constant.MakeInt64(int64(d.iota)))
343
344                                         var init ast.Expr
345                                         if i < len(d.init) {
346                                                 init = d.init[i]
347                                         }
348
349                                         d := &declInfo{file: fileScope, vtyp: d.typ, init: init, inherited: d.inherited}
350                                         check.declarePkgObj(name, obj, d)
351                                 }
352
353                         case varDecl:
354                                 lhs := make([]*Var, len(d.spec.Names))
355                                 // If there's exactly one rhs initializer, use
356                                 // the same declInfo d1 for all lhs variables
357                                 // so that each lhs variable depends on the same
358                                 // rhs initializer (n:1 var declaration).
359                                 var d1 *declInfo
360                                 if len(d.spec.Values) == 1 {
361                                         // The lhs elements are only set up after the for loop below,
362                                         // but that's ok because declareVar only collects the declInfo
363                                         // for a later phase.
364                                         d1 = &declInfo{file: fileScope, lhs: lhs, vtyp: d.spec.Type, init: d.spec.Values[0]}
365                                 }
366
367                                 // declare all variables
368                                 for i, name := range d.spec.Names {
369                                         obj := NewVar(name.Pos(), pkg, name.Name, nil)
370                                         lhs[i] = obj
371
372                                         di := d1
373                                         if di == nil {
374                                                 // individual assignments
375                                                 var init ast.Expr
376                                                 if i < len(d.spec.Values) {
377                                                         init = d.spec.Values[i]
378                                                 }
379                                                 di = &declInfo{file: fileScope, vtyp: d.spec.Type, init: init}
380                                         }
381
382                                         check.declarePkgObj(name, obj, di)
383                                 }
384                         case typeDecl:
385                                 if d.spec.TypeParams.NumFields() != 0 && !check.allowVersion(pkg, 1, 18) {
386                                         check.softErrorf(d.spec.TypeParams.List[0], _UnsupportedFeature, "type parameters require go1.18 or later")
387                                 }
388                                 obj := NewTypeName(d.spec.Name.Pos(), pkg, d.spec.Name.Name, nil)
389                                 check.declarePkgObj(d.spec.Name, obj, &declInfo{file: fileScope, tdecl: d.spec})
390                         case funcDecl:
391                                 name := d.decl.Name.Name
392                                 obj := NewFunc(d.decl.Name.Pos(), pkg, name, nil)
393                                 hasTParamError := false // avoid duplicate type parameter errors
394                                 if d.decl.Recv.NumFields() == 0 {
395                                         // regular function
396                                         if d.decl.Recv != nil {
397                                                 check.error(d.decl.Recv, _BadRecv, "method is missing receiver")
398                                                 // treat as function
399                                         }
400                                         if name == "init" || (name == "main" && check.pkg.name == "main") {
401                                                 code := _InvalidInitDecl
402                                                 if name == "main" {
403                                                         code = _InvalidMainDecl
404                                                 }
405                                                 if d.decl.Type.TypeParams.NumFields() != 0 {
406                                                         check.softErrorf(d.decl.Type.TypeParams.List[0], code, "func %s must have no type parameters", name)
407                                                         hasTParamError = true
408                                                 }
409                                                 if t := d.decl.Type; t.Params.NumFields() != 0 || t.Results != nil {
410                                                         // TODO(rFindley) Should this be a hard error?
411                                                         check.softErrorf(d.decl, code, "func %s must have no arguments and no return values", name)
412                                                 }
413                                         }
414                                         if name == "init" {
415                                                 // don't declare init functions in the package scope - they are invisible
416                                                 obj.parent = pkg.scope
417                                                 check.recordDef(d.decl.Name, obj)
418                                                 // init functions must have a body
419                                                 if d.decl.Body == nil {
420                                                         // TODO(gri) make this error message consistent with the others above
421                                                         check.softErrorf(obj, _MissingInitBody, "missing function body")
422                                                 }
423                                         } else {
424                                                 check.declare(pkg.scope, d.decl.Name, obj, token.NoPos)
425                                         }
426                                 } else {
427                                         // method
428
429                                         // TODO(rFindley) earlier versions of this code checked that methods
430                                         //                have no type parameters, but this is checked later
431                                         //                when type checking the function type. Confirm that
432                                         //                we don't need to check tparams here.
433
434                                         ptr, recv, _ := check.unpackRecv(d.decl.Recv.List[0].Type, false)
435                                         // (Methods with invalid receiver cannot be associated to a type, and
436                                         // methods with blank _ names are never found; no need to collect any
437                                         // of them. They will still be type-checked with all the other functions.)
438                                         if recv != nil && name != "_" {
439                                                 methods = append(methods, methodInfo{obj, ptr, recv})
440                                         }
441                                         check.recordDef(d.decl.Name, obj)
442                                 }
443                                 if d.decl.Type.TypeParams.NumFields() != 0 && !check.allowVersion(pkg, 1, 18) && !hasTParamError {
444                                         check.softErrorf(d.decl.Type.TypeParams.List[0], _UnsupportedFeature, "type parameters require go1.18 or later")
445                                 }
446                                 info := &declInfo{file: fileScope, fdecl: d.decl}
447                                 // Methods are not package-level objects but we still track them in the
448                                 // object map so that we can handle them like regular functions (if the
449                                 // receiver is invalid); also we need their fdecl info when associating
450                                 // them with their receiver base type, below.
451                                 check.objMap[obj] = info
452                                 obj.setOrder(uint32(len(check.objMap)))
453                         }
454                 })
455         }
456
457         // verify that objects in package and file scopes have different names
458         for _, scope := range fileScopes {
459                 for name, obj := range scope.elems {
460                         if alt := pkg.scope.Lookup(name); alt != nil {
461                                 obj = resolve(name, obj)
462                                 if pkg, ok := obj.(*PkgName); ok {
463                                         check.errorf(alt, _DuplicateDecl, "%s already declared through import of %s", alt.Name(), pkg.Imported())
464                                         check.reportAltDecl(pkg)
465                                 } else {
466                                         check.errorf(alt, _DuplicateDecl, "%s already declared through dot-import of %s", alt.Name(), obj.Pkg())
467                                         // TODO(gri) dot-imported objects don't have a position; reportAltDecl won't print anything
468                                         check.reportAltDecl(obj)
469                                 }
470                         }
471                 }
472         }
473
474         // Now that we have all package scope objects and all methods,
475         // associate methods with receiver base type name where possible.
476         // Ignore methods that have an invalid receiver. They will be
477         // type-checked later, with regular functions.
478         if methods == nil {
479                 return // nothing to do
480         }
481         check.methods = make(map[*TypeName][]*Func)
482         for i := range methods {
483                 m := &methods[i]
484                 // Determine the receiver base type and associate m with it.
485                 ptr, base := check.resolveBaseTypeName(m.ptr, m.recv)
486                 if base != nil {
487                         m.obj.hasPtrRecv_ = ptr
488                         check.methods[base] = append(check.methods[base], m.obj)
489                 }
490         }
491 }
492
493 // unpackRecv unpacks a receiver type and returns its components: ptr indicates whether
494 // rtyp is a pointer receiver, rname is the receiver type name, and tparams are its
495 // type parameters, if any. The type parameters are only unpacked if unpackParams is
496 // set. If rname is nil, the receiver is unusable (i.e., the source has a bug which we
497 // cannot easily work around).
498 func (check *Checker) unpackRecv(rtyp ast.Expr, unpackParams bool) (ptr bool, rname *ast.Ident, tparams []*ast.Ident) {
499 L: // unpack receiver type
500         // This accepts invalid receivers such as ***T and does not
501         // work for other invalid receivers, but we don't care. The
502         // validity of receiver expressions is checked elsewhere.
503         for {
504                 switch t := rtyp.(type) {
505                 case *ast.ParenExpr:
506                         rtyp = t.X
507                 case *ast.StarExpr:
508                         ptr = true
509                         rtyp = t.X
510                 default:
511                         break L
512                 }
513         }
514
515         // unpack type parameters, if any
516         switch rtyp.(type) {
517         case *ast.IndexExpr, *ast.IndexListExpr:
518                 ix := typeparams.UnpackIndexExpr(rtyp)
519                 rtyp = ix.X
520                 if unpackParams {
521                         for _, arg := range ix.Indices {
522                                 var par *ast.Ident
523                                 switch arg := arg.(type) {
524                                 case *ast.Ident:
525                                         par = arg
526                                 case *ast.BadExpr:
527                                         // ignore - error already reported by parser
528                                 case nil:
529                                         check.invalidAST(ix.Orig, "parameterized receiver contains nil parameters")
530                                 default:
531                                         check.errorf(arg, _BadDecl, "receiver type parameter %s must be an identifier", arg)
532                                 }
533                                 if par == nil {
534                                         par = &ast.Ident{NamePos: arg.Pos(), Name: "_"}
535                                 }
536                                 tparams = append(tparams, par)
537                         }
538                 }
539         }
540
541         // unpack receiver name
542         if name, _ := rtyp.(*ast.Ident); name != nil {
543                 rname = name
544         }
545
546         return
547 }
548
549 // resolveBaseTypeName returns the non-alias base type name for typ, and whether
550 // there was a pointer indirection to get to it. The base type name must be declared
551 // in package scope, and there can be at most one pointer indirection. If no such type
552 // name exists, the returned base is nil.
553 func (check *Checker) resolveBaseTypeName(seenPtr bool, name *ast.Ident) (ptr bool, base *TypeName) {
554         // Algorithm: Starting from a type expression, which may be a name,
555         // we follow that type through alias declarations until we reach a
556         // non-alias type name. If we encounter anything but pointer types or
557         // parentheses we're done. If we encounter more than one pointer type
558         // we're done.
559         ptr = seenPtr
560         var seen map[*TypeName]bool
561         var typ ast.Expr = name
562         for {
563                 typ = unparen(typ)
564
565                 // check if we have a pointer type
566                 if pexpr, _ := typ.(*ast.StarExpr); pexpr != nil {
567                         // if we've already seen a pointer, we're done
568                         if ptr {
569                                 return false, nil
570                         }
571                         ptr = true
572                         typ = unparen(pexpr.X) // continue with pointer base type
573                 }
574
575                 // typ must be a name
576                 name, _ := typ.(*ast.Ident)
577                 if name == nil {
578                         return false, nil
579                 }
580
581                 // name must denote an object found in the current package scope
582                 // (note that dot-imported objects are not in the package scope!)
583                 obj := check.pkg.scope.Lookup(name.Name)
584                 if obj == nil {
585                         return false, nil
586                 }
587
588                 // the object must be a type name...
589                 tname, _ := obj.(*TypeName)
590                 if tname == nil {
591                         return false, nil
592                 }
593
594                 // ... which we have not seen before
595                 if seen[tname] {
596                         return false, nil
597                 }
598
599                 // we're done if tdecl defined tname as a new type
600                 // (rather than an alias)
601                 tdecl := check.objMap[tname].tdecl // must exist for objects in package scope
602                 if !tdecl.Assign.IsValid() {
603                         return ptr, tname
604                 }
605
606                 // otherwise, continue resolving
607                 typ = tdecl.Type
608                 if seen == nil {
609                         seen = make(map[*TypeName]bool)
610                 }
611                 seen[tname] = true
612         }
613 }
614
615 // packageObjects typechecks all package objects, but not function bodies.
616 func (check *Checker) packageObjects() {
617         // process package objects in source order for reproducible results
618         objList := make([]Object, len(check.objMap))
619         i := 0
620         for obj := range check.objMap {
621                 objList[i] = obj
622                 i++
623         }
624         sort.Sort(inSourceOrder(objList))
625
626         // add new methods to already type-checked types (from a prior Checker.Files call)
627         for _, obj := range objList {
628                 if obj, _ := obj.(*TypeName); obj != nil && obj.typ != nil {
629                         check.collectMethods(obj)
630                 }
631         }
632
633         // We process non-alias type declarations first, followed by alias declarations,
634         // and then everything else. This appears to avoid most situations where the type
635         // of an alias is needed before it is available.
636         // There may still be cases where this is not good enough (see also issue #25838).
637         // In those cases Checker.ident will report an error ("invalid use of type alias").
638         var aliasList []*TypeName
639         var othersList []Object // everything that's not a type
640         // phase 1: non-alias type declarations
641         for _, obj := range objList {
642                 if tname, _ := obj.(*TypeName); tname != nil {
643                         if check.objMap[tname].tdecl.Assign.IsValid() {
644                                 aliasList = append(aliasList, tname)
645                         } else {
646                                 check.objDecl(obj, nil)
647                         }
648                 } else {
649                         othersList = append(othersList, obj)
650                 }
651         }
652         // phase 2: alias type declarations
653         for _, obj := range aliasList {
654                 check.objDecl(obj, nil)
655         }
656         // phase 3: all other declarations
657         for _, obj := range othersList {
658                 check.objDecl(obj, nil)
659         }
660
661         // At this point we may have a non-empty check.methods map; this means that not all
662         // entries were deleted at the end of typeDecl because the respective receiver base
663         // types were not found. In that case, an error was reported when declaring those
664         // methods. We can now safely discard this map.
665         check.methods = nil
666 }
667
668 // inSourceOrder implements the sort.Sort interface.
669 type inSourceOrder []Object
670
671 func (a inSourceOrder) Len() int           { return len(a) }
672 func (a inSourceOrder) Less(i, j int) bool { return a[i].order() < a[j].order() }
673 func (a inSourceOrder) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
674
675 // unusedImports checks for unused imports.
676 func (check *Checker) unusedImports() {
677         // If function bodies are not checked, packages' uses are likely missing - don't check.
678         if check.conf.IgnoreFuncBodies {
679                 return
680         }
681
682         // spec: "It is illegal (...) to directly import a package without referring to
683         // any of its exported identifiers. To import a package solely for its side-effects
684         // (initialization), use the blank identifier as explicit package name."
685
686         for _, obj := range check.imports {
687                 if !obj.used && obj.name != "_" {
688                         check.errorUnusedPkg(obj)
689                 }
690         }
691 }
692
693 func (check *Checker) errorUnusedPkg(obj *PkgName) {
694         // If the package was imported with a name other than the final
695         // import path element, show it explicitly in the error message.
696         // Note that this handles both renamed imports and imports of
697         // packages containing unconventional package declarations.
698         // Note that this uses / always, even on Windows, because Go import
699         // paths always use forward slashes.
700         path := obj.imported.path
701         elem := path
702         if i := strings.LastIndex(elem, "/"); i >= 0 {
703                 elem = elem[i+1:]
704         }
705         if obj.name == "" || obj.name == "." || obj.name == elem {
706                 check.softErrorf(obj, _UnusedImport, "%q imported but not used", path)
707         } else {
708                 check.softErrorf(obj, _UnusedImport, "%q imported but not used as %s", path, obj.name)
709         }
710 }
711
712 // dir makes a good-faith attempt to return the directory
713 // portion of path. If path is empty, the result is ".".
714 // (Per the go/build package dependency tests, we cannot import
715 // path/filepath and simply use filepath.Dir.)
716 func dir(path string) string {
717         if i := strings.LastIndexAny(path, `/\`); i > 0 {
718                 return path[:i]
719         }
720         // i <= 0
721         return "."
722 }