github.com/sean-/go@v0.0.0-20151219100004-97f854cd7bb6/src/go/types/api.go (about)

     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 checked 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 // import "go/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  // See go/importer for existing implementations.
    56  type Importer interface {
    57  	// Import returns the imported package for the given import
    58  	// path, or an error if the package couldn't be imported.
    59  	// Import is responsible for returning the same package for
    60  	// matching import paths.
    61  	Import(path string) (*Package, error)
    62  }
    63  
    64  // A Config specifies the configuration for type checking.
    65  // The zero value for Config is a ready-to-use default configuration.
    66  type Config struct {
    67  	// If IgnoreFuncBodies is set, function bodies are not
    68  	// type-checked.
    69  	IgnoreFuncBodies bool
    70  
    71  	// If FakeImportC is set, `import "C"` (for packages requiring Cgo)
    72  	// declares an empty "C" package and errors are omitted for qualified
    73  	// identifiers referring to package C (which won't find an object).
    74  	// This feature is intended for the standard library cmd/api tool.
    75  	//
    76  	// Caution: Effects may be unpredictable due to follow-up errors.
    77  	//          Do not use casually!
    78  	FakeImportC bool
    79  
    80  	// If Error != nil, it is called with each error found
    81  	// during type checking; err has dynamic type Error.
    82  	// Secondary errors (for instance, to enumerate all types
    83  	// involved in an invalid recursive type declaration) have
    84  	// error strings that start with a '\t' character.
    85  	// If Error == nil, type-checking stops with the first
    86  	// error found.
    87  	Error func(err error)
    88  
    89  	// Importer is called for each import declaration except when
    90  	// importing package "unsafe". An error is reported if an
    91  	// importer is needed but none was installed.
    92  	Importer Importer
    93  
    94  	// If Sizes != nil, it provides the sizing functions for package unsafe.
    95  	// Otherwise &StdSizes{WordSize: 8, MaxAlign: 8} is used instead.
    96  	Sizes Sizes
    97  
    98  	// If DisableUnusedImportCheck is set, packages are not checked
    99  	// for unused imports.
   100  	DisableUnusedImportCheck bool
   101  }
   102  
   103  // Info holds result type information for a type-checked package.
   104  // Only the information for which a map is provided is collected.
   105  // If the package has type errors, the collected information may
   106  // be incomplete.
   107  type Info struct {
   108  	// Types maps expressions to their types, and for constant
   109  	// expressions, their values. Invalid expressions are omitted.
   110  	//
   111  	// For (possibly parenthesized) identifiers denoting built-in
   112  	// functions, the recorded signatures are call-site specific:
   113  	// if the call result is not a constant, the recorded type is
   114  	// an argument-specific signature. Otherwise, the recorded type
   115  	// is invalid.
   116  	//
   117  	// Identifiers on the lhs of declarations (i.e., the identifiers
   118  	// which are being declared) are collected in the Defs map.
   119  	// Identifiers denoting packages are collected in the Uses maps.
   120  	Types map[ast.Expr]TypeAndValue
   121  
   122  	// Defs maps identifiers to the objects they define (including
   123  	// package names, dots "." of dot-imports, and blank "_" identifiers).
   124  	// For identifiers that do not denote objects (e.g., the package name
   125  	// in package clauses, or symbolic variables t in t := x.(type) of
   126  	// type switch headers), the corresponding objects are nil.
   127  	//
   128  	// For an anonymous field, Defs returns the field *Var it defines.
   129  	//
   130  	// Invariant: Defs[id] == nil || Defs[id].Pos() == id.Pos()
   131  	Defs map[*ast.Ident]Object
   132  
   133  	// Uses maps identifiers to the objects they denote.
   134  	//
   135  	// For an anonymous field, Uses returns the *TypeName it denotes.
   136  	//
   137  	// Invariant: Uses[id].Pos() != id.Pos()
   138  	Uses map[*ast.Ident]Object
   139  
   140  	// Implicits maps nodes to their implicitly declared objects, if any.
   141  	// The following node and object types may appear:
   142  	//
   143  	//	node               declared object
   144  	//
   145  	//	*ast.ImportSpec    *PkgName for dot-imports and imports without renames
   146  	//	*ast.CaseClause    type-specific *Var for each type switch case clause (incl. default)
   147  	//      *ast.Field         anonymous parameter *Var
   148  	//
   149  	Implicits map[ast.Node]Object
   150  
   151  	// Selections maps selector expressions (excluding qualified identifiers)
   152  	// to their corresponding selections.
   153  	Selections map[*ast.SelectorExpr]*Selection
   154  
   155  	// Scopes maps ast.Nodes to the scopes they define. Package scopes are not
   156  	// associated with a specific node but with all files belonging to a package.
   157  	// Thus, the package scope can be found in the type-checked Package object.
   158  	// Scopes nest, with the Universe scope being the outermost scope, enclosing
   159  	// the package scope, which contains (one or more) files scopes, which enclose
   160  	// function scopes which in turn enclose statement and function literal scopes.
   161  	// Note that even though package-level functions are declared in the package
   162  	// scope, the function scopes are embedded in the file scope of the file
   163  	// containing the function declaration.
   164  	//
   165  	// The following node types may appear in Scopes:
   166  	//
   167  	//	*ast.File
   168  	//	*ast.FuncType
   169  	//	*ast.BlockStmt
   170  	//	*ast.IfStmt
   171  	//	*ast.SwitchStmt
   172  	//	*ast.TypeSwitchStmt
   173  	//	*ast.CaseClause
   174  	//	*ast.CommClause
   175  	//	*ast.ForStmt
   176  	//	*ast.RangeStmt
   177  	//
   178  	Scopes map[ast.Node]*Scope
   179  
   180  	// InitOrder is the list of package-level initializers in the order in which
   181  	// they must be executed. Initializers referring to variables related by an
   182  	// initialization dependency appear in topological order, the others appear
   183  	// in source order. Variables without an initialization expression do not
   184  	// appear in this list.
   185  	InitOrder []*Initializer
   186  }
   187  
   188  // TypeOf returns the type of expression e, or nil if not found.
   189  // Precondition: the Types, Uses and Defs maps are populated.
   190  //
   191  func (info *Info) TypeOf(e ast.Expr) Type {
   192  	if t, ok := info.Types[e]; ok {
   193  		return t.Type
   194  	}
   195  	if id, _ := e.(*ast.Ident); id != nil {
   196  		if obj := info.ObjectOf(id); obj != nil {
   197  			return obj.Type()
   198  		}
   199  	}
   200  	return nil
   201  }
   202  
   203  // ObjectOf returns the object denoted by the specified id,
   204  // or nil if not found.
   205  //
   206  // If id is an anonymous struct field, ObjectOf returns the field (*Var)
   207  // it uses, not the type (*TypeName) it defines.
   208  //
   209  // Precondition: the Uses and Defs maps are populated.
   210  //
   211  func (info *Info) ObjectOf(id *ast.Ident) Object {
   212  	if obj, _ := info.Defs[id]; obj != nil {
   213  		return obj
   214  	}
   215  	return info.Uses[id]
   216  }
   217  
   218  // TypeAndValue reports the type and value (for constants)
   219  // of the corresponding expression.
   220  type TypeAndValue struct {
   221  	mode  operandMode
   222  	Type  Type
   223  	Value constant.Value
   224  }
   225  
   226  // TODO(gri) Consider eliminating the IsVoid predicate. Instead, report
   227  // "void" values as regular values but with the empty tuple type.
   228  
   229  // IsVoid reports whether the corresponding expression
   230  // is a function call without results.
   231  func (tv TypeAndValue) IsVoid() bool {
   232  	return tv.mode == novalue
   233  }
   234  
   235  // IsType reports whether the corresponding expression specifies a type.
   236  func (tv TypeAndValue) IsType() bool {
   237  	return tv.mode == typexpr
   238  }
   239  
   240  // IsBuiltin reports whether the corresponding expression denotes
   241  // a (possibly parenthesized) built-in function.
   242  func (tv TypeAndValue) IsBuiltin() bool {
   243  	return tv.mode == builtin
   244  }
   245  
   246  // IsValue reports whether the corresponding expression is a value.
   247  // Builtins are not considered values. Constant values have a non-
   248  // nil Value.
   249  func (tv TypeAndValue) IsValue() bool {
   250  	switch tv.mode {
   251  	case constant_, variable, mapindex, value, commaok:
   252  		return true
   253  	}
   254  	return false
   255  }
   256  
   257  // IsNil reports whether the corresponding expression denotes the
   258  // predeclared value nil.
   259  func (tv TypeAndValue) IsNil() bool {
   260  	return tv.mode == value && tv.Type == Typ[UntypedNil]
   261  }
   262  
   263  // Addressable reports whether the corresponding expression
   264  // is addressable (https://golang.org/ref/spec#Address_operators).
   265  func (tv TypeAndValue) Addressable() bool {
   266  	return tv.mode == variable
   267  }
   268  
   269  // Assignable reports whether the corresponding expression
   270  // is assignable to (provided a value of the right type).
   271  func (tv TypeAndValue) Assignable() bool {
   272  	return tv.mode == variable || tv.mode == mapindex
   273  }
   274  
   275  // HasOk reports whether the corresponding expression may be
   276  // used on the lhs of a comma-ok assignment.
   277  func (tv TypeAndValue) HasOk() bool {
   278  	return tv.mode == commaok || tv.mode == mapindex
   279  }
   280  
   281  // An Initializer describes a package-level variable, or a list of variables in case
   282  // of a multi-valued initialization expression, and the corresponding initialization
   283  // expression.
   284  type Initializer struct {
   285  	Lhs []*Var // var Lhs = Rhs
   286  	Rhs ast.Expr
   287  }
   288  
   289  func (init *Initializer) String() string {
   290  	var buf bytes.Buffer
   291  	for i, lhs := range init.Lhs {
   292  		if i > 0 {
   293  			buf.WriteString(", ")
   294  		}
   295  		buf.WriteString(lhs.Name())
   296  	}
   297  	buf.WriteString(" = ")
   298  	WriteExpr(&buf, init.Rhs)
   299  	return buf.String()
   300  }
   301  
   302  // Check type-checks a package and returns the resulting package object and
   303  // the first error if any. Additionally, if info != nil, Check populates each
   304  // of the non-nil maps in the Info struct.
   305  //
   306  // The package is marked as complete if no errors occurred, otherwise it is
   307  // incomplete. See Config.Error for controlling behavior in the presence of
   308  // errors.
   309  //
   310  // The package is specified by a list of *ast.Files and corresponding
   311  // file set, and the package path the package is identified with.
   312  // The clean path must not be empty or dot (".").
   313  func (conf *Config) Check(path string, fset *token.FileSet, files []*ast.File, info *Info) (*Package, error) {
   314  	pkg := NewPackage(path, "")
   315  	return pkg, NewChecker(conf, fset, pkg, info).Files(files)
   316  }
   317  
   318  // AssertableTo reports whether a value of type V can be asserted to have type T.
   319  func AssertableTo(V *Interface, T Type) bool {
   320  	m, _ := assertableTo(V, T)
   321  	return m == nil
   322  }
   323  
   324  // AssignableTo reports whether a value of type V is assignable to a variable of type T.
   325  func AssignableTo(V, T Type) bool {
   326  	x := operand{mode: value, typ: V}
   327  	return x.assignableTo(nil, T, nil) // config not needed for non-constant x
   328  }
   329  
   330  // ConvertibleTo reports whether a value of type V is convertible to a value of type T.
   331  func ConvertibleTo(V, T Type) bool {
   332  	x := operand{mode: value, typ: V}
   333  	return x.convertibleTo(nil, T) // config not needed for non-constant x
   334  }
   335  
   336  // Implements reports whether type V implements interface T.
   337  func Implements(V Type, T *Interface) bool {
   338  	f, _ := MissingMethod(V, T, true)
   339  	return f == nil
   340  }