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.
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
27 // The deps field tracks initialization expression dependencies.
28 deps map[Object]bool // lazily initialized
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
37 // addDep adds obj to the set of objects d's init expression depends on.
38 func (d *declInfo) addDep(obj Object) {
41 m = make(map[Object]bool)
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) {
58 const code = _WrongAssignCount
60 case init == nil && r == 0:
61 // var decl w/o init expr
63 check.errorf(s, code, "missing type or init expr")
66 if l < len(s.Values) {
69 check.errorf(n, code, "extra init expr %s", n)
70 // TODO(gri) avoid declared but not used error here
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
76 case l > r && (init != nil || r != 1):
78 check.errorf(n, code, "missing init expr for %s", n)
82 func validatedImportPath(path string) (string, error) {
83 s, err := strconv.Unquote(path)
88 return "", fmt.Errorf("empty string")
90 const illegalChars = `!"#$%&'()*,:;<=>?[\]^{|}` + "`\uFFFD"
92 if !unicode.IsGraphic(r) || unicode.IsSpace(r) || strings.ContainsRune(illegalChars, r) {
93 return s, fmt.Errorf("invalid character %#U", r)
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())
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")
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")
118 check.declare(check.pkg.scope, ident, obj, token.NoPos)
119 check.objMap[obj] = d
120 obj.setOrder(uint32(len(check.objMap)))
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()
129 return fmt.Sprintf("file[%d]", fileNo)
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]
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
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)
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)
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
172 check.errorf(atPos(pos), _BrokenImport, "could not import %s (%s)", path, err)
174 // create a new fake package
175 // come up with a sensible package name (heuristic)
177 if i := len(name); i > 0 && name[i-1] == '/' {
180 if i := strings.LastIndex(name, "/"); i >= 0 {
183 imp = NewPackage(path, name)
185 // continue to use the package as best as we can
186 imp.fake = true // avoid follow-up lookup failures
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]++
197 // something went wrong (importer may have returned incomplete package without error)
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() {
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
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)
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())
231 fileScope := NewScope(check.pkg.scope, pos, end, check.filename(fileNo))
232 check.recordScope(file, fileScope)
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)
239 check.walkDecls(file.Decls, func(d decl) {
240 switch d := d.(type) {
243 path, err := validatedImportPath(d.spec.Path.Value)
245 check.errorf(d.spec.Path, _BadImportPath, "invalid import path (%s)", err)
249 imp := check.importPackage(d.spec.Path.Pos(), path, fileDir)
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)
262 // local name overrides imported package name
264 if d.spec.Name != nil {
265 name = d.spec.Name.Name
267 // match cmd/compile (not prescribed by spec)
268 check.errorf(d.spec.Name, _ImportCRenamed, `cannot rename import "C"`)
272 check.errorf(d.spec.Name, _InvalidInitDecl, "cannot declare init - must be func")
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)
282 check.recordImplicit(d.spec, obj)
286 // match cmd/compile (not prescribed by spec)
290 // add import to file scope
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!
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)
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)
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)
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)))
326 d := &declInfo{file: fileScope, typ: d.typ, init: init}
327 check.declarePkgObj(name, obj, d)
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).
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]}
344 // declare all variables
345 for i, name := range d.spec.Names {
346 obj := NewVar(name.Pos(), pkg, name.Name, nil)
351 // individual assignments
353 if i < len(d.spec.Values) {
354 init = d.spec.Values[i]
356 di = &declInfo{file: fileScope, typ: d.spec.Type, init: init}
359 check.declarePkgObj(name, obj, di)
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()})
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 {
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")
379 check.declare(pkg.scope, d.decl.Name, obj, token.NoPos)
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.)
387 methods = append(methods, obj)
389 check.recordDef(d.decl.Name, obj)
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)))
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)
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)
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.
422 return // nothing to do
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 {
429 // Determine the receiver base type and associate f with it.
430 ptr, base := check.resolveBaseTypeName(list[0].Type)
433 check.methods[base] = append(check.methods[base], f)
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
449 var seen map[*TypeName]bool
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
460 typ = unparen(pexpr.X) // continue with pointer base type
463 // typ must be a name
464 name, _ := typ.(*ast.Ident)
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)
476 // the object must be a type name...
477 tname, _ := obj.(*TypeName)
482 // ... which we have not seen before
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
494 // otherwise, continue resolving
497 seen = make(map[*TypeName]bool)
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))
508 for obj := range check.objMap {
512 sort.Sort(inSourceOrder(objList))
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)
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
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)
536 check.objDecl(obj, nil)
539 for _, obj := range aliasList {
540 check.objDecl(obj, nil)
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.
550 // inSourceOrder implements the sort.Sort interface.
551 type inSourceOrder []Object
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] }
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 {
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."
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.
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)
580 check.softErrorf(obj, _UnusedImport, "%q imported but not used as %s", path, obj.name)
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)
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 {
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 {