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