Source file src/go/types/api.go

     1  // Copyright 2012 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 declares the data types and implements
     6  // the algorithms for type-checking of Go packages. Use
     7  // [Config.Check] to invoke the type checker for a package.
     8  // Alternatively, create a new type checker with [NewChecker]
     9  // and invoke it incrementally by calling [Checker.Files].
    10  //
    11  // Type-checking consists of several interdependent phases:
    12  //
    13  // Name resolution maps each identifier ([ast.Ident]) in the program
    14  // to the symbol ([Object]) it denotes. Use the Defs and Uses fields
    15  // of [Info] or the [Info.ObjectOf] method to find the symbol for an
    16  // identifier, and use the Implicits field of [Info] to find the
    17  // symbol for certain other kinds of syntax node.
    18  //
    19  // Constant folding computes the exact constant value
    20  // ([constant.Value]) of every expression ([ast.Expr]) that is a
    21  // compile-time constant. Use the Types field of [Info] to find the
    22  // results of constant folding for an expression.
    23  //
    24  // Type deduction computes the type ([Type]) of every expression
    25  // ([ast.Expr]) and checks for compliance with the language
    26  // specification. Use the Types field of [Info] for the results of
    27  // type deduction.
    28  //
    29  // Applications that need to type-check one or more complete packages
    30  // of Go source code may find it more convenient not to invoke the
    31  // type checker directly but instead to use the Load function in
    32  // package [golang.org/x/tools/go/packages].
    33  //
    34  // For a tutorial, see https://go.dev/s/types-tutorial.
    35  package types
    36  
    37  import (
    38  	"bytes"
    39  	"fmt"
    40  	"go/ast"
    41  	"go/constant"
    42  	"go/token"
    43  	. "internal/types/errors"
    44  	_ "unsafe" // for linkname
    45  )
    46  
    47  // An Error describes a type-checking error; it implements the error interface.
    48  // A "soft" error is an error that still permits a valid interpretation of a
    49  // package (such as "unused variable"); "hard" errors may lead to unpredictable
    50  // behavior if ignored.
    51  type Error struct {
    52  	Fset *token.FileSet // file set for interpretation of Pos
    53  	Pos  token.Pos      // error position
    54  	Msg  string         // error message
    55  	Soft bool           // if set, error is "soft"
    56  
    57  	// go116code is a future API, unexported as the set of error codes is large
    58  	// and likely to change significantly during experimentation. Tools wishing
    59  	// to preview this feature may read go116code using reflection (see
    60  	// errorcodes_test.go), but beware that there is no guarantee of future
    61  	// compatibility.
    62  	go116code  Code
    63  	go116start token.Pos
    64  	go116end   token.Pos
    65  }
    66  
    67  // Error returns an error string formatted as follows:
    68  // filename:line:column: message
    69  func (err Error) Error() string {
    70  	return fmt.Sprintf("%s: %s", err.Fset.Position(err.Pos), err.Msg)
    71  }
    72  
    73  // An ArgumentError holds an error associated with an argument index.
    74  type ArgumentError struct {
    75  	Index int
    76  	Err   error
    77  }
    78  
    79  func (e *ArgumentError) Error() string { return e.Err.Error() }
    80  func (e *ArgumentError) Unwrap() error { return e.Err }
    81  
    82  // An Importer resolves import paths to Packages.
    83  //
    84  // CAUTION: This interface does not support the import of locally
    85  // vendored packages. See https://golang.org/s/go15vendor.
    86  // If possible, external implementations should implement [ImporterFrom].
    87  type Importer interface {
    88  	// Import returns the imported package for the given import path.
    89  	// The semantics is like for ImporterFrom.ImportFrom except that
    90  	// dir and mode are ignored (since they are not present).
    91  	Import(path string) (*Package, error)
    92  }
    93  
    94  // ImportMode is reserved for future use.
    95  type ImportMode int
    96  
    97  // An ImporterFrom resolves import paths to packages; it
    98  // supports vendoring per https://golang.org/s/go15vendor.
    99  // Use go/importer to obtain an ImporterFrom implementation.
   100  type ImporterFrom interface {
   101  	// Importer is present for backward-compatibility. Calling
   102  	// Import(path) is the same as calling ImportFrom(path, "", 0);
   103  	// i.e., locally vendored packages may not be found.
   104  	// The types package does not call Import if an ImporterFrom
   105  	// is present.
   106  	Importer
   107  
   108  	// ImportFrom returns the imported package for the given import
   109  	// path when imported by a package file located in dir.
   110  	// If the import failed, besides returning an error, ImportFrom
   111  	// is encouraged to cache and return a package anyway, if one
   112  	// was created. This will reduce package inconsistencies and
   113  	// follow-on type checker errors due to the missing package.
   114  	// The mode value must be 0; it is reserved for future use.
   115  	// Two calls to ImportFrom with the same path and dir must
   116  	// return the same package.
   117  	ImportFrom(path, dir string, mode ImportMode) (*Package, error)
   118  }
   119  
   120  // A Config specifies the configuration for type checking.
   121  // The zero value for Config is a ready-to-use default configuration.
   122  type Config struct {
   123  	// Context is the context used for resolving global identifiers. If nil, the
   124  	// type checker will initialize this field with a newly created context.
   125  	Context *Context
   126  
   127  	// GoVersion describes the accepted Go language version. The string must
   128  	// start with a prefix of the form "go%d.%d" (e.g. "go1.20", "go1.21rc1", or
   129  	// "go1.21.0") or it must be empty; an empty string disables Go language
   130  	// version checks. If the format is invalid, invoking the type checker will
   131  	// result in an error.
   132  	GoVersion string
   133  
   134  	// If IgnoreFuncBodies is set, function bodies are not
   135  	// type-checked.
   136  	IgnoreFuncBodies bool
   137  
   138  	// If FakeImportC is set, `import "C"` (for packages requiring Cgo)
   139  	// declares an empty "C" package and errors are omitted for qualified
   140  	// identifiers referring to package C (which won't find an object).
   141  	// This feature is intended for the standard library cmd/api tool.
   142  	//
   143  	// Caution: Effects may be unpredictable due to follow-on errors.
   144  	//          Do not use casually!
   145  	FakeImportC bool
   146  
   147  	// If go115UsesCgo is set, the type checker expects the
   148  	// _cgo_gotypes.go file generated by running cmd/cgo to be
   149  	// provided as a package source file. Qualified identifiers
   150  	// referring to package C will be resolved to cgo-provided
   151  	// declarations within _cgo_gotypes.go.
   152  	//
   153  	// It is an error to set both FakeImportC and go115UsesCgo.
   154  	go115UsesCgo bool
   155  
   156  	// If _Trace is set, a debug trace is printed to stdout.
   157  	_Trace bool
   158  
   159  	// If Error != nil, it is called with each error found
   160  	// during type checking; err has dynamic type Error.
   161  	// Secondary errors (for instance, to enumerate all types
   162  	// involved in an invalid recursive type declaration) have
   163  	// error strings that start with a '\t' character.
   164  	// If Error == nil, type-checking stops with the first
   165  	// error found.
   166  	Error func(err error)
   167  
   168  	// An importer is used to import packages referred to from
   169  	// import declarations.
   170  	// If the installed importer implements ImporterFrom, the type
   171  	// checker calls ImportFrom instead of Import.
   172  	// The type checker reports an error if an importer is needed
   173  	// but none was installed.
   174  	Importer Importer
   175  
   176  	// If Sizes != nil, it provides the sizing functions for package unsafe.
   177  	// Otherwise SizesFor("gc", "amd64") is used instead.
   178  	Sizes Sizes
   179  
   180  	// If DisableUnusedImportCheck is set, packages are not checked
   181  	// for unused imports.
   182  	DisableUnusedImportCheck bool
   183  
   184  	// If a non-empty _ErrorURL format string is provided, it is used
   185  	// to format an error URL link that is appended to the first line
   186  	// of an error message. ErrorURL must be a format string containing
   187  	// exactly one "%s" format, e.g. "[go.dev/e/%s]".
   188  	_ErrorURL string
   189  
   190  	// If EnableAlias is set, alias declarations produce an Alias type. Otherwise
   191  	// the alias information is only in the type name, which points directly to
   192  	// the actual (aliased) type.
   193  	//
   194  	// This setting must not differ among concurrent type-checking operations,
   195  	// since it affects the behavior of Universe.Lookup("any").
   196  	//
   197  	// This flag will eventually be removed (with Go 1.24 at the earliest).
   198  	_EnableAlias bool
   199  }
   200  
   201  // Linkname for use from srcimporter.
   202  //go:linkname srcimporter_setUsesCgo
   203  
   204  func srcimporter_setUsesCgo(conf *Config) {
   205  	conf.go115UsesCgo = true
   206  }
   207  
   208  // Info holds result type information for a type-checked package.
   209  // Only the information for which a map is provided is collected.
   210  // If the package has type errors, the collected information may
   211  // be incomplete.
   212  type Info struct {
   213  	// Types maps expressions to their types, and for constant
   214  	// expressions, also their values. Invalid expressions are
   215  	// omitted.
   216  	//
   217  	// For (possibly parenthesized) identifiers denoting built-in
   218  	// functions, the recorded signatures are call-site specific:
   219  	// if the call result is not a constant, the recorded type is
   220  	// an argument-specific signature. Otherwise, the recorded type
   221  	// is invalid.
   222  	//
   223  	// The Types map does not record the type of every identifier,
   224  	// only those that appear where an arbitrary expression is
   225  	// permitted. For instance:
   226  	// - an identifier f in a selector expression x.f is found
   227  	//   only in the Selections map;
   228  	// - an identifier z in a variable declaration 'var z int'
   229  	//   is found only in the Defs map;
   230  	// - an identifier p denoting a package in a qualified
   231  	//   identifier p.X is found only in the Uses map.
   232  	//
   233  	// Similarly, no type is recorded for the (synthetic) FuncType
   234  	// node in a FuncDecl.Type field, since there is no corresponding
   235  	// syntactic function type expression in the source in this case
   236  	// Instead, the function type is found in the Defs map entry for
   237  	// the corresponding function declaration.
   238  	Types map[ast.Expr]TypeAndValue
   239  
   240  	// Instances maps identifiers denoting generic types or functions to their
   241  	// type arguments and instantiated type.
   242  	//
   243  	// For example, Instances will map the identifier for 'T' in the type
   244  	// instantiation T[int, string] to the type arguments [int, string] and
   245  	// resulting instantiated *Named type. Given a generic function
   246  	// func F[A any](A), Instances will map the identifier for 'F' in the call
   247  	// expression F(int(1)) to the inferred type arguments [int], and resulting
   248  	// instantiated *Signature.
   249  	//
   250  	// Invariant: Instantiating Uses[id].Type() with Instances[id].TypeArgs
   251  	// results in an equivalent of Instances[id].Type.
   252  	Instances map[*ast.Ident]Instance
   253  
   254  	// Defs maps identifiers to the objects they define (including
   255  	// package names, dots "." of dot-imports, and blank "_" identifiers).
   256  	// For identifiers that do not denote objects (e.g., the package name
   257  	// in package clauses, or symbolic variables t in t := x.(type) of
   258  	// type switch headers), the corresponding objects are nil.
   259  	//
   260  	// For an embedded field, Defs returns the field *Var it defines.
   261  	//
   262  	// In ill-typed code, such as a duplicate declaration of the
   263  	// same name, Defs may lack an entry for a declaring identifier.
   264  	//
   265  	// Invariant: Defs[id] == nil || Defs[id].Pos() == id.Pos()
   266  	Defs map[*ast.Ident]Object
   267  
   268  	// Uses maps identifiers to the objects they denote.
   269  	//
   270  	// For an embedded field, Uses returns the *TypeName it denotes.
   271  	//
   272  	// Invariant: Uses[id].Pos() != id.Pos()
   273  	Uses map[*ast.Ident]Object
   274  
   275  	// Implicits maps nodes to their implicitly declared objects, if any.
   276  	// The following node and object types may appear:
   277  	//
   278  	//     node               declared object
   279  	//
   280  	//     *ast.ImportSpec    *PkgName for imports without renames
   281  	//     *ast.CaseClause    type-specific *Var for each type switch case clause (incl. default)
   282  	//     *ast.Field         anonymous parameter *Var (incl. unnamed results)
   283  	//
   284  	Implicits map[ast.Node]Object
   285  
   286  	// Selections maps selector expressions (excluding qualified identifiers)
   287  	// to their corresponding selections.
   288  	Selections map[*ast.SelectorExpr]*Selection
   289  
   290  	// Scopes maps ast.Nodes to the scopes they define. Package scopes are not
   291  	// associated with a specific node but with all files belonging to a package.
   292  	// Thus, the package scope can be found in the type-checked Package object.
   293  	// Scopes nest, with the Universe scope being the outermost scope, enclosing
   294  	// the package scope, which contains (one or more) files scopes, which enclose
   295  	// function scopes which in turn enclose statement and function literal scopes.
   296  	// Note that even though package-level functions are declared in the package
   297  	// scope, the function scopes are embedded in the file scope of the file
   298  	// containing the function declaration.
   299  	//
   300  	// The Scope of a function contains the declarations of any
   301  	// type parameters, parameters, and named results, plus any
   302  	// local declarations in the body block.
   303  	// It is coextensive with the complete extent of the
   304  	// function's syntax ([*ast.FuncDecl] or [*ast.FuncLit]).
   305  	// The Scopes mapping does not contain an entry for the
   306  	// function body ([*ast.BlockStmt]); the function's scope is
   307  	// associated with the [*ast.FuncType].
   308  	//
   309  	// The following node types may appear in Scopes:
   310  	//
   311  	//     *ast.File
   312  	//     *ast.FuncType
   313  	//     *ast.TypeSpec
   314  	//     *ast.BlockStmt
   315  	//     *ast.IfStmt
   316  	//     *ast.SwitchStmt
   317  	//     *ast.TypeSwitchStmt
   318  	//     *ast.CaseClause
   319  	//     *ast.CommClause
   320  	//     *ast.ForStmt
   321  	//     *ast.RangeStmt
   322  	//
   323  	Scopes map[ast.Node]*Scope
   324  
   325  	// InitOrder is the list of package-level initializers in the order in which
   326  	// they must be executed. Initializers referring to variables related by an
   327  	// initialization dependency appear in topological order, the others appear
   328  	// in source order. Variables without an initialization expression do not
   329  	// appear in this list.
   330  	InitOrder []*Initializer
   331  
   332  	// FileVersions maps a file to its Go version string.
   333  	// If the file doesn't specify a version, the reported
   334  	// string is Config.GoVersion.
   335  	// Version strings begin with “go”, like “go1.21”, and
   336  	// are suitable for use with the [go/version] package.
   337  	FileVersions map[*ast.File]string
   338  }
   339  
   340  func (info *Info) recordTypes() bool {
   341  	return info.Types != nil
   342  }
   343  
   344  // TypeOf returns the type of expression e, or nil if not found.
   345  // Precondition: the Types, Uses and Defs maps are populated.
   346  func (info *Info) TypeOf(e ast.Expr) Type {
   347  	if t, ok := info.Types[e]; ok {
   348  		return t.Type
   349  	}
   350  	if id, _ := e.(*ast.Ident); id != nil {
   351  		if obj := info.ObjectOf(id); obj != nil {
   352  			return obj.Type()
   353  		}
   354  	}
   355  	return nil
   356  }
   357  
   358  // ObjectOf returns the object denoted by the specified id,
   359  // or nil if not found.
   360  //
   361  // If id is an embedded struct field, [Info.ObjectOf] returns the field (*[Var])
   362  // it defines, not the type (*[TypeName]) it uses.
   363  //
   364  // Precondition: the Uses and Defs maps are populated.
   365  func (info *Info) ObjectOf(id *ast.Ident) Object {
   366  	if obj := info.Defs[id]; obj != nil {
   367  		return obj
   368  	}
   369  	return info.Uses[id]
   370  }
   371  
   372  // PkgNameOf returns the local package name defined by the import,
   373  // or nil if not found.
   374  //
   375  // For dot-imports, the package name is ".".
   376  //
   377  // Precondition: the Defs and Implicts maps are populated.
   378  func (info *Info) PkgNameOf(imp *ast.ImportSpec) *PkgName {
   379  	var obj Object
   380  	if imp.Name != nil {
   381  		obj = info.Defs[imp.Name]
   382  	} else {
   383  		obj = info.Implicits[imp]
   384  	}
   385  	pkgname, _ := obj.(*PkgName)
   386  	return pkgname
   387  }
   388  
   389  // TypeAndValue reports the type and value (for constants)
   390  // of the corresponding expression.
   391  type TypeAndValue struct {
   392  	mode  operandMode
   393  	Type  Type
   394  	Value constant.Value
   395  }
   396  
   397  // IsVoid reports whether the corresponding expression
   398  // is a function call without results.
   399  func (tv TypeAndValue) IsVoid() bool {
   400  	return tv.mode == novalue
   401  }
   402  
   403  // IsType reports whether the corresponding expression specifies a type.
   404  func (tv TypeAndValue) IsType() bool {
   405  	return tv.mode == typexpr
   406  }
   407  
   408  // IsBuiltin reports whether the corresponding expression denotes
   409  // a (possibly parenthesized) built-in function.
   410  func (tv TypeAndValue) IsBuiltin() bool {
   411  	return tv.mode == builtin
   412  }
   413  
   414  // IsValue reports whether the corresponding expression is a value.
   415  // Builtins are not considered values. Constant values have a non-
   416  // nil Value.
   417  func (tv TypeAndValue) IsValue() bool {
   418  	switch tv.mode {
   419  	case constant_, variable, mapindex, value, commaok, commaerr:
   420  		return true
   421  	}
   422  	return false
   423  }
   424  
   425  // IsNil reports whether the corresponding expression denotes the
   426  // predeclared value nil.
   427  func (tv TypeAndValue) IsNil() bool {
   428  	return tv.mode == value && tv.Type == Typ[UntypedNil]
   429  }
   430  
   431  // Addressable reports whether the corresponding expression
   432  // is addressable (https://golang.org/ref/spec#Address_operators).
   433  func (tv TypeAndValue) Addressable() bool {
   434  	return tv.mode == variable
   435  }
   436  
   437  // Assignable reports whether the corresponding expression
   438  // is assignable to (provided a value of the right type).
   439  func (tv TypeAndValue) Assignable() bool {
   440  	return tv.mode == variable || tv.mode == mapindex
   441  }
   442  
   443  // HasOk reports whether the corresponding expression may be
   444  // used on the rhs of a comma-ok assignment.
   445  func (tv TypeAndValue) HasOk() bool {
   446  	return tv.mode == commaok || tv.mode == mapindex
   447  }
   448  
   449  // Instance reports the type arguments and instantiated type for type and
   450  // function instantiations. For type instantiations, [Type] will be of dynamic
   451  // type *[Named]. For function instantiations, [Type] will be of dynamic type
   452  // *Signature.
   453  type Instance struct {
   454  	TypeArgs *TypeList
   455  	Type     Type
   456  }
   457  
   458  // An Initializer describes a package-level variable, or a list of variables in case
   459  // of a multi-valued initialization expression, and the corresponding initialization
   460  // expression.
   461  type Initializer struct {
   462  	Lhs []*Var // var Lhs = Rhs
   463  	Rhs ast.Expr
   464  }
   465  
   466  func (init *Initializer) String() string {
   467  	var buf bytes.Buffer
   468  	for i, lhs := range init.Lhs {
   469  		if i > 0 {
   470  			buf.WriteString(", ")
   471  		}
   472  		buf.WriteString(lhs.Name())
   473  	}
   474  	buf.WriteString(" = ")
   475  	WriteExpr(&buf, init.Rhs)
   476  	return buf.String()
   477  }
   478  
   479  // Check type-checks a package and returns the resulting package object and
   480  // the first error if any. Additionally, if info != nil, Check populates each
   481  // of the non-nil maps in the [Info] struct.
   482  //
   483  // The package is marked as complete if no errors occurred, otherwise it is
   484  // incomplete. See [Config.Error] for controlling behavior in the presence of
   485  // errors.
   486  //
   487  // The package is specified by a list of *ast.Files and corresponding
   488  // file set, and the package path the package is identified with.
   489  // The clean path must not be empty or dot (".").
   490  func (conf *Config) Check(path string, fset *token.FileSet, files []*ast.File, info *Info) (*Package, error) {
   491  	pkg := NewPackage(path, "")
   492  	return pkg, NewChecker(conf, fset, pkg, info).Files(files)
   493  }
   494  

View as plain text