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