...

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

View as plain text