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