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