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