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