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