...

Source file src/go/types/api.go

Documentation: go/types

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

View as plain text