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