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) {
59 case init == nil && r == 0:
60 // var decl w/o init expr
62 check.errorf(s.Pos(), "missing type or init expr")
65 if l < len(s.Values) {
68 check.errorf(n.Pos(), "extra init expr %s", n)
69 // TODO(gri) avoid declared but not used error here
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
75 case l > r && (init != nil || r != 1):
77 check.errorf(n.Pos(), "missing init expr for %s", n)
81 func validatedImportPath(path string) (string, error) {
82 s, err := strconv.Unquote(path)
87 return "", fmt.Errorf("empty string")
89 const illegalChars = `!"#$%&'()*,:;<=>?[\]^{|}` + "`\uFFFD"
91 if !unicode.IsGraphic(r) || unicode.IsSpace(r) || strings.ContainsRune(illegalChars, r) {
92 return s, fmt.Errorf("invalid character %#U", r)
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())
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")
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")
117 check.declare(check.pkg.scope, ident, obj, token.NoPos)
118 check.objMap[obj] = d
119 obj.setOrder(uint32(len(check.objMap)))
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()
128 return fmt.Sprintf("file[%d]", fileNo)
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]
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
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)
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)
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
171 check.errorf(pos, "could not import %s (%s)", path, err)
173 // create a new fake package
174 // come up with a sensible package name (heuristic)
176 if i := len(name); i > 0 && name[i-1] == '/' {
179 if i := strings.LastIndex(name, "/"); i >= 0 {
182 imp = NewPackage(path, name)
184 // continue to use the package as best as we can
185 imp.fake = true // avoid follow-up lookup failures
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]++
196 // something went wrong (importer may have returned incomplete package without error)
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() {
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
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)
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())
230 fileScope := NewScope(check.pkg.scope, pos, end, check.filename(fileNo))
231 check.recordScope(file, fileScope)
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)
238 check.walkDecls(file.Decls, func(d decl) {
239 switch d := d.(type) {
242 path, err := validatedImportPath(d.spec.Path.Value)
244 check.errorf(d.spec.Path.Pos(), "invalid import path (%s)", err)
248 imp := check.importPackage(d.spec.Path.Pos(), path, fileDir)
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)
261 // local name overrides imported package name
263 if d.spec.Name != nil {
264 name = d.spec.Name.Name
266 // match cmd/compile (not prescribed by spec)
267 check.errorf(d.spec.Name.Pos(), `cannot rename import "C"`)
271 check.errorf(d.spec.Name.Pos(), "cannot declare init - must be func")
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)
281 check.recordImplicit(d.spec, obj)
285 // match cmd/compile (not prescribed by spec)
289 // add import to file scope
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!
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)
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())
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)
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)))
325 d := &declInfo{file: fileScope, typ: d.typ, init: init}
326 check.declarePkgObj(name, obj, d)
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).
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]}
343 // declare all variables
344 for i, name := range d.spec.Names {
345 obj := NewVar(name.Pos(), pkg, name.Name, nil)
350 // individual assignments
352 if i < len(d.spec.Values) {
353 init = d.spec.Values[i]
355 di = &declInfo{file: fileScope, typ: d.spec.Type, init: init}
358 check.declarePkgObj(name, obj, di)
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()})
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 {
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")
378 check.declare(pkg.scope, d.decl.Name, obj, token.NoPos)
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.)
386 methods = append(methods, obj)
388 check.recordDef(d.decl.Name, obj)
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)))
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)
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)
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.
421 return // nothing to do
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 {
428 // Determine the receiver base type and associate f with it.
429 ptr, base := check.resolveBaseTypeName(list[0].Type)
432 check.methods[base] = append(check.methods[base], f)
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
448 var seen map[*TypeName]bool
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
459 typ = unparen(pexpr.X) // continue with pointer base type
462 // typ must be a name
463 name, _ := typ.(*ast.Ident)
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)
475 // the object must be a type name...
476 tname, _ := obj.(*TypeName)
481 // ... which we have not seen before
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
493 // otherwise, continue resolving
496 seen = make(map[*TypeName]bool)
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))
507 for obj := range check.objMap {
511 sort.Sort(inSourceOrder(objList))
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)
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
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)
535 check.objDecl(obj, nil)
538 for _, obj := range aliasList {
539 check.objDecl(obj, nil)
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.
549 // inSourceOrder implements the sort.Sort interface.
550 type inSourceOrder []Object
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] }
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 {
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."
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.
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)
579 check.softErrorf(obj.pos, "%q imported but not used as %s", path, obj.name)
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)
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 {
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 {