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

View as plain text