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