Debian Codegraph @

src/go/types/object.go

raw
1 // Code generated by "go test -run=Generate -write=all"; DO NOT EDIT.
2 // Source: ../../cmd/compile/internal/types2/object.go
3
4 // Copyright 2013 The Go Authors. All rights reserved.
5 // Use of this source code is governed by a BSD-style
6 // license that can be found in the LICENSE file.
7
8 package types
9
10 import (
11 "bytes"
12 "fmt"
13 "go/constant"
14 "go/token"
15 "strings"
16 "unicode"
17 "unicode/utf8"
18 )
19
20 // An Object is a named language entity.
21 // An Object may be a constant ([Const]), type name ([TypeName]),
22 // variable or struct field ([Var]), function or method ([Func]),
23 // imported package ([PkgName]), label ([Label]),
24 // built-in function ([Builtin]),
25 // or the predeclared identifier 'nil' ([Nil]).
26 //
27 // The environment, which is structured as a tree of Scopes,
28 // maps each name to the unique Object that it denotes.
29 type Object interface {
30 Parent() *Scope // scope in which this object is declared; nil for methods and struct fields
31 Pos() token.Pos // position of object identifier in declaration
32 Pkg() *Package // package to which this object belongs; nil for labels and objects in the Universe scope
33 Name() string // package local object name
34 Type() Type // object type
35 Exported() bool // reports whether the name starts with a capital letter
36 Id() string // object name if exported, qualified name if not exported (see func Id)
37
38 // String returns a human-readable string of the object.
39 // Use [ObjectString] to control how package names are formatted in the string.
40 String() string
41
42 // order reflects a package-level object's source order: if object
43 // a is before object b in the source, then a.order() < b.order().
44 // order returns a value > 0 for package-level objects; it returns
45 // 0 for all other objects (including objects in file scopes).
46 order() uint32
47
48 // setType sets the type of the object.
49 setType(Type)
50
51 // setOrder sets the order number of the object. It must be > 0.
52 setOrder(uint32)
53
54 // setParent sets the parent scope of the object.
55 setParent(*Scope)
56
57 // sameId reports whether obj.Id() and Id(pkg, name) are the same.
58 // If foldCase is true, names are considered equal if they are equal with case folding
59 // and their packages are ignored (e.g., pkg1.m, pkg1.M, pkg2.m, and pkg2.M are all equal).
60 sameId(pkg *Package, name string, foldCase bool) bool
61
62 // scopePos returns the start position of the scope of this Object
63 scopePos() token.Pos
64
65 // setScopePos sets the start position of the scope for this Object.
66 setScopePos(pos token.Pos)
67 }
68
69 func isExported(name string) bool {
70 ch, _ := utf8.DecodeRuneInString(name)
71 return unicode.IsUpper(ch)
72 }
73
74 // Id returns name if it is exported, otherwise it
75 // returns the name qualified with the package path.
76 func Id(pkg *Package, name string) string {
77 if isExported(name) {
78 return name
79 }
80 // unexported names need the package path for differentiation
81 // (if there's no package, make sure we don't start with '.'
82 // as that may change the order of methods between a setup
83 // inside a package and outside a package - which breaks some
84 // tests)
85 path := "_"
86 // pkg is nil for objects in Universe scope and possibly types
87 // introduced via Eval (see also comment in object.sameId)
88 if pkg != nil && pkg.path != "" {
89 path = pkg.path
90 }
91 return path + "." + name
92 }
93
94 // An object implements the common parts of an Object.
95 type object struct {
96 parent *Scope
97 pos token.Pos
98 pkg *Package
99 name string
100 typ Type
101 order_ uint32
102 scopePos_ token.Pos
103 }
104
105 // Parent returns the scope in which the object is declared.
106 // The result is nil for methods and struct fields.
107 func (obj *object) Parent() *Scope { return obj.parent }
108
109 // Pos returns the declaration position of the object's identifier.
110 func (obj *object) Pos() token.Pos { return obj.pos }
111
112 // Pkg returns the package to which the object belongs.
113 // The result is nil for labels and objects in the Universe scope.
114 func (obj *object) Pkg() *Package { return obj.pkg }
115
116 // Name returns the object's (package-local, unqualified) name.
117 func (obj *object) Name() string { return obj.name }
118
119 // Type returns the object's type.
120 func (obj *object) Type() Type { return obj.typ }
121
122 // Exported reports whether the object is exported (starts with a capital letter).
123 // It doesn't take into account whether the object is in a local (function) scope
124 // or not.
125 func (obj *object) Exported() bool { return isExported(obj.name) }
126
127 // Id is a wrapper for Id(obj.Pkg(), obj.Name()).
128 func (obj *object) Id() string { return Id(obj.pkg, obj.name) }
129
130 func (obj *object) String() string { panic("abstract") }
131 func (obj *object) order() uint32 { return obj.order_ }
132 func (obj *object) scopePos() token.Pos { return obj.scopePos_ }
133
134 func (obj *object) setParent(parent *Scope) { obj.parent = parent }
135 func (obj *object) setType(typ Type) { obj.typ = typ }
136 func (obj *object) setOrder(order uint32) { assert(order > 0); obj.order_ = order }
137 func (obj *object) setScopePos(pos token.Pos) { obj.scopePos_ = pos }
138
139 func (obj *object) sameId(pkg *Package, name string, foldCase bool) bool {
140 // If we don't care about capitalization, we also ignore packages.
141 if foldCase && strings.EqualFold(obj.name, name) {
142 return true
143 }
144 // spec:
145 // "Two identifiers are different if they are spelled differently,
146 // or if they appear in different packages and are not exported.
147 // Otherwise, they are the same."
148 if obj.name != name {
149 return false
150 }
151 // obj.Name == name
152 if obj.Exported() {
153 return true
154 }
155 // not exported, so packages must be the same
156 return samePkg(obj.pkg, pkg)
157 }
158
159 // cmp reports whether object a is ordered before object b.
160 // cmp returns:
161 //
162 // -1 if a is before b
163 // 0 if a is equivalent to b
164 // +1 if a is behind b
165 //
166 // Objects are ordered nil before non-nil, exported before
167 // non-exported, then by name, and finally (for non-exported
168 // functions) by package path.
169 func (a *object) cmp(b *object) int {
170 if a == b {
171 return 0
172 }
173
174 // Nil before non-nil.
175 if a == nil {
176 return -1
177 }
178 if b == nil {
179 return +1
180 }
181
182 // Exported functions before non-exported.
183 ea := isExported(a.name)
184 eb := isExported(b.name)
185 if ea != eb {
186 if ea {
187 return -1
188 }
189 return +1
190 }
191
192 // Order by name and then (for non-exported names) by package.
193 if a.name != b.name {
194 return strings.Compare(a.name, b.name)
195 }
196 if !ea {
197 return strings.Compare(a.pkg.path, b.pkg.path)
198 }
199
200 return 0
201 }
202
203 // A PkgName represents an imported Go package.
204 // PkgNames don't have a type.
205 type PkgName struct {
206 object
207 imported *Package
208 }
209
210 // NewPkgName returns a new PkgName object representing an imported package.
211 // The remaining arguments set the attributes found with all Objects.
212 func NewPkgName(pos token.Pos, pkg *Package, name string, imported *Package) *PkgName {
213 return &PkgName{object{nil, pos, pkg, name, Typ[Invalid], 0, nopos}, imported}
214 }
215
216 // Imported returns the package that was imported.
217 // It is distinct from Pkg(), which is the package containing the import statement.
218 func (obj *PkgName) Imported() *Package { return obj.imported }
219
220 // A Const represents a declared constant.
221 type Const struct {
222 object
223 val constant.Value
224 }
225
226 // NewConst returns a new constant with value val.
227 // The remaining arguments set the attributes found with all Objects.
228 func NewConst(pos token.Pos, pkg *Package, name string, typ Type, val constant.Value) *Const {
229 return &Const{object{nil, pos, pkg, name, typ, 0, nopos}, val}
230 }
231
232 // Val returns the constant's value.
233 func (obj *Const) Val() constant.Value { return obj.val }
234
235 func (*Const) isDependency() {} // a constant may be a dependency of an initialization expression
236
237 // A TypeName is an [Object] that represents a type with a name:
238 // a defined type ([Named]),
239 // an alias type ([Alias]),
240 // a type parameter ([TypeParam]),
241 // or a predeclared type such as int or error.
242 type TypeName struct {
243 object
244 }
245
246 // NewTypeName returns a new type name denoting the given typ.
247 // The remaining arguments set the attributes found with all Objects.
248 //
249 // The typ argument may be a defined (Named) type or an alias type.
250 // It may also be nil such that the returned TypeName can be used as
251 // argument for NewNamed, which will set the TypeName's type as a side-
252 // effect.
253 func NewTypeName(pos token.Pos, pkg *Package, name string, typ Type) *TypeName {
254 return &TypeName{object{nil, pos, pkg, name, typ, 0, nopos}}
255 }
256
257 // NewTypeNameLazy returns a new defined type like NewTypeName, but it
258 // lazily calls unpack to finish constructing the Named object.
259 func _NewTypeNameLazy(pos token.Pos, pkg *Package, name string, load func(*Named) ([]*TypeParam, Type, []*Func, []func())) *TypeName {
260 obj := NewTypeName(pos, pkg, name, nil)
261 n := (*Checker)(nil).newNamed(obj, nil, nil)
262 n.loader = load
263 return obj
264 }
265
266 // IsAlias reports whether obj is an alias name for a type.
267 func (obj *TypeName) IsAlias() bool {
268 switch t := obj.typ.(type) {
269 case nil:
270 return false
271 // case *Alias:
272 // handled by default case
273 case *Basic:
274 // unsafe.Pointer is not an alias.
275 if obj.pkg == Unsafe {
276 return false
277 }
278 // Any user-defined type name for a basic type is an alias for a
279 // basic type (because basic types are pre-declared in the Universe
280 // scope, outside any package scope), and so is any type name with
281 // a different name than the name of the basic type it refers to.
282 // Additionally, we need to look for "byte" and "rune" because they
283 // are aliases but have the same names (for better error messages).
284 return obj.pkg != nil || t.name != obj.name || t == universeByte || t == universeRune
285 case *Named:
286 return obj != t.obj
287 case *TypeParam:
288 return obj != t.obj
289 default:
290 return true
291 }
292 }
293
294 // A Var represents a declared variable (including function parameters and results, and struct fields).
295 type Var struct {
296 object
297 origin *Var // if non-nil, the Var from which this one was instantiated
298 kind VarKind
299 embedded bool // if set, the variable is an embedded struct field, and name is the type name
300 }
301
302 // A VarKind discriminates the various kinds of variables.
303 type VarKind uint8
304
305 const (
306 _ VarKind = iota // (not meaningful)
307 PackageVar // a package-level variable
308 LocalVar // a local variable
309 RecvVar // a method receiver variable
310 ParamVar // a function parameter variable
311 ResultVar // a function result variable
312 FieldVar // a struct field
313 )
314
315 var varKindNames = [...]string{
316 0: "VarKind(0)",
317 PackageVar: "PackageVar",
318 LocalVar: "LocalVar",
319 RecvVar: "RecvVar",
320 ParamVar: "ParamVar",
321 ResultVar: "ResultVar",
322 FieldVar: "FieldVar",
323 }
324
325 func (kind VarKind) String() string {
326 if 0 <= kind && int(kind) < len(varKindNames) {
327 return varKindNames[kind]
328 }
329 return fmt.Sprintf("VarKind(%d)", kind)
330 }
331
332 // Kind reports what kind of variable v is.
333 func (v *Var) Kind() VarKind { return v.kind }
334
335 // SetKind sets the kind of the variable.
336 // It should be used only immediately after [NewVar] or [NewParam].
337 func (v *Var) SetKind(kind VarKind) { v.kind = kind }
338
339 // NewVar returns a new variable.
340 // The arguments set the attributes found with all Objects.
341 //
342 // The caller must subsequently call [Var.SetKind]
343 // if the desired Var is not of kind [PackageVar].
344 func NewVar(pos token.Pos, pkg *Package, name string, typ Type) *Var {
345 return newVar(PackageVar, pos, pkg, name, typ)
346 }
347
348 // NewParam returns a new variable representing a function parameter.
349 //
350 // The caller must subsequently call [Var.SetKind] if the desired Var
351 // is not of kind [ParamVar]: for example, [RecvVar] or [ResultVar].
352 func NewParam(pos token.Pos, pkg *Package, name string, typ Type) *Var {
353 return newVar(ParamVar, pos, pkg, name, typ)
354 }
355
356 // NewField returns a new variable representing a struct field.
357 // For embedded fields, the name is the unqualified type name
358 // under which the field is accessible.
359 func NewField(pos token.Pos, pkg *Package, name string, typ Type, embedded bool) *Var {
360 v := newVar(FieldVar, pos, pkg, name, typ)
361 v.embedded = embedded
362 return v
363 }
364
365 // newVar returns a new variable.
366 // The arguments set the attributes found with all Objects.
367 func newVar(kind VarKind, pos token.Pos, pkg *Package, name string, typ Type) *Var {
368 return &Var{object: object{nil, pos, pkg, name, typ, 0, nopos}, kind: kind}
369 }
370
371 // Anonymous reports whether the variable is an embedded field.
372 // Same as Embedded; only present for backward-compatibility.
373 func (obj *Var) Anonymous() bool { return obj.embedded }
374
375 // Embedded reports whether the variable is an embedded field.
376 func (obj *Var) Embedded() bool { return obj.embedded }
377
378 // IsField reports whether the variable is a struct field.
379 func (obj *Var) IsField() bool { return obj.kind == FieldVar }
380
381 // Origin returns the canonical Var for its receiver, i.e. the Var object
382 // recorded in Info.Defs.
383 //
384 // For synthetic Vars created during instantiation (such as struct fields or
385 // function parameters that depend on type arguments), this will be the
386 // corresponding Var on the generic (uninstantiated) type. For all other Vars
387 // Origin returns the receiver.
388 func (obj *Var) Origin() *Var {
389 if obj.origin != nil {
390 return obj.origin
391 }
392 return obj
393 }
394
395 func (*Var) isDependency() {} // a variable may be a dependency of an initialization expression
396
397 // A Func represents a declared function, concrete method, or abstract
398 // (interface) method. Its Type() is always a *Signature.
399 // An abstract method may belong to many interfaces due to embedding.
400 type Func struct {
401 object
402 hasPtrRecv_ bool // only valid for methods that don't have a type yet; use hasPtrRecv() to read
403 origin *Func // if non-nil, the Func from which this one was instantiated
404 }
405
406 // NewFunc returns a new function with the given signature, representing
407 // the function's type.
408 func NewFunc(pos token.Pos, pkg *Package, name string, sig *Signature) *Func {
409 var typ Type
410 if sig != nil {
411 typ = sig
412 } else {
413 // Don't store a (typed) nil *Signature.
414 // We can't simply replace it with new(Signature) either,
415 // as this would violate object.{Type,color} invariants.
416 // TODO(adonovan): propose to disallow NewFunc with nil *Signature.
417 }
418 return &Func{object{nil, pos, pkg, name, typ, 0, nopos}, false, nil}
419 }
420
421 // Signature returns the signature (type) of the function or method.
422 func (obj *Func) Signature() *Signature {
423 if obj.typ != nil {
424 return obj.typ.(*Signature) // normal case
425 }
426 // No signature: Signature was called either:
427 // - within go/types, before a FuncDecl's initially
428 // nil Func.Type was lazily populated, indicating
429 // a types bug; or
430 // - by a client after NewFunc(..., nil),
431 // which is arguably a client bug, but we need a
432 // proposal to tighten NewFunc's precondition.
433 // For now, return a trivial signature.
434 return new(Signature)
435 }
436
437 // FullName returns the package- or receiver-type-qualified name of
438 // function or method obj.
439 func (obj *Func) FullName() string {
440 var buf bytes.Buffer
441 writeFuncName(&buf, obj, nil)
442 return buf.String()
443 }
444
445 // Scope returns the scope of the function's body block.
446 // The result is nil for imported or instantiated functions and methods
447 // (but there is also no mechanism to get to an instantiated function).
448 func (obj *Func) Scope() *Scope { return obj.typ.(*Signature).scope }
449
450 // Origin returns the canonical Func for its receiver, i.e. the Func object
451 // recorded in Info.Defs.
452 //
453 // For synthetic functions created during instantiation (such as methods on an
454 // instantiated Named type or interface methods that depend on type arguments),
455 // this will be the corresponding Func on the generic (uninstantiated) type.
456 // For all other Funcs Origin returns the receiver.
457 func (obj *Func) Origin() *Func {
458 if obj.origin != nil {
459 return obj.origin
460 }
461 return obj
462 }
463
464 // Pkg returns the package to which the function belongs.
465 //
466 // The result is nil for methods of types in the Universe scope,
467 // like method Error of the error built-in interface type.
468 func (obj *Func) Pkg() *Package { return obj.object.Pkg() }
469
470 // hasPtrRecv reports whether the receiver is of the form *T for the given method obj.
471 func (obj *Func) hasPtrRecv() bool {
472 // If a method's receiver type is set, use that as the source of truth for the receiver.
473 // Caution: Checker.funcDecl (decl.go) marks a function by setting its type to an empty
474 // signature. We may reach here before the signature is fully set up: we must explicitly
475 // check if the receiver is set (we cannot just look for non-nil obj.typ).
476 if sig, _ := obj.typ.(*Signature); sig != nil && sig.recv != nil {
477 _, isPtr := deref(sig.recv.typ)
478 return isPtr
479 }
480
481 // If a method's type is not set it may be a method/function that is:
482 // 1) client-supplied (via NewFunc with no signature), or
483 // 2) internally created but not yet type-checked.
484 // For case 1) we can't do anything; the client must know what they are doing.
485 // For case 2) we can use the information gathered by the resolver.
486 return obj.hasPtrRecv_
487 }
488
489 func (*Func) isDependency() {} // a function may be a dependency of an initialization expression
490
491 // A Label represents a declared label.
492 // Labels don't have a type.
493 type Label struct {
494 object
495 used bool // set if the label was used
496 }
497
498 // NewLabel returns a new label.
499 func NewLabel(pos token.Pos, pkg *Package, name string) *Label {
500 return &Label{object{pos: pos, pkg: pkg, name: name, typ: Typ[Invalid]}, false}
501 }
502
503 // A Builtin represents a built-in function.
504 // Builtins don't have a valid type.
505 type Builtin struct {
506 object
507 id builtinId
508 }
509
510 func newBuiltin(id builtinId) *Builtin {
511 return &Builtin{object{name: predeclaredFuncs[id].name, typ: Typ[Invalid]}, id}
512 }
513
514 // Nil represents the predeclared value nil.
515 type Nil struct {
516 object
517 }
518
519 func writeObject(buf *bytes.Buffer, obj Object, qf Qualifier) {
520 var tname *TypeName
521 typ := obj.Type()
522
523 switch obj := obj.(type) {
524 case *PkgName:
525 fmt.Fprintf(buf, "package %s", obj.Name())
526 if path := obj.imported.path; path != "" && path != obj.name {
527 fmt.Fprintf(buf, " (%q)", path)
528 }
529 return
530
531 case *Const:
532 buf.WriteString("const")
533
534 case *TypeName:
535 tname = obj
536 buf.WriteString("type")
537 if isTypeParam(typ) {
538 buf.WriteString(" parameter")
539 }
540
541 case *Var:
542 if obj.IsField() {
543 buf.WriteString("field")
544 } else {
545 buf.WriteString("var")
546 }
547
548 case *Func:
549 buf.WriteString("func ")
550 writeFuncName(buf, obj, qf)
551 if typ != nil {
552 WriteSignature(buf, typ.(*Signature), qf)
553 }
554 return
555
556 case *Label:
557 buf.WriteString("label")
558 typ = nil
559
560 case *Builtin:
561 buf.WriteString("builtin")
562 typ = nil
563
564 case *Nil:
565 buf.WriteString("nil")
566 return
567
568 default:
569 panic(fmt.Sprintf("writeObject(%T)", obj))
570 }
571
572 buf.WriteByte(' ')
573
574 // For package-level objects, qualify the name.
575 if obj.Pkg() != nil && obj.Pkg().scope.Lookup(obj.Name()) == obj {
576 buf.WriteString(packagePrefix(obj.Pkg(), qf))
577 }
578 buf.WriteString(obj.Name())
579
580 if typ == nil {
581 return
582 }
583
584 if tname != nil {
585 switch t := typ.(type) {
586 case *Basic:
587 // Don't print anything more for basic types since there's
588 // no more information.
589 return
590 case genericType:
591 if t.TypeParams().Len() > 0 {
592 newTypeWriter(buf, qf).tParamList(t.TypeParams().list())
593 }
594 }
595 if tname.IsAlias() {
596 buf.WriteString(" =")
597 if alias, ok := typ.(*Alias); ok { // materialized? (gotypesalias=1)
598 typ = alias.fromRHS
599 }
600 } else if t, _ := typ.(*TypeParam); t != nil {
601 typ = t.bound
602 } else {
603 // TODO(gri) should this be fromRHS for *Named?
604 // (See discussion in #66559.)
605 typ = typ.Underlying()
606 }
607 }
608
609 // Special handling for any: because WriteType will format 'any' as 'any',
610 // resulting in the object string `type any = any` rather than `type any =
611 // interface{}`. To avoid this, swap in a different empty interface.
612 if obj.Name() == "any" && obj.Parent() == Universe {
613 assert(Identical(typ, &emptyInterface))
614 typ = &emptyInterface
615 }
616
617 buf.WriteByte(' ')
618 WriteType(buf, typ, qf)
619 }
620
621 func packagePrefix(pkg *Package, qf Qualifier) string {
622 if pkg == nil {
623 return ""
624 }
625 var s string
626 if qf != nil {
627 s = qf(pkg)
628 } else {
629 s = pkg.Path()
630 }
631 if s != "" {
632 s += "."
633 }
634 return s
635 }
636
637 // ObjectString returns the string form of obj.
638 // The Qualifier controls the printing of
639 // package-level objects, and may be nil.
640 func ObjectString(obj Object, qf Qualifier) string {
641 var buf bytes.Buffer
642 writeObject(&buf, obj, qf)
643 return buf.String()
644 }
645
646 func (obj *PkgName) String() string { return ObjectString(obj, nil) }
647 func (obj *Const) String() string { return ObjectString(obj, nil) }
648 func (obj *TypeName) String() string { return ObjectString(obj, nil) }
649 func (obj *Var) String() string { return ObjectString(obj, nil) }
650 func (obj *Func) String() string { return ObjectString(obj, nil) }
651 func (obj *Label) String() string { return ObjectString(obj, nil) }
652 func (obj *Builtin) String() string { return ObjectString(obj, nil) }
653 func (obj *Nil) String() string { return ObjectString(obj, nil) }
654
655 func writeFuncName(buf *bytes.Buffer, f *Func, qf Qualifier) {
656 if f.typ != nil {
657 sig := f.typ.(*Signature)
658 if recv := sig.Recv(); recv != nil {
659 buf.WriteByte('(')
660 if _, ok := recv.Type().(*Interface); ok {
661 // gcimporter creates abstract methods of
662 // named interfaces using the interface type
663 // (not the named type) as the receiver.
664 // Don't print it in full.
665 buf.WriteString("interface")
666 } else {
667 WriteType(buf, recv.Type(), qf)
668 }
669 buf.WriteByte(')')
670 buf.WriteByte('.')
671 } else if f.pkg != nil {
672 buf.WriteString(packagePrefix(f.pkg, qf))
673 }
674 }
675 buf.WriteString(f.name)
676 }
677
678 // objectKind returns a description of the object's kind.
679 func objectKind(obj Object) string {
680 switch obj := obj.(type) {
681 case *PkgName:
682 return "package name"
683 case *Const:
684 return "constant"
685 case *TypeName:
686 if obj.IsAlias() {
687 return "type alias"
688 } else if _, ok := obj.Type().(*TypeParam); ok {
689 return "type parameter"
690 } else {
691 return "defined type"
692 }
693 case *Var:
694 switch obj.Kind() {
695 case PackageVar:
696 return "package-level variable"
697 case LocalVar:
698 return "local variable"
699 case RecvVar:
700 return "receiver"
701 case ParamVar:
702 return "parameter"
703 case ResultVar:
704 return "result variable"
705 case FieldVar:
706 return "struct field"
707 }
708 case *Func:
709 if obj.Signature().Recv() != nil {
710 return "method"
711 } else {
712 return "function"
713 }
714 case *Label:
715 return "label"
716 case *Builtin:
717 return "built-in function"
718 case *Nil:
719 return "untyped nil"
720 }
721 if debug {
722 panic(fmt.Sprintf("unknown symbol (%T)", obj))
723 }
724 return "unknown symbol"
725 }