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) {
59 check.errorf(pos, "extra init expr at %s", n.Pos())
61 check.errorf(n, "extra init expr %s", n)
63 case l > r && (constDecl || r != 1): // if r == 1 it may be a multi-valued function and we can't say anything yet
65 check.errorf(n, "missing init expr for %s", n.Value)
69 func validatedImportPath(path string) (string, error) {
70 s, err := strconv.Unquote(path)
75 return "", fmt.Errorf("empty string")
77 const illegalChars = `!"#$%&'()*,:;<=>?[\]^{|}` + "`\uFFFD"
79 if !unicode.IsGraphic(r) || unicode.IsSpace(r) || strings.ContainsRune(illegalChars, r) {
80 return s, fmt.Errorf("invalid character %#U", r)
86 // declarePkgObj declares obj in the package scope, records its ident -> obj mapping,
87 // and updates check.objMap. The object must not be a function or method.
88 func (check *Checker) declarePkgObj(ident *syntax.Name, obj Object, d *declInfo) {
89 assert(ident.Value == obj.Name())
91 // spec: "A package-scope or file-scope identifier with name init
92 // may only be declared to be a function with this (func()) signature."
93 if ident.Value == "init" {
94 check.error(ident, "cannot declare init - must be func")
98 // spec: "The main package must have package name main and declare
99 // a function main that takes no arguments and returns no value."
100 if ident.Value == "main" && check.pkg.name == "main" {
101 check.error(ident, "cannot declare main - must be func")
105 check.declare(check.pkg.scope, ident, obj, nopos)
106 check.objMap[obj] = d
107 obj.setOrder(uint32(len(check.objMap)))
110 // filename returns a filename suitable for debugging output.
111 func (check *Checker) filename(fileNo int) string {
112 file := check.files[fileNo]
113 if pos := file.Pos(); pos.IsKnown() {
114 // return check.fset.File(pos).Name()
115 // TODO(gri) do we need the actual file name here?
116 return pos.RelFilename()
118 return fmt.Sprintf("file[%d]", fileNo)
121 func (check *Checker) importPackage(pos syntax.Pos, path, dir string) *Package {
122 // If we already have a package for the given (path, dir)
123 // pair, use it instead of doing a full import.
124 // Checker.impMap only caches packages that are marked Complete
125 // or fake (dummy packages for failed imports). Incomplete but
126 // non-fake packages do require an import to complete them.
127 key := importKey{path, dir}
128 imp := check.impMap[key]
133 // no package yet => import it
134 if path == "C" && (check.conf.FakeImportC || check.conf.go115UsesCgo) {
135 imp = NewPackage("C", "C")
136 imp.fake = true // package scope is not populated
137 imp.cgo = check.conf.go115UsesCgo
141 if importer := check.conf.Importer; importer == nil {
142 err = fmt.Errorf("Config.Importer not installed")
143 } else if importerFrom, ok := importer.(ImporterFrom); ok {
144 imp, err = importerFrom.ImportFrom(path, dir, 0)
145 if imp == nil && err == nil {
146 err = fmt.Errorf("Config.Importer.ImportFrom(%s, %s, 0) returned nil but no error", path, dir)
149 imp, err = importer.Import(path)
150 if imp == nil && err == nil {
151 err = fmt.Errorf("Config.Importer.Import(%s) returned nil but no error", path)
154 // make sure we have a valid package name
155 // (errors here can only happen through manipulation of packages after creation)
156 if err == nil && imp != nil && (imp.name == "_" || imp.name == "") {
157 err = fmt.Errorf("invalid package name: %q", imp.name)
158 imp = nil // create fake package below
161 check.errorf(pos, "could not import %s (%s)", path, err)
163 // create a new fake package
164 // come up with a sensible package name (heuristic)
166 if i := len(name); i > 0 && name[i-1] == '/' {
169 if i := strings.LastIndex(name, "/"); i >= 0 {
172 imp = NewPackage(path, name)
174 // continue to use the package as best as we can
175 imp.fake = true // avoid follow-up lookup failures
179 // package should be complete or marked fake, but be cautious
180 if imp.complete || imp.fake {
181 check.impMap[key] = imp
182 // Once we've formatted an error message once, keep the pkgPathMap
183 // up-to-date on subsequent imports.
184 if check.pkgPathMap != nil {
185 check.markImports(imp)
190 // something went wrong (importer may have returned incomplete package without error)
194 // collectObjects collects all file and package objects and inserts them
195 // into their respective scopes. It also performs imports and associates
196 // methods with receiver base type names.
197 func (check *Checker) collectObjects() {
201 // pkgImports is the set of packages already imported by any package file seen
202 // so far. Used to avoid duplicate entries in pkg.imports. Allocate and populate
203 // it (pkg.imports may not be empty if we are checking test files incrementally).
204 // Note that pkgImports is keyed by package (and thus package path), not by an
205 // importKey value. Two different importKey values may map to the same package
206 // which is why we cannot use the check.impMap here.
207 var pkgImports = make(map[*Package]bool)
208 for _, imp := range pkg.imports {
209 pkgImports[imp] = true
212 type methodInfo struct {
214 ptr bool // true if pointer receiver
215 recv *syntax.Name // receiver type name
217 var methods []methodInfo // collected methods with valid receivers and non-blank _ names
218 var fileScopes []*Scope
219 for fileNo, file := range check.files {
220 // The package identifier denotes the current package,
221 // but there is no corresponding package object.
222 check.recordDef(file.PkgName, nil)
224 fileScope := NewScope(check.pkg.scope, syntax.StartPos(file), syntax.EndPos(file), check.filename(fileNo))
225 fileScopes = append(fileScopes, fileScope)
226 check.recordScope(file, fileScope)
228 // determine file directory, necessary to resolve imports
229 // FileName may be "" (typically for tests) in which case
230 // we get "." as the directory which is what we would want.
231 fileDir := dir(file.PkgName.Pos().RelFilename()) // TODO(gri) should this be filename?
233 first := -1 // index of first ConstDecl in the current group, or -1
234 var last *syntax.ConstDecl // last ConstDecl with init expressions, or nil
235 for index, decl := range file.DeclList {
236 if _, ok := decl.(*syntax.ConstDecl); !ok {
237 first = -1 // we're not in a constant declaration
240 switch s := decl.(type) {
241 case *syntax.ImportDecl:
243 if s.Path == nil || s.Path.Bad {
244 continue // error reported during parsing
246 path, err := validatedImportPath(s.Path.Value)
248 check.errorf(s.Path, "invalid import path (%s)", err)
252 imp := check.importPackage(s.Path.Pos(), path, fileDir)
258 // typecheck ignores imports of package unsafe for
259 // calculating height.
260 // TODO(mdempsky): Revisit this. This seems fine, but I
261 // don't remember explicitly considering this case.
262 } else if h := imp.height + 1; h > pkg.height {
266 // local name overrides imported package name
268 if s.LocalPkgName != nil {
269 name = s.LocalPkgName.Value
271 // match cmd/compile (not prescribed by spec)
272 check.error(s.LocalPkgName, `cannot rename import "C"`)
278 check.error(s, "cannot import package as init - init must be a func")
282 // add package to list of explicit imports
283 // (this functionality is provided as a convenience
284 // for clients; it is not needed for type-checking)
285 if !pkgImports[imp] {
286 pkgImports[imp] = true
287 pkg.imports = append(pkg.imports, imp)
290 pkgName := NewPkgName(s.Pos(), pkg, name, imp)
291 if s.LocalPkgName != nil {
292 // in a dot-import, the dot represents the package
293 check.recordDef(s.LocalPkgName, pkgName)
295 check.recordImplicit(s, pkgName)
299 // match cmd/compile (not prescribed by spec)
303 // add import to file scope
304 check.imports = append(check.imports, pkgName)
307 if check.dotImportMap == nil {
308 check.dotImportMap = make(map[dotImportKey]*PkgName)
310 // merge imported scope with file scope
311 for _, obj := range imp.scope.elems {
312 // A package scope may contain non-exported objects,
313 // do not import them!
315 // declare dot-imported object
316 // (Do not use check.declare because it modifies the object
317 // via Object.setScopePos, which leads to a race condition;
318 // the object may be imported into more than one file scope
319 // concurrently. See issue #32154.)
320 if alt := fileScope.Insert(obj); alt != nil {
322 err.errorf(s.LocalPkgName, "%s redeclared in this block", obj.Name())
323 err.recordAltDecl(alt)
326 check.dotImportMap[dotImportKey{fileScope, obj}] = pkgName
331 // declare imported package object in file scope
332 // (no need to provide s.LocalPkgName since we called check.recordDef earlier)
333 check.declare(fileScope, nil, pkgName, nopos)
336 case *syntax.ConstDecl:
337 // iota is the index of the current constDecl within the group
338 if first < 0 || file.DeclList[index-1].(*syntax.ConstDecl).Group != s.Group {
342 iota := constant.MakeInt64(int64(index - first))
344 // determine which initialization expressions to use
347 case s.Type != nil || s.Values != nil:
351 last = new(syntax.ConstDecl) // make sure last exists
355 // declare all constants
356 values := unpackExpr(last.Values)
357 for i, name := range s.NameList {
358 obj := NewConst(name.Pos(), pkg, name.Value, nil, iota)
365 d := &declInfo{file: fileScope, vtyp: last.Type, init: init, inherited: inherited}
366 check.declarePkgObj(name, obj, d)
369 // Constants must always have init values.
370 check.arity(s.Pos(), s.NameList, values, true, inherited)
372 case *syntax.VarDecl:
373 lhs := make([]*Var, len(s.NameList))
374 // If there's exactly one rhs initializer, use
375 // the same declInfo d1 for all lhs variables
376 // so that each lhs variable depends on the same
377 // rhs initializer (n:1 var declaration).
379 if _, ok := s.Values.(*syntax.ListExpr); !ok {
380 // The lhs elements are only set up after the for loop below,
381 // but that's ok because declarePkgObj only collects the declInfo
382 // for a later phase.
383 d1 = &declInfo{file: fileScope, lhs: lhs, vtyp: s.Type, init: s.Values}
386 // declare all variables
387 values := unpackExpr(s.Values)
388 for i, name := range s.NameList {
389 obj := NewVar(name.Pos(), pkg, name.Value, nil)
394 // individual assignments
399 d = &declInfo{file: fileScope, vtyp: s.Type, init: init}
402 check.declarePkgObj(name, obj, d)
405 // If we have no type, we must have values.
406 if s.Type == nil || values != nil {
407 check.arity(s.Pos(), s.NameList, values, false, false)
410 case *syntax.TypeDecl:
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:
415 d := s // TODO(gri) get rid of this
417 obj := NewFunc(d.Name.Pos(), pkg, name, nil)
420 if name == "init" || name == "main" && pkg.name == "main" {
421 if d.TParamList != nil {
422 check.softErrorf(d, "func %s must have no type parameters", name)
424 if t := d.Type; len(t.ParamList) != 0 || len(t.ResultList) != 0 {
425 check.softErrorf(d, "func %s must have no arguments and no return values", name)
428 // don't declare init functions in the package scope - they are invisible
430 obj.parent = pkg.scope
431 check.recordDef(d.Name, obj)
432 // init functions must have a body
434 // TODO(gri) make this error message consistent with the others above
435 check.softErrorf(obj.pos, "missing function body")
438 check.declare(pkg.scope, d.Name, obj, nopos)
443 if !acceptMethodTypeParams && len(d.TParamList) != 0 {
444 //check.error(d.TParamList.Pos(), invalidAST + "method must have no type parameters")
445 check.error(d, invalidAST+"method must have no type parameters")
447 ptr, recv, _ := check.unpackRecv(d.Recv.Type, false)
448 // (Methods with invalid receiver cannot be associated to a type, and
449 // methods with blank _ names are never found; no need to collect any
450 // of them. They will still be type-checked with all the other functions.)
451 if recv != nil && name != "_" {
452 methods = append(methods, methodInfo{obj, ptr, recv})
454 check.recordDef(d.Name, obj)
456 info := &declInfo{file: fileScope, fdecl: d}
457 // Methods are not package-level objects but we still track them in the
458 // object map so that we can handle them like regular functions (if the
459 // receiver is invalid); also we need their fdecl info when associating
460 // them with their receiver base type, below.
461 check.objMap[obj] = info
462 obj.setOrder(uint32(len(check.objMap)))
465 check.errorf(s, invalidAST+"unknown syntax.Decl node %T", s)
470 // verify that objects in package and file scopes have different names
471 for _, scope := range fileScopes {
472 for _, obj := range scope.elems {
473 if alt := pkg.scope.Lookup(obj.Name()); alt != nil {
475 if pkg, ok := obj.(*PkgName); ok {
476 err.errorf(alt, "%s already declared through import of %s", alt.Name(), pkg.Imported())
477 err.recordAltDecl(pkg)
479 err.errorf(alt, "%s already declared through dot-import of %s", alt.Name(), obj.Pkg())
480 // TODO(gri) dot-imported objects don't have a position; recordAltDecl won't print anything
481 err.recordAltDecl(obj)
488 // Now that we have all package scope objects and all methods,
489 // associate methods with receiver base type name where possible.
490 // Ignore methods that have an invalid receiver. They will be
491 // type-checked later, with regular functions.
493 check.methods = make(map[*TypeName][]*Func)
494 for i := range methods {
496 // Determine the receiver base type and associate m with it.
497 ptr, base := check.resolveBaseTypeName(m.ptr, m.recv)
499 m.obj.hasPtrRecv = ptr
500 check.methods[base] = append(check.methods[base], m.obj)
506 // unpackRecv unpacks a receiver type and returns its components: ptr indicates whether
507 // rtyp is a pointer receiver, rname is the receiver type name, and tparams are its
508 // type parameters, if any. The type parameters are only unpacked if unpackParams is
509 // set. If rname is nil, the receiver is unusable (i.e., the source has a bug which we
510 // cannot easily work around).
511 func (check *Checker) unpackRecv(rtyp syntax.Expr, unpackParams bool) (ptr bool, rname *syntax.Name, tparams []*syntax.Name) {
512 L: // unpack receiver type
513 // This accepts invalid receivers such as ***T and does not
514 // work for other invalid receivers, but we don't care. The
515 // validity of receiver expressions is checked elsewhere.
517 switch t := rtyp.(type) {
518 case *syntax.ParenExpr:
520 // case *ast.StarExpr:
523 case *syntax.Operation:
524 if t.Op != syntax.Mul || t.Y != nil {
534 // unpack type parameters, if any
535 if ptyp, _ := rtyp.(*syntax.IndexExpr); ptyp != nil {
538 for _, arg := range unpackExpr(ptyp.Index) {
540 switch arg := arg.(type) {
543 case *syntax.BadExpr:
544 // ignore - error already reported by parser
546 check.error(ptyp, invalidAST+"parameterized receiver contains nil parameters")
548 check.errorf(arg, "receiver type parameter %s must be an identifier", arg)
551 par = syntax.NewName(arg.Pos(), "_")
553 tparams = append(tparams, par)
559 // unpack receiver name
560 if name, _ := rtyp.(*syntax.Name); name != nil {
567 // resolveBaseTypeName returns the non-alias base type name for typ, and whether
568 // there was a pointer indirection to get to it. The base type name must be declared
569 // in package scope, and there can be at most one pointer indirection. If no such type
570 // name exists, the returned base is nil.
571 func (check *Checker) resolveBaseTypeName(seenPtr bool, typ syntax.Expr) (ptr bool, base *TypeName) {
572 // Algorithm: Starting from a type expression, which may be a name,
573 // we follow that type through alias declarations until we reach a
574 // non-alias type name. If we encounter anything but pointer types or
575 // parentheses we're done. If we encounter more than one pointer type
578 var seen map[*TypeName]bool
582 // check if we have a pointer type
583 // if pexpr, _ := typ.(*ast.StarExpr); pexpr != nil {
584 if pexpr, _ := typ.(*syntax.Operation); pexpr != nil && pexpr.Op == syntax.Mul && pexpr.Y == nil {
585 // if we've already seen a pointer, we're done
590 typ = unparen(pexpr.X) // continue with pointer base type
593 // typ must be a name
594 name, _ := typ.(*syntax.Name)
599 // name must denote an object found in the current package scope
600 // (note that dot-imported objects are not in the package scope!)
601 obj := check.pkg.scope.Lookup(name.Value)
606 // the object must be a type name...
607 tname, _ := obj.(*TypeName)
612 // ... which we have not seen before
617 // we're done if tdecl defined tname as a new type
618 // (rather than an alias)
619 tdecl := check.objMap[tname].tdecl // must exist for objects in package scope
624 // otherwise, continue resolving
627 seen = make(map[*TypeName]bool)
633 // packageObjects typechecks all package objects, but not function bodies.
634 func (check *Checker) packageObjects() {
635 // process package objects in source order for reproducible results
636 objList := make([]Object, len(check.objMap))
638 for obj := range check.objMap {
642 sort.Sort(inSourceOrder(objList))
644 // add new methods to already type-checked types (from a prior Checker.Files call)
645 for _, obj := range objList {
646 if obj, _ := obj.(*TypeName); obj != nil && obj.typ != nil {
647 check.collectMethods(obj)
651 // We process non-alias declarations first, in order to avoid situations where
652 // the type of an alias declaration is needed before it is available. In general
653 // this is still not enough, as it is possible to create sufficiently convoluted
654 // recursive type definitions that will cause a type alias to be needed before it
655 // is available (see issue #25838 for examples).
656 // As an aside, the cmd/compiler suffers from the same problem (#25838).
657 var aliasList []*TypeName
659 for _, obj := range objList {
660 // If we have a type alias, collect it for the 2nd phase.
661 if tname, _ := obj.(*TypeName); tname != nil && check.objMap[tname].tdecl.Alias {
662 aliasList = append(aliasList, tname)
666 check.objDecl(obj, nil)
669 for _, obj := range aliasList {
670 check.objDecl(obj, nil)
673 // At this point we may have a non-empty check.methods map; this means that not all
674 // entries were deleted at the end of typeDecl because the respective receiver base
675 // types were not found. In that case, an error was reported when declaring those
676 // methods. We can now safely discard this map.
680 // inSourceOrder implements the sort.Sort interface.
681 type inSourceOrder []Object
683 func (a inSourceOrder) Len() int { return len(a) }
684 func (a inSourceOrder) Less(i, j int) bool { return a[i].order() < a[j].order() }
685 func (a inSourceOrder) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
687 // unusedImports checks for unused imports.
688 func (check *Checker) unusedImports() {
689 // if function bodies are not checked, packages' uses are likely missing - don't check
690 if check.conf.IgnoreFuncBodies {
694 // spec: "It is illegal (...) to directly import a package without referring to
695 // any of its exported identifiers. To import a package solely for its side-effects
696 // (initialization), use the blank identifier as explicit package name."
698 for _, obj := range check.imports {
699 if !obj.used && obj.name != "_" {
700 check.errorUnusedPkg(obj)
705 func (check *Checker) errorUnusedPkg(obj *PkgName) {
706 // If the package was imported with a name other than the final
707 // import path element, show it explicitly in the error message.
708 // Note that this handles both renamed imports and imports of
709 // packages containing unconventional package declarations.
710 // Note that this uses / always, even on Windows, because Go import
711 // paths always use forward slashes.
712 path := obj.imported.path
714 if i := strings.LastIndex(elem, "/"); i >= 0 {
717 if obj.name == "" || obj.name == "." || obj.name == elem {
718 if check.conf.CompilerErrorMessages {
719 check.softErrorf(obj, "imported and not used: %q", path)
721 check.softErrorf(obj, "%q imported but not used", path)
724 if check.conf.CompilerErrorMessages {
725 check.softErrorf(obj, "imported and not used: %q as %s", path, obj.name)
727 check.softErrorf(obj, "%q imported but not used as %s", path, obj.name)
732 // dir makes a good-faith attempt to return the directory
733 // portion of path. If path is empty, the result is ".".
734 // (Per the go/build package dependency tests, we cannot import
735 // path/filepath and simply use filepath.Dir.)
736 func dir(path string) string {
737 if i := strings.LastIndexAny(path, `/\`); i > 0 {