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

View as plain text