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