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.
11 "go/internal/typeparams"
19 // A declInfo describes a package-level const, type, var, or func declaration.
20 type declInfo struct {
21 file *Scope // scope of file containing this declaration
22 lhs []*Var // lhs of n:1 variable declarations, or nil
23 vtyp ast.Expr // type, or nil (for const and var declarations only)
24 init ast.Expr // init/orig expression, or nil (for const and var declarations only)
25 inherited bool // if set, the init expression is inherited from a previous constant declaration
26 tdecl *ast.TypeSpec // type declaration, or nil
27 fdecl *ast.FuncDecl // func declaration, or nil
29 // The deps field tracks initialization expression dependencies.
30 deps map[Object]bool // lazily initialized
33 // hasInitializer reports whether the declared object has an initialization
34 // expression or function body.
35 func (d *declInfo) hasInitializer() bool {
36 return d.init != nil || d.fdecl != nil && d.fdecl.Body != nil
39 // addDep adds obj to the set of objects d's init expression depends on.
40 func (d *declInfo) addDep(obj Object) {
43 m = make(map[Object]bool)
49 // arityMatch checks that the lhs and rhs of a const or var decl
50 // have the appropriate number of names and init exprs. For const
51 // decls, init is the value spec providing the init exprs; for
52 // var decls, init is nil (the init exprs are in s in this case).
53 func (check *Checker) arityMatch(s, init *ast.ValueSpec) {
60 const code = _WrongAssignCount
62 case init == nil && r == 0:
63 // var decl w/o init expr
65 check.errorf(s, code, "missing type or init expr")
68 if l < len(s.Values) {
71 check.errorf(n, code, "extra init expr %s", n)
72 // TODO(gri) avoid declared but not used error here
74 // init exprs "inherited"
75 check.errorf(s, code, "extra init expr at %s", check.fset.Position(init.Pos()))
76 // TODO(gri) avoid declared but not used error here
78 case l > r && (init != nil || r != 1):
80 check.errorf(n, code, "missing init expr for %s", n)
84 func validatedImportPath(path string) (string, error) {
85 s, err := strconv.Unquote(path)
90 return "", fmt.Errorf("empty string")
92 const illegalChars = `!"#$%&'()*,:;<=>?[\]^{|}` + "`\uFFFD"
94 if !unicode.IsGraphic(r) || unicode.IsSpace(r) || strings.ContainsRune(illegalChars, r) {
95 return s, fmt.Errorf("invalid character %#U", r)
101 // declarePkgObj declares obj in the package scope, records its ident -> obj mapping,
102 // and updates check.objMap. The object must not be a function or method.
103 func (check *Checker) declarePkgObj(ident *ast.Ident, obj Object, d *declInfo) {
104 assert(ident.Name == obj.Name())
106 // spec: "A package-scope or file-scope identifier with name init
107 // may only be declared to be a function with this (func()) signature."
108 if ident.Name == "init" {
109 check.errorf(ident, _InvalidInitDecl, "cannot declare init - must be func")
113 // spec: "The main package must have package name main and declare
114 // a function main that takes no arguments and returns no value."
115 if ident.Name == "main" && check.pkg.name == "main" {
116 check.errorf(ident, _InvalidMainDecl, "cannot declare main - must be func")
120 check.declare(check.pkg.scope, ident, obj, token.NoPos)
121 check.objMap[obj] = d
122 obj.setOrder(uint32(len(check.objMap)))
125 // filename returns a filename suitable for debugging output.
126 func (check *Checker) filename(fileNo int) string {
127 file := check.files[fileNo]
128 if pos := file.Pos(); pos.IsValid() {
129 return check.fset.File(pos).Name()
131 return fmt.Sprintf("file[%d]", fileNo)
134 func (check *Checker) importPackage(at positioner, path, dir string) *Package {
135 // If we already have a package for the given (path, dir)
136 // pair, use it instead of doing a full import.
137 // Checker.impMap only caches packages that are marked Complete
138 // or fake (dummy packages for failed imports). Incomplete but
139 // non-fake packages do require an import to complete them.
140 key := importKey{path, dir}
141 imp := check.impMap[key]
146 // no package yet => import it
147 if path == "C" && (check.conf.FakeImportC || check.conf.go115UsesCgo) {
148 imp = NewPackage("C", "C")
149 imp.fake = true // package scope is not populated
150 imp.cgo = check.conf.go115UsesCgo
154 if importer := check.conf.Importer; importer == nil {
155 err = fmt.Errorf("Config.Importer not installed")
156 } else if importerFrom, ok := importer.(ImporterFrom); ok {
157 imp, err = importerFrom.ImportFrom(path, dir, 0)
158 if imp == nil && err == nil {
159 err = fmt.Errorf("Config.Importer.ImportFrom(%s, %s, 0) returned nil but no error", path, dir)
162 imp, err = importer.Import(path)
163 if imp == nil && err == nil {
164 err = fmt.Errorf("Config.Importer.Import(%s) returned nil but no error", path)
167 // make sure we have a valid package name
168 // (errors here can only happen through manipulation of packages after creation)
169 if err == nil && imp != nil && (imp.name == "_" || imp.name == "") {
170 err = fmt.Errorf("invalid package name: %q", imp.name)
171 imp = nil // create fake package below
174 check.errorf(at, _BrokenImport, "could not import %s (%s)", path, err)
176 // create a new fake package
177 // come up with a sensible package name (heuristic)
179 if i := len(name); i > 0 && name[i-1] == '/' {
182 if i := strings.LastIndex(name, "/"); i >= 0 {
185 imp = NewPackage(path, name)
187 // continue to use the package as best as we can
188 imp.fake = true // avoid follow-up lookup failures
192 // package should be complete or marked fake, but be cautious
193 if imp.complete || imp.fake {
194 check.impMap[key] = imp
195 // Once we've formatted an error message, keep the pkgPathMap
196 // up-to-date on subsequent imports. It is used for package
197 // qualification in error messages.
198 if check.pkgPathMap != nil {
199 check.markImports(imp)
204 // something went wrong (importer may have returned incomplete package without error)
208 // collectObjects collects all file and package objects and inserts them
209 // into their respective scopes. It also performs imports and associates
210 // methods with receiver base type names.
211 func (check *Checker) collectObjects() {
214 // pkgImports is the set of packages already imported by any package file seen
215 // so far. Used to avoid duplicate entries in pkg.imports. Allocate and populate
216 // it (pkg.imports may not be empty if we are checking test files incrementally).
217 // Note that pkgImports is keyed by package (and thus package path), not by an
218 // importKey value. Two different importKey values may map to the same package
219 // which is why we cannot use the check.impMap here.
220 var pkgImports = make(map[*Package]bool)
221 for _, imp := range pkg.imports {
222 pkgImports[imp] = true
225 type methodInfo struct {
227 ptr bool // true if pointer receiver
228 recv *ast.Ident // receiver type name
230 var methods []methodInfo // collected methods with valid receivers and non-blank _ names
231 var fileScopes []*Scope
232 for fileNo, file := range check.files {
233 // The package identifier denotes the current package,
234 // but there is no corresponding package object.
235 check.recordDef(file.Name, nil)
237 // Use the actual source file extent rather than *ast.File extent since the
238 // latter doesn't include comments which appear at the start or end of the file.
239 // Be conservative and use the *ast.File extent if we don't have a *token.File.
240 pos, end := file.Pos(), file.End()
241 if f := check.fset.File(file.Pos()); f != nil {
242 pos, end = token.Pos(f.Base()), token.Pos(f.Base()+f.Size())
244 fileScope := NewScope(check.pkg.scope, pos, end, check.filename(fileNo))
245 fileScopes = append(fileScopes, fileScope)
246 check.recordScope(file, fileScope)
248 // determine file directory, necessary to resolve imports
249 // FileName may be "" (typically for tests) in which case
250 // we get "." as the directory which is what we would want.
251 fileDir := dir(check.fset.Position(file.Name.Pos()).Filename)
253 check.walkDecls(file.Decls, func(d decl) {
254 switch d := d.(type) {
257 path, err := validatedImportPath(d.spec.Path.Value)
259 check.errorf(d.spec.Path, _BadImportPath, "invalid import path (%s)", err)
263 imp := check.importPackage(d.spec.Path, path, fileDir)
268 // local name overrides imported package name
270 if d.spec.Name != nil {
271 name = d.spec.Name.Name
273 // match 1.17 cmd/compile (not prescribed by spec)
274 check.errorf(d.spec.Name, _ImportCRenamed, `cannot rename import "C"`)
280 check.errorf(d.spec, _InvalidInitDecl, "cannot import package as init - init must be a func")
284 // add package to list of explicit imports
285 // (this functionality is provided as a convenience
286 // for clients; it is not needed for type-checking)
287 if !pkgImports[imp] {
288 pkgImports[imp] = true
289 pkg.imports = append(pkg.imports, imp)
292 pkgName := NewPkgName(d.spec.Pos(), pkg, name, imp)
293 if d.spec.Name != nil {
294 // in a dot-import, the dot represents the package
295 check.recordDef(d.spec.Name, pkgName)
297 check.recordImplicit(d.spec, pkgName)
301 // match 1.17 cmd/compile (not prescribed by spec)
305 // add import to file scope
306 check.imports = append(check.imports, pkgName)
309 if check.dotImportMap == nil {
310 check.dotImportMap = make(map[dotImportKey]*PkgName)
312 // merge imported scope with file scope
313 for name, obj := range imp.scope.elems {
314 // Note: Avoid eager resolve(name, obj) here, so we only
315 // resolve dot-imported objects as needed.
317 // A package scope may contain non-exported objects,
318 // do not import them!
319 if token.IsExported(name) {
320 // declare dot-imported object
321 // (Do not use check.declare because it modifies the object
322 // via Object.setScopePos, which leads to a race condition;
323 // the object may be imported into more than one file scope
324 // concurrently. See issue #32154.)
325 if alt := fileScope.Lookup(name); alt != nil {
326 check.errorf(d.spec.Name, _DuplicateDecl, "%s redeclared in this block", alt.Name())
327 check.reportAltDecl(alt)
329 fileScope.insert(name, obj)
330 check.dotImportMap[dotImportKey{fileScope, name}] = pkgName
335 // declare imported package object in file scope
336 // (no need to provide s.Name since we called check.recordDef earlier)
337 check.declare(fileScope, nil, pkgName, token.NoPos)
340 // declare all constants
341 for i, name := range d.spec.Names {
342 obj := NewConst(name.Pos(), pkg, name.Name, nil, constant.MakeInt64(int64(d.iota)))
349 d := &declInfo{file: fileScope, vtyp: d.typ, init: init, inherited: d.inherited}
350 check.declarePkgObj(name, obj, d)
354 lhs := make([]*Var, len(d.spec.Names))
355 // If there's exactly one rhs initializer, use
356 // the same declInfo d1 for all lhs variables
357 // so that each lhs variable depends on the same
358 // rhs initializer (n:1 var declaration).
360 if len(d.spec.Values) == 1 {
361 // The lhs elements are only set up after the for loop below,
362 // but that's ok because declareVar only collects the declInfo
363 // for a later phase.
364 d1 = &declInfo{file: fileScope, lhs: lhs, vtyp: d.spec.Type, init: d.spec.Values[0]}
367 // declare all variables
368 for i, name := range d.spec.Names {
369 obj := NewVar(name.Pos(), pkg, name.Name, nil)
374 // individual assignments
376 if i < len(d.spec.Values) {
377 init = d.spec.Values[i]
379 di = &declInfo{file: fileScope, vtyp: d.spec.Type, init: init}
382 check.declarePkgObj(name, obj, di)
385 if d.spec.TypeParams.NumFields() != 0 && !check.allowVersion(pkg, 1, 18) {
386 check.softErrorf(d.spec.TypeParams.List[0], _UnsupportedFeature, "type parameters require go1.18 or later")
388 obj := NewTypeName(d.spec.Name.Pos(), pkg, d.spec.Name.Name, nil)
389 check.declarePkgObj(d.spec.Name, obj, &declInfo{file: fileScope, tdecl: d.spec})
391 name := d.decl.Name.Name
392 obj := NewFunc(d.decl.Name.Pos(), pkg, name, nil)
393 hasTParamError := false // avoid duplicate type parameter errors
394 if d.decl.Recv.NumFields() == 0 {
396 if d.decl.Recv != nil {
397 check.error(d.decl.Recv, _BadRecv, "method is missing receiver")
400 if name == "init" || (name == "main" && check.pkg.name == "main") {
401 code := _InvalidInitDecl
403 code = _InvalidMainDecl
405 if d.decl.Type.TypeParams.NumFields() != 0 {
406 check.softErrorf(d.decl.Type.TypeParams.List[0], code, "func %s must have no type parameters", name)
407 hasTParamError = true
409 if t := d.decl.Type; t.Params.NumFields() != 0 || t.Results != nil {
410 // TODO(rFindley) Should this be a hard error?
411 check.softErrorf(d.decl, code, "func %s must have no arguments and no return values", name)
415 // don't declare init functions in the package scope - they are invisible
416 obj.parent = pkg.scope
417 check.recordDef(d.decl.Name, obj)
418 // init functions must have a body
419 if d.decl.Body == nil {
420 // TODO(gri) make this error message consistent with the others above
421 check.softErrorf(obj, _MissingInitBody, "missing function body")
424 check.declare(pkg.scope, d.decl.Name, obj, token.NoPos)
429 // TODO(rFindley) earlier versions of this code checked that methods
430 // have no type parameters, but this is checked later
431 // when type checking the function type. Confirm that
432 // we don't need to check tparams here.
434 ptr, recv, _ := check.unpackRecv(d.decl.Recv.List[0].Type, false)
435 // (Methods with invalid receiver cannot be associated to a type, and
436 // methods with blank _ names are never found; no need to collect any
437 // of them. They will still be type-checked with all the other functions.)
438 if recv != nil && name != "_" {
439 methods = append(methods, methodInfo{obj, ptr, recv})
441 check.recordDef(d.decl.Name, obj)
443 if d.decl.Type.TypeParams.NumFields() != 0 && !check.allowVersion(pkg, 1, 18) && !hasTParamError {
444 check.softErrorf(d.decl.Type.TypeParams.List[0], _UnsupportedFeature, "type parameters require go1.18 or later")
446 info := &declInfo{file: fileScope, fdecl: d.decl}
447 // Methods are not package-level objects but we still track them in the
448 // object map so that we can handle them like regular functions (if the
449 // receiver is invalid); also we need their fdecl info when associating
450 // them with their receiver base type, below.
451 check.objMap[obj] = info
452 obj.setOrder(uint32(len(check.objMap)))
457 // verify that objects in package and file scopes have different names
458 for _, scope := range fileScopes {
459 for name, obj := range scope.elems {
460 if alt := pkg.scope.Lookup(name); alt != nil {
461 obj = resolve(name, obj)
462 if pkg, ok := obj.(*PkgName); ok {
463 check.errorf(alt, _DuplicateDecl, "%s already declared through import of %s", alt.Name(), pkg.Imported())
464 check.reportAltDecl(pkg)
466 check.errorf(alt, _DuplicateDecl, "%s already declared through dot-import of %s", alt.Name(), obj.Pkg())
467 // TODO(gri) dot-imported objects don't have a position; reportAltDecl won't print anything
468 check.reportAltDecl(obj)
474 // Now that we have all package scope objects and all methods,
475 // associate methods with receiver base type name where possible.
476 // Ignore methods that have an invalid receiver. They will be
477 // type-checked later, with regular functions.
479 return // nothing to do
481 check.methods = make(map[*TypeName][]*Func)
482 for i := range methods {
484 // Determine the receiver base type and associate m with it.
485 ptr, base := check.resolveBaseTypeName(m.ptr, m.recv)
487 m.obj.hasPtrRecv_ = ptr
488 check.methods[base] = append(check.methods[base], m.obj)
493 // unpackRecv unpacks a receiver type and returns its components: ptr indicates whether
494 // rtyp is a pointer receiver, rname is the receiver type name, and tparams are its
495 // type parameters, if any. The type parameters are only unpacked if unpackParams is
496 // set. If rname is nil, the receiver is unusable (i.e., the source has a bug which we
497 // cannot easily work around).
498 func (check *Checker) unpackRecv(rtyp ast.Expr, unpackParams bool) (ptr bool, rname *ast.Ident, tparams []*ast.Ident) {
499 L: // unpack receiver type
500 // This accepts invalid receivers such as ***T and does not
501 // work for other invalid receivers, but we don't care. The
502 // validity of receiver expressions is checked elsewhere.
504 switch t := rtyp.(type) {
515 // unpack type parameters, if any
517 case *ast.IndexExpr, *ast.IndexListExpr:
518 ix := typeparams.UnpackIndexExpr(rtyp)
521 for _, arg := range ix.Indices {
523 switch arg := arg.(type) {
527 // ignore - error already reported by parser
529 check.invalidAST(ix.Orig, "parameterized receiver contains nil parameters")
531 check.errorf(arg, _BadDecl, "receiver type parameter %s must be an identifier", arg)
534 par = &ast.Ident{NamePos: arg.Pos(), Name: "_"}
536 tparams = append(tparams, par)
541 // unpack receiver name
542 if name, _ := rtyp.(*ast.Ident); name != nil {
549 // resolveBaseTypeName returns the non-alias base type name for typ, and whether
550 // there was a pointer indirection to get to it. The base type name must be declared
551 // in package scope, and there can be at most one pointer indirection. If no such type
552 // name exists, the returned base is nil.
553 func (check *Checker) resolveBaseTypeName(seenPtr bool, name *ast.Ident) (ptr bool, base *TypeName) {
554 // Algorithm: Starting from a type expression, which may be a name,
555 // we follow that type through alias declarations until we reach a
556 // non-alias type name. If we encounter anything but pointer types or
557 // parentheses we're done. If we encounter more than one pointer type
560 var seen map[*TypeName]bool
561 var typ ast.Expr = name
565 // check if we have a pointer type
566 if pexpr, _ := typ.(*ast.StarExpr); pexpr != nil {
567 // if we've already seen a pointer, we're done
572 typ = unparen(pexpr.X) // continue with pointer base type
575 // typ must be a name
576 name, _ := typ.(*ast.Ident)
581 // name must denote an object found in the current package scope
582 // (note that dot-imported objects are not in the package scope!)
583 obj := check.pkg.scope.Lookup(name.Name)
588 // the object must be a type name...
589 tname, _ := obj.(*TypeName)
594 // ... which we have not seen before
599 // we're done if tdecl defined tname as a new type
600 // (rather than an alias)
601 tdecl := check.objMap[tname].tdecl // must exist for objects in package scope
602 if !tdecl.Assign.IsValid() {
606 // otherwise, continue resolving
609 seen = make(map[*TypeName]bool)
615 // packageObjects typechecks all package objects, but not function bodies.
616 func (check *Checker) packageObjects() {
617 // process package objects in source order for reproducible results
618 objList := make([]Object, len(check.objMap))
620 for obj := range check.objMap {
624 sort.Sort(inSourceOrder(objList))
626 // add new methods to already type-checked types (from a prior Checker.Files call)
627 for _, obj := range objList {
628 if obj, _ := obj.(*TypeName); obj != nil && obj.typ != nil {
629 check.collectMethods(obj)
633 // We process non-alias type declarations first, followed by alias declarations,
634 // and then everything else. This appears to avoid most situations where the type
635 // of an alias is needed before it is available.
636 // There may still be cases where this is not good enough (see also issue #25838).
637 // In those cases Checker.ident will report an error ("invalid use of type alias").
638 var aliasList []*TypeName
639 var othersList []Object // everything that's not a type
640 // phase 1: non-alias type declarations
641 for _, obj := range objList {
642 if tname, _ := obj.(*TypeName); tname != nil {
643 if check.objMap[tname].tdecl.Assign.IsValid() {
644 aliasList = append(aliasList, tname)
646 check.objDecl(obj, nil)
649 othersList = append(othersList, obj)
652 // phase 2: alias type declarations
653 for _, obj := range aliasList {
654 check.objDecl(obj, nil)
656 // phase 3: all other declarations
657 for _, obj := range othersList {
658 check.objDecl(obj, nil)
661 // At this point we may have a non-empty check.methods map; this means that not all
662 // entries were deleted at the end of typeDecl because the respective receiver base
663 // types were not found. In that case, an error was reported when declaring those
664 // methods. We can now safely discard this map.
668 // inSourceOrder implements the sort.Sort interface.
669 type inSourceOrder []Object
671 func (a inSourceOrder) Len() int { return len(a) }
672 func (a inSourceOrder) Less(i, j int) bool { return a[i].order() < a[j].order() }
673 func (a inSourceOrder) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
675 // unusedImports checks for unused imports.
676 func (check *Checker) unusedImports() {
677 // If function bodies are not checked, packages' uses are likely missing - don't check.
678 if check.conf.IgnoreFuncBodies {
682 // spec: "It is illegal (...) to directly import a package without referring to
683 // any of its exported identifiers. To import a package solely for its side-effects
684 // (initialization), use the blank identifier as explicit package name."
686 for _, obj := range check.imports {
687 if !obj.used && obj.name != "_" {
688 check.errorUnusedPkg(obj)
693 func (check *Checker) errorUnusedPkg(obj *PkgName) {
694 // If the package was imported with a name other than the final
695 // import path element, show it explicitly in the error message.
696 // Note that this handles both renamed imports and imports of
697 // packages containing unconventional package declarations.
698 // Note that this uses / always, even on Windows, because Go import
699 // paths always use forward slashes.
700 path := obj.imported.path
702 if i := strings.LastIndex(elem, "/"); i >= 0 {
705 if obj.name == "" || obj.name == "." || obj.name == elem {
706 check.softErrorf(obj, _UnusedImport, "%q imported but not used", path)
708 check.softErrorf(obj, _UnusedImport, "%q imported but not used as %s", path, obj.name)
712 // dir makes a good-faith attempt to return the directory
713 // portion of path. If path is empty, the result is ".".
714 // (Per the go/build package dependency tests, we cannot import
715 // path/filepath and simply use filepath.Dir.)
716 func dir(path string) string {
717 if i := strings.LastIndexAny(path, `/\`); i > 0 {