Source file src/go/types/resolver.go

     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/internal/typeparams"
    12  	"go/token"
    13  	"sort"
    14  	"strconv"
    15  	"strings"
    16  	"unicode"
    17  )
    18  
    19  // A declInfo describes a package-level const, type, var, or func declaration.
    20  type declInfo struct {
    21  	file      *Scope        // scope of file containing this declaration
    22  	lhs       []*Var        // lhs of n:1 variable declarations, or nil
    23  	vtyp      ast.Expr      // type, or nil (for const and var declarations only)
    24  	init      ast.Expr      // init/orig expression, or nil (for const and var declarations only)
    25  	inherited bool          // if set, the init expression is inherited from a previous constant declaration
    26  	tdecl     *ast.TypeSpec // type declaration, or nil
    27  	fdecl     *ast.FuncDecl // func declaration, or nil
    28  
    29  	// The deps field tracks initialization expression dependencies.
    30  	deps map[Object]bool // lazily initialized
    31  }
    32  
    33  // hasInitializer reports whether the declared object has an initialization
    34  // expression or function body.
    35  func (d *declInfo) hasInitializer() bool {
    36  	return d.init != nil || d.fdecl != nil && d.fdecl.Body != nil
    37  }
    38  
    39  // addDep adds obj to the set of objects d's init expression depends on.
    40  func (d *declInfo) addDep(obj Object) {
    41  	m := d.deps
    42  	if m == nil {
    43  		m = make(map[Object]bool)
    44  		d.deps = m
    45  	}
    46  	m[obj] = true
    47  }
    48  
    49  // arityMatch checks that the lhs and rhs of a const or var decl
    50  // have the appropriate number of names and init exprs. For const
    51  // decls, init is the value spec providing the init exprs; for
    52  // var decls, init is nil (the init exprs are in s in this case).
    53  func (check *Checker) arityMatch(s, init *ast.ValueSpec) {
    54  	l := len(s.Names)
    55  	r := len(s.Values)
    56  	if init != nil {
    57  		r = len(init.Values)
    58  	}
    59  
    60  	const code = _WrongAssignCount
    61  	switch {
    62  	case init == nil && r == 0:
    63  		// var decl w/o init expr
    64  		if s.Type == nil {
    65  			check.errorf(s, code, "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, code, "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, code, "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, code, "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, _InvalidInitDecl, "cannot declare init - must be func")
   110  		return
   111  	}
   112  
   113  	// spec: "The main package must have package name main and declare
   114  	// a function main that takes no arguments and returns no value."
   115  	if ident.Name == "main" && check.pkg.name == "main" {
   116  		check.errorf(ident, _InvalidMainDecl, "cannot declare main - must be func")
   117  		return
   118  	}
   119  
   120  	check.declare(check.pkg.scope, ident, obj, token.NoPos)
   121  	check.objMap[obj] = d
   122  	obj.setOrder(uint32(len(check.objMap)))
   123  }
   124  
   125  // filename returns a filename suitable for debugging output.
   126  func (check *Checker) filename(fileNo int) string {
   127  	file := check.files[fileNo]
   128  	if pos := file.Pos(); pos.IsValid() {
   129  		return check.fset.File(pos).Name()
   130  	}
   131  	return fmt.Sprintf("file[%d]", fileNo)
   132  }
   133  
   134  func (check *Checker) importPackage(at positioner, path, dir string) *Package {
   135  	// If we already have a package for the given (path, dir)
   136  	// pair, use it instead of doing a full import.
   137  	// Checker.impMap only caches packages that are marked Complete
   138  	// or fake (dummy packages for failed imports). Incomplete but
   139  	// non-fake packages do require an import to complete them.
   140  	key := importKey{path, dir}
   141  	imp := check.impMap[key]
   142  	if imp != nil {
   143  		return imp
   144  	}
   145  
   146  	// no package yet => import it
   147  	if path == "C" && (check.conf.FakeImportC || check.conf.go115UsesCgo) {
   148  		imp = NewPackage("C", "C")
   149  		imp.fake = true // package scope is not populated
   150  		imp.cgo = check.conf.go115UsesCgo
   151  	} else {
   152  		// ordinary import
   153  		var err error
   154  		if importer := check.conf.Importer; importer == nil {
   155  			err = fmt.Errorf("Config.Importer not installed")
   156  		} else if importerFrom, ok := importer.(ImporterFrom); ok {
   157  			imp, err = importerFrom.ImportFrom(path, dir, 0)
   158  			if imp == nil && err == nil {
   159  				err = fmt.Errorf("Config.Importer.ImportFrom(%s, %s, 0) returned nil but no error", path, dir)
   160  			}
   161  		} else {
   162  			imp, err = importer.Import(path)
   163  			if imp == nil && err == nil {
   164  				err = fmt.Errorf("Config.Importer.Import(%s) returned nil but no error", path)
   165  			}
   166  		}
   167  		// make sure we have a valid package name
   168  		// (errors here can only happen through manipulation of packages after creation)
   169  		if err == nil && imp != nil && (imp.name == "_" || imp.name == "") {
   170  			err = fmt.Errorf("invalid package name: %q", imp.name)
   171  			imp = nil // create fake package below
   172  		}
   173  		if err != nil {
   174  			check.errorf(at, _BrokenImport, "could not import %s (%s)", path, err)
   175  			if imp == nil {
   176  				// create a new fake package
   177  				// come up with a sensible package name (heuristic)
   178  				name := path
   179  				if i := len(name); i > 0 && name[i-1] == '/' {
   180  					name = name[:i-1]
   181  				}
   182  				if i := strings.LastIndex(name, "/"); i >= 0 {
   183  					name = name[i+1:]
   184  				}
   185  				imp = NewPackage(path, name)
   186  			}
   187  			// continue to use the package as best as we can
   188  			imp.fake = true // avoid follow-up lookup failures
   189  		}
   190  	}
   191  
   192  	// package should be complete or marked fake, but be cautious
   193  	if imp.complete || imp.fake {
   194  		check.impMap[key] = imp
   195  		// Once we've formatted an error message once, keep the pkgPathMap
   196  		// up-to-date on subsequent imports.
   197  		if check.pkgPathMap != nil {
   198  			check.markImports(imp)
   199  		}
   200  		return imp
   201  	}
   202  
   203  	// something went wrong (importer may have returned incomplete package without error)
   204  	return nil
   205  }
   206  
   207  // collectObjects collects all file and package objects and inserts them
   208  // into their respective scopes. It also performs imports and associates
   209  // methods with receiver base type names.
   210  func (check *Checker) collectObjects() {
   211  	pkg := check.pkg
   212  
   213  	// pkgImports is the set of packages already imported by any package file seen
   214  	// so far. Used to avoid duplicate entries in pkg.imports. Allocate and populate
   215  	// it (pkg.imports may not be empty if we are checking test files incrementally).
   216  	// Note that pkgImports is keyed by package (and thus package path), not by an
   217  	// importKey value. Two different importKey values may map to the same package
   218  	// which is why we cannot use the check.impMap here.
   219  	var pkgImports = make(map[*Package]bool)
   220  	for _, imp := range pkg.imports {
   221  		pkgImports[imp] = true
   222  	}
   223  
   224  	type methodInfo struct {
   225  		obj  *Func      // method
   226  		ptr  bool       // true if pointer receiver
   227  		recv *ast.Ident // receiver type name
   228  	}
   229  	var methods []methodInfo // collected methods with valid receivers and non-blank _ names
   230  	var fileScopes []*Scope
   231  	for fileNo, file := range check.files {
   232  		// The package identifier denotes the current package,
   233  		// but there is no corresponding package object.
   234  		check.recordDef(file.Name, nil)
   235  
   236  		// Use the actual source file extent rather than *ast.File extent since the
   237  		// latter doesn't include comments which appear at the start or end of the file.
   238  		// Be conservative and use the *ast.File extent if we don't have a *token.File.
   239  		pos, end := file.Pos(), file.End()
   240  		if f := check.fset.File(file.Pos()); f != nil {
   241  			pos, end = token.Pos(f.Base()), token.Pos(f.Base()+f.Size())
   242  		}
   243  		fileScope := NewScope(check.pkg.scope, pos, end, check.filename(fileNo))
   244  		fileScopes = append(fileScopes, fileScope)
   245  		check.recordScope(file, fileScope)
   246  
   247  		// determine file directory, necessary to resolve imports
   248  		// FileName may be "" (typically for tests) in which case
   249  		// we get "." as the directory which is what we would want.
   250  		fileDir := dir(check.fset.Position(file.Name.Pos()).Filename)
   251  
   252  		check.walkDecls(file.Decls, func(d decl) {
   253  			switch d := d.(type) {
   254  			case importDecl:
   255  				// import package
   256  				path, err := validatedImportPath(d.spec.Path.Value)
   257  				if err != nil {
   258  					check.errorf(d.spec.Path, _BadImportPath, "invalid import path (%s)", err)
   259  					return
   260  				}
   261  
   262  				imp := check.importPackage(d.spec.Path, path, fileDir)
   263  				if imp == nil {
   264  					return
   265  				}
   266  
   267  				// local name overrides imported package name
   268  				name := imp.name
   269  				if d.spec.Name != nil {
   270  					name = d.spec.Name.Name
   271  					if path == "C" {
   272  						// match cmd/compile (not prescribed by spec)
   273  						check.errorf(d.spec.Name, _ImportCRenamed, `cannot rename import "C"`)
   274  						return
   275  					}
   276  				}
   277  
   278  				if name == "init" {
   279  					check.errorf(d.spec, _InvalidInitDecl, "cannot import package as init - init must be a func")
   280  					return
   281  				}
   282  
   283  				// add package to list of explicit imports
   284  				// (this functionality is provided as a convenience
   285  				// for clients; it is not needed for type-checking)
   286  				if !pkgImports[imp] {
   287  					pkgImports[imp] = true
   288  					pkg.imports = append(pkg.imports, imp)
   289  				}
   290  
   291  				pkgName := NewPkgName(d.spec.Pos(), pkg, name, imp)
   292  				if d.spec.Name != nil {
   293  					// in a dot-import, the dot represents the package
   294  					check.recordDef(d.spec.Name, pkgName)
   295  				} else {
   296  					check.recordImplicit(d.spec, pkgName)
   297  				}
   298  
   299  				if path == "C" {
   300  					// match cmd/compile (not prescribed by spec)
   301  					pkgName.used = true
   302  				}
   303  
   304  				// add import to file scope
   305  				check.imports = append(check.imports, pkgName)
   306  				if name == "." {
   307  					// dot-import
   308  					if check.dotImportMap == nil {
   309  						check.dotImportMap = make(map[dotImportKey]*PkgName)
   310  					}
   311  					// merge imported scope with file scope
   312  					for name, obj := range imp.scope.elems {
   313  						// Note: Avoid eager resolve(name, obj) here, so we only
   314  						// resolve dot-imported objects as needed.
   315  
   316  						// A package scope may contain non-exported objects,
   317  						// do not import them!
   318  						if token.IsExported(name) {
   319  							// declare dot-imported object
   320  							// (Do not use check.declare because it modifies the object
   321  							// via Object.setScopePos, which leads to a race condition;
   322  							// the object may be imported into more than one file scope
   323  							// concurrently. See issue #32154.)
   324  							if alt := fileScope.Lookup(name); alt != nil {
   325  								check.errorf(d.spec.Name, _DuplicateDecl, "%s redeclared in this block", alt.Name())
   326  								check.reportAltDecl(alt)
   327  							} else {
   328  								fileScope.insert(name, obj)
   329  								check.dotImportMap[dotImportKey{fileScope, name}] = pkgName
   330  							}
   331  						}
   332  					}
   333  				} else {
   334  					// declare imported package object in file scope
   335  					// (no need to provide s.Name since we called check.recordDef earlier)
   336  					check.declare(fileScope, nil, pkgName, token.NoPos)
   337  				}
   338  			case constDecl:
   339  				// declare all constants
   340  				for i, name := range d.spec.Names {
   341  					obj := NewConst(name.Pos(), pkg, name.Name, nil, constant.MakeInt64(int64(d.iota)))
   342  
   343  					var init ast.Expr
   344  					if i < len(d.init) {
   345  						init = d.init[i]
   346  					}
   347  
   348  					d := &declInfo{file: fileScope, vtyp: d.typ, init: init, inherited: d.inherited}
   349  					check.declarePkgObj(name, obj, d)
   350  				}
   351  
   352  			case varDecl:
   353  				lhs := make([]*Var, len(d.spec.Names))
   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).
   358  				var d1 *declInfo
   359  				if len(d.spec.Values) == 1 {
   360  					// The lhs elements are only set up after the for loop below,
   361  					// but that's ok because declareVar only collects the declInfo
   362  					// for a later phase.
   363  					d1 = &declInfo{file: fileScope, lhs: lhs, vtyp: d.spec.Type, init: d.spec.Values[0]}
   364  				}
   365  
   366  				// declare all variables
   367  				for i, name := range d.spec.Names {
   368  					obj := NewVar(name.Pos(), pkg, name.Name, nil)
   369  					lhs[i] = obj
   370  
   371  					di := d1
   372  					if di == nil {
   373  						// individual assignments
   374  						var init ast.Expr
   375  						if i < len(d.spec.Values) {
   376  							init = d.spec.Values[i]
   377  						}
   378  						di = &declInfo{file: fileScope, vtyp: d.spec.Type, init: init}
   379  					}
   380  
   381  					check.declarePkgObj(name, obj, di)
   382  				}
   383  			case typeDecl:
   384  				if d.spec.TypeParams.NumFields() != 0 && !check.allowVersion(pkg, 1, 18) {
   385  					check.softErrorf(d.spec.TypeParams.List[0], _UnsupportedFeature, "type parameters require go1.18 or later")
   386  				}
   387  				obj := NewTypeName(d.spec.Name.Pos(), pkg, d.spec.Name.Name, nil)
   388  				check.declarePkgObj(d.spec.Name, obj, &declInfo{file: fileScope, tdecl: d.spec})
   389  			case funcDecl:
   390  				name := d.decl.Name.Name
   391  				obj := NewFunc(d.decl.Name.Pos(), pkg, name, nil)
   392  				hasTParamError := false // avoid duplicate type parameter errors
   393  				if d.decl.Recv.NumFields() == 0 {
   394  					// regular function
   395  					if d.decl.Recv != nil {
   396  						check.error(d.decl.Recv, _BadRecv, "method is missing receiver")
   397  						// treat as function
   398  					}
   399  					if name == "init" || (name == "main" && check.pkg.name == "main") {
   400  						code := _InvalidInitDecl
   401  						if name == "main" {
   402  							code = _InvalidMainDecl
   403  						}
   404  						if d.decl.Type.TypeParams.NumFields() != 0 {
   405  							check.softErrorf(d.decl.Type.TypeParams.List[0], code, "func %s must have no type parameters", name)
   406  							hasTParamError = true
   407  						}
   408  						if t := d.decl.Type; t.Params.NumFields() != 0 || t.Results != nil {
   409  							// TODO(rFindley) Should this be a hard error?
   410  							check.softErrorf(d.decl, code, "func %s must have no arguments and no return values", name)
   411  						}
   412  					}
   413  					if name == "init" {
   414  						// don't declare init functions in the package scope - they are invisible
   415  						obj.parent = pkg.scope
   416  						check.recordDef(d.decl.Name, obj)
   417  						// init functions must have a body
   418  						if d.decl.Body == nil {
   419  							// TODO(gri) make this error message consistent with the others above
   420  							check.softErrorf(obj, _MissingInitBody, "missing function body")
   421  						}
   422  					} else {
   423  						check.declare(pkg.scope, d.decl.Name, obj, token.NoPos)
   424  					}
   425  				} else {
   426  					// method
   427  
   428  					// TODO(rFindley) earlier versions of this code checked that methods
   429  					//                have no type parameters, but this is checked later
   430  					//                when type checking the function type. Confirm that
   431  					//                we don't need to check tparams here.
   432  
   433  					ptr, recv, _ := check.unpackRecv(d.decl.Recv.List[0].Type, false)
   434  					// (Methods with invalid receiver cannot be associated to a type, and
   435  					// methods with blank _ names are never found; no need to collect any
   436  					// of them. They will still be type-checked with all the other functions.)
   437  					if recv != nil && name != "_" {
   438  						methods = append(methods, methodInfo{obj, ptr, recv})
   439  					}
   440  					check.recordDef(d.decl.Name, obj)
   441  				}
   442  				if d.decl.Type.TypeParams.NumFields() != 0 && !check.allowVersion(pkg, 1, 18) && !hasTParamError {
   443  					check.softErrorf(d.decl.Type.TypeParams.List[0], _UnsupportedFeature, "type parameters require go1.18 or later")
   444  				}
   445  				info := &declInfo{file: fileScope, fdecl: d.decl}
   446  				// Methods are not package-level objects but we still track them in the
   447  				// object map so that we can handle them like regular functions (if the
   448  				// receiver is invalid); also we need their fdecl info when associating
   449  				// them with their receiver base type, below.
   450  				check.objMap[obj] = info
   451  				obj.setOrder(uint32(len(check.objMap)))
   452  			}
   453  		})
   454  	}
   455  
   456  	// verify that objects in package and file scopes have different names
   457  	for _, scope := range fileScopes {
   458  		for name, obj := range scope.elems {
   459  			if alt := pkg.scope.Lookup(name); alt != nil {
   460  				obj = resolve(name, obj)
   461  				if pkg, ok := obj.(*PkgName); ok {
   462  					check.errorf(alt, _DuplicateDecl, "%s already declared through import of %s", alt.Name(), pkg.Imported())
   463  					check.reportAltDecl(pkg)
   464  				} else {
   465  					check.errorf(alt, _DuplicateDecl, "%s already declared through dot-import of %s", alt.Name(), obj.Pkg())
   466  					// TODO(gri) dot-imported objects don't have a position; reportAltDecl won't print anything
   467  					check.reportAltDecl(obj)
   468  				}
   469  			}
   470  		}
   471  	}
   472  
   473  	// Now that we have all package scope objects and all methods,
   474  	// associate methods with receiver base type name where possible.
   475  	// Ignore methods that have an invalid receiver. They will be
   476  	// type-checked later, with regular functions.
   477  	if methods == nil {
   478  		return // nothing to do
   479  	}
   480  	check.methods = make(map[*TypeName][]*Func)
   481  	for i := range methods {
   482  		m := &methods[i]
   483  		// Determine the receiver base type and associate m with it.
   484  		ptr, base := check.resolveBaseTypeName(m.ptr, m.recv)
   485  		if base != nil {
   486  			m.obj.hasPtrRecv_ = ptr
   487  			check.methods[base] = append(check.methods[base], m.obj)
   488  		}
   489  	}
   490  }
   491  
   492  // unpackRecv unpacks a receiver type and returns its components: ptr indicates whether
   493  // rtyp is a pointer receiver, rname is the receiver type name, and tparams are its
   494  // type parameters, if any. The type parameters are only unpacked if unpackParams is
   495  // set. If rname is nil, the receiver is unusable (i.e., the source has a bug which we
   496  // cannot easily work around).
   497  func (check *Checker) unpackRecv(rtyp ast.Expr, unpackParams bool) (ptr bool, rname *ast.Ident, tparams []*ast.Ident) {
   498  L: // unpack receiver type
   499  	// This accepts invalid receivers such as ***T and does not
   500  	// work for other invalid receivers, but we don't care. The
   501  	// validity of receiver expressions is checked elsewhere.
   502  	for {
   503  		switch t := rtyp.(type) {
   504  		case *ast.ParenExpr:
   505  			rtyp = t.X
   506  		case *ast.StarExpr:
   507  			ptr = true
   508  			rtyp = t.X
   509  		default:
   510  			break L
   511  		}
   512  	}
   513  
   514  	// unpack type parameters, if any
   515  	switch rtyp.(type) {
   516  	case *ast.IndexExpr, *ast.IndexListExpr:
   517  		ix := typeparams.UnpackIndexExpr(rtyp)
   518  		rtyp = ix.X
   519  		if unpackParams {
   520  			for _, arg := range ix.Indices {
   521  				var par *ast.Ident
   522  				switch arg := arg.(type) {
   523  				case *ast.Ident:
   524  					par = arg
   525  				case *ast.BadExpr:
   526  					// ignore - error already reported by parser
   527  				case nil:
   528  					check.invalidAST(ix.Orig, "parameterized receiver contains nil parameters")
   529  				default:
   530  					check.errorf(arg, _BadDecl, "receiver type parameter %s must be an identifier", arg)
   531  				}
   532  				if par == nil {
   533  					par = &ast.Ident{NamePos: arg.Pos(), Name: "_"}
   534  				}
   535  				tparams = append(tparams, par)
   536  			}
   537  		}
   538  	}
   539  
   540  	// unpack receiver name
   541  	if name, _ := rtyp.(*ast.Ident); name != nil {
   542  		rname = name
   543  	}
   544  
   545  	return
   546  }
   547  
   548  // resolveBaseTypeName returns the non-alias base type name for typ, and whether
   549  // there was a pointer indirection to get to it. The base type name must be declared
   550  // in package scope, and there can be at most one pointer indirection. If no such type
   551  // name exists, the returned base is nil.
   552  func (check *Checker) resolveBaseTypeName(seenPtr bool, name *ast.Ident) (ptr bool, base *TypeName) {
   553  	// Algorithm: Starting from a type expression, which may be a name,
   554  	// we follow that type through alias declarations until we reach a
   555  	// non-alias type name. If we encounter anything but pointer types or
   556  	// parentheses we're done. If we encounter more than one pointer type
   557  	// we're done.
   558  	ptr = seenPtr
   559  	var seen map[*TypeName]bool
   560  	var typ ast.Expr = name
   561  	for {
   562  		typ = unparen(typ)
   563  
   564  		// check if we have a pointer type
   565  		if pexpr, _ := typ.(*ast.StarExpr); pexpr != nil {
   566  			// if we've already seen a pointer, we're done
   567  			if ptr {
   568  				return false, nil
   569  			}
   570  			ptr = true
   571  			typ = unparen(pexpr.X) // continue with pointer base type
   572  		}
   573  
   574  		// typ must be a name
   575  		name, _ := typ.(*ast.Ident)
   576  		if name == nil {
   577  			return false, nil
   578  		}
   579  
   580  		// name must denote an object found in the current package scope
   581  		// (note that dot-imported objects are not in the package scope!)
   582  		obj := check.pkg.scope.Lookup(name.Name)
   583  		if obj == nil {
   584  			return false, nil
   585  		}
   586  
   587  		// the object must be a type name...
   588  		tname, _ := obj.(*TypeName)
   589  		if tname == nil {
   590  			return false, nil
   591  		}
   592  
   593  		// ... which we have not seen before
   594  		if seen[tname] {
   595  			return false, nil
   596  		}
   597  
   598  		// we're done if tdecl defined tname as a new type
   599  		// (rather than an alias)
   600  		tdecl := check.objMap[tname].tdecl // must exist for objects in package scope
   601  		if !tdecl.Assign.IsValid() {
   602  			return ptr, tname
   603  		}
   604  
   605  		// otherwise, continue resolving
   606  		typ = tdecl.Type
   607  		if seen == nil {
   608  			seen = make(map[*TypeName]bool)
   609  		}
   610  		seen[tname] = true
   611  	}
   612  }
   613  
   614  // packageObjects typechecks all package objects, but not function bodies.
   615  func (check *Checker) packageObjects() {
   616  	// process package objects in source order for reproducible results
   617  	objList := make([]Object, len(check.objMap))
   618  	i := 0
   619  	for obj := range check.objMap {
   620  		objList[i] = obj
   621  		i++
   622  	}
   623  	sort.Sort(inSourceOrder(objList))
   624  
   625  	// add new methods to already type-checked types (from a prior Checker.Files call)
   626  	for _, obj := range objList {
   627  		if obj, _ := obj.(*TypeName); obj != nil && obj.typ != nil {
   628  			check.collectMethods(obj)
   629  		}
   630  	}
   631  
   632  	// We process non-alias type declarations first, followed by alias declarations,
   633  	// and then everything else. This appears to avoid most situations where the type
   634  	// of an alias is needed before it is available.
   635  	// There may still be cases where this is not good enough (see also issue #25838).
   636  	// In those cases Checker.ident will report an error ("invalid use of type alias").
   637  	var aliasList []*TypeName
   638  	var othersList []Object // everything that's not a type
   639  	// phase 1: non-alias type declarations
   640  	for _, obj := range objList {
   641  		if tname, _ := obj.(*TypeName); tname != nil {
   642  			if check.objMap[tname].tdecl.Assign.IsValid() {
   643  				aliasList = append(aliasList, tname)
   644  			} else {
   645  				check.objDecl(obj, nil)
   646  			}
   647  		} else {
   648  			othersList = append(othersList, obj)
   649  		}
   650  	}
   651  	// phase 2: alias type declarations
   652  	for _, obj := range aliasList {
   653  		check.objDecl(obj, nil)
   654  	}
   655  	// phase 3: all other declarations
   656  	for _, obj := range othersList {
   657  		check.objDecl(obj, nil)
   658  	}
   659  
   660  	// At this point we may have a non-empty check.methods map; this means that not all
   661  	// entries were deleted at the end of typeDecl because the respective receiver base
   662  	// types were not found. In that case, an error was reported when declaring those
   663  	// methods. We can now safely discard this map.
   664  	check.methods = nil
   665  }
   666  
   667  // inSourceOrder implements the sort.Sort interface.
   668  type inSourceOrder []Object
   669  
   670  func (a inSourceOrder) Len() int           { return len(a) }
   671  func (a inSourceOrder) Less(i, j int) bool { return a[i].order() < a[j].order() }
   672  func (a inSourceOrder) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
   673  
   674  // unusedImports checks for unused imports.
   675  func (check *Checker) unusedImports() {
   676  	// if function bodies are not checked, packages' uses are likely missing - don't check
   677  	if check.conf.IgnoreFuncBodies {
   678  		return
   679  	}
   680  
   681  	// spec: "It is illegal (...) to directly import a package without referring to
   682  	// any of its exported identifiers. To import a package solely for its side-effects
   683  	// (initialization), use the blank identifier as explicit package name."
   684  
   685  	for _, obj := range check.imports {
   686  		if !obj.used && obj.name != "_" {
   687  			check.errorUnusedPkg(obj)
   688  		}
   689  	}
   690  }
   691  
   692  func (check *Checker) errorUnusedPkg(obj *PkgName) {
   693  	// If the package was imported with a name other than the final
   694  	// import path element, show it explicitly in the error message.
   695  	// Note that this handles both renamed imports and imports of
   696  	// packages containing unconventional package declarations.
   697  	// Note that this uses / always, even on Windows, because Go import
   698  	// paths always use forward slashes.
   699  	path := obj.imported.path
   700  	elem := path
   701  	if i := strings.LastIndex(elem, "/"); i >= 0 {
   702  		elem = elem[i+1:]
   703  	}
   704  	if obj.name == "" || obj.name == "." || obj.name == elem {
   705  		check.softErrorf(obj, _UnusedImport, "%q imported but not used", path)
   706  	} else {
   707  		check.softErrorf(obj, _UnusedImport, "%q imported but not used as %s", path, obj.name)
   708  	}
   709  }
   710  
   711  // dir makes a good-faith attempt to return the directory
   712  // portion of path. If path is empty, the result is ".".
   713  // (Per the go/build package dependency tests, we cannot import
   714  // path/filepath and simply use filepath.Dir.)
   715  func dir(path string) string {
   716  	if i := strings.LastIndexAny(path, `/\`); i > 0 {
   717  		return path[:i]
   718  	}
   719  	// i <= 0
   720  	return "."
   721  }
   722  

View as plain text