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

View as plain text