github.com/bir3/gocompiler@v0.3.205/src/go/types/check.go (about)

     1  // Copyright 2011 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  // This file implements the Check function, which drives type-checking.
     6  
     7  package types
     8  
     9  import (
    10  	"errors"
    11  	"fmt"
    12  	"github.com/bir3/gocompiler/src/go/ast"
    13  	"github.com/bir3/gocompiler/src/go/constant"
    14  	"github.com/bir3/gocompiler/src/go/token"
    15  	. "github.com/bir3/gocompiler/src/internal/types/errors"
    16  )
    17  
    18  // debugging/development support
    19  const (
    20  	debug = false // leave on during development
    21  	trace = false // turn on for detailed type resolution traces
    22  )
    23  
    24  // exprInfo stores information about an untyped expression.
    25  type exprInfo struct {
    26  	isLhs bool // expression is lhs operand of a shift with delayed type-check
    27  	mode  operandMode
    28  	typ   *Basic
    29  	val   constant.Value // constant value; or nil (if not a constant)
    30  }
    31  
    32  // An environment represents the environment within which an object is
    33  // type-checked.
    34  type environment struct {
    35  	decl          *declInfo              // package-level declaration whose init expression/function body is checked
    36  	scope         *Scope                 // top-most scope for lookups
    37  	pos           token.Pos              // if valid, identifiers are looked up as if at position pos (used by Eval)
    38  	iota          constant.Value         // value of iota in a constant declaration; nil otherwise
    39  	errpos        positioner             // if set, identifier position of a constant with inherited initializer
    40  	inTParamList  bool                   // set if inside a type parameter list
    41  	sig           *Signature             // function signature if inside a function; nil otherwise
    42  	isPanic       map[*ast.CallExpr]bool // set of panic call expressions (used for termination check)
    43  	hasLabel      bool                   // set if a function makes use of labels (only ~1% of functions); unused outside functions
    44  	hasCallOrRecv bool                   // set if an expression contains a function call or channel receive operation
    45  }
    46  
    47  // lookup looks up name in the current environment and returns the matching object, or nil.
    48  func (env *environment) lookup(name string) Object {
    49  	_, obj := env.scope.LookupParent(name, env.pos)
    50  	return obj
    51  }
    52  
    53  // An importKey identifies an imported package by import path and source directory
    54  // (directory containing the file containing the import). In practice, the directory
    55  // may always be the same, or may not matter. Given an (import path, directory), an
    56  // importer must always return the same package (but given two different import paths,
    57  // an importer may still return the same package by mapping them to the same package
    58  // paths).
    59  type importKey struct {
    60  	path, dir string
    61  }
    62  
    63  // A dotImportKey describes a dot-imported object in the given scope.
    64  type dotImportKey struct {
    65  	scope *Scope
    66  	name  string
    67  }
    68  
    69  // An action describes a (delayed) action.
    70  type action struct {
    71  	f    func()      // action to be executed
    72  	desc *actionDesc // action description; may be nil, requires debug to be set
    73  }
    74  
    75  // If debug is set, describef sets a printf-formatted description for action a.
    76  // Otherwise, it is a no-op.
    77  func (a *action) describef(pos positioner, format string, args ...any) {
    78  	if debug {
    79  		a.desc = &actionDesc{pos, format, args}
    80  	}
    81  }
    82  
    83  // An actionDesc provides information on an action.
    84  // For debugging only.
    85  type actionDesc struct {
    86  	pos    positioner
    87  	format string
    88  	args   []any
    89  }
    90  
    91  // A Checker maintains the state of the type checker.
    92  // It must be created with NewChecker.
    93  type Checker struct {
    94  	// package information
    95  	// (initialized by NewChecker, valid for the life-time of checker)
    96  	conf *Config
    97  	ctxt *Context // context for de-duplicating instances
    98  	fset *token.FileSet
    99  	pkg  *Package
   100  	*Info
   101  	version version                // accepted language version
   102  	nextID  uint64                 // unique Id for type parameters (first valid Id is 1)
   103  	objMap  map[Object]*declInfo   // maps package-level objects and (non-interface) methods to declaration info
   104  	impMap  map[importKey]*Package // maps (import path, source directory) to (complete or fake) package
   105  	valids  instanceLookup         // valid *Named (incl. instantiated) types per the validType check
   106  
   107  	// pkgPathMap maps package names to the set of distinct import paths we've
   108  	// seen for that name, anywhere in the import graph. It is used for
   109  	// disambiguating package names in error messages.
   110  	//
   111  	// pkgPathMap is allocated lazily, so that we don't pay the price of building
   112  	// it on the happy path. seenPkgMap tracks the packages that we've already
   113  	// walked.
   114  	pkgPathMap map[string]map[string]bool
   115  	seenPkgMap map[*Package]bool
   116  
   117  	// information collected during type-checking of a set of package files
   118  	// (initialized by Files, valid only for the duration of check.Files;
   119  	// maps and lists are allocated on demand)
   120  	files         []*ast.File               // package files
   121  	imports       []*PkgName                // list of imported packages
   122  	dotImportMap  map[dotImportKey]*PkgName // maps dot-imported objects to the package they were dot-imported through
   123  	recvTParamMap map[*ast.Ident]*TypeParam // maps blank receiver type parameters to their type
   124  	brokenAliases map[*TypeName]bool        // set of aliases with broken (not yet determined) types
   125  	unionTypeSets map[*Union]*_TypeSet      // computed type sets for union types
   126  	mono          monoGraph                 // graph for detecting non-monomorphizable instantiation loops
   127  
   128  	firstErr error                 // first error encountered
   129  	methods  map[*TypeName][]*Func // maps package scope type names to associated non-blank (non-interface) methods
   130  	untyped  map[ast.Expr]exprInfo // map of expressions without final type
   131  	delayed  []action              // stack of delayed action segments; segments are processed in FIFO order
   132  	objPath  []Object              // path of object dependencies during type inference (for cycle reporting)
   133  	cleaners []cleaner             // list of types that may need a final cleanup at the end of type-checking
   134  
   135  	// environment within which the current object is type-checked (valid only
   136  	// for the duration of type-checking a specific object)
   137  	environment
   138  
   139  	// debugging
   140  	indent int // indentation for tracing
   141  }
   142  
   143  // addDeclDep adds the dependency edge (check.decl -> to) if check.decl exists
   144  func (check *Checker) addDeclDep(to Object) {
   145  	from := check.decl
   146  	if from == nil {
   147  		return // not in a package-level init expression
   148  	}
   149  	if _, found := check.objMap[to]; !found {
   150  		return // to is not a package-level object
   151  	}
   152  	from.addDep(to)
   153  }
   154  
   155  // brokenAlias records that alias doesn't have a determined type yet.
   156  // It also sets alias.typ to Typ[Invalid].
   157  func (check *Checker) brokenAlias(alias *TypeName) {
   158  	if check.brokenAliases == nil {
   159  		check.brokenAliases = make(map[*TypeName]bool)
   160  	}
   161  	check.brokenAliases[alias] = true
   162  	alias.typ = Typ[Invalid]
   163  }
   164  
   165  // validAlias records that alias has the valid type typ (possibly Typ[Invalid]).
   166  func (check *Checker) validAlias(alias *TypeName, typ Type) {
   167  	delete(check.brokenAliases, alias)
   168  	alias.typ = typ
   169  }
   170  
   171  // isBrokenAlias reports whether alias doesn't have a determined type yet.
   172  func (check *Checker) isBrokenAlias(alias *TypeName) bool {
   173  	return alias.typ == Typ[Invalid] && check.brokenAliases[alias]
   174  }
   175  
   176  func (check *Checker) rememberUntyped(e ast.Expr, lhs bool, mode operandMode, typ *Basic, val constant.Value) {
   177  	m := check.untyped
   178  	if m == nil {
   179  		m = make(map[ast.Expr]exprInfo)
   180  		check.untyped = m
   181  	}
   182  	m[e] = exprInfo{lhs, mode, typ, val}
   183  }
   184  
   185  // later pushes f on to the stack of actions that will be processed later;
   186  // either at the end of the current statement, or in case of a local constant
   187  // or variable declaration, before the constant or variable is in scope
   188  // (so that f still sees the scope before any new declarations).
   189  // later returns the pushed action so one can provide a description
   190  // via action.describef for debugging, if desired.
   191  func (check *Checker) later(f func()) *action {
   192  	i := len(check.delayed)
   193  	check.delayed = append(check.delayed, action{f: f})
   194  	return &check.delayed[i]
   195  }
   196  
   197  // push pushes obj onto the object path and returns its index in the path.
   198  func (check *Checker) push(obj Object) int {
   199  	check.objPath = append(check.objPath, obj)
   200  	return len(check.objPath) - 1
   201  }
   202  
   203  // pop pops and returns the topmost object from the object path.
   204  func (check *Checker) pop() Object {
   205  	i := len(check.objPath) - 1
   206  	obj := check.objPath[i]
   207  	check.objPath[i] = nil
   208  	check.objPath = check.objPath[:i]
   209  	return obj
   210  }
   211  
   212  type cleaner interface {
   213  	cleanup()
   214  }
   215  
   216  // needsCleanup records objects/types that implement the cleanup method
   217  // which will be called at the end of type-checking.
   218  func (check *Checker) needsCleanup(c cleaner) {
   219  	check.cleaners = append(check.cleaners, c)
   220  }
   221  
   222  // NewChecker returns a new Checker instance for a given package.
   223  // Package files may be added incrementally via checker.Files.
   224  func NewChecker(conf *Config, fset *token.FileSet, pkg *Package, info *Info) *Checker {
   225  	// make sure we have a configuration
   226  	if conf == nil {
   227  		conf = new(Config)
   228  	}
   229  
   230  	// make sure we have an info struct
   231  	if info == nil {
   232  		info = new(Info)
   233  	}
   234  
   235  	version, err := parseGoVersion(conf.GoVersion)
   236  	if err != nil {
   237  		panic(fmt.Sprintf("invalid Go version %q (%v)", conf.GoVersion, err))
   238  	}
   239  
   240  	return &Checker{
   241  		conf:    conf,
   242  		ctxt:    conf.Context,
   243  		fset:    fset,
   244  		pkg:     pkg,
   245  		Info:    info,
   246  		version: version,
   247  		objMap:  make(map[Object]*declInfo),
   248  		impMap:  make(map[importKey]*Package),
   249  	}
   250  }
   251  
   252  // initFiles initializes the files-specific portion of checker.
   253  // The provided files must all belong to the same package.
   254  func (check *Checker) initFiles(files []*ast.File) {
   255  	// start with a clean slate (check.Files may be called multiple times)
   256  	check.files = nil
   257  	check.imports = nil
   258  	check.dotImportMap = nil
   259  
   260  	check.firstErr = nil
   261  	check.methods = nil
   262  	check.untyped = nil
   263  	check.delayed = nil
   264  	check.objPath = nil
   265  	check.cleaners = nil
   266  
   267  	// determine package name and collect valid files
   268  	pkg := check.pkg
   269  	for _, file := range files {
   270  		switch name := file.Name.Name; pkg.name {
   271  		case "":
   272  			if name != "_" {
   273  				pkg.name = name
   274  			} else {
   275  				check.error(file.Name, BlankPkgName, "invalid package name _")
   276  			}
   277  			fallthrough
   278  
   279  		case name:
   280  			check.files = append(check.files, file)
   281  
   282  		default:
   283  			check.errorf(atPos(file.Package), MismatchedPkgName, "package %s; expected %s", name, pkg.name)
   284  			// ignore this file
   285  		}
   286  	}
   287  }
   288  
   289  // A bailout panic is used for early termination.
   290  type bailout struct{}
   291  
   292  func (check *Checker) handleBailout(err *error) {
   293  	switch p := recover().(type) {
   294  	case nil, bailout:
   295  		// normal return or early exit
   296  		*err = check.firstErr
   297  	default:
   298  		// re-panic
   299  		panic(p)
   300  	}
   301  }
   302  
   303  // Files checks the provided files as part of the checker's package.
   304  func (check *Checker) Files(files []*ast.File) error { return check.checkFiles(files) }
   305  
   306  var errBadCgo = errors.New("cannot use FakeImportC and go115UsesCgo together")
   307  
   308  func (check *Checker) checkFiles(files []*ast.File) (err error) {
   309  	if check.conf.FakeImportC && check.conf.go115UsesCgo {
   310  		return errBadCgo
   311  	}
   312  
   313  	defer check.handleBailout(&err)
   314  
   315  	print := func(msg string) {
   316  		if trace {
   317  			fmt.Println()
   318  			fmt.Println(msg)
   319  		}
   320  	}
   321  
   322  	print("== initFiles ==")
   323  	check.initFiles(files)
   324  
   325  	print("== collectObjects ==")
   326  	check.collectObjects()
   327  
   328  	print("== packageObjects ==")
   329  	check.packageObjects()
   330  
   331  	print("== processDelayed ==")
   332  	check.processDelayed(0) // incl. all functions
   333  
   334  	print("== cleanup ==")
   335  	check.cleanup()
   336  
   337  	print("== initOrder ==")
   338  	check.initOrder()
   339  
   340  	if !check.conf.DisableUnusedImportCheck {
   341  		print("== unusedImports ==")
   342  		check.unusedImports()
   343  	}
   344  
   345  	print("== recordUntyped ==")
   346  	check.recordUntyped()
   347  
   348  	if check.firstErr == nil {
   349  		// TODO(mdempsky): Ensure monomorph is safe when errors exist.
   350  		check.monomorph()
   351  	}
   352  
   353  	check.pkg.complete = true
   354  
   355  	// no longer needed - release memory
   356  	check.imports = nil
   357  	check.dotImportMap = nil
   358  	check.pkgPathMap = nil
   359  	check.seenPkgMap = nil
   360  	check.recvTParamMap = nil
   361  	check.brokenAliases = nil
   362  	check.unionTypeSets = nil
   363  	check.ctxt = nil
   364  
   365  	// TODO(rFindley) There's more memory we should release at this point.
   366  
   367  	return
   368  }
   369  
   370  // processDelayed processes all delayed actions pushed after top.
   371  func (check *Checker) processDelayed(top int) {
   372  	// If each delayed action pushes a new action, the
   373  	// stack will continue to grow during this loop.
   374  	// However, it is only processing functions (which
   375  	// are processed in a delayed fashion) that may
   376  	// add more actions (such as nested functions), so
   377  	// this is a sufficiently bounded process.
   378  	for i := top; i < len(check.delayed); i++ {
   379  		a := &check.delayed[i]
   380  		if trace {
   381  			if a.desc != nil {
   382  				check.trace(a.desc.pos.Pos(), "-- "+a.desc.format, a.desc.args...)
   383  			} else {
   384  				check.trace(token.NoPos, "-- delayed %p", a.f)
   385  			}
   386  		}
   387  		a.f() // may append to check.delayed
   388  		if trace {
   389  			fmt.Println()
   390  		}
   391  	}
   392  	assert(top <= len(check.delayed)) // stack must not have shrunk
   393  	check.delayed = check.delayed[:top]
   394  }
   395  
   396  // cleanup runs cleanup for all collected cleaners.
   397  func (check *Checker) cleanup() {
   398  	// Don't use a range clause since Named.cleanup may add more cleaners.
   399  	for i := 0; i < len(check.cleaners); i++ {
   400  		check.cleaners[i].cleanup()
   401  	}
   402  	check.cleaners = nil
   403  }
   404  
   405  func (check *Checker) record(x *operand) {
   406  	// convert x into a user-friendly set of values
   407  	// TODO(gri) this code can be simplified
   408  	var typ Type
   409  	var val constant.Value
   410  	switch x.mode {
   411  	case invalid:
   412  		typ = Typ[Invalid]
   413  	case novalue:
   414  		typ = (*Tuple)(nil)
   415  	case constant_:
   416  		typ = x.typ
   417  		val = x.val
   418  	default:
   419  		typ = x.typ
   420  	}
   421  	assert(x.expr != nil && typ != nil)
   422  
   423  	if isUntyped(typ) {
   424  		// delay type and value recording until we know the type
   425  		// or until the end of type checking
   426  		check.rememberUntyped(x.expr, false, x.mode, typ.(*Basic), val)
   427  	} else {
   428  		check.recordTypeAndValue(x.expr, x.mode, typ, val)
   429  	}
   430  }
   431  
   432  func (check *Checker) recordUntyped() {
   433  	if !debug && check.Types == nil {
   434  		return // nothing to do
   435  	}
   436  
   437  	for x, info := range check.untyped {
   438  		if debug && isTyped(info.typ) {
   439  			check.dump("%v: %s (type %s) is typed", x.Pos(), x, info.typ)
   440  			unreachable()
   441  		}
   442  		check.recordTypeAndValue(x, info.mode, info.typ, info.val)
   443  	}
   444  }
   445  
   446  func (check *Checker) recordTypeAndValue(x ast.Expr, mode operandMode, typ Type, val constant.Value) {
   447  	assert(x != nil)
   448  	assert(typ != nil)
   449  	if mode == invalid {
   450  		return // omit
   451  	}
   452  	if mode == constant_ {
   453  		assert(val != nil)
   454  		// We check allBasic(typ, IsConstType) here as constant expressions may be
   455  		// recorded as type parameters.
   456  		assert(typ == Typ[Invalid] || allBasic(typ, IsConstType))
   457  	}
   458  	if m := check.Types; m != nil {
   459  		m[x] = TypeAndValue{mode, typ, val}
   460  	}
   461  }
   462  
   463  func (check *Checker) recordBuiltinType(f ast.Expr, sig *Signature) {
   464  	// f must be a (possibly parenthesized, possibly qualified)
   465  	// identifier denoting a built-in (including unsafe's non-constant
   466  	// functions Add and Slice): record the signature for f and possible
   467  	// children.
   468  	for {
   469  		check.recordTypeAndValue(f, builtin, sig, nil)
   470  		switch p := f.(type) {
   471  		case *ast.Ident, *ast.SelectorExpr:
   472  			return // we're done
   473  		case *ast.ParenExpr:
   474  			f = p.X
   475  		default:
   476  			unreachable()
   477  		}
   478  	}
   479  }
   480  
   481  func (check *Checker) recordCommaOkTypes(x ast.Expr, a [2]Type) {
   482  	assert(x != nil)
   483  	if a[0] == nil || a[1] == nil {
   484  		return
   485  	}
   486  	assert(isTyped(a[0]) && isTyped(a[1]) && (isBoolean(a[1]) || a[1] == universeError))
   487  	if m := check.Types; m != nil {
   488  		for {
   489  			tv := m[x]
   490  			assert(tv.Type != nil) // should have been recorded already
   491  			pos := x.Pos()
   492  			tv.Type = NewTuple(
   493  				NewVar(pos, check.pkg, "", a[0]),
   494  				NewVar(pos, check.pkg, "", a[1]),
   495  			)
   496  			m[x] = tv
   497  			// if x is a parenthesized expression (p.X), update p.X
   498  			p, _ := x.(*ast.ParenExpr)
   499  			if p == nil {
   500  				break
   501  			}
   502  			x = p.X
   503  		}
   504  	}
   505  }
   506  
   507  // recordInstance records instantiation information into check.Info, if the
   508  // Instances map is non-nil. The given expr must be an ident, selector, or
   509  // index (list) expr with ident or selector operand.
   510  //
   511  // TODO(rfindley): the expr parameter is fragile. See if we can access the
   512  // instantiated identifier in some other way.
   513  func (check *Checker) recordInstance(expr ast.Expr, targs []Type, typ Type) {
   514  	ident := instantiatedIdent(expr)
   515  	assert(ident != nil)
   516  	assert(typ != nil)
   517  	if m := check.Instances; m != nil {
   518  		m[ident] = Instance{newTypeList(targs), typ}
   519  	}
   520  }
   521  
   522  func instantiatedIdent(expr ast.Expr) *ast.Ident {
   523  	var selOrIdent ast.Expr
   524  	switch e := expr.(type) {
   525  	case *ast.IndexExpr:
   526  		selOrIdent = e.X
   527  	case *ast.IndexListExpr:
   528  		selOrIdent = e.X
   529  	case *ast.SelectorExpr, *ast.Ident:
   530  		selOrIdent = e
   531  	}
   532  	switch x := selOrIdent.(type) {
   533  	case *ast.Ident:
   534  		return x
   535  	case *ast.SelectorExpr:
   536  		return x.Sel
   537  	}
   538  	panic("instantiated ident not found")
   539  }
   540  
   541  func (check *Checker) recordDef(id *ast.Ident, obj Object) {
   542  	assert(id != nil)
   543  	if m := check.Defs; m != nil {
   544  		m[id] = obj
   545  	}
   546  }
   547  
   548  func (check *Checker) recordUse(id *ast.Ident, obj Object) {
   549  	assert(id != nil)
   550  	assert(obj != nil)
   551  	if m := check.Uses; m != nil {
   552  		m[id] = obj
   553  	}
   554  }
   555  
   556  func (check *Checker) recordImplicit(node ast.Node, obj Object) {
   557  	assert(node != nil)
   558  	assert(obj != nil)
   559  	if m := check.Implicits; m != nil {
   560  		m[node] = obj
   561  	}
   562  }
   563  
   564  func (check *Checker) recordSelection(x *ast.SelectorExpr, kind SelectionKind, recv Type, obj Object, index []int, indirect bool) {
   565  	assert(obj != nil && (recv == nil || len(index) > 0))
   566  	check.recordUse(x.Sel, obj)
   567  	if m := check.Selections; m != nil {
   568  		m[x] = &Selection{kind, recv, obj, index, indirect}
   569  	}
   570  }
   571  
   572  func (check *Checker) recordScope(node ast.Node, scope *Scope) {
   573  	assert(node != nil)
   574  	assert(scope != nil)
   575  	if m := check.Scopes; m != nil {
   576  		m[node] = scope
   577  	}
   578  }