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