Debian Codegraph @

src/cmd/compile/internal/types2/object.go

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