2 // Copyright 2013 The Go Authors. All rights reserved.
3 // Use of this source code is governed by a BSD-style
4 // license that can be found in the LICENSE file.
9 "cmd/compile/internal/syntax"
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 syntax.Expr // type, or nil (for const and var declarations only)
23 init syntax.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 *syntax.TypeDecl // type declaration, or nil
26 fdecl *syntax.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 // arity checks that the lhs and rhs of a const or var decl
49 // have a matching number of names and initialization values.
50 // If inherited is set, the initialization values are from
51 // another (constant) declaration.
52 func (check *Checker) arity(pos syntax.Pos, names []*syntax.Name, inits []syntax.Expr, constDecl, inherited bool) {
60 check.errorf(pos, "extra init expr at %s", n.Pos())
62 check.errorf(n, "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, "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.errorf(ident, "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.errorf(ident, "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, "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 check.pkgCnt[imp.name]++
187 // something went wrong (importer may have returned incomplete package without error)
191 // collectObjects collects all file and package objects and inserts them
192 // into their respective scopes. It also performs imports and associates
193 // methods with receiver base type names.
194 func (check *Checker) collectObjects() {
197 // pkgImports is the set of packages already imported by any package file seen
198 // so far. Used to avoid duplicate entries in pkg.imports. Allocate and populate
199 // it (pkg.imports may not be empty if we are checking test files incrementally).
200 // Note that pkgImports is keyed by package (and thus package path), not by an
201 // importKey value. Two different importKey values may map to the same package
202 // which is why we cannot use the check.impMap here.
203 var pkgImports = make(map[*Package]bool)
204 for _, imp := range pkg.imports {
205 pkgImports[imp] = true
208 type methodInfo struct {
210 ptr bool // true if pointer receiver
211 recv *syntax.Name // receiver type name
213 var methods []methodInfo // collected methods with valid receivers and non-blank _ names
214 var fileScopes []*Scope
215 for fileNo, file := range check.files {
216 // The package identifier denotes the current package,
217 // but there is no corresponding package object.
218 check.recordDef(file.PkgName, nil)
220 fileScope := NewScope(check.pkg.scope, startPos(file), endPos(file), check.filename(fileNo))
221 fileScopes = append(fileScopes, fileScope)
222 check.recordScope(file, fileScope)
224 // determine file directory, necessary to resolve imports
225 // FileName may be "" (typically for tests) in which case
226 // we get "." as the directory which is what we would want.
227 fileDir := dir(file.PkgName.Pos().RelFilename()) // TODO(gri) should this be filename?
229 first := -1 // index of first ConstDecl in the current group, or -1
230 var last *syntax.ConstDecl // last ConstDecl with init expressions, or nil
231 for index, decl := range file.DeclList {
232 if _, ok := decl.(*syntax.ConstDecl); !ok {
233 first = -1 // we're not in a constant declaration
236 switch s := decl.(type) {
237 case *syntax.ImportDecl:
239 if s.Path == nil || s.Path.Bad {
240 continue // error reported during parsing
242 path, err := validatedImportPath(s.Path.Value)
244 check.errorf(s.Path, "invalid import path (%s)", err)
248 imp := check.importPackage(s.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 s.LocalPkgName != nil {
264 name = s.LocalPkgName.Value
266 // match cmd/compile (not prescribed by spec)
267 check.errorf(s.LocalPkgName, `cannot rename import "C"`)
271 check.errorf(s.LocalPkgName, "cannot declare init - must be func")
276 obj := NewPkgName(s.Pos(), pkg, name, imp)
277 if s.LocalPkgName != nil {
278 // in a dot-import, the dot represents the package
279 check.recordDef(s.LocalPkgName, obj)
281 check.recordImplicit(s, 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(s.LocalPkgName, "%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, s.Pos())
311 // declare imported package object in file scope
312 // (no need to provide s.LocalPkgName since we called check.recordDef earlier)
313 check.declare(fileScope, nil, obj, nopos)
316 case *syntax.ConstDecl:
317 // iota is the index of the current constDecl within the group
318 if first < 0 || file.DeclList[index-1].(*syntax.ConstDecl).Group != s.Group {
322 iota := constant.MakeInt64(int64(index - first))
324 // determine which initialization expressions to use
327 case s.Type != nil || s.Values != nil:
331 last = new(syntax.ConstDecl) // make sure last exists
335 // declare all constants
336 values := unpackExpr(last.Values)
337 for i, name := range s.NameList {
338 obj := NewConst(name.Pos(), pkg, name.Value, nil, iota)
345 d := &declInfo{file: fileScope, vtyp: last.Type, init: init, inherited: inherited}
346 check.declarePkgObj(name, obj, d)
349 // Constants must always have init values.
350 check.arity(s.Pos(), s.NameList, values, true, inherited)
352 case *syntax.VarDecl:
353 lhs := make([]*Var, len(s.NameList))
354 // If there's exactly one rhs initializer, use
355 // the same declInfo d1 for all lhs variables
356 // so that each lhs variable depends on the same
357 // rhs initializer (n:1 var declaration).
359 if _, ok := s.Values.(*syntax.ListExpr); !ok {
360 // The lhs elements are only set up after the for loop below,
361 // but that's ok because declarePkgObj only collects the declInfo
362 // for a later phase.
363 d1 = &declInfo{file: fileScope, lhs: lhs, vtyp: s.Type, init: s.Values}
366 // declare all variables
367 values := unpackExpr(s.Values)
368 for i, name := range s.NameList {
369 obj := NewVar(name.Pos(), pkg, name.Value, nil)
374 // individual assignments
379 d = &declInfo{file: fileScope, vtyp: s.Type, init: init}
382 check.declarePkgObj(name, obj, d)
385 // If we have no type, we must have values.
386 if s.Type == nil || values != nil {
387 check.arity(s.Pos(), s.NameList, values, false, false)
390 case *syntax.TypeDecl:
391 obj := NewTypeName(s.Name.Pos(), pkg, s.Name.Value, nil)
392 check.declarePkgObj(s.Name, obj, &declInfo{file: fileScope, tdecl: s})
394 case *syntax.FuncDecl:
395 d := s // TODO(gri) get rid of this
397 obj := NewFunc(d.Name.Pos(), pkg, name, nil)
400 if name == "init" || name == "main" && pkg.name == "main" {
401 if d.TParamList != nil {
402 check.softErrorf(d, "func %s must have no type parameters", name)
404 if t := d.Type; len(t.ParamList) != 0 || len(t.ResultList) != 0 {
405 check.softErrorf(d, "func %s must have no arguments and no return values", name)
408 // don't declare init functions in the package scope - they are invisible
410 obj.parent = pkg.scope
411 check.recordDef(d.Name, obj)
412 // init functions must have a body
414 // TODO(gri) make this error message consistent with the others above
415 check.softErrorf(obj.pos, "missing function body")
418 check.declare(pkg.scope, d.Name, obj, nopos)
423 if !methodTypeParamsOk && len(d.TParamList) != 0 {
424 //check.invalidASTf(d.TParamList.Pos(), "method must have no type parameters")
425 check.invalidASTf(d, "method must have no type parameters")
427 ptr, recv, _ := check.unpackRecv(d.Recv.Type, false)
428 // (Methods with invalid receiver cannot be associated to a type, and
429 // methods with blank _ names are never found; no need to collect any
430 // of them. They will still be type-checked with all the other functions.)
431 if recv != nil && name != "_" {
432 methods = append(methods, methodInfo{obj, ptr, recv})
434 check.recordDef(d.Name, obj)
436 info := &declInfo{file: fileScope, fdecl: d}
437 // Methods are not package-level objects but we still track them in the
438 // object map so that we can handle them like regular functions (if the
439 // receiver is invalid); also we need their fdecl info when associating
440 // them with their receiver base type, below.
441 check.objMap[obj] = info
442 obj.setOrder(uint32(len(check.objMap)))
445 check.invalidASTf(s, "unknown syntax.Decl node %T", s)
450 // verify that objects in package and file scopes have different names
451 for _, scope := range fileScopes {
452 for _, obj := range scope.elems {
453 if alt := pkg.scope.Lookup(obj.Name()); alt != nil {
454 if pkg, ok := obj.(*PkgName); ok {
455 check.errorf(alt, "%s already declared through import of %s", alt.Name(), pkg.Imported())
456 check.reportAltDecl(pkg)
458 check.errorf(alt, "%s already declared through dot-import of %s", alt.Name(), obj.Pkg())
459 // TODO(gri) dot-imported objects don't have a position; reportAltDecl won't print anything
460 check.reportAltDecl(obj)
466 // Now that we have all package scope objects and all methods,
467 // associate methods with receiver base type name where possible.
468 // Ignore methods that have an invalid receiver. They will be
469 // type-checked later, with regular functions.
471 check.methods = make(map[*TypeName][]*Func)
472 for i := range methods {
474 // Determine the receiver base type and associate m with it.
475 ptr, base := check.resolveBaseTypeName(m.ptr, m.recv)
477 m.obj.hasPtrRecv = ptr
478 check.methods[base] = append(check.methods[base], m.obj)
484 // unpackRecv unpacks a receiver type and returns its components: ptr indicates whether
485 // rtyp is a pointer receiver, rname is the receiver type name, and tparams are its
486 // type parameters, if any. The type parameters are only unpacked if unpackParams is
487 // set. If rname is nil, the receiver is unusable (i.e., the source has a bug which we
488 // cannot easily work around).
489 func (check *Checker) unpackRecv(rtyp syntax.Expr, unpackParams bool) (ptr bool, rname *syntax.Name, tparams []*syntax.Name) {
490 L: // unpack receiver type
491 // This accepts invalid receivers such as ***T and does not
492 // work for other invalid receivers, but we don't care. The
493 // validity of receiver expressions is checked elsewhere.
495 switch t := rtyp.(type) {
496 case *syntax.ParenExpr:
498 // case *ast.StarExpr:
501 case *syntax.Operation:
502 if t.Op != syntax.Mul || t.Y != nil {
512 // unpack type parameters, if any
513 if ptyp, _ := rtyp.(*syntax.IndexExpr); ptyp != nil {
516 for _, arg := range unpackExpr(ptyp.Index) {
518 switch arg := arg.(type) {
521 case *syntax.BadExpr:
522 // ignore - error already reported by parser
524 check.invalidASTf(ptyp, "parameterized receiver contains nil parameters")
526 check.errorf(arg, "receiver type parameter %s must be an identifier", arg)
529 par = syntax.NewName(arg.Pos(), "_")
531 tparams = append(tparams, par)
537 // unpack receiver name
538 if name, _ := rtyp.(*syntax.Name); name != nil {
545 // resolveBaseTypeName returns the non-alias base type name for typ, and whether
546 // there was a pointer indirection to get to it. The base type name must be declared
547 // in package scope, and there can be at most one pointer indirection. If no such type
548 // name exists, the returned base is nil.
549 func (check *Checker) resolveBaseTypeName(seenPtr bool, typ syntax.Expr) (ptr bool, base *TypeName) {
550 // Algorithm: Starting from a type expression, which may be a name,
551 // we follow that type through alias declarations until we reach a
552 // non-alias type name. If we encounter anything but pointer types or
553 // parentheses we're done. If we encounter more than one pointer type
556 var seen map[*TypeName]bool
560 // check if we have a pointer type
561 // if pexpr, _ := typ.(*ast.StarExpr); pexpr != nil {
562 if pexpr, _ := typ.(*syntax.Operation); pexpr != nil && pexpr.Op == syntax.Mul && pexpr.Y == nil {
563 // if we've already seen a pointer, we're done
568 typ = unparen(pexpr.X) // continue with pointer base type
571 // typ must be a name
572 name, _ := typ.(*syntax.Name)
577 // name must denote an object found in the current package scope
578 // (note that dot-imported objects are not in the package scope!)
579 obj := check.pkg.scope.Lookup(name.Value)
584 // the object must be a type name...
585 tname, _ := obj.(*TypeName)
590 // ... which we have not seen before
595 // we're done if tdecl defined tname as a new type
596 // (rather than an alias)
597 tdecl := check.objMap[tname].tdecl // must exist for objects in package scope
602 // otherwise, continue resolving
605 seen = make(map[*TypeName]bool)
611 // packageObjects typechecks all package objects, but not function bodies.
612 func (check *Checker) packageObjects() {
613 // process package objects in source order for reproducible results
614 objList := make([]Object, len(check.objMap))
616 for obj := range check.objMap {
620 sort.Sort(inSourceOrder(objList))
622 // add new methods to already type-checked types (from a prior Checker.Files call)
623 for _, obj := range objList {
624 if obj, _ := obj.(*TypeName); obj != nil && obj.typ != nil {
625 check.collectMethods(obj)
629 // We process non-alias declarations first, in order to avoid situations where
630 // the type of an alias declaration is needed before it is available. In general
631 // this is still not enough, as it is possible to create sufficiently convoluted
632 // recursive type definitions that will cause a type alias to be needed before it
633 // is available (see issue #25838 for examples).
634 // As an aside, the cmd/compiler suffers from the same problem (#25838).
635 var aliasList []*TypeName
637 for _, obj := range objList {
638 // If we have a type alias, collect it for the 2nd phase.
639 if tname, _ := obj.(*TypeName); tname != nil && check.objMap[tname].tdecl.Alias {
640 aliasList = append(aliasList, tname)
644 check.objDecl(obj, nil)
647 for _, obj := range aliasList {
648 check.objDecl(obj, nil)
651 // At this point we may have a non-empty check.methods map; this means that not all
652 // entries were deleted at the end of typeDecl because the respective receiver base
653 // types were not found. In that case, an error was reported when declaring those
654 // methods. We can now safely discard this map.
658 // inSourceOrder implements the sort.Sort interface.
659 type inSourceOrder []Object
661 func (a inSourceOrder) Len() int { return len(a) }
662 func (a inSourceOrder) Less(i, j int) bool { return a[i].order() < a[j].order() }
663 func (a inSourceOrder) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
665 // unusedImports checks for unused imports.
666 func (check *Checker) unusedImports() {
667 // if function bodies are not checked, packages' uses are likely missing - don't check
668 if check.conf.IgnoreFuncBodies {
672 // spec: "It is illegal (...) to directly import a package without referring to
673 // any of its exported identifiers. To import a package solely for its side-effects
674 // (initialization), use the blank identifier as explicit package name."
676 // check use of regular imported packages
677 for _, scope := range check.pkg.scope.children /* file scopes */ {
678 for _, obj := range scope.elems {
679 if obj, ok := obj.(*PkgName); ok {
680 // Unused "blank imports" are automatically ignored
681 // since _ identifiers are not entered into scopes.
683 path := obj.imported.path
684 base := pkgName(path)
685 if obj.name == base {
686 if check.conf.CompilerErrorMessages {
687 check.softErrorf(obj.pos, "%q imported and not used", path)
689 check.softErrorf(obj.pos, "%q imported but not used", path)
692 if check.conf.CompilerErrorMessages {
693 check.softErrorf(obj.pos, "%q imported and not used as %s", path, obj.name)
695 check.softErrorf(obj.pos, "%q imported but not used as %s", path, obj.name)
703 // check use of dot-imported packages
704 for _, unusedDotImports := range check.unusedDotImports {
705 for pkg, pos := range unusedDotImports {
706 if check.conf.CompilerErrorMessages {
707 check.softErrorf(pos, "%q imported and not used", pkg.path)
709 check.softErrorf(pos, "%q imported but not used", pkg.path)
715 // pkgName returns the package name (last element) of an import path.
716 func pkgName(path string) string {
717 if i := strings.LastIndex(path, "/"); i >= 0 {
723 // dir makes a good-faith attempt to return the directory
724 // portion of path. If path is empty, the result is ".".
725 // (Per the go/build package dependency tests, we cannot import
726 // path/filepath and simply use filepath.Dir.)
727 func dir(path string) string {
728 if i := strings.LastIndexAny(path, `/\`); i > 0 {