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