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  	"cmp"
     9  	"fmt"
    10  	"go/ast"
    11  	"go/constant"
    12  	"go/token"
    13  	. "internal/types/errors"
    14  	"slices"
    15  	"strconv"
    16  	"strings"
    17  	"unicode"
    18  )
    19  
    20  // A declInfo describes a package-level const, type, var, or func declaration.
    21  type declInfo struct {
    22  	file      *Scope        // scope of file containing this declaration
    23  	version   goVersion     // Go version of file containing this declaration
    24  	lhs       []*Var        // lhs of n:1 variable declarations, or nil
    25  	vtyp      ast.Expr      // type, or nil (for const and var declarations only)
    26  	init      ast.Expr      // init/orig expression, or nil (for const and var declarations only)
    27  	inherited bool          // if set, the init expression is inherited from a previous constant declaration
    28  	tdecl     *ast.TypeSpec // type declaration, or nil
    29  	fdecl     *ast.FuncDecl // func declaration, or nil
    30  
    31  	// The deps field tracks initialization expression dependencies.
    32  	deps map[Object]bool // lazily initialized
    33  }
    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(map[Object]bool)
    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  	const code = WrongAssignCount
    63  	switch {
    64  	case init == nil && r == 0:
    65  		// var decl w/o init expr
    66  		if s.Type == nil {
    67  			check.error(s, code, "missing type or init expr")
    68  		}
    69  	case l < r:
    70  		if l < len(s.Values) {
    71  			// init exprs from s
    72  			n := s.Values[l]
    73  			check.errorf(n, code, "extra init expr %s", n)
    74  			// TODO(gri) avoid declared and not used error here
    75  		} else {
    76  			// init exprs "inherited"
    77  			check.errorf(s, code, "extra init expr at %s", check.fset.Position(init.Pos()))
    78  			// TODO(gri) avoid declared and not used error here
    79  		}
    80  	case l > r && (init != nil || r != 1):
    81  		n := s.Names[r]
    82  		check.errorf(n, code, "missing init expr for %s", n)
    83  	}
    84  }
    85  
    86  func validatedImportPath(path string) (string, error) {
    87  	s, err := strconv.Unquote(path)
    88  	if err != nil {
    89  		return "", err
    90  	}
    91  	if s == "" {
    92  		return "", fmt.Errorf("empty string")
    93  	}
    94  	const illegalChars = `!"#$%&'()*,:;<=>?[\]^{|}` + "`\uFFFD"
    95  	for _, r := range s {
    96  		if !unicode.IsGraphic(r) || unicode.IsSpace(r) || strings.ContainsRune(illegalChars, r) {
    97  			return s, fmt.Errorf("invalid character %#U", r)
    98  		}
    99  	}
   100  	return s, nil
   101  }
   102  
   103  // declarePkgObj declares obj in the package scope, records its ident -> obj mapping,
   104  // and updates check.objMap. The object must not be a function or method.
   105  func (check *Checker) declarePkgObj(ident *ast.Ident, obj Object, d *declInfo) {
   106  	assert(ident.Name == obj.Name())
   107  
   108  	// spec: "A package-scope or file-scope identifier with name init
   109  	// may only be declared to be a function with this (func()) signature."
   110  	if ident.Name == "init" {
   111  		check.error(ident, InvalidInitDecl, "cannot declare init - must be func")
   112  		return
   113  	}
   114  
   115  	// spec: "The main package must have package name main and declare
   116  	// a function main that takes no arguments and returns no value."
   117  	if ident.Name == "main" && check.pkg.name == "main" {
   118  		check.error(ident, InvalidMainDecl, "cannot declare main - must be func")
   119  		return
   120  	}
   121  
   122  	check.declare(check.pkg.scope, ident, obj, nopos)
   123  	check.objMap[obj] = d
   124  	obj.setOrder(uint32(len(check.objMap)))
   125  }
   126  
   127  // filename returns a filename suitable for debugging output.
   128  func (check *Checker) filename(fileNo int) string {
   129  	file := check.files[fileNo]
   130  	if pos := file.Pos(); pos.IsValid() {
   131  		return check.fset.File(pos).Name()
   132  	}
   133  	return fmt.Sprintf("file[%d]", fileNo)
   134  }
   135  
   136  func (check *Checker) importPackage(at positioner, path, dir string) *Package {
   137  	// If we already have a package for the given (path, dir)
   138  	// pair, use it instead of doing a full import.
   139  	// Checker.impMap only caches packages that are marked Complete
   140  	// or fake (dummy packages for failed imports). Incomplete but
   141  	// non-fake packages do require an import to complete them.
   142  	key := importKey{path, dir}
   143  	imp := check.impMap[key]
   144  	if imp != nil {
   145  		return imp
   146  	}
   147  
   148  	// no package yet => import it
   149  	if path == "C" && (check.conf.FakeImportC || check.conf.go115UsesCgo) {
   150  		if check.conf.FakeImportC && check.conf.go115UsesCgo {
   151  			check.error(at, BadImportPath, "cannot use FakeImportC and go115UsesCgo together")
   152  		}
   153  		imp = NewPackage("C", "C")
   154  		imp.fake = true // package scope is not populated
   155  		imp.cgo = check.conf.go115UsesCgo
   156  	} else {
   157  		// ordinary import
   158  		var err error
   159  		if importer := check.conf.Importer; importer == nil {
   160  			err = fmt.Errorf("Config.Importer not installed")
   161  		} else if importerFrom, ok := importer.(ImporterFrom); ok {
   162  			imp, err = importerFrom.ImportFrom(path, dir, 0)
   163  			if imp == nil && err == nil {
   164  				err = fmt.Errorf("Config.Importer.ImportFrom(%s, %s, 0) returned nil but no error", path, dir)
   165  			}
   166  		} else {
   167  			imp, err = importer.Import(path)
   168  			if imp == nil && err == nil {
   169  				err = fmt.Errorf("Config.Importer.Import(%s) returned nil but no error", path)
   170  			}
   171  		}
   172  		// make sure we have a valid package name
   173  		// (errors here can only happen through manipulation of packages after creation)
   174  		if err == nil && imp != nil && (imp.name == "_" || imp.name == "") {
   175  			err = fmt.Errorf("invalid package name: %q", imp.name)
   176  			imp = nil // create fake package below
   177  		}
   178  		if err != nil {
   179  			check.errorf(at, BrokenImport, "could not import %s (%s)", path, err)
   180  			if imp == nil {
   181  				// create a new fake package
   182  				// come up with a sensible package name (heuristic)
   183  				name := path
   184  				if i := len(name); i > 0 && name[i-1] == '/' {
   185  					name = name[:i-1]
   186  				}
   187  				if i := strings.LastIndex(name, "/"); i >= 0 {
   188  					name = name[i+1:]
   189  				}
   190  				imp = NewPackage(path, name)
   191  			}
   192  			// continue to use the package as best as we can
   193  			imp.fake = true // avoid follow-up lookup failures
   194  		}
   195  	}
   196  
   197  	// package should be complete or marked fake, but be cautious
   198  	if imp.complete || imp.fake {
   199  		check.impMap[key] = imp
   200  		// Once we've formatted an error message, keep the pkgPathMap
   201  		// up-to-date on subsequent imports. It is used for package
   202  		// qualification in error messages.
   203  		if check.pkgPathMap != nil {
   204  			check.markImports(imp)
   205  		}
   206  		return imp
   207  	}
   208  
   209  	// something went wrong (importer may have returned incomplete package without error)
   210  	return nil
   211  }
   212  
   213  // collectObjects collects all file and package objects and inserts them
   214  // into their respective scopes. It also performs imports and associates
   215  // methods with receiver base type names.
   216  func (check *Checker) collectObjects() {
   217  	pkg := check.pkg
   218  
   219  	// pkgImports is the set of packages already imported by any package file seen
   220  	// so far. Used to avoid duplicate entries in pkg.imports. Allocate and populate
   221  	// it (pkg.imports may not be empty if we are checking test files incrementally).
   222  	// Note that pkgImports is keyed by package (and thus package path), not by an
   223  	// importKey value. Two different importKey values may map to the same package
   224  	// which is why we cannot use the check.impMap here.
   225  	var pkgImports = make(map[*Package]bool)
   226  	for _, imp := range pkg.imports {
   227  		pkgImports[imp] = true
   228  	}
   229  
   230  	type methodInfo struct {
   231  		obj  *Func      // method
   232  		ptr  bool       // true if pointer receiver
   233  		recv *ast.Ident // receiver type name
   234  	}
   235  	var methods []methodInfo // collected methods with valid receivers and non-blank _ names
   236  
   237  	fileScopes := make([]*Scope, len(check.files)) // fileScopes[i] corresponds to check.files[i]
   238  	for fileNo, file := range check.files {
   239  		check.version = asGoVersion(check.versions[file])
   240  
   241  		// The package identifier denotes the current package,
   242  		// but there is no corresponding package object.
   243  		check.recordDef(file.Name, nil)
   244  
   245  		// Use the actual source file extent rather than *ast.File extent since the
   246  		// latter doesn't include comments which appear at the start or end of the file.
   247  		// Be conservative and use the *ast.File extent if we don't have a *token.File.
   248  		pos, end := file.Pos(), file.End()
   249  		if f := check.fset.File(file.Pos()); f != nil {
   250  			pos, end = token.Pos(f.Base()), token.Pos(f.Base()+f.Size())
   251  		}
   252  		fileScope := NewScope(pkg.scope, pos, end, check.filename(fileNo))
   253  		fileScopes[fileNo] = fileScope
   254  		check.recordScope(file, fileScope)
   255  
   256  		// determine file directory, necessary to resolve imports
   257  		// FileName may be "" (typically for tests) in which case
   258  		// we get "." as the directory which is what we would want.
   259  		fileDir := dir(check.fset.Position(file.Name.Pos()).Filename)
   260  
   261  		check.walkDecls(file.Decls, func(d decl) {
   262  			switch d := d.(type) {
   263  			case importDecl:
   264  				// import package
   265  				if d.spec.Path.Value == "" {
   266  					return // error reported by parser
   267  				}
   268  				path, err := validatedImportPath(d.spec.Path.Value)
   269  				if err != nil {
   270  					check.errorf(d.spec.Path, BadImportPath, "invalid import path (%s)", err)
   271  					return
   272  				}
   273  
   274  				imp := check.importPackage(d.spec.Path, path, fileDir)
   275  				if imp == nil {
   276  					return
   277  				}
   278  
   279  				// local name overrides imported package name
   280  				name := imp.name
   281  				if d.spec.Name != nil {
   282  					name = d.spec.Name.Name
   283  					if path == "C" {
   284  						// match 1.17 cmd/compile (not prescribed by spec)
   285  						check.error(d.spec.Name, ImportCRenamed, `cannot rename import "C"`)
   286  						return
   287  					}
   288  				}
   289  
   290  				if name == "init" {
   291  					check.error(d.spec, InvalidInitDecl, "cannot import package as init - init must be a func")
   292  					return
   293  				}
   294  
   295  				// add package to list of explicit imports
   296  				// (this functionality is provided as a convenience
   297  				// for clients; it is not needed for type-checking)
   298  				if !pkgImports[imp] {
   299  					pkgImports[imp] = true
   300  					pkg.imports = append(pkg.imports, imp)
   301  				}
   302  
   303  				pkgName := NewPkgName(d.spec.Pos(), pkg, name, imp)
   304  				if d.spec.Name != nil {
   305  					// in a dot-import, the dot represents the package
   306  					check.recordDef(d.spec.Name, pkgName)
   307  				} else {
   308  					check.recordImplicit(d.spec, pkgName)
   309  				}
   310  
   311  				if imp.fake {
   312  					// match 1.17 cmd/compile (not prescribed by spec)
   313  					pkgName.used = true
   314  				}
   315  
   316  				// add import to file scope
   317  				check.imports = append(check.imports, pkgName)
   318  				if name == "." {
   319  					// dot-import
   320  					if check.dotImportMap == nil {
   321  						check.dotImportMap = make(map[dotImportKey]*PkgName)
   322  					}
   323  					// merge imported scope with file scope
   324  					for name, obj := range imp.scope.elems {
   325  						// Note: Avoid eager resolve(name, obj) here, so we only
   326  						// resolve dot-imported objects as needed.
   327  
   328  						// A package scope may contain non-exported objects,
   329  						// do not import them!
   330  						if token.IsExported(name) {
   331  							// declare dot-imported object
   332  							// (Do not use check.declare because it modifies the object
   333  							// via Object.setScopePos, which leads to a race condition;
   334  							// the object may be imported into more than one file scope
   335  							// concurrently. See go.dev/issue/32154.)
   336  							if alt := fileScope.Lookup(name); alt != nil {
   337  								err := check.newError(DuplicateDecl)
   338  								err.addf(d.spec.Name, "%s redeclared in this block", alt.Name())
   339  								err.addAltDecl(alt)
   340  								err.report()
   341  							} else {
   342  								fileScope.insert(name, obj)
   343  								check.dotImportMap[dotImportKey{fileScope, name}] = pkgName
   344  							}
   345  						}
   346  					}
   347  				} else {
   348  					// declare imported package object in file scope
   349  					// (no need to provide s.Name since we called check.recordDef earlier)
   350  					check.declare(fileScope, nil, pkgName, nopos)
   351  				}
   352  			case constDecl:
   353  				// declare all constants
   354  				for i, name := range d.spec.Names {
   355  					obj := NewConst(name.Pos(), pkg, name.Name, nil, constant.MakeInt64(int64(d.iota)))
   356  
   357  					var init ast.Expr
   358  					if i < len(d.init) {
   359  						init = d.init[i]
   360  					}
   361  
   362  					d := &declInfo{file: fileScope, version: check.version, vtyp: d.typ, init: init, inherited: d.inherited}
   363  					check.declarePkgObj(name, obj, d)
   364  				}
   365  
   366  			case varDecl:
   367  				lhs := make([]*Var, len(d.spec.Names))
   368  				// If there's exactly one rhs initializer, use
   369  				// the same declInfo d1 for all lhs variables
   370  				// so that each lhs variable depends on the same
   371  				// rhs initializer (n:1 var declaration).
   372  				var d1 *declInfo
   373  				if len(d.spec.Values) == 1 {
   374  					// The lhs elements are only set up after the for loop below,
   375  					// but that's ok because declareVar only collects the declInfo
   376  					// for a later phase.
   377  					d1 = &declInfo{file: fileScope, version: check.version, lhs: lhs, vtyp: d.spec.Type, init: d.spec.Values[0]}
   378  				}
   379  
   380  				// declare all variables
   381  				for i, name := range d.spec.Names {
   382  					obj := NewVar(name.Pos(), pkg, name.Name, nil)
   383  					lhs[i] = obj
   384  
   385  					di := d1
   386  					if di == nil {
   387  						// individual assignments
   388  						var init ast.Expr
   389  						if i < len(d.spec.Values) {
   390  							init = d.spec.Values[i]
   391  						}
   392  						di = &declInfo{file: fileScope, version: check.version, vtyp: d.spec.Type, init: init}
   393  					}
   394  
   395  					check.declarePkgObj(name, obj, di)
   396  				}
   397  			case typeDecl:
   398  				obj := NewTypeName(d.spec.Name.Pos(), pkg, d.spec.Name.Name, nil)
   399  				check.declarePkgObj(d.spec.Name, obj, &declInfo{file: fileScope, version: check.version, tdecl: d.spec})
   400  			case funcDecl:
   401  				name := d.decl.Name.Name
   402  				obj := NewFunc(d.decl.Name.Pos(), pkg, name, nil) // signature set later
   403  				hasTParamError := false                           // avoid duplicate type parameter errors
   404  				if d.decl.Recv.NumFields() == 0 {
   405  					// regular function
   406  					if d.decl.Recv != nil {
   407  						check.error(d.decl.Recv, BadRecv, "method has no receiver")
   408  						// treat as function
   409  					}
   410  					if name == "init" || (name == "main" && check.pkg.name == "main") {
   411  						code := InvalidInitDecl
   412  						if name == "main" {
   413  							code = InvalidMainDecl
   414  						}
   415  						if d.decl.Type.TypeParams.NumFields() != 0 {
   416  							check.softErrorf(d.decl.Type.TypeParams.List[0], code, "func %s must have no type parameters", name)
   417  							hasTParamError = true
   418  						}
   419  						if t := d.decl.Type; t.Params.NumFields() != 0 || t.Results != nil {
   420  							// TODO(rFindley) Should this be a hard error?
   421  							check.softErrorf(d.decl.Name, code, "func %s must have no arguments and no return values", name)
   422  						}
   423  					}
   424  					if name == "init" {
   425  						// don't declare init functions in the package scope - they are invisible
   426  						obj.parent = pkg.scope
   427  						check.recordDef(d.decl.Name, obj)
   428  						// init functions must have a body
   429  						if d.decl.Body == nil {
   430  							// TODO(gri) make this error message consistent with the others above
   431  							check.softErrorf(obj, MissingInitBody, "missing function body")
   432  						}
   433  					} else {
   434  						check.declare(pkg.scope, d.decl.Name, obj, nopos)
   435  					}
   436  				} else {
   437  					// method
   438  
   439  					// TODO(rFindley) earlier versions of this code checked that methods
   440  					//                have no type parameters, but this is checked later
   441  					//                when type checking the function type. Confirm that
   442  					//                we don't need to check tparams here.
   443  
   444  					ptr, base, _ := check.unpackRecv(d.decl.Recv.List[0].Type, false)
   445  					// (Methods with invalid receiver cannot be associated to a type, and
   446  					// methods with blank _ names are never found; no need to collect any
   447  					// of them. They will still be type-checked with all the other functions.)
   448  					if recv, _ := base.(*ast.Ident); recv != nil && name != "_" {
   449  						methods = append(methods, methodInfo{obj, ptr, recv})
   450  					}
   451  					check.recordDef(d.decl.Name, obj)
   452  				}
   453  				_ = d.decl.Type.TypeParams.NumFields() != 0 && !hasTParamError && check.verifyVersionf(d.decl.Type.TypeParams.List[0], go1_18, "type parameter")
   454  				info := &declInfo{file: fileScope, version: check.version, fdecl: d.decl}
   455  				// Methods are not package-level objects but we still track them in the
   456  				// object map so that we can handle them like regular functions (if the
   457  				// receiver is invalid); also we need their fdecl info when associating
   458  				// them with their receiver base type, below.
   459  				check.objMap[obj] = info
   460  				obj.setOrder(uint32(len(check.objMap)))
   461  			}
   462  		})
   463  	}
   464  
   465  	// verify that objects in package and file scopes have different names
   466  	for _, scope := range fileScopes {
   467  		for name, obj := range scope.elems {
   468  			if alt := pkg.scope.Lookup(name); alt != nil {
   469  				obj = resolve(name, obj)
   470  				err := check.newError(DuplicateDecl)
   471  				if pkg, ok := obj.(*PkgName); ok {
   472  					err.addf(alt, "%s already declared through import of %s", alt.Name(), pkg.Imported())
   473  					err.addAltDecl(pkg)
   474  				} else {
   475  					err.addf(alt, "%s already declared through dot-import of %s", alt.Name(), obj.Pkg())
   476  					// TODO(gri) dot-imported objects don't have a position; addAltDecl won't print anything
   477  					err.addAltDecl(obj)
   478  				}
   479  				err.report()
   480  			}
   481  		}
   482  	}
   483  
   484  	// Now that we have all package scope objects and all methods,
   485  	// associate methods with receiver base type name where possible.
   486  	// Ignore methods that have an invalid receiver. They will be
   487  	// type-checked later, with regular functions.
   488  	if methods == nil {
   489  		return
   490  	}
   491  
   492  	// lookupScope returns the file scope which contains the given name,
   493  	// or nil if the name is not found in any scope. The search does not
   494  	// step inside blocks (function bodies).
   495  	// This function is only used in conjuction with import "C", and even
   496  	// then only rarely. It doesn't have to be particularly fast.
   497  	lookupScope := func(name *ast.Ident) *Scope {
   498  		for i, file := range check.files {
   499  			found := false
   500  			ast.Inspect(file, func(n ast.Node) bool {
   501  				if found {
   502  					return false // we're done
   503  				}
   504  				switch n := n.(type) {
   505  				case *ast.Ident:
   506  					if n == name {
   507  						found = true
   508  						return false
   509  					}
   510  				case *ast.BlockStmt:
   511  					return false // don't descend into function bodies
   512  				}
   513  				return true
   514  			})
   515  			if found {
   516  				return fileScopes[i]
   517  			}
   518  		}
   519  		return nil
   520  	}
   521  
   522  	check.methods = make(map[*TypeName][]*Func)
   523  	for i := range methods {
   524  		m := &methods[i]
   525  		// Determine the receiver base type and associate m with it.
   526  		ptr, base := check.resolveBaseTypeName(m.ptr, m.recv, lookupScope)
   527  		if base != nil {
   528  			m.obj.hasPtrRecv_ = ptr
   529  			check.methods[base] = append(check.methods[base], m.obj)
   530  		}
   531  	}
   532  }
   533  
   534  // unpackRecv unpacks a receiver type expression and returns its components: ptr indicates
   535  // whether rtyp is a pointer receiver, base is the receiver base type expression stripped
   536  // of its type parameters (if any), and tparams are its type parameter names, if any. The
   537  // type parameters are only unpacked if unpackParams is set. For instance, given the rtyp
   538  //
   539  //	*T[A, _]
   540  //
   541  // ptr is true, base is T, and tparams is [A, _] (assuming unpackParams is set).
   542  // Note that base may not be a *ast.Ident for erroneous programs.
   543  func (check *Checker) unpackRecv(rtyp ast.Expr, unpackParams bool) (ptr bool, base ast.Expr, tparams []*ast.Ident) {
   544  	// unpack receiver type
   545  	base = ast.Unparen(rtyp)
   546  	if t, _ := base.(*ast.StarExpr); t != nil {
   547  		ptr = true
   548  		base = ast.Unparen(t.X)
   549  	}
   550  
   551  	// unpack type parameters, if any
   552  	switch base.(type) {
   553  	case *ast.IndexExpr, *ast.IndexListExpr:
   554  		ix := unpackIndexedExpr(base)
   555  		base = ix.x
   556  		if unpackParams {
   557  			for _, arg := range ix.indices {
   558  				var par *ast.Ident
   559  				switch arg := arg.(type) {
   560  				case *ast.Ident:
   561  					par = arg
   562  				case *ast.BadExpr:
   563  					// ignore - error already reported by parser
   564  				case nil:
   565  					check.error(ix.orig, InvalidSyntaxTree, "parameterized receiver contains nil parameters")
   566  				default:
   567  					check.errorf(arg, BadDecl, "receiver type parameter %s must be an identifier", arg)
   568  				}
   569  				if par == nil {
   570  					par = &ast.Ident{NamePos: arg.Pos(), Name: "_"}
   571  				}
   572  				tparams = append(tparams, par)
   573  			}
   574  		}
   575  	}
   576  
   577  	return
   578  }
   579  
   580  // resolveBaseTypeName returns the non-alias base type name for typ, and whether
   581  // there was a pointer indirection to get to it. The base type name must be declared
   582  // in package scope, and there can be at most one pointer indirection. If no such type
   583  // name exists, the returned base is nil.
   584  func (check *Checker) resolveBaseTypeName(seenPtr bool, typ ast.Expr, lookupScope func(*ast.Ident) *Scope) (ptr bool, base *TypeName) {
   585  	// Algorithm: Starting from a type expression, which may be a name,
   586  	// we follow that type through alias declarations until we reach a
   587  	// non-alias type name. If we encounter anything but pointer types or
   588  	// parentheses we're done. If we encounter more than one pointer type
   589  	// we're done.
   590  	ptr = seenPtr
   591  	var seen map[*TypeName]bool
   592  	for {
   593  		// Note: this differs from types2, but is necessary. The syntax parser
   594  		// strips unnecessary parens.
   595  		typ = ast.Unparen(typ)
   596  
   597  		// check if we have a pointer type
   598  		if pexpr, _ := typ.(*ast.StarExpr); pexpr != nil {
   599  			// if we've already seen a pointer, we're done
   600  			if ptr {
   601  				return false, nil
   602  			}
   603  			ptr = true
   604  			typ = ast.Unparen(pexpr.X) // continue with pointer base type
   605  		}
   606  
   607  		// typ must be a name, or a C.name cgo selector.
   608  		var name string
   609  		switch typ := typ.(type) {
   610  		case *ast.Ident:
   611  			name = typ.Name
   612  		case *ast.SelectorExpr:
   613  			// C.struct_foo is a valid type name for packages using cgo.
   614  			// See go.dev/issue/59944.
   615  			// TODO(gri) why is it possible to associate methods with C types?
   616  			//
   617  			// Detect this case, and adjust name so that the correct TypeName is
   618  			// resolved below.
   619  			if ident, _ := typ.X.(*ast.Ident); ident != nil && ident.Name == "C" {
   620  				// Check whether "C" actually resolves to an import of "C", by looking
   621  				// in the appropriate file scope.
   622  				obj := lookupScope(ident).Lookup(ident.Name) // the fileScope must always be found
   623  				// If Config.go115UsesCgo is set, the typechecker will resolve Cgo
   624  				// selectors to their cgo name. We must do the same here.
   625  				if pname, _ := obj.(*PkgName); pname != nil {
   626  					if pname.imported.cgo { // only set if Config.go115UsesCgo is set
   627  						name = "_Ctype_" + typ.Sel.Name
   628  					}
   629  				}
   630  			}
   631  			if name == "" {
   632  				return false, nil
   633  			}
   634  		default:
   635  			return false, nil
   636  		}
   637  
   638  		// name must denote an object found in the current package scope
   639  		// (note that dot-imported objects are not in the package scope!)
   640  		obj := check.pkg.scope.Lookup(name)
   641  		if obj == nil {
   642  			return false, nil
   643  		}
   644  
   645  		// the object must be a type name...
   646  		tname, _ := obj.(*TypeName)
   647  		if tname == nil {
   648  			return false, nil
   649  		}
   650  
   651  		// ... which we have not seen before
   652  		if seen[tname] {
   653  			return false, nil
   654  		}
   655  
   656  		// we're done if tdecl defined tname as a new type
   657  		// (rather than an alias)
   658  		tdecl := check.objMap[tname].tdecl // must exist for objects in package scope
   659  		if !tdecl.Assign.IsValid() {
   660  			return ptr, tname
   661  		}
   662  
   663  		// otherwise, continue resolving
   664  		typ = tdecl.Type
   665  		if seen == nil {
   666  			seen = make(map[*TypeName]bool)
   667  		}
   668  		seen[tname] = true
   669  	}
   670  }
   671  
   672  // packageObjects typechecks all package objects, but not function bodies.
   673  func (check *Checker) packageObjects() {
   674  	// process package objects in source order for reproducible results
   675  	objList := make([]Object, len(check.objMap))
   676  	i := 0
   677  	for obj := range check.objMap {
   678  		objList[i] = obj
   679  		i++
   680  	}
   681  	slices.SortFunc(objList, func(a, b Object) int {
   682  		return cmp.Compare(a.order(), b.order())
   683  	})
   684  
   685  	// add new methods to already type-checked types (from a prior Checker.Files call)
   686  	for _, obj := range objList {
   687  		if obj, _ := obj.(*TypeName); obj != nil && obj.typ != nil {
   688  			check.collectMethods(obj)
   689  		}
   690  	}
   691  
   692  	if false && check.conf._EnableAlias {
   693  		// With Alias nodes we can process declarations in any order.
   694  		//
   695  		// TODO(adonovan): unfortunately, Alias nodes
   696  		// (GODEBUG=gotypesalias=1) don't entirely resolve
   697  		// problems with cycles. For example, in
   698  		// GOROOT/test/typeparam/issue50259.go,
   699  		//
   700  		// 	type T[_ any] struct{}
   701  		// 	type A T[B]
   702  		// 	type B = T[A]
   703  		//
   704  		// TypeName A has Type Named during checking, but by
   705  		// the time the unified export data is written out,
   706  		// its Type is Invalid.
   707  		//
   708  		// Investigate and reenable this branch.
   709  		for _, obj := range objList {
   710  			check.objDecl(obj, nil)
   711  		}
   712  	} else {
   713  		// Without Alias nodes, we process non-alias type declarations first, followed by
   714  		// alias declarations, and then everything else. This appears to avoid most situations
   715  		// where the type of an alias is needed before it is available.
   716  		// There may still be cases where this is not good enough (see also go.dev/issue/25838).
   717  		// In those cases Checker.ident will report an error ("invalid use of type alias").
   718  		var aliasList []*TypeName
   719  		var othersList []Object // everything that's not a type
   720  		// phase 1: non-alias type declarations
   721  		for _, obj := range objList {
   722  			if tname, _ := obj.(*TypeName); tname != nil {
   723  				if check.objMap[tname].tdecl.Assign.IsValid() {
   724  					aliasList = append(aliasList, tname)
   725  				} else {
   726  					check.objDecl(obj, nil)
   727  				}
   728  			} else {
   729  				othersList = append(othersList, obj)
   730  			}
   731  		}
   732  		// phase 2: alias type declarations
   733  		for _, obj := range aliasList {
   734  			check.objDecl(obj, nil)
   735  		}
   736  		// phase 3: all other declarations
   737  		for _, obj := range othersList {
   738  			check.objDecl(obj, nil)
   739  		}
   740  	}
   741  
   742  	// At this point we may have a non-empty check.methods map; this means that not all
   743  	// entries were deleted at the end of typeDecl because the respective receiver base
   744  	// types were not found. In that case, an error was reported when declaring those
   745  	// methods. We can now safely discard this map.
   746  	check.methods = nil
   747  }
   748  
   749  // unusedImports checks for unused imports.
   750  func (check *Checker) unusedImports() {
   751  	// If function bodies are not checked, packages' uses are likely missing - don't check.
   752  	if check.conf.IgnoreFuncBodies {
   753  		return
   754  	}
   755  
   756  	// spec: "It is illegal (...) to directly import a package without referring to
   757  	// any of its exported identifiers. To import a package solely for its side-effects
   758  	// (initialization), use the blank identifier as explicit package name."
   759  
   760  	for _, obj := range check.imports {
   761  		if !obj.used && obj.name != "_" {
   762  			check.errorUnusedPkg(obj)
   763  		}
   764  	}
   765  }
   766  
   767  func (check *Checker) errorUnusedPkg(obj *PkgName) {
   768  	// If the package was imported with a name other than the final
   769  	// import path element, show it explicitly in the error message.
   770  	// Note that this handles both renamed imports and imports of
   771  	// packages containing unconventional package declarations.
   772  	// Note that this uses / always, even on Windows, because Go import
   773  	// paths always use forward slashes.
   774  	path := obj.imported.path
   775  	elem := path
   776  	if i := strings.LastIndex(elem, "/"); i >= 0 {
   777  		elem = elem[i+1:]
   778  	}
   779  	if obj.name == "" || obj.name == "." || obj.name == elem {
   780  		check.softErrorf(obj, UnusedImport, "%q imported and not used", path)
   781  	} else {
   782  		check.softErrorf(obj, UnusedImport, "%q imported as %s and not used", path, obj.name)
   783  	}
   784  }
   785  
   786  // dir makes a good-faith attempt to return the directory
   787  // portion of path. If path is empty, the result is ".".
   788  // (Per the go/build package dependency tests, we cannot import
   789  // path/filepath and simply use filepath.Dir.)
   790  func dir(path string) string {
   791  	if i := strings.LastIndexAny(path, `/\`); i > 0 {
   792  		return path[:i]
   793  	}
   794  	// i <= 0
   795  	return "."
   796  }
   797  

View as plain text