github.com/hlts2/go@v0.0.0-20170904000733-812b34efaed8/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  		// make sure we have a valid package name
   161  		// (errors here can only happen through manipulation of packages after creation)
   162  		if err == nil && imp != nil && (imp.name == "_" || imp.name == "") {
   163  			err = fmt.Errorf("invalid package name: %q", imp.name)
   164  			imp = nil // create fake package below
   165  		}
   166  		if err != nil {
   167  			check.errorf(pos, "could not import %s (%s)", path, err)
   168  			if imp == nil {
   169  				// create a new fake package
   170  				// come up with a sensible package name (heuristic)
   171  				name := path
   172  				if i := len(name); i > 0 && name[i-1] == '/' {
   173  					name = name[:i-1]
   174  				}
   175  				if i := strings.LastIndex(name, "/"); i >= 0 {
   176  					name = name[i+1:]
   177  				}
   178  				imp = NewPackage(path, name)
   179  			}
   180  			// continue to use the package as best as we can
   181  			imp.fake = true // avoid follow-up lookup failures
   182  		}
   183  	}
   184  
   185  	// package should be complete or marked fake, but be cautious
   186  	if imp.complete || imp.fake {
   187  		check.impMap[key] = imp
   188  		return imp
   189  	}
   190  
   191  	// something went wrong (importer may have returned incomplete package without error)
   192  	return nil
   193  }
   194  
   195  // collectObjects collects all file and package objects and inserts them
   196  // into their respective scopes. It also performs imports and associates
   197  // methods with receiver base type names.
   198  func (check *Checker) collectObjects() {
   199  	pkg := check.pkg
   200  
   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
   210  	}
   211  
   212  	for fileNo, file := range check.files {
   213  		// The package identifier denotes the current package,
   214  		// but there is no corresponding package object.
   215  		check.recordDef(file.Name, nil)
   216  
   217  		// Use the actual source file extent rather than *ast.File extent since the
   218  		// latter doesn't include comments which appear at the start or end of the file.
   219  		// Be conservative and use the *ast.File extent if we don't have a *token.File.
   220  		pos, end := file.Pos(), file.End()
   221  		if f := check.fset.File(file.Pos()); f != nil {
   222  			pos, end = token.Pos(f.Base()), token.Pos(f.Base()+f.Size())
   223  		}
   224  		fileScope := NewScope(check.pkg.scope, pos, end, check.filename(fileNo))
   225  		check.recordScope(file, fileScope)
   226  
   227  		// determine file directory, necessary to resolve imports
   228  		// FileName may be "" (typically for tests) in which case
   229  		// we get "." as the directory which is what we would want.
   230  		fileDir := dir(check.fset.Position(file.Name.Pos()).Filename)
   231  
   232  		for _, decl := range file.Decls {
   233  			switch d := decl.(type) {
   234  			case *ast.BadDecl:
   235  				// ignore
   236  
   237  			case *ast.GenDecl:
   238  				var last *ast.ValueSpec // last ValueSpec with type or init exprs seen
   239  				for iota, spec := range d.Specs {
   240  					switch s := spec.(type) {
   241  					case *ast.ImportSpec:
   242  						// import package
   243  						path, err := validatedImportPath(s.Path.Value)
   244  						if err != nil {
   245  							check.errorf(s.Path.Pos(), "invalid import path (%s)", err)
   246  							continue
   247  						}
   248  
   249  						imp := check.importPackage(s.Path.Pos(), path, fileDir)
   250  						if imp == nil {
   251  							continue
   252  						}
   253  
   254  						// add package to list of explicit imports
   255  						// (this functionality is provided as a convenience
   256  						// for clients; it is not needed for type-checking)
   257  						if !pkgImports[imp] {
   258  							pkgImports[imp] = true
   259  							pkg.imports = append(pkg.imports, imp)
   260  						}
   261  
   262  						// local name overrides imported package name
   263  						name := imp.name
   264  						if s.Name != nil {
   265  							name = s.Name.Name
   266  							if path == "C" {
   267  								// match cmd/compile (not prescribed by spec)
   268  								check.errorf(s.Name.Pos(), `cannot rename import "C"`)
   269  								continue
   270  							}
   271  							if name == "init" {
   272  								check.errorf(s.Name.Pos(), "cannot declare init - must be func")
   273  								continue
   274  							}
   275  						}
   276  
   277  						obj := NewPkgName(s.Pos(), pkg, name, imp)
   278  						if s.Name != nil {
   279  							// in a dot-import, the dot represents the package
   280  							check.recordDef(s.Name, obj)
   281  						} else {
   282  							check.recordImplicit(s, obj)
   283  						}
   284  
   285  						if path == "C" {
   286  							// match cmd/compile (not prescribed by spec)
   287  							obj.used = true
   288  						}
   289  
   290  						// add import to file scope
   291  						if name == "." {
   292  							// merge imported scope with file scope
   293  							for _, obj := range imp.scope.elems {
   294  								// A package scope may contain non-exported objects,
   295  								// do not import them!
   296  								if obj.Exported() {
   297  									// TODO(gri) When we import a package, we create
   298  									// a new local package object. We should do the
   299  									// same for each dot-imported object. That way
   300  									// they can have correct position information.
   301  									// (We must not modify their existing position
   302  									// information because the same package - found
   303  									// via Config.Packages - may be dot-imported in
   304  									// another package!)
   305  									check.declare(fileScope, nil, obj, token.NoPos)
   306  								}
   307  							}
   308  							// add position to set of dot-import positions for this file
   309  							// (this is only needed for "imported but not used" errors)
   310  							check.addUnusedDotImport(fileScope, imp, s.Pos())
   311  						} else {
   312  							// declare imported package object in file scope
   313  							check.declare(fileScope, nil, obj, token.NoPos)
   314  						}
   315  
   316  					case *ast.ValueSpec:
   317  						switch d.Tok {
   318  						case token.CONST:
   319  							// determine which initialization expressions to use
   320  							switch {
   321  							case s.Type != nil || len(s.Values) > 0:
   322  								last = s
   323  							case last == nil:
   324  								last = new(ast.ValueSpec) // make sure last exists
   325  							}
   326  
   327  							// declare all constants
   328  							for i, name := range s.Names {
   329  								obj := NewConst(name.Pos(), pkg, name.Name, nil, constant.MakeInt64(int64(iota)))
   330  
   331  								var init ast.Expr
   332  								if i < len(last.Values) {
   333  									init = last.Values[i]
   334  								}
   335  
   336  								d := &declInfo{file: fileScope, typ: last.Type, init: init}
   337  								check.declarePkgObj(name, obj, d)
   338  							}
   339  
   340  							check.arityMatch(s, last)
   341  
   342  						case token.VAR:
   343  							lhs := make([]*Var, len(s.Names))
   344  							// If there's exactly one rhs initializer, use
   345  							// the same declInfo d1 for all lhs variables
   346  							// so that each lhs variable depends on the same
   347  							// rhs initializer (n:1 var declaration).
   348  							var d1 *declInfo
   349  							if len(s.Values) == 1 {
   350  								// The lhs elements are only set up after the for loop below,
   351  								// but that's ok because declareVar only collects the declInfo
   352  								// for a later phase.
   353  								d1 = &declInfo{file: fileScope, lhs: lhs, typ: s.Type, init: s.Values[0]}
   354  							}
   355  
   356  							// declare all variables
   357  							for i, name := range s.Names {
   358  								obj := NewVar(name.Pos(), pkg, name.Name, nil)
   359  								lhs[i] = obj
   360  
   361  								d := d1
   362  								if d == nil {
   363  									// individual assignments
   364  									var init ast.Expr
   365  									if i < len(s.Values) {
   366  										init = s.Values[i]
   367  									}
   368  									d = &declInfo{file: fileScope, typ: s.Type, init: init}
   369  								}
   370  
   371  								check.declarePkgObj(name, obj, d)
   372  							}
   373  
   374  							check.arityMatch(s, nil)
   375  
   376  						default:
   377  							check.invalidAST(s.Pos(), "invalid token %s", d.Tok)
   378  						}
   379  
   380  					case *ast.TypeSpec:
   381  						obj := NewTypeName(s.Name.Pos(), pkg, s.Name.Name, nil)
   382  						check.declarePkgObj(s.Name, obj, &declInfo{file: fileScope, typ: s.Type, alias: s.Assign.IsValid()})
   383  
   384  					default:
   385  						check.invalidAST(s.Pos(), "unknown ast.Spec node %T", s)
   386  					}
   387  				}
   388  
   389  			case *ast.FuncDecl:
   390  				name := d.Name.Name
   391  				obj := NewFunc(d.Name.Pos(), pkg, name, nil)
   392  				if d.Recv == nil {
   393  					// regular function
   394  					if name == "init" {
   395  						// don't declare init functions in the package scope - they are invisible
   396  						obj.parent = pkg.scope
   397  						check.recordDef(d.Name, obj)
   398  						// init functions must have a body
   399  						if d.Body == nil {
   400  							check.softErrorf(obj.pos, "missing function body")
   401  						}
   402  					} else {
   403  						check.declare(pkg.scope, d.Name, obj, token.NoPos)
   404  					}
   405  				} else {
   406  					// method
   407  					check.recordDef(d.Name, obj)
   408  					// Associate method with receiver base type name, if possible.
   409  					// Ignore methods that have an invalid receiver, or a blank _
   410  					// receiver name. They will be type-checked later, with regular
   411  					// functions.
   412  					if list := d.Recv.List; len(list) > 0 {
   413  						typ := list[0].Type
   414  						if ptr, _ := typ.(*ast.StarExpr); ptr != nil {
   415  							typ = ptr.X
   416  						}
   417  						if base, _ := typ.(*ast.Ident); base != nil && base.Name != "_" {
   418  							check.assocMethod(base.Name, obj)
   419  						}
   420  					}
   421  				}
   422  				info := &declInfo{file: fileScope, fdecl: d}
   423  				check.objMap[obj] = info
   424  				obj.setOrder(uint32(len(check.objMap)))
   425  
   426  			default:
   427  				check.invalidAST(d.Pos(), "unknown ast.Decl node %T", d)
   428  			}
   429  		}
   430  	}
   431  
   432  	// verify that objects in package and file scopes have different names
   433  	for _, scope := range check.pkg.scope.children /* file scopes */ {
   434  		for _, obj := range scope.elems {
   435  			if alt := pkg.scope.Lookup(obj.Name()); alt != nil {
   436  				if pkg, ok := obj.(*PkgName); ok {
   437  					check.errorf(alt.Pos(), "%s already declared through import of %s", alt.Name(), pkg.Imported())
   438  					check.reportAltDecl(pkg)
   439  				} else {
   440  					check.errorf(alt.Pos(), "%s already declared through dot-import of %s", alt.Name(), obj.Pkg())
   441  					// TODO(gri) dot-imported objects don't have a position; reportAltDecl won't print anything
   442  					check.reportAltDecl(obj)
   443  				}
   444  			}
   445  		}
   446  	}
   447  }
   448  
   449  // packageObjects typechecks all package objects in objList, but not function bodies.
   450  func (check *Checker) packageObjects(objList []Object) {
   451  	// add new methods to already type-checked types (from a prior Checker.Files call)
   452  	for _, obj := range objList {
   453  		if obj, _ := obj.(*TypeName); obj != nil && obj.typ != nil {
   454  			check.addMethodDecls(obj)
   455  		}
   456  	}
   457  
   458  	// pre-allocate space for type declaration paths so that the underlying array is reused
   459  	typePath := make([]*TypeName, 0, 8)
   460  
   461  	for _, obj := range objList {
   462  		check.objDecl(obj, nil, typePath)
   463  	}
   464  
   465  	// At this point we may have a non-empty check.methods map; this means that not all
   466  	// entries were deleted at the end of typeDecl because the respective receiver base
   467  	// types were not found. In that case, an error was reported when declaring those
   468  	// methods. We can now safely discard this map.
   469  	check.methods = nil
   470  }
   471  
   472  // functionBodies typechecks all function bodies.
   473  func (check *Checker) functionBodies() {
   474  	for _, f := range check.funcs {
   475  		check.funcBody(f.decl, f.name, f.sig, f.body)
   476  	}
   477  }
   478  
   479  // unusedImports checks for unused imports.
   480  func (check *Checker) unusedImports() {
   481  	// if function bodies are not checked, packages' uses are likely missing - don't check
   482  	if check.conf.IgnoreFuncBodies {
   483  		return
   484  	}
   485  
   486  	// spec: "It is illegal (...) to directly import a package without referring to
   487  	// any of its exported identifiers. To import a package solely for its side-effects
   488  	// (initialization), use the blank identifier as explicit package name."
   489  
   490  	// check use of regular imported packages
   491  	for _, scope := range check.pkg.scope.children /* file scopes */ {
   492  		for _, obj := range scope.elems {
   493  			if obj, ok := obj.(*PkgName); ok {
   494  				// Unused "blank imports" are automatically ignored
   495  				// since _ identifiers are not entered into scopes.
   496  				if !obj.used {
   497  					path := obj.imported.path
   498  					base := pkgName(path)
   499  					if obj.name == base {
   500  						check.softErrorf(obj.pos, "%q imported but not used", path)
   501  					} else {
   502  						check.softErrorf(obj.pos, "%q imported but not used as %s", path, obj.name)
   503  					}
   504  				}
   505  			}
   506  		}
   507  	}
   508  
   509  	// check use of dot-imported packages
   510  	for _, unusedDotImports := range check.unusedDotImports {
   511  		for pkg, pos := range unusedDotImports {
   512  			check.softErrorf(pos, "%q imported but not used", pkg.path)
   513  		}
   514  	}
   515  }
   516  
   517  // pkgName returns the package name (last element) of an import path.
   518  func pkgName(path string) string {
   519  	if i := strings.LastIndex(path, "/"); i >= 0 {
   520  		path = path[i+1:]
   521  	}
   522  	return path
   523  }
   524  
   525  // dir makes a good-faith attempt to return the directory
   526  // portion of path. If path is empty, the result is ".".
   527  // (Per the go/build package dependency tests, we cannot import
   528  // path/filepath and simply use filepath.Dir.)
   529  func dir(path string) string {
   530  	if i := strings.LastIndexAny(path, `/\`); i > 0 {
   531  		return path[:i]
   532  	}
   533  	// i <= 0
   534  	return "."
   535  }