Black Lives Matter. Support the Equal Justice Initiative.

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

View as plain text