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 vtyp ast.Expr // type, or nil (for const and var declarations only)
23 init ast.Expr // init/orig expression, or nil (for const and var declarations only)
24 inherited bool // if set, the init expression is inherited from a previous constant declaration
25 tdecl *ast.TypeSpec // type declaration, or nil
26 fdecl *ast.FuncDecl // func declaration, or nil
28 // The deps field tracks initialization expression dependencies.
29 deps map[Object]bool // lazily initialized
32 // hasInitializer reports whether the declared object has an initialization
33 // expression or function body.
34 func (d *declInfo) hasInitializer() bool {
35 return d.init != nil || d.fdecl != nil && d.fdecl.Body != nil
38 // addDep adds obj to the set of objects d's init expression depends on.
39 func (d *declInfo) addDep(obj Object) {
42 m = make(map[Object]bool)
48 // arityMatch checks that the lhs and rhs of a const or var decl
49 // have the appropriate number of names and init exprs. For const
50 // decls, init is the value spec providing the init exprs; for
51 // var decls, init is nil (the init exprs are in s in this case).
52 func (check *Checker) arityMatch(s, init *ast.ValueSpec) {
59 const code = _WrongAssignCount
61 case init == nil && r == 0:
62 // var decl w/o init expr
64 check.errorf(s, code, "missing type or init expr")
67 if l < len(s.Values) {
70 check.errorf(n, code, "extra init expr %s", n)
71 // TODO(gri) avoid declared but not used error here
73 // init exprs "inherited"
74 check.errorf(s, code, "extra init expr at %s", check.fset.Position(init.Pos()))
75 // TODO(gri) avoid declared but not used error here
77 case l > r && (init != nil || r != 1):
79 check.errorf(n, code, "missing init expr for %s", n)
83 func validatedImportPath(path string) (string, error) {
84 s, err := strconv.Unquote(path)
89 return "", fmt.Errorf("empty string")
91 const illegalChars = `!"#$%&'()*,:;<=>?[\]^{|}` + "`\uFFFD"
93 if !unicode.IsGraphic(r) || unicode.IsSpace(r) || strings.ContainsRune(illegalChars, r) {
94 return s, fmt.Errorf("invalid character %#U", r)
100 // declarePkgObj declares obj in the package scope, records its ident -> obj mapping,
101 // and updates check.objMap. The object must not be a function or method.
102 func (check *Checker) declarePkgObj(ident *ast.Ident, obj Object, d *declInfo) {
103 assert(ident.Name == obj.Name())
105 // spec: "A package-scope or file-scope identifier with name init
106 // may only be declared to be a function with this (func()) signature."
107 if ident.Name == "init" {
108 check.errorf(ident, _InvalidInitDecl, "cannot declare init - must be func")
112 // spec: "The main package must have package name main and declare
113 // a function main that takes no arguments and returns no value."
114 if ident.Name == "main" && check.pkg.name == "main" {
115 check.errorf(ident, _InvalidMainDecl, "cannot declare main - must be func")
119 check.declare(check.pkg.scope, ident, obj, token.NoPos)
120 check.objMap[obj] = d
121 obj.setOrder(uint32(len(check.objMap)))
124 // filename returns a filename suitable for debugging output.
125 func (check *Checker) filename(fileNo int) string {
126 file := check.files[fileNo]
127 if pos := file.Pos(); pos.IsValid() {
128 return check.fset.File(pos).Name()
130 return fmt.Sprintf("file[%d]", fileNo)
133 func (check *Checker) importPackage(pos token.Pos, path, dir string) *Package {
134 // If we already have a package for the given (path, dir)
135 // pair, use it instead of doing a full import.
136 // Checker.impMap only caches packages that are marked Complete
137 // or fake (dummy packages for failed imports). Incomplete but
138 // non-fake packages do require an import to complete them.
139 key := importKey{path, dir}
140 imp := check.impMap[key]
145 // no package yet => import it
146 if path == "C" && (check.conf.FakeImportC || check.conf.go115UsesCgo) {
147 imp = NewPackage("C", "C")
148 imp.fake = true // package scope is not populated
149 imp.cgo = check.conf.go115UsesCgo
153 if importer := check.conf.Importer; importer == nil {
154 err = fmt.Errorf("Config.Importer not installed")
155 } else if importerFrom, ok := importer.(ImporterFrom); ok {
156 imp, err = importerFrom.ImportFrom(path, dir, 0)
157 if imp == nil && err == nil {
158 err = fmt.Errorf("Config.Importer.ImportFrom(%s, %s, 0) returned nil but no error", path, dir)
161 imp, err = importer.Import(path)
162 if imp == nil && err == nil {
163 err = fmt.Errorf("Config.Importer.Import(%s) returned nil but no error", path)
166 // make sure we have a valid package name
167 // (errors here can only happen through manipulation of packages after creation)
168 if err == nil && imp != nil && (imp.name == "_" || imp.name == "") {
169 err = fmt.Errorf("invalid package name: %q", imp.name)
170 imp = nil // create fake package below
173 check.errorf(atPos(pos), _BrokenImport, "could not import %s (%s)", path, err)
175 // create a new fake package
176 // come up with a sensible package name (heuristic)
178 if i := len(name); i > 0 && name[i-1] == '/' {
181 if i := strings.LastIndex(name, "/"); i >= 0 {
184 imp = NewPackage(path, name)
186 // continue to use the package as best as we can
187 imp.fake = true // avoid follow-up lookup failures
191 // package should be complete or marked fake, but be cautious
192 if imp.complete || imp.fake {
193 check.impMap[key] = imp
194 check.pkgCnt[imp.name]++
198 // something went wrong (importer may have returned incomplete package without error)
202 // collectObjects collects all file and package objects and inserts them
203 // into their respective scopes. It also performs imports and associates
204 // methods with receiver base type names.
205 func (check *Checker) collectObjects() {
208 // pkgImports is the set of packages already imported by any package file seen
209 // so far. Used to avoid duplicate entries in pkg.imports. Allocate and populate
210 // it (pkg.imports may not be empty if we are checking test files incrementally).
211 // Note that pkgImports is keyed by package (and thus package path), not by an
212 // importKey value. Two different importKey values may map to the same package
213 // which is why we cannot use the check.impMap here.
214 var pkgImports = make(map[*Package]bool)
215 for _, imp := range pkg.imports {
216 pkgImports[imp] = true
219 type methodInfo struct {
221 ptr bool // true if pointer receiver
222 recv *ast.Ident // receiver type name
224 var methods []methodInfo // collected methods with valid receivers and non-blank _ names
225 var fileScopes []*Scope
226 for fileNo, file := range check.files {
227 // The package identifier denotes the current package,
228 // but there is no corresponding package object.
229 check.recordDef(file.Name, nil)
231 // Use the actual source file extent rather than *ast.File extent since the
232 // latter doesn't include comments which appear at the start or end of the file.
233 // Be conservative and use the *ast.File extent if we don't have a *token.File.
234 pos, end := file.Pos(), file.End()
235 if f := check.fset.File(file.Pos()); f != nil {
236 pos, end = token.Pos(f.Base()), token.Pos(f.Base()+f.Size())
238 fileScope := NewScope(check.pkg.scope, pos, end, check.filename(fileNo))
239 fileScopes = append(fileScopes, fileScope)
240 check.recordScope(file, fileScope)
242 // determine file directory, necessary to resolve imports
243 // FileName may be "" (typically for tests) in which case
244 // we get "." as the directory which is what we would want.
245 fileDir := dir(check.fset.Position(file.Name.Pos()).Filename)
247 check.walkDecls(file.Decls, func(d decl) {
248 switch d := d.(type) {
251 path, err := validatedImportPath(d.spec.Path.Value)
253 check.errorf(d.spec.Path, _BadImportPath, "invalid import path (%s)", err)
257 imp := check.importPackage(d.spec.Path.Pos(), path, fileDir)
262 // add package to list of explicit imports
263 // (this functionality is provided as a convenience
264 // for clients; it is not needed for type-checking)
265 if !pkgImports[imp] {
266 pkgImports[imp] = true
267 pkg.imports = append(pkg.imports, imp)
270 // local name overrides imported package name
272 if d.spec.Name != nil {
273 name = d.spec.Name.Name
275 // match cmd/compile (not prescribed by spec)
276 check.errorf(d.spec.Name, _ImportCRenamed, `cannot rename import "C"`)
280 check.errorf(d.spec.Name, _InvalidInitDecl, "cannot declare init - must be func")
285 obj := NewPkgName(d.spec.Pos(), pkg, name, imp)
286 if d.spec.Name != nil {
287 // in a dot-import, the dot represents the package
288 check.recordDef(d.spec.Name, obj)
290 check.recordImplicit(d.spec, obj)
294 // match cmd/compile (not prescribed by spec)
298 // add import to file scope
300 // merge imported scope with file scope
301 for _, obj := range imp.scope.elems {
302 // A package scope may contain non-exported objects,
303 // do not import them!
305 // declare dot-imported object
306 // (Do not use check.declare because it modifies the object
307 // via Object.setScopePos, which leads to a race condition;
308 // the object may be imported into more than one file scope
309 // concurrently. See issue #32154.)
310 if alt := fileScope.Insert(obj); alt != nil {
311 check.errorf(d.spec.Name, _DuplicateDecl, "%s redeclared in this block", obj.Name())
312 check.reportAltDecl(alt)
316 // add position to set of dot-import positions for this file
317 // (this is only needed for "imported but not used" errors)
318 check.addUnusedDotImport(fileScope, imp, d.spec)
320 // declare imported package object in file scope
321 // (no need to provide s.Name since we called check.recordDef earlier)
322 check.declare(fileScope, nil, obj, token.NoPos)
325 // declare all constants
326 for i, name := range d.spec.Names {
327 obj := NewConst(name.Pos(), pkg, name.Name, nil, constant.MakeInt64(int64(d.iota)))
334 d := &declInfo{file: fileScope, vtyp: d.typ, init: init, inherited: d.inherited}
335 check.declarePkgObj(name, obj, d)
339 lhs := make([]*Var, len(d.spec.Names))
340 // If there's exactly one rhs initializer, use
341 // the same declInfo d1 for all lhs variables
342 // so that each lhs variable depends on the same
343 // rhs initializer (n:1 var declaration).
345 if len(d.spec.Values) == 1 {
346 // The lhs elements are only set up after the for loop below,
347 // but that's ok because declareVar only collects the declInfo
348 // for a later phase.
349 d1 = &declInfo{file: fileScope, lhs: lhs, vtyp: d.spec.Type, init: d.spec.Values[0]}
352 // declare all variables
353 for i, name := range d.spec.Names {
354 obj := NewVar(name.Pos(), pkg, name.Name, nil)
359 // individual assignments
361 if i < len(d.spec.Values) {
362 init = d.spec.Values[i]
364 di = &declInfo{file: fileScope, vtyp: d.spec.Type, init: init}
367 check.declarePkgObj(name, obj, di)
370 obj := NewTypeName(d.spec.Name.Pos(), pkg, d.spec.Name.Name, nil)
371 check.declarePkgObj(d.spec.Name, obj, &declInfo{file: fileScope, tdecl: d.spec})
373 info := &declInfo{file: fileScope, fdecl: d.decl}
374 name := d.decl.Name.Name
375 obj := NewFunc(d.decl.Name.Pos(), pkg, name, nil)
376 if !d.decl.IsMethod() {
378 if d.decl.Recv != nil {
379 check.error(d.decl.Recv, _BadRecv, "method is missing receiver")
383 if d.decl.Type.TParams != nil {
384 check.softErrorf(d.decl.Type.TParams, _InvalidInitSig, "func init must have no type parameters")
386 if t := d.decl.Type; t.Params.NumFields() != 0 || t.Results != nil {
387 // TODO(rFindley) Should this be a hard error?
388 check.softErrorf(d.decl, _InvalidInitSig, "func init must have no arguments and no return values")
390 // don't declare init functions in the package scope - they are invisible
391 obj.parent = pkg.scope
392 check.recordDef(d.decl.Name, obj)
393 // init functions must have a body
394 if d.decl.Body == nil {
395 // TODO(gri) make this error message consistent with the others above
396 check.softErrorf(obj, _MissingInitBody, "missing function body")
399 check.declare(pkg.scope, d.decl.Name, obj, token.NoPos)
403 if d.decl.Type.TParams != nil {
404 check.invalidAST(d.decl.Type.TParams, "method must have no type parameters")
406 ptr, recv, _ := check.unpackRecv(d.decl.Recv.List[0].Type, false)
407 // (Methods with invalid receiver cannot be associated to a type, and
408 // methods with blank _ names are never found; no need to collect any
409 // of them. They will still be type-checked with all the other functions.)
410 if recv != nil && name != "_" {
411 methods = append(methods, methodInfo{obj, ptr, recv})
413 check.recordDef(d.decl.Name, obj)
415 // Methods are not package-level objects but we still track them in the
416 // object map so that we can handle them like regular functions (if the
417 // receiver is invalid); also we need their fdecl info when associating
418 // them with their receiver base type, below.
419 check.objMap[obj] = info
420 obj.setOrder(uint32(len(check.objMap)))
425 // verify that objects in package and file scopes have different names
426 for _, scope := range fileScopes {
427 for _, obj := range scope.elems {
428 if alt := pkg.scope.Lookup(obj.Name()); alt != nil {
429 if pkg, ok := obj.(*PkgName); ok {
430 check.errorf(alt, _DuplicateDecl, "%s already declared through import of %s", alt.Name(), pkg.Imported())
431 check.reportAltDecl(pkg)
433 check.errorf(alt, _DuplicateDecl, "%s already declared through dot-import of %s", alt.Name(), obj.Pkg())
434 // TODO(gri) dot-imported objects don't have a position; reportAltDecl won't print anything
435 check.reportAltDecl(obj)
441 // Now that we have all package scope objects and all methods,
442 // associate methods with receiver base type name where possible.
443 // Ignore methods that have an invalid receiver. They will be
444 // type-checked later, with regular functions.
446 return // nothing to do
448 check.methods = make(map[*TypeName][]*Func)
449 for i := range methods {
451 // Determine the receiver base type and associate m with it.
452 ptr, base := check.resolveBaseTypeName(m.ptr, m.recv)
454 m.obj.hasPtrRecv = ptr
455 check.methods[base] = append(check.methods[base], m.obj)
460 // unpackRecv unpacks a receiver type and returns its components: ptr indicates whether
461 // rtyp is a pointer receiver, rname is the receiver type name, and tparams are its
462 // type parameters, if any. The type parameters are only unpacked if unpackParams is
463 // set. If rname is nil, the receiver is unusable (i.e., the source has a bug which we
464 // cannot easily work around).
465 func (check *Checker) unpackRecv(rtyp ast.Expr, unpackParams bool) (ptr bool, rname *ast.Ident, tparams []*ast.Ident) {
466 L: // unpack receiver type
467 // This accepts invalid receivers such as ***T and does not
468 // work for other invalid receivers, but we don't care. The
469 // validity of receiver expressions is checked elsewhere.
471 switch t := rtyp.(type) {
482 // unpack type parameters, if any
483 switch ptyp := rtyp.(type) {
485 panic("unimplemented")
489 for _, arg := range ptyp.Args {
491 switch arg := arg.(type) {
495 // ignore - error already reported by parser
497 check.invalidAST(ptyp, "parameterized receiver contains nil parameters")
499 check.errorf(arg, 0, "receiver type parameter %s must be an identifier", arg)
502 par = &ast.Ident{NamePos: arg.Pos(), Name: "_"}
504 tparams = append(tparams, par)
509 // unpack receiver name
510 if name, _ := rtyp.(*ast.Ident); name != nil {
517 // resolveBaseTypeName returns the non-alias base type name for typ, and whether
518 // there was a pointer indirection to get to it. The base type name must be declared
519 // in package scope, and there can be at most one pointer indirection. If no such type
520 // name exists, the returned base is nil.
521 func (check *Checker) resolveBaseTypeName(seenPtr bool, name *ast.Ident) (ptr bool, base *TypeName) {
522 // Algorithm: Starting from a type expression, which may be a name,
523 // we follow that type through alias declarations until we reach a
524 // non-alias type name. If we encounter anything but pointer types or
525 // parentheses we're done. If we encounter more than one pointer type
528 var seen map[*TypeName]bool
529 var typ ast.Expr = name
533 // check if we have a pointer type
534 if pexpr, _ := typ.(*ast.StarExpr); pexpr != nil {
535 // if we've already seen a pointer, we're done
540 typ = unparen(pexpr.X) // continue with pointer base type
543 // typ must be a name
544 name, _ := typ.(*ast.Ident)
549 // name must denote an object found in the current package scope
550 // (note that dot-imported objects are not in the package scope!)
551 obj := check.pkg.scope.Lookup(name.Name)
556 // the object must be a type name...
557 tname, _ := obj.(*TypeName)
562 // ... which we have not seen before
567 // we're done if tdecl defined tname as a new type
568 // (rather than an alias)
569 tdecl := check.objMap[tname].tdecl // must exist for objects in package scope
570 if !tdecl.Assign.IsValid() {
574 // otherwise, continue resolving
577 seen = make(map[*TypeName]bool)
583 // packageObjects typechecks all package objects, but not function bodies.
584 func (check *Checker) packageObjects() {
585 // process package objects in source order for reproducible results
586 objList := make([]Object, len(check.objMap))
588 for obj := range check.objMap {
592 sort.Sort(inSourceOrder(objList))
594 // add new methods to already type-checked types (from a prior Checker.Files call)
595 for _, obj := range objList {
596 if obj, _ := obj.(*TypeName); obj != nil && obj.typ != nil {
597 check.collectMethods(obj)
601 // We process non-alias declarations first, in order to avoid situations where
602 // the type of an alias declaration is needed before it is available. In general
603 // this is still not enough, as it is possible to create sufficiently convoluted
604 // recursive type definitions that will cause a type alias to be needed before it
605 // is available (see issue #25838 for examples).
606 // As an aside, the cmd/compiler suffers from the same problem (#25838).
607 var aliasList []*TypeName
609 for _, obj := range objList {
610 // If we have a type alias, collect it for the 2nd phase.
611 if tname, _ := obj.(*TypeName); tname != nil && check.objMap[tname].tdecl.Assign.IsValid() {
612 aliasList = append(aliasList, tname)
616 check.objDecl(obj, nil)
619 for _, obj := range aliasList {
620 check.objDecl(obj, nil)
623 // At this point we may have a non-empty check.methods map; this means that not all
624 // entries were deleted at the end of typeDecl because the respective receiver base
625 // types were not found. In that case, an error was reported when declaring those
626 // methods. We can now safely discard this map.
630 // inSourceOrder implements the sort.Sort interface.
631 type inSourceOrder []Object
633 func (a inSourceOrder) Len() int { return len(a) }
634 func (a inSourceOrder) Less(i, j int) bool { return a[i].order() < a[j].order() }
635 func (a inSourceOrder) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
637 // unusedImports checks for unused imports.
638 func (check *Checker) unusedImports() {
639 // if function bodies are not checked, packages' uses are likely missing - don't check
640 if check.conf.IgnoreFuncBodies {
644 // spec: "It is illegal (...) to directly import a package without referring to
645 // any of its exported identifiers. To import a package solely for its side-effects
646 // (initialization), use the blank identifier as explicit package name."
648 // check use of regular imported packages
649 for _, scope := range check.pkg.scope.children /* file scopes */ {
650 for _, obj := range scope.elems {
651 if obj, ok := obj.(*PkgName); ok {
652 // Unused "blank imports" are automatically ignored
653 // since _ identifiers are not entered into scopes.
655 path := obj.imported.path
656 base := pkgName(path)
657 if obj.name == base {
658 check.softErrorf(obj, _UnusedImport, "%q imported but not used", path)
660 check.softErrorf(obj, _UnusedImport, "%q imported but not used as %s", path, obj.name)
667 // check use of dot-imported packages
668 for _, unusedDotImports := range check.unusedDotImports {
669 for pkg, pos := range unusedDotImports {
670 check.softErrorf(pos, _UnusedImport, "%q imported but not used", pkg.path)
675 // pkgName returns the package name (last element) of an import path.
676 func pkgName(path string) string {
677 if i := strings.LastIndex(path, "/"); i >= 0 {
683 // dir makes a good-faith attempt to return the directory
684 // portion of path. If path is empty, the result is ".".
685 // (Per the go/build package dependency tests, we cannot import
686 // path/filepath and simply use filepath.Dir.)
687 func dir(path string) string {
688 if i := strings.LastIndexAny(path, `/\`); i > 0 {