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.
8 "cmd/compile/internal/syntax"
17 // A declInfo describes a package-level const, type, var, or func declaration.
18 type declInfo struct {
19 file *Scope // scope of file containing this declaration
20 lhs []*Var // lhs of n:1 variable declarations, or nil
21 vtyp syntax.Expr // type, or nil (for const and var declarations only)
22 init syntax.Expr // init/orig expression, or nil (for const and var declarations only)
23 inherited bool // if set, the init expression is inherited from a previous constant declaration
24 tdecl *syntax.TypeDecl // type declaration, or nil
25 fdecl *syntax.FuncDecl // func declaration, or nil
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 // arity checks that the lhs and rhs of a const or var decl
48 // have a matching number of names and initialization values.
49 // If inherited is set, the initialization values are from
50 // another (constant) declaration.
51 func (check *Checker) arity(pos syntax.Pos, names []*syntax.Name, inits []syntax.Expr, constDecl, inherited bool) {
55 const code = _WrongAssignCount
60 check.errorf(pos, code, "extra init expr at %s", n.Pos())
62 check.errorf(n, code, "extra init expr %s", n)
64 case l > r && (constDecl || r != 1): // if r == 1 it may be a multi-valued function and we can't say anything yet
66 check.errorf(n, code, "missing init expr for %s", n.Value)
70 func validatedImportPath(path string) (string, error) {
71 s, err := strconv.Unquote(path)
76 return "", fmt.Errorf("empty string")
78 const illegalChars = `!"#$%&'()*,:;<=>?[\]^{|}` + "`\uFFFD"
80 if !unicode.IsGraphic(r) || unicode.IsSpace(r) || strings.ContainsRune(illegalChars, r) {
81 return s, fmt.Errorf("invalid character %#U", r)
87 // declarePkgObj declares obj in the package scope, records its ident -> obj mapping,
88 // and updates check.objMap. The object must not be a function or method.
89 func (check *Checker) declarePkgObj(ident *syntax.Name, obj Object, d *declInfo) {
90 assert(ident.Value == obj.Name())
92 // spec: "A package-scope or file-scope identifier with name init
93 // may only be declared to be a function with this (func()) signature."
94 if ident.Value == "init" {
95 check.error(ident, _InvalidInitDecl, "cannot declare init - must be func")
99 // spec: "The main package must have package name main and declare
100 // a function main that takes no arguments and returns no value."
101 if ident.Value == "main" && check.pkg.name == "main" {
102 check.error(ident, _InvalidMainDecl, "cannot declare main - must be func")
106 check.declare(check.pkg.scope, ident, obj, nopos)
107 check.objMap[obj] = d
108 obj.setOrder(uint32(len(check.objMap)))
111 // filename returns a filename suitable for debugging output.
112 func (check *Checker) filename(fileNo int) string {
113 file := check.files[fileNo]
114 if pos := file.Pos(); pos.IsKnown() {
115 // return check.fset.File(pos).Name()
116 // TODO(gri) do we need the actual file name here?
117 return pos.RelFilename()
119 return fmt.Sprintf("file[%d]", fileNo)
122 func (check *Checker) importPackage(pos syntax.Pos, path, dir string) *Package {
123 // If we already have a package for the given (path, dir)
124 // pair, use it instead of doing a full import.
125 // Checker.impMap only caches packages that are marked Complete
126 // or fake (dummy packages for failed imports). Incomplete but
127 // non-fake packages do require an import to complete them.
128 key := importKey{path, dir}
129 imp := check.impMap[key]
134 // no package yet => import it
135 if path == "C" && (check.conf.FakeImportC || check.conf.go115UsesCgo) {
136 imp = NewPackage("C", "C")
137 imp.fake = true // package scope is not populated
138 imp.cgo = check.conf.go115UsesCgo
142 if importer := check.conf.Importer; importer == nil {
143 err = fmt.Errorf("Config.Importer not installed")
144 } else if importerFrom, ok := importer.(ImporterFrom); ok {
145 imp, err = importerFrom.ImportFrom(path, dir, 0)
146 if imp == nil && err == nil {
147 err = fmt.Errorf("Config.Importer.ImportFrom(%s, %s, 0) returned nil but no error", path, dir)
150 imp, err = importer.Import(path)
151 if imp == nil && err == nil {
152 err = fmt.Errorf("Config.Importer.Import(%s) returned nil but no error", path)
155 // make sure we have a valid package name
156 // (errors here can only happen through manipulation of packages after creation)
157 if err == nil && imp != nil && (imp.name == "_" || imp.name == "") {
158 err = fmt.Errorf("invalid package name: %q", imp.name)
159 imp = nil // create fake package below
162 check.errorf(pos, _BrokenImport, "could not import %s (%s)", path, err)
164 // create a new fake package
165 // come up with a sensible package name (heuristic)
167 if i := len(name); i > 0 && name[i-1] == '/' {
170 if i := strings.LastIndex(name, "/"); i >= 0 {
173 imp = NewPackage(path, name)
175 // continue to use the package as best as we can
176 imp.fake = true // avoid follow-up lookup failures
180 // package should be complete or marked fake, but be cautious
181 if imp.complete || imp.fake {
182 check.impMap[key] = imp
183 // Once we've formatted an error message, keep the pkgPathMap
184 // up-to-date on subsequent imports. It is used for package
185 // qualification in error messages.
186 if check.pkgPathMap != nil {
187 check.markImports(imp)
192 // something went wrong (importer may have returned incomplete package without error)
196 // collectObjects collects all file and package objects and inserts them
197 // into their respective scopes. It also performs imports and associates
198 // methods with receiver base type names.
199 func (check *Checker) collectObjects() {
202 // pkgImports is the set of packages already imported by any package file seen
203 // so far. Used to avoid duplicate entries in pkg.imports. Allocate and populate
204 // it (pkg.imports may not be empty if we are checking test files incrementally).
205 // Note that pkgImports is keyed by package (and thus package path), not by an
206 // importKey value. Two different importKey values may map to the same package
207 // which is why we cannot use the check.impMap here.
208 var pkgImports = make(map[*Package]bool)
209 for _, imp := range pkg.imports {
210 pkgImports[imp] = true
213 type methodInfo struct {
215 ptr bool // true if pointer receiver
216 recv *syntax.Name // receiver type name
218 var methods []methodInfo // collected methods with valid receivers and non-blank _ names
219 var fileScopes []*Scope
220 for fileNo, file := range check.files {
221 // The package identifier denotes the current package,
222 // but there is no corresponding package object.
223 check.recordDef(file.PkgName, nil)
225 fileScope := NewScope(check.pkg.scope, syntax.StartPos(file), syntax.EndPos(file), check.filename(fileNo))
226 fileScopes = append(fileScopes, fileScope)
227 check.recordScope(file, fileScope)
229 // determine file directory, necessary to resolve imports
230 // FileName may be "" (typically for tests) in which case
231 // we get "." as the directory which is what we would want.
232 fileDir := dir(file.PkgName.Pos().RelFilename()) // TODO(gri) should this be filename?
234 first := -1 // index of first ConstDecl in the current group, or -1
235 var last *syntax.ConstDecl // last ConstDecl with init expressions, or nil
236 for index, decl := range file.DeclList {
237 if _, ok := decl.(*syntax.ConstDecl); !ok {
238 first = -1 // we're not in a constant declaration
241 switch s := decl.(type) {
242 case *syntax.ImportDecl:
244 if s.Path == nil || s.Path.Bad {
245 continue // error reported during parsing
247 path, err := validatedImportPath(s.Path.Value)
249 check.errorf(s.Path, _BadImportPath, "invalid import path (%s)", err)
253 imp := check.importPackage(s.Path.Pos(), path, fileDir)
258 // local name overrides imported package name
260 if s.LocalPkgName != nil {
261 name = s.LocalPkgName.Value
263 // match 1.17 cmd/compile (not prescribed by spec)
264 check.error(s.LocalPkgName, _ImportCRenamed, `cannot rename import "C"`)
270 check.error(s, _InvalidInitDecl, "cannot import package as init - init must be a func")
274 // add package to list of explicit imports
275 // (this functionality is provided as a convenience
276 // for clients; it is not needed for type-checking)
277 if !pkgImports[imp] {
278 pkgImports[imp] = true
279 pkg.imports = append(pkg.imports, imp)
282 pkgName := NewPkgName(s.Pos(), pkg, name, imp)
283 if s.LocalPkgName != nil {
284 // in a dot-import, the dot represents the package
285 check.recordDef(s.LocalPkgName, pkgName)
287 check.recordImplicit(s, pkgName)
291 // match 1.17 cmd/compile (not prescribed by spec)
295 // add import to file scope
296 check.imports = append(check.imports, pkgName)
299 if check.dotImportMap == nil {
300 check.dotImportMap = make(map[dotImportKey]*PkgName)
302 // merge imported scope with file scope
303 for name, obj := range imp.scope.elems {
304 // Note: Avoid eager resolve(name, obj) here, so we only
305 // resolve dot-imported objects as needed.
307 // A package scope may contain non-exported objects,
308 // do not import them!
309 if isExported(name) {
310 // declare dot-imported object
311 // (Do not use check.declare because it modifies the object
312 // via Object.setScopePos, which leads to a race condition;
313 // the object may be imported into more than one file scope
314 // concurrently. See issue #32154.)
315 if alt := fileScope.Lookup(name); alt != nil {
317 err.code = _DuplicateDecl
318 err.errorf(s.LocalPkgName, "%s redeclared in this block", alt.Name())
319 err.recordAltDecl(alt)
322 fileScope.insert(name, obj)
323 check.dotImportMap[dotImportKey{fileScope, name}] = pkgName
328 // declare imported package object in file scope
329 // (no need to provide s.LocalPkgName since we called check.recordDef earlier)
330 check.declare(fileScope, nil, pkgName, nopos)
333 case *syntax.ConstDecl:
334 // iota is the index of the current constDecl within the group
335 if first < 0 || s.Group == nil || file.DeclList[index-1].(*syntax.ConstDecl).Group != s.Group {
339 iota := constant.MakeInt64(int64(index - first))
341 // determine which initialization expressions to use
344 case s.Type != nil || s.Values != nil:
348 last = new(syntax.ConstDecl) // make sure last exists
352 // declare all constants
353 values := unpackExpr(last.Values)
354 for i, name := range s.NameList {
355 obj := NewConst(name.Pos(), pkg, name.Value, nil, iota)
362 d := &declInfo{file: fileScope, vtyp: last.Type, init: init, inherited: inherited}
363 check.declarePkgObj(name, obj, d)
366 // Constants must always have init values.
367 check.arity(s.Pos(), s.NameList, values, true, inherited)
369 case *syntax.VarDecl:
370 lhs := make([]*Var, len(s.NameList))
371 // If there's exactly one rhs initializer, use
372 // the same declInfo d1 for all lhs variables
373 // so that each lhs variable depends on the same
374 // rhs initializer (n:1 var declaration).
376 if _, ok := s.Values.(*syntax.ListExpr); !ok {
377 // The lhs elements are only set up after the for loop below,
378 // but that's ok because declarePkgObj only collects the declInfo
379 // for a later phase.
380 d1 = &declInfo{file: fileScope, lhs: lhs, vtyp: s.Type, init: s.Values}
383 // declare all variables
384 values := unpackExpr(s.Values)
385 for i, name := range s.NameList {
386 obj := NewVar(name.Pos(), pkg, name.Value, nil)
391 // individual assignments
396 d = &declInfo{file: fileScope, vtyp: s.Type, init: init}
399 check.declarePkgObj(name, obj, d)
402 // If we have no type, we must have values.
403 if s.Type == nil || values != nil {
404 check.arity(s.Pos(), s.NameList, values, false, false)
407 case *syntax.TypeDecl:
408 if len(s.TParamList) != 0 && !check.allowVersion(pkg, 1, 18) {
409 check.versionErrorf(s.TParamList[0], "go1.18", "type parameter")
411 obj := NewTypeName(s.Name.Pos(), pkg, s.Name.Value, nil)
412 check.declarePkgObj(s.Name, obj, &declInfo{file: fileScope, tdecl: s})
414 case *syntax.FuncDecl:
416 obj := NewFunc(s.Name.Pos(), pkg, name, nil)
417 hasTParamError := false // avoid duplicate type parameter errors
420 if name == "init" || name == "main" && pkg.name == "main" {
421 code := _InvalidInitDecl
423 code = _InvalidMainDecl
425 if len(s.TParamList) != 0 {
426 check.softErrorf(s.TParamList[0], code, "func %s must have no type parameters", name)
427 hasTParamError = true
429 if t := s.Type; len(t.ParamList) != 0 || len(t.ResultList) != 0 {
430 check.softErrorf(s.Name, code, "func %s must have no arguments and no return values", name)
433 // don't declare init functions in the package scope - they are invisible
435 obj.parent = pkg.scope
436 check.recordDef(s.Name, obj)
437 // init functions must have a body
439 // TODO(gri) make this error message consistent with the others above
440 check.softErrorf(obj.pos, _MissingInitBody, "missing function body")
443 check.declare(pkg.scope, s.Name, obj, nopos)
448 ptr, recv, _ := check.unpackRecv(s.Recv.Type, false)
449 // Methods with invalid receiver cannot be associated to a type, and
450 // methods with blank _ names are never found; no need to collect any
451 // of them. They will still be type-checked with all the other functions.
452 if recv != nil && name != "_" {
453 methods = append(methods, methodInfo{obj, ptr, recv})
455 check.recordDef(s.Name, obj)
457 if len(s.TParamList) != 0 && !check.allowVersion(pkg, 1, 18) && !hasTParamError {
458 check.versionErrorf(s.TParamList[0], "go1.18", "type parameter")
460 info := &declInfo{file: fileScope, fdecl: s}
461 // Methods are not package-level objects but we still track them in the
462 // object map so that we can handle them like regular functions (if the
463 // receiver is invalid); also we need their fdecl info when associating
464 // them with their receiver base type, below.
465 check.objMap[obj] = info
466 obj.setOrder(uint32(len(check.objMap)))
469 check.errorf(s, 0, invalidAST+"unknown syntax.Decl node %T", s)
474 // verify that objects in package and file scopes have different names
475 for _, scope := range fileScopes {
476 for name, obj := range scope.elems {
477 if alt := pkg.scope.Lookup(name); alt != nil {
478 obj = resolve(name, obj)
480 err.code = _DuplicateDecl
481 if pkg, ok := obj.(*PkgName); ok {
482 err.errorf(alt, "%s already declared through import of %s", alt.Name(), pkg.Imported())
483 err.recordAltDecl(pkg)
485 err.errorf(alt, "%s already declared through dot-import of %s", alt.Name(), obj.Pkg())
486 // TODO(gri) dot-imported objects don't have a position; recordAltDecl won't print anything
487 err.recordAltDecl(obj)
494 // Now that we have all package scope objects and all methods,
495 // associate methods with receiver base type name where possible.
496 // Ignore methods that have an invalid receiver. They will be
497 // type-checked later, with regular functions.
499 check.methods = make(map[*TypeName][]*Func)
500 for i := range methods {
502 // Determine the receiver base type and associate m with it.
503 ptr, base := check.resolveBaseTypeName(m.ptr, m.recv)
505 m.obj.hasPtrRecv_ = ptr
506 check.methods[base] = append(check.methods[base], m.obj)
512 // unpackRecv unpacks a receiver type and returns its components: ptr indicates whether
513 // rtyp is a pointer receiver, rname is the receiver type name, and tparams are its
514 // type parameters, if any. The type parameters are only unpacked if unpackParams is
515 // set. If rname is nil, the receiver is unusable (i.e., the source has a bug which we
516 // cannot easily work around).
517 func (check *Checker) unpackRecv(rtyp syntax.Expr, unpackParams bool) (ptr bool, rname *syntax.Name, tparams []*syntax.Name) {
518 L: // unpack receiver type
519 // This accepts invalid receivers such as ***T and does not
520 // work for other invalid receivers, but we don't care. The
521 // validity of receiver expressions is checked elsewhere.
523 switch t := rtyp.(type) {
524 case *syntax.ParenExpr:
526 // case *ast.StarExpr:
529 case *syntax.Operation:
530 if t.Op != syntax.Mul || t.Y != nil {
540 // unpack type parameters, if any
541 if ptyp, _ := rtyp.(*syntax.IndexExpr); ptyp != nil {
544 for _, arg := range unpackExpr(ptyp.Index) {
546 switch arg := arg.(type) {
549 case *syntax.BadExpr:
550 // ignore - error already reported by parser
552 check.error(ptyp, 0, invalidAST+"parameterized receiver contains nil parameters")
554 check.errorf(arg, _BadDecl, "receiver type parameter %s must be an identifier", arg)
557 par = syntax.NewName(arg.Pos(), "_")
559 tparams = append(tparams, par)
565 // unpack receiver name
566 if name, _ := rtyp.(*syntax.Name); name != nil {
573 // resolveBaseTypeName returns the non-alias base type name for typ, and whether
574 // there was a pointer indirection to get to it. The base type name must be declared
575 // in package scope, and there can be at most one pointer indirection. If no such type
576 // name exists, the returned base is nil.
577 func (check *Checker) resolveBaseTypeName(seenPtr bool, typ syntax.Expr) (ptr bool, base *TypeName) {
578 // Algorithm: Starting from a type expression, which may be a name,
579 // we follow that type through alias declarations until we reach a
580 // non-alias type name. If we encounter anything but pointer types or
581 // parentheses we're done. If we encounter more than one pointer type
584 var seen map[*TypeName]bool
588 // check if we have a pointer type
589 // if pexpr, _ := typ.(*ast.StarExpr); pexpr != nil {
590 if pexpr, _ := typ.(*syntax.Operation); pexpr != nil && pexpr.Op == syntax.Mul && pexpr.Y == nil {
591 // if we've already seen a pointer, we're done
596 typ = unparen(pexpr.X) // continue with pointer base type
599 // typ must be a name
600 name, _ := typ.(*syntax.Name)
605 // name must denote an object found in the current package scope
606 // (note that dot-imported objects are not in the package scope!)
607 obj := check.pkg.scope.Lookup(name.Value)
612 // the object must be a type name...
613 tname, _ := obj.(*TypeName)
618 // ... which we have not seen before
623 // we're done if tdecl defined tname as a new type
624 // (rather than an alias)
625 tdecl := check.objMap[tname].tdecl // must exist for objects in package scope
630 // otherwise, continue resolving
633 seen = make(map[*TypeName]bool)
639 // packageObjects typechecks all package objects, but not function bodies.
640 func (check *Checker) packageObjects() {
641 // process package objects in source order for reproducible results
642 objList := make([]Object, len(check.objMap))
644 for obj := range check.objMap {
648 sort.Sort(inSourceOrder(objList))
650 // add new methods to already type-checked types (from a prior Checker.Files call)
651 for _, obj := range objList {
652 if obj, _ := obj.(*TypeName); obj != nil && obj.typ != nil {
653 check.collectMethods(obj)
657 // We process non-alias type declarations first, followed by alias declarations,
658 // and then everything else. This appears to avoid most situations where the type
659 // of an alias is needed before it is available.
660 // There may still be cases where this is not good enough (see also issue #25838).
661 // In those cases Checker.ident will report an error ("invalid use of type alias").
662 var aliasList []*TypeName
663 var othersList []Object // everything that's not a type
664 // phase 1: non-alias type declarations
665 for _, obj := range objList {
666 if tname, _ := obj.(*TypeName); tname != nil {
667 if check.objMap[tname].tdecl.Alias {
668 aliasList = append(aliasList, tname)
670 check.objDecl(obj, nil)
673 othersList = append(othersList, obj)
676 // phase 2: alias type declarations
677 for _, obj := range aliasList {
678 check.objDecl(obj, nil)
680 // phase 3: all other declarations
681 for _, obj := range othersList {
682 check.objDecl(obj, nil)
685 // At this point we may have a non-empty check.methods map; this means that not all
686 // entries were deleted at the end of typeDecl because the respective receiver base
687 // types were not found. In that case, an error was reported when declaring those
688 // methods. We can now safely discard this map.
692 // inSourceOrder implements the sort.Sort interface.
693 type inSourceOrder []Object
695 func (a inSourceOrder) Len() int { return len(a) }
696 func (a inSourceOrder) Less(i, j int) bool { return a[i].order() < a[j].order() }
697 func (a inSourceOrder) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
699 // unusedImports checks for unused imports.
700 func (check *Checker) unusedImports() {
701 // If function bodies are not checked, packages' uses are likely missing - don't check.
702 if check.conf.IgnoreFuncBodies {
706 // spec: "It is illegal (...) to directly import a package without referring to
707 // any of its exported identifiers. To import a package solely for its side-effects
708 // (initialization), use the blank identifier as explicit package name."
710 for _, obj := range check.imports {
711 if !obj.used && obj.name != "_" {
712 check.errorUnusedPkg(obj)
717 func (check *Checker) errorUnusedPkg(obj *PkgName) {
718 // If the package was imported with a name other than the final
719 // import path element, show it explicitly in the error message.
720 // Note that this handles both renamed imports and imports of
721 // packages containing unconventional package declarations.
722 // Note that this uses / always, even on Windows, because Go import
723 // paths always use forward slashes.
724 path := obj.imported.path
726 if i := strings.LastIndex(elem, "/"); i >= 0 {
729 if obj.name == "" || obj.name == "." || obj.name == elem {
730 check.softErrorf(obj, _UnusedImport, "%q imported and not used", path)
732 check.softErrorf(obj, _UnusedImport, "%q imported as %s and not used", path, obj.name)
736 // dir makes a good-faith attempt to return the directory
737 // portion of path. If path is empty, the result is ".".
738 // (Per the go/build package dependency tests, we cannot import
739 // path/filepath and simply use filepath.Dir.)
740 func dir(path string) string {
741 if i := strings.LastIndexAny(path, `/\`); i > 0 {