github.com/tidwall/go@v0.0.0-20170415222209-6694a6888b7d/src/go/types/resolver.go (about)

     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.
     4  
     5  package types
     6  
     7  import (
     8  	"fmt"
     9  	"go/ast"
    10  	"go/constant"
    11  	"go/token"
    12  	"strconv"
    13  	"strings"
    14  	"unicode"
    15  )
    16  
    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  	typ   ast.Expr      // type, or nil
    22  	init  ast.Expr      // init/orig expression, or nil
    23  	fdecl *ast.FuncDecl // func declaration, or nil
    24  	alias bool          // type alias declaration
    25  
    26  	// The deps field tracks initialization expression dependencies.
    27  	// As a special (overloaded) case, it also tracks dependencies of
    28  	// interface types on embedded interfaces (see ordering.go).
    29  	deps objSet // lazily initialized
    30  }
    31  
    32  // An objSet is simply a set of objects.
    33  type objSet map[Object]bool
    34  
    35  // hasInitializer reports whether the declared object has an initialization
    36  // expression or function body.
    37  func (d *declInfo) hasInitializer() bool {
    38  	return d.init != nil || d.fdecl != nil && d.fdecl.Body != nil
    39  }
    40  
    41  // addDep adds obj to the set of objects d's init expression depends on.
    42  func (d *declInfo) addDep(obj Object) {
    43  	m := d.deps
    44  	if m == nil {
    45  		m = make(objSet)
    46  		d.deps = m
    47  	}
    48  	m[obj] = true
    49  }
    50  
    51  // arityMatch checks that the lhs and rhs of a const or var decl
    52  // have the appropriate number of names and init exprs. For const
    53  // decls, init is the value spec providing the init exprs; for
    54  // var decls, init is nil (the init exprs are in s in this case).
    55  func (check *Checker) arityMatch(s, init *ast.ValueSpec) {
    56  	l := len(s.Names)
    57  	r := len(s.Values)
    58  	if init != nil {
    59  		r = len(init.Values)
    60  	}
    61  
    62  	switch {
    63  	case init == nil && r == 0:
    64  		// var decl w/o init expr
    65  		if s.Type == nil {
    66  			check.errorf(s.Pos(), "missing type or init expr")
    67  		}
    68  	case l < r:
    69  		if l < len(s.Values) {
    70  			// init exprs from s
    71  			n := s.Values[l]
    72  			check.errorf(n.Pos(), "extra init expr %s", n)
    73  			// TODO(gri) avoid declared but not used error here
    74  		} else {
    75  			// init exprs "inherited"
    76  			check.errorf(s.Pos(), "extra init expr at %s", check.fset.Position(init.Pos()))
    77  			// TODO(gri) avoid declared but not used error here
    78  		}
    79  	case l > r && (init != nil || r != 1):
    80  		n := s.Names[r]
    81  		check.errorf(n.Pos(), "missing init expr for %s", n)
    82  	}
    83  }
    84  
    85  func validatedImportPath(path string) (string, error) {
    86  	s, err := strconv.Unquote(path)
    87  	if err != nil {
    88  		return "", err
    89  	}
    90  	if s == "" {
    91  		return "", fmt.Errorf("empty string")
    92  	}
    93  	const illegalChars = `!"#$%&'()*,:;<=>?[\]^{|}` + "`\uFFFD"
    94  	for _, r := range s {
    95  		if !unicode.IsGraphic(r) || unicode.IsSpace(r) || strings.ContainsRune(illegalChars, r) {
    96  			return s, fmt.Errorf("invalid character %#U", r)
    97  		}
    98  	}
    99  	return s, nil
   100  }
   101  
   102  // declarePkgObj declares obj in the package scope, records its ident -> obj mapping,
   103  // and updates check.objMap. The object must not be a function or method.
   104  func (check *Checker) declarePkgObj(ident *ast.Ident, obj Object, d *declInfo) {
   105  	assert(ident.Name == obj.Name())
   106  
   107  	// spec: "A package-scope or file-scope identifier with name init
   108  	// may only be declared to be a function with this (func()) signature."
   109  	if ident.Name == "init" {
   110  		check.errorf(ident.Pos(), "cannot declare init - must be func")
   111  		return
   112  	}
   113  
   114  	check.declare(check.pkg.scope, ident, obj, token.NoPos)
   115  	check.objMap[obj] = d
   116  	obj.setOrder(uint32(len(check.objMap)))
   117  }
   118  
   119  // filename returns a filename suitable for debugging output.
   120  func (check *Checker) filename(fileNo int) string {
   121  	file := check.files[fileNo]
   122  	if pos := file.Pos(); pos.IsValid() {
   123  		return check.fset.File(pos).Name()
   124  	}
   125  	return fmt.Sprintf("file[%d]", fileNo)
   126  }
   127  
   128  func (check *Checker) importPackage(pos token.Pos, path, dir string) *Package {
   129  	// If we already have a package for the given (path, dir)
   130  	// pair, use it instead of doing a full import.
   131  	// Checker.impMap only caches packages that are marked Complete
   132  	// or fake (dummy packages for failed imports). Incomplete but
   133  	// non-fake packages do require an import to complete them.
   134  	key := importKey{path, dir}
   135  	imp := check.impMap[key]
   136  	if imp != nil {
   137  		return imp
   138  	}
   139  
   140  	// no package yet => import it
   141  	if path == "C" && check.conf.FakeImportC {
   142  		imp = NewPackage("C", "C")
   143  		imp.fake = true
   144  	} else {
   145  		// ordinary import
   146  		var err error
   147  		if importer := check.conf.Importer; importer == nil {
   148  			err = fmt.Errorf("Config.Importer not installed")
   149  		} else if importerFrom, ok := importer.(ImporterFrom); ok {
   150  			imp, err = importerFrom.ImportFrom(path, dir, 0)
   151  			if imp == nil && err == nil {
   152  				err = fmt.Errorf("Config.Importer.ImportFrom(%s, %s, 0) returned nil but no error", path, dir)
   153  			}
   154  		} else {
   155  			imp, err = importer.Import(path)
   156  			if imp == nil && err == nil {
   157  				err = fmt.Errorf("Config.Importer.Import(%s) returned nil but no error", path)
   158  			}
   159  		}
   160  		if err != nil {
   161  			check.errorf(pos, "could not import %s (%s)", path, err)
   162  			if imp == nil {
   163  				// create a new fake package
   164  				// come up with a sensible package name (heuristic)
   165  				name := path
   166  				if i := len(name); i > 0 && name[i-1] == '/' {
   167  					name = name[:i-1]
   168  				}
   169  				if i := strings.LastIndex(name, "/"); i >= 0 {
   170  					name = name[i+1:]
   171  				}
   172  				imp = NewPackage(path, name)
   173  			}
   174  			// continue to use the package as best as we can
   175  			imp.fake = true // avoid follow-up lookup failures
   176  		}
   177  	}
   178  
   179  	// package should be complete or marked fake, but be cautious
   180  	if imp.complete || imp.fake {
   181  		check.impMap[key] = imp
   182  		return imp
   183  	}
   184  
   185  	// something went wrong (importer may have returned incomplete package without error)
   186  	return nil
   187  }
   188  
   189  // collectObjects collects all file and package objects and inserts them
   190  // into their respective scopes. It also performs imports and associates
   191  // methods with receiver base type names.
   192  func (check *Checker) collectObjects() {
   193  	pkg := check.pkg
   194  
   195  	// pkgImports is the set of packages already imported by any package file seen
   196  	// so far. Used to avoid duplicate entries in pkg.imports. Allocate and populate
   197  	// it (pkg.imports may not be empty if we are checking test files incrementally).
   198  	// Note that pkgImports is keyed by package (and thus package path), not by an
   199  	// importKey value. Two different importKey values may map to the same package
   200  	// which is why we cannot use the check.impMap here.
   201  	var pkgImports = make(map[*Package]bool)
   202  	for _, imp := range pkg.imports {
   203  		pkgImports[imp] = true
   204  	}
   205  
   206  	for fileNo, file := range check.files {
   207  		// The package identifier denotes the current package,
   208  		// but there is no corresponding package object.
   209  		check.recordDef(file.Name, nil)
   210  
   211  		// Use the actual source file extent rather than *ast.File extent since the
   212  		// latter doesn't include comments which appear at the start or end of the file.
   213  		// Be conservative and use the *ast.File extent if we don't have a *token.File.
   214  		pos, end := file.Pos(), file.End()
   215  		if f := check.fset.File(file.Pos()); f != nil {
   216  			pos, end = token.Pos(f.Base()), token.Pos(f.Base()+f.Size())
   217  		}
   218  		fileScope := NewScope(check.pkg.scope, pos, end, check.filename(fileNo))
   219  		check.recordScope(file, fileScope)
   220  
   221  		// determine file directory, necessary to resolve imports
   222  		// FileName may be "" (typically for tests) in which case
   223  		// we get "." as the directory which is what we would want.
   224  		fileDir := dir(check.fset.Position(file.Name.Pos()).Filename)
   225  
   226  		for _, decl := range file.Decls {
   227  			switch d := decl.(type) {
   228  			case *ast.BadDecl:
   229  				// ignore
   230  
   231  			case *ast.GenDecl:
   232  				var last *ast.ValueSpec // last ValueSpec with type or init exprs seen
   233  				for iota, spec := range d.Specs {
   234  					switch s := spec.(type) {
   235  					case *ast.ImportSpec:
   236  						// import package
   237  						path, err := validatedImportPath(s.Path.Value)
   238  						if err != nil {
   239  							check.errorf(s.Path.Pos(), "invalid import path (%s)", err)
   240  							continue
   241  						}
   242  
   243  						imp := check.importPackage(s.Path.Pos(), path, fileDir)
   244  						if imp == nil {
   245  							continue
   246  						}
   247  
   248  						// add package to list of explicit imports
   249  						// (this functionality is provided as a convenience
   250  						// for clients; it is not needed for type-checking)
   251  						if !pkgImports[imp] {
   252  							pkgImports[imp] = true
   253  							pkg.imports = append(pkg.imports, imp)
   254  						}
   255  
   256  						// local name overrides imported package name
   257  						name := imp.name
   258  						if s.Name != nil {
   259  							name = s.Name.Name
   260  							if path == "C" {
   261  								// match cmd/compile (not prescribed by spec)
   262  								check.errorf(s.Name.Pos(), `cannot rename import "C"`)
   263  								continue
   264  							}
   265  							if name == "init" {
   266  								check.errorf(s.Name.Pos(), "cannot declare init - must be func")
   267  								continue
   268  							}
   269  						}
   270  
   271  						obj := NewPkgName(s.Pos(), pkg, name, imp)
   272  						if s.Name != nil {
   273  							// in a dot-import, the dot represents the package
   274  							check.recordDef(s.Name, obj)
   275  						} else {
   276  							check.recordImplicit(s, obj)
   277  						}
   278  
   279  						if path == "C" {
   280  							// match cmd/compile (not prescribed by spec)
   281  							obj.used = true
   282  						}
   283  
   284  						// add import to file scope
   285  						if name == "." {
   286  							// merge imported scope with file scope
   287  							for _, obj := range imp.scope.elems {
   288  								// A package scope may contain non-exported objects,
   289  								// do not import them!
   290  								if obj.Exported() {
   291  									// TODO(gri) When we import a package, we create
   292  									// a new local package object. We should do the
   293  									// same for each dot-imported object. That way
   294  									// they can have correct position information.
   295  									// (We must not modify their existing position
   296  									// information because the same package - found
   297  									// via Config.Packages - may be dot-imported in
   298  									// another package!)
   299  									check.declare(fileScope, nil, obj, token.NoPos)
   300  									check.recordImplicit(s, obj)
   301  								}
   302  							}
   303  							// add position to set of dot-import positions for this file
   304  							// (this is only needed for "imported but not used" errors)
   305  							check.addUnusedDotImport(fileScope, imp, s.Pos())
   306  						} else {
   307  							// declare imported package object in file scope
   308  							check.declare(fileScope, nil, obj, token.NoPos)
   309  						}
   310  
   311  					case *ast.ValueSpec:
   312  						switch d.Tok {
   313  						case token.CONST:
   314  							// determine which initialization expressions to use
   315  							switch {
   316  							case s.Type != nil || len(s.Values) > 0:
   317  								last = s
   318  							case last == nil:
   319  								last = new(ast.ValueSpec) // make sure last exists
   320  							}
   321  
   322  							// declare all constants
   323  							for i, name := range s.Names {
   324  								obj := NewConst(name.Pos(), pkg, name.Name, nil, constant.MakeInt64(int64(iota)))
   325  
   326  								var init ast.Expr
   327  								if i < len(last.Values) {
   328  									init = last.Values[i]
   329  								}
   330  
   331  								d := &declInfo{file: fileScope, typ: last.Type, init: init}
   332  								check.declarePkgObj(name, obj, d)
   333  							}
   334  
   335  							check.arityMatch(s, last)
   336  
   337  						case token.VAR:
   338  							lhs := make([]*Var, len(s.Names))
   339  							// If there's exactly one rhs initializer, use
   340  							// the same declInfo d1 for all lhs variables
   341  							// so that each lhs variable depends on the same
   342  							// rhs initializer (n:1 var declaration).
   343  							var d1 *declInfo
   344  							if len(s.Values) == 1 {
   345  								// The lhs elements are only set up after the for loop below,
   346  								// but that's ok because declareVar only collects the declInfo
   347  								// for a later phase.
   348  								d1 = &declInfo{file: fileScope, lhs: lhs, typ: s.Type, init: s.Values[0]}
   349  							}
   350  
   351  							// declare all variables
   352  							for i, name := range s.Names {
   353  								obj := NewVar(name.Pos(), pkg, name.Name, nil)
   354  								lhs[i] = obj
   355  
   356  								d := d1
   357  								if d == nil {
   358  									// individual assignments
   359  									var init ast.Expr
   360  									if i < len(s.Values) {
   361  										init = s.Values[i]
   362  									}
   363  									d = &declInfo{file: fileScope, typ: s.Type, init: init}
   364  								}
   365  
   366  								check.declarePkgObj(name, obj, d)
   367  							}
   368  
   369  							check.arityMatch(s, nil)
   370  
   371  						default:
   372  							check.invalidAST(s.Pos(), "invalid token %s", d.Tok)
   373  						}
   374  
   375  					case *ast.TypeSpec:
   376  						obj := NewTypeName(s.Name.Pos(), pkg, s.Name.Name, nil)
   377  						check.declarePkgObj(s.Name, obj, &declInfo{file: fileScope, typ: s.Type, alias: s.Assign.IsValid()})
   378  
   379  					default:
   380  						check.invalidAST(s.Pos(), "unknown ast.Spec node %T", s)
   381  					}
   382  				}
   383  
   384  			case *ast.FuncDecl:
   385  				name := d.Name.Name
   386  				obj := NewFunc(d.Name.Pos(), pkg, name, nil)
   387  				if d.Recv == nil {
   388  					// regular function
   389  					if name == "init" {
   390  						// don't declare init functions in the package scope - they are invisible
   391  						obj.parent = pkg.scope
   392  						check.recordDef(d.Name, obj)
   393  						// init functions must have a body
   394  						if d.Body == nil {
   395  							check.softErrorf(obj.pos, "missing function body")
   396  						}
   397  					} else {
   398  						check.declare(pkg.scope, d.Name, obj, token.NoPos)
   399  					}
   400  				} else {
   401  					// method
   402  					check.recordDef(d.Name, obj)
   403  					// Associate method with receiver base type name, if possible.
   404  					// Ignore methods that have an invalid receiver, or a blank _
   405  					// receiver name. They will be type-checked later, with regular
   406  					// functions.
   407  					if list := d.Recv.List; len(list) > 0 {
   408  						typ := list[0].Type
   409  						if ptr, _ := typ.(*ast.StarExpr); ptr != nil {
   410  							typ = ptr.X
   411  						}
   412  						if base, _ := typ.(*ast.Ident); base != nil && base.Name != "_" {
   413  							check.assocMethod(base.Name, obj)
   414  						}
   415  					}
   416  				}
   417  				info := &declInfo{file: fileScope, fdecl: d}
   418  				check.objMap[obj] = info
   419  				obj.setOrder(uint32(len(check.objMap)))
   420  
   421  			default:
   422  				check.invalidAST(d.Pos(), "unknown ast.Decl node %T", d)
   423  			}
   424  		}
   425  	}
   426  
   427  	// verify that objects in package and file scopes have different names
   428  	for _, scope := range check.pkg.scope.children /* file scopes */ {
   429  		for _, obj := range scope.elems {
   430  			if alt := pkg.scope.Lookup(obj.Name()); alt != nil {
   431  				if pkg, ok := obj.(*PkgName); ok {
   432  					check.errorf(alt.Pos(), "%s already declared through import of %s", alt.Name(), pkg.Imported())
   433  					check.reportAltDecl(pkg)
   434  				} else {
   435  					check.errorf(alt.Pos(), "%s already declared through dot-import of %s", alt.Name(), obj.Pkg())
   436  					// TODO(gri) dot-imported objects don't have a position; reportAltDecl won't print anything
   437  					check.reportAltDecl(obj)
   438  				}
   439  			}
   440  		}
   441  	}
   442  }
   443  
   444  // packageObjects typechecks all package objects in objList, but not function bodies.
   445  func (check *Checker) packageObjects(objList []Object) {
   446  	// add new methods to already type-checked types (from a prior Checker.Files call)
   447  	for _, obj := range objList {
   448  		if obj, _ := obj.(*TypeName); obj != nil && obj.typ != nil {
   449  			check.addMethodDecls(obj)
   450  		}
   451  	}
   452  
   453  	// pre-allocate space for type declaration paths so that the underlying array is reused
   454  	typePath := make([]*TypeName, 0, 8)
   455  
   456  	for _, obj := range objList {
   457  		check.objDecl(obj, nil, typePath)
   458  	}
   459  
   460  	// At this point we may have a non-empty check.methods map; this means that not all
   461  	// entries were deleted at the end of typeDecl because the respective receiver base
   462  	// types were not found. In that case, an error was reported when declaring those
   463  	// methods. We can now safely discard this map.
   464  	check.methods = nil
   465  }
   466  
   467  // functionBodies typechecks all function bodies.
   468  func (check *Checker) functionBodies() {
   469  	for _, f := range check.funcs {
   470  		check.funcBody(f.decl, f.name, f.sig, f.body)
   471  	}
   472  }
   473  
   474  // unusedImports checks for unused imports.
   475  func (check *Checker) unusedImports() {
   476  	// if function bodies are not checked, packages' uses are likely missing - don't check
   477  	if check.conf.IgnoreFuncBodies {
   478  		return
   479  	}
   480  
   481  	// spec: "It is illegal (...) to directly import a package without referring to
   482  	// any of its exported identifiers. To import a package solely for its side-effects
   483  	// (initialization), use the blank identifier as explicit package name."
   484  
   485  	// check use of regular imported packages
   486  	for _, scope := range check.pkg.scope.children /* file scopes */ {
   487  		for _, obj := range scope.elems {
   488  			if obj, ok := obj.(*PkgName); ok {
   489  				// Unused "blank imports" are automatically ignored
   490  				// since _ identifiers are not entered into scopes.
   491  				if !obj.used {
   492  					path := obj.imported.path
   493  					base := pkgName(path)
   494  					if obj.name == base {
   495  						check.softErrorf(obj.pos, "%q imported but not used", path)
   496  					} else {
   497  						check.softErrorf(obj.pos, "%q imported but not used as %s", path, obj.name)
   498  					}
   499  				}
   500  			}
   501  		}
   502  	}
   503  
   504  	// check use of dot-imported packages
   505  	for _, unusedDotImports := range check.unusedDotImports {
   506  		for pkg, pos := range unusedDotImports {
   507  			check.softErrorf(pos, "%q imported but not used", pkg.path)
   508  		}
   509  	}
   510  }
   511  
   512  // pkgName returns the package name (last element) of an import path.
   513  func pkgName(path string) string {
   514  	if i := strings.LastIndex(path, "/"); i >= 0 {
   515  		path = path[i+1:]
   516  	}
   517  	return path
   518  }
   519  
   520  // dir makes a good-faith attempt to return the directory
   521  // portion of path. If path is empty, the result is ".".
   522  // (Per the go/build package dependency tests, we cannot import
   523  // path/filepath and simply use filepath.Dir.)
   524  func dir(path string) string {
   525  	if i := strings.LastIndexAny(path, `/\`); i > 0 {
   526  		return path[:i]
   527  	}
   528  	// i <= 0
   529  	return "."
   530  }