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.
9 "cmd/compile/internal/syntax"
16 // An Object describes a named language entity such as a package,
17 // constant, type, variable, function (incl. methods), or label.
18 // All objects implement the Object interface.
19 type Object interface {
20 Parent() *Scope // scope in which this object is declared; nil for methods and struct fields
21 Pos() syntax.Pos // position of object identifier in declaration
22 Pkg() *Package // package to which this object belongs; nil for labels and objects in the Universe scope
23 Name() string // package local object name
24 Type() Type // object type
25 Exported() bool // reports whether the name starts with a capital letter
26 Id() string // object name if exported, qualified name if not exported (see func Id)
28 // String returns a human-readable string of the object.
31 // order reflects a package-level object's source order: if object
32 // a is before object b in the source, then a.order() < b.order().
33 // order returns a value > 0 for package-level objects; it returns
34 // 0 for all other objects (including objects in file scopes).
37 // color returns the object's color.
40 // setType sets the type of the object.
43 // setOrder sets the order number of the object. It must be > 0.
46 // setColor sets the object's color. It must not be white.
49 // setParent sets the parent scope of the object.
52 // sameId reports whether obj.Id() and Id(pkg, name) are the same.
53 sameId(pkg *Package, name string) bool
55 // scopePos returns the start position of the scope of this Object
58 // setScopePos sets the start position of the scope for this Object.
59 setScopePos(pos syntax.Pos)
62 func isExported(name string) bool {
63 ch, _ := utf8.DecodeRuneInString(name)
64 return unicode.IsUpper(ch)
67 // Id returns name if it is exported, otherwise it
68 // returns the name qualified with the package path.
69 func Id(pkg *Package, name string) string {
73 // unexported names need the package path for differentiation
74 // (if there's no package, make sure we don't start with '.'
75 // as that may change the order of methods between a setup
76 // inside a package and outside a package - which breaks some
79 // pkg is nil for objects in Universe scope and possibly types
80 // introduced via Eval (see also comment in object.sameId)
81 if pkg != nil && pkg.path != "" {
84 return path + "." + name
87 // An object implements the common parts of an Object.
99 // color encodes the color of an object (see Checker.objDecl for details).
102 // An object may be painted in one of three colors.
103 // Color values other than white or black are considered grey.
107 grey // must be > white and black
110 func (c color) String() string {
121 // colorFor returns the (initial) color for an object depending on
122 // whether its type t is known or not.
123 func colorFor(t Type) color {
130 // Parent returns the scope in which the object is declared.
131 // The result is nil for methods and struct fields.
132 func (obj *object) Parent() *Scope { return obj.parent }
134 // Pos returns the declaration position of the object's identifier.
135 func (obj *object) Pos() syntax.Pos { return obj.pos }
137 // Pkg returns the package to which the object belongs.
138 // The result is nil for labels and objects in the Universe scope.
139 func (obj *object) Pkg() *Package { return obj.pkg }
141 // Name returns the object's (package-local, unqualified) name.
142 func (obj *object) Name() string { return obj.name }
144 // Type returns the object's type.
145 func (obj *object) Type() Type { return obj.typ }
147 // Exported reports whether the object is exported (starts with a capital letter).
148 // It doesn't take into account whether the object is in a local (function) scope
150 func (obj *object) Exported() bool { return isExported(obj.name) }
152 // Id is a wrapper for Id(obj.Pkg(), obj.Name()).
153 func (obj *object) Id() string { return Id(obj.pkg, obj.name) }
155 func (obj *object) String() string { panic("abstract") }
156 func (obj *object) order() uint32 { return obj.order_ }
157 func (obj *object) color() color { return obj.color_ }
158 func (obj *object) scopePos() syntax.Pos { return obj.scopePos_ }
160 func (obj *object) setParent(parent *Scope) { obj.parent = parent }
161 func (obj *object) setType(typ Type) { obj.typ = typ }
162 func (obj *object) setOrder(order uint32) { assert(order > 0); obj.order_ = order }
163 func (obj *object) setColor(color color) { assert(color != white); obj.color_ = color }
164 func (obj *object) setScopePos(pos syntax.Pos) { obj.scopePos_ = pos }
166 func (obj *object) sameId(pkg *Package, name string) bool {
168 // "Two identifiers are different if they are spelled differently,
169 // or if they appear in different packages and are not exported.
170 // Otherwise, they are the same."
171 if name != obj.name {
178 // not exported, so packages must be the same (pkg == nil for
179 // fields in Universe scope; this can only happen for types
180 // introduced via Eval)
181 if pkg == nil || obj.pkg == nil {
182 return pkg == obj.pkg
184 // pkg != nil && obj.pkg != nil
185 return pkg.path == obj.pkg.path
188 // less reports whether object a is ordered before object b.
190 // Objects are ordered nil before non-nil, exported before
191 // non-exported, then by name, and finally (for non-exported
192 // functions) by package height and path.
193 func (a *object) less(b *object) bool {
198 // Nil before non-nil.
206 // Exported functions before non-exported.
207 ea := isExported(a.name)
208 eb := isExported(b.name)
213 // Order by name and then (for non-exported names) by package.
214 if a.name != b.name {
215 return a.name < b.name
218 if a.pkg.height != b.pkg.height {
219 return a.pkg.height < b.pkg.height
221 return a.pkg.path < b.pkg.path
227 // A PkgName represents an imported Go package.
228 // PkgNames don't have a type.
229 type PkgName struct {
232 used bool // set if the package was used
235 // NewPkgName returns a new PkgName object representing an imported package.
236 // The remaining arguments set the attributes found with all Objects.
237 func NewPkgName(pos syntax.Pos, pkg *Package, name string, imported *Package) *PkgName {
238 return &PkgName{object{nil, pos, pkg, name, Typ[Invalid], 0, black, nopos}, imported, false}
241 // Imported returns the package that was imported.
242 // It is distinct from Pkg(), which is the package containing the import statement.
243 func (obj *PkgName) Imported() *Package { return obj.imported }
245 // A Const represents a declared constant.
251 // NewConst returns a new constant with value val.
252 // The remaining arguments set the attributes found with all Objects.
253 func NewConst(pos syntax.Pos, pkg *Package, name string, typ Type, val constant.Value) *Const {
254 return &Const{object{nil, pos, pkg, name, typ, 0, colorFor(typ), nopos}, val}
257 // Val returns the constant's value.
258 func (obj *Const) Val() constant.Value { return obj.val }
260 func (*Const) isDependency() {} // a constant may be a dependency of an initialization expression
262 // A TypeName represents a name for a (defined or alias) type.
263 type TypeName struct {
267 // NewTypeName returns a new type name denoting the given typ.
268 // The remaining arguments set the attributes found with all Objects.
270 // The typ argument may be a defined (Named) type or an alias type.
271 // It may also be nil such that the returned TypeName can be used as
272 // argument for NewNamed, which will set the TypeName's type as a side-
274 func NewTypeName(pos syntax.Pos, pkg *Package, name string, typ Type) *TypeName {
275 return &TypeName{object{nil, pos, pkg, name, typ, 0, colorFor(typ), nopos}}
278 // NewTypeNameLazy returns a new defined type like NewTypeName, but it
279 // lazily calls resolve to finish constructing the Named object.
280 func NewTypeNameLazy(pos syntax.Pos, pkg *Package, name string, load func(named *Named) (tparams []*TypeParam, underlying Type, methods []*Func)) *TypeName {
281 obj := NewTypeName(pos, pkg, name, nil)
283 resolve := func(_ *Context, t *Named) (*TypeParamList, Type, *methodList) {
284 tparams, underlying, methods := load(t)
286 switch underlying.(type) {
288 panic(fmt.Sprintf("invalid underlying type %T", t.underlying))
291 return bindTParams(tparams), underlying, newMethodList(methods)
294 NewNamed(obj, nil, nil).resolver = resolve
298 // IsAlias reports whether obj is an alias name for a type.
299 func (obj *TypeName) IsAlias() bool {
300 switch t := obj.typ.(type) {
304 // unsafe.Pointer is not an alias.
305 if obj.pkg == Unsafe {
308 // Any user-defined type name for a basic type is an alias for a
309 // basic type (because basic types are pre-declared in the Universe
310 // scope, outside any package scope), and so is any type name with
311 // a different name than the name of the basic type it refers to.
312 // Additionally, we need to look for "byte" and "rune" because they
313 // are aliases but have the same names (for better error messages).
314 return obj.pkg != nil || t.name != obj.name || t == universeByte || t == universeRune
324 // A Variable represents a declared variable (including function parameters and results, and struct fields).
327 embedded bool // if set, the variable is an embedded struct field, and name is the type name
328 isField bool // var is struct field
329 used bool // set if the variable was used
330 origin *Var // if non-nil, the Var from which this one was instantiated
333 // NewVar returns a new variable.
334 // The arguments set the attributes found with all Objects.
335 func NewVar(pos syntax.Pos, pkg *Package, name string, typ Type) *Var {
336 return &Var{object: object{nil, pos, pkg, name, typ, 0, colorFor(typ), nopos}}
339 // NewParam returns a new variable representing a function parameter.
340 func NewParam(pos syntax.Pos, pkg *Package, name string, typ Type) *Var {
341 return &Var{object: object{nil, pos, pkg, name, typ, 0, colorFor(typ), nopos}, used: true} // parameters are always 'used'
344 // NewField returns a new variable representing a struct field.
345 // For embedded fields, the name is the unqualified type name
346 // under which the field is accessible.
347 func NewField(pos syntax.Pos, pkg *Package, name string, typ Type, embedded bool) *Var {
348 return &Var{object: object{nil, pos, pkg, name, typ, 0, colorFor(typ), nopos}, embedded: embedded, isField: true}
351 // Anonymous reports whether the variable is an embedded field.
352 // Same as Embedded; only present for backward-compatibility.
353 func (obj *Var) Anonymous() bool { return obj.embedded }
355 // Embedded reports whether the variable is an embedded field.
356 func (obj *Var) Embedded() bool { return obj.embedded }
358 // IsField reports whether the variable is a struct field.
359 func (obj *Var) IsField() bool { return obj.isField }
361 // Origin returns the canonical Var for its receiver, i.e. the Var object
362 // recorded in Info.Defs.
364 // For synthetic Vars created during instantiation (such as struct fields or
365 // function parameters that depend on type arguments), this will be the
366 // corresponding Var on the generic (uninstantiated) type. For all other Vars
367 // Origin returns the receiver.
368 func (obj *Var) Origin() *Var {
369 if obj.origin != nil {
375 func (*Var) isDependency() {} // a variable may be a dependency of an initialization expression
377 // A Func represents a declared function, concrete method, or abstract
378 // (interface) method. Its Type() is always a *Signature.
379 // An abstract method may belong to many interfaces due to embedding.
382 hasPtrRecv_ bool // only valid for methods that don't have a type yet; use hasPtrRecv() to read
383 origin *Func // if non-nil, the Func from which this one was instantiated
386 // NewFunc returns a new function with the given signature, representing
387 // the function's type.
388 func NewFunc(pos syntax.Pos, pkg *Package, name string, sig *Signature) *Func {
389 // don't store a (typed) nil signature
394 return &Func{object{nil, pos, pkg, name, typ, 0, colorFor(typ), nopos}, false, nil}
397 // FullName returns the package- or receiver-type-qualified name of
398 // function or method obj.
399 func (obj *Func) FullName() string {
401 writeFuncName(&buf, obj, nil)
405 // Scope returns the scope of the function's body block.
406 // The result is nil for imported or instantiated functions and methods
407 // (but there is also no mechanism to get to an instantiated function).
408 func (obj *Func) Scope() *Scope { return obj.typ.(*Signature).scope }
410 // Origin returns the canonical Func for its receiver, i.e. the Func object
411 // recorded in Info.Defs.
413 // For synthetic functions created during instantiation (such as methods on an
414 // instantiated Named type or interface methods that depend on type arguments),
415 // this will be the corresponding Func on the generic (uninstantiated) type.
416 // For all other Funcs Origin returns the receiver.
417 func (obj *Func) Origin() *Func {
418 if obj.origin != nil {
424 // hasPtrRecv reports whether the receiver is of the form *T for the given method obj.
425 func (obj *Func) hasPtrRecv() bool {
426 // If a method's receiver type is set, use that as the source of truth for the receiver.
427 // Caution: Checker.funcDecl (decl.go) marks a function by setting its type to an empty
428 // signature. We may reach here before the signature is fully set up: we must explicitly
429 // check if the receiver is set (we cannot just look for non-nil obj.typ).
430 if sig, _ := obj.typ.(*Signature); sig != nil && sig.recv != nil {
431 _, isPtr := deref(sig.recv.typ)
435 // If a method's type is not set it may be a method/function that is:
436 // 1) client-supplied (via NewFunc with no signature), or
437 // 2) internally created but not yet type-checked.
438 // For case 1) we can't do anything; the client must know what they are doing.
439 // For case 2) we can use the information gathered by the resolver.
440 return obj.hasPtrRecv_
443 func (*Func) isDependency() {} // a function may be a dependency of an initialization expression
445 // A Label represents a declared label.
446 // Labels don't have a type.
449 used bool // set if the label was used
452 // NewLabel returns a new label.
453 func NewLabel(pos syntax.Pos, pkg *Package, name string) *Label {
454 return &Label{object{pos: pos, pkg: pkg, name: name, typ: Typ[Invalid], color_: black}, false}
457 // A Builtin represents a built-in function.
458 // Builtins don't have a valid type.
459 type Builtin struct {
464 func newBuiltin(id builtinId) *Builtin {
465 return &Builtin{object{name: predeclaredFuncs[id].name, typ: Typ[Invalid], color_: black}, id}
468 // Nil represents the predeclared value nil.
473 func writeObject(buf *bytes.Buffer, obj Object, qf Qualifier) {
477 switch obj := obj.(type) {
479 fmt.Fprintf(buf, "package %s", obj.Name())
480 if path := obj.imported.path; path != "" && path != obj.name {
481 fmt.Fprintf(buf, " (%q)", path)
486 buf.WriteString("const")
490 buf.WriteString("type")
491 if isTypeParam(typ) {
492 buf.WriteString(" parameter")
497 buf.WriteString("field")
499 buf.WriteString("var")
503 buf.WriteString("func ")
504 writeFuncName(buf, obj, qf)
506 WriteSignature(buf, typ.(*Signature), qf)
511 buf.WriteString("label")
515 buf.WriteString("builtin")
519 buf.WriteString("nil")
523 panic(fmt.Sprintf("writeObject(%T)", obj))
528 // For package-level objects, qualify the name.
529 if obj.Pkg() != nil && obj.Pkg().scope.Lookup(obj.Name()) == obj {
530 writePackage(buf, obj.Pkg(), qf)
532 buf.WriteString(obj.Name())
539 switch t := typ.(type) {
541 // Don't print anything more for basic types since there's
542 // no more information.
545 if t.TypeParams().Len() > 0 {
546 newTypeWriter(buf, qf).tParamList(t.TypeParams().list())
550 buf.WriteString(" =")
551 } else if t, _ := typ.(*TypeParam); t != nil {
554 // TODO(gri) should this be fromRHS for *Named?
559 // Special handling for any: because WriteType will format 'any' as 'any',
560 // resulting in the object string `type any = any` rather than `type any =
561 // interface{}`. To avoid this, swap in a different empty interface.
562 if obj == universeAny {
563 assert(Identical(typ, &emptyInterface))
564 typ = &emptyInterface
568 WriteType(buf, typ, qf)
571 func writePackage(buf *bytes.Buffer, pkg *Package, qf Qualifier) {
587 // ObjectString returns the string form of obj.
588 // The Qualifier controls the printing of
589 // package-level objects, and may be nil.
590 func ObjectString(obj Object, qf Qualifier) string {
592 writeObject(&buf, obj, qf)
596 func (obj *PkgName) String() string { return ObjectString(obj, nil) }
597 func (obj *Const) String() string { return ObjectString(obj, nil) }
598 func (obj *TypeName) String() string { return ObjectString(obj, nil) }
599 func (obj *Var) String() string { return ObjectString(obj, nil) }
600 func (obj *Func) String() string { return ObjectString(obj, nil) }
601 func (obj *Label) String() string { return ObjectString(obj, nil) }
602 func (obj *Builtin) String() string { return ObjectString(obj, nil) }
603 func (obj *Nil) String() string { return ObjectString(obj, nil) }
605 func writeFuncName(buf *bytes.Buffer, f *Func, qf Qualifier) {
607 sig := f.typ.(*Signature)
608 if recv := sig.Recv(); recv != nil {
610 if _, ok := recv.Type().(*Interface); ok {
611 // gcimporter creates abstract methods of
612 // named interfaces using the interface type
613 // (not the named type) as the receiver.
614 // Don't print it in full.
615 buf.WriteString("interface")
617 WriteType(buf, recv.Type(), qf)
621 } else if f.pkg != nil {
622 writePackage(buf, f.pkg, qf)
625 buf.WriteString(f.name)