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