]> Cypherpunks.ru repositories - gostls13.git/blob - src/cmd/compile/internal/types2/object.go
591adeac3da31449901247edf80614af75c86b09
[gostls13.git] / src / cmd / compile / internal / types2 / object.go
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         "unicode"
13         "unicode/utf8"
14 )
15
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)
27
28         // String returns a human-readable string of the object.
29         String() string
30
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).
35         order() uint32
36
37         // color returns the object's color.
38         color() color
39
40         // setType sets the type of the object.
41         setType(Type)
42
43         // setOrder sets the order number of the object. It must be > 0.
44         setOrder(uint32)
45
46         // setColor sets the object's color. It must not be white.
47         setColor(color color)
48
49         // setParent sets the parent scope of the object.
50         setParent(*Scope)
51
52         // sameId reports whether obj.Id() and Id(pkg, name) are the same.
53         sameId(pkg *Package, name string) bool
54
55         // scopePos returns the start position of the scope of this Object
56         scopePos() syntax.Pos
57
58         // setScopePos sets the start position of the scope for this Object.
59         setScopePos(pos syntax.Pos)
60 }
61
62 func isExported(name string) bool {
63         ch, _ := utf8.DecodeRuneInString(name)
64         return unicode.IsUpper(ch)
65 }
66
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 {
70         if isExported(name) {
71                 return name
72         }
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
77         // tests)
78         path := "_"
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 != "" {
82                 path = pkg.path
83         }
84         return path + "." + name
85 }
86
87 // An object implements the common parts of an Object.
88 type object struct {
89         parent    *Scope
90         pos       syntax.Pos
91         pkg       *Package
92         name      string
93         typ       Type
94         order_    uint32
95         color_    color
96         scopePos_ syntax.Pos
97 }
98
99 // color encodes the color of an object (see Checker.objDecl for details).
100 type color uint32
101
102 // An object may be painted in one of three colors.
103 // Color values other than white or black are considered grey.
104 const (
105         white color = iota
106         black
107         grey // must be > white and black
108 )
109
110 func (c color) String() string {
111         switch c {
112         case white:
113                 return "white"
114         case black:
115                 return "black"
116         default:
117                 return "grey"
118         }
119 }
120
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 {
124         if t != nil {
125                 return black
126         }
127         return white
128 }
129
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 }
133
134 // Pos returns the declaration position of the object's identifier.
135 func (obj *object) Pos() syntax.Pos { return obj.pos }
136
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 }
140
141 // Name returns the object's (package-local, unqualified) name.
142 func (obj *object) Name() string { return obj.name }
143
144 // Type returns the object's type.
145 func (obj *object) Type() Type { return obj.typ }
146
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
149 // or not.
150 func (obj *object) Exported() bool { return isExported(obj.name) }
151
152 // Id is a wrapper for Id(obj.Pkg(), obj.Name()).
153 func (obj *object) Id() string { return Id(obj.pkg, obj.name) }
154
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_ }
159
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 }
165
166 func (obj *object) sameId(pkg *Package, name string) bool {
167         // spec:
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 {
172                 return false
173         }
174         // obj.Name == name
175         if obj.Exported() {
176                 return true
177         }
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
183         }
184         // pkg != nil && obj.pkg != nil
185         return pkg.path == obj.pkg.path
186 }
187
188 // less reports whether object a is ordered before object b.
189 //
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 path.
193 func (a *object) less(b *object) bool {
194         if a == b {
195                 return false
196         }
197
198         // Nil before non-nil.
199         if a == nil {
200                 return true
201         }
202         if b == nil {
203                 return false
204         }
205
206         // Exported functions before non-exported.
207         ea := isExported(a.name)
208         eb := isExported(b.name)
209         if ea != eb {
210                 return ea
211         }
212
213         // Order by name and then (for non-exported names) by package.
214         if a.name != b.name {
215                 return a.name < b.name
216         }
217         if !ea {
218                 return a.pkg.path < b.pkg.path
219         }
220
221         return false
222 }
223
224 // A PkgName represents an imported Go package.
225 // PkgNames don't have a type.
226 type PkgName struct {
227         object
228         imported *Package
229         used     bool // set if the package was used
230 }
231
232 // NewPkgName returns a new PkgName object representing an imported package.
233 // The remaining arguments set the attributes found with all Objects.
234 func NewPkgName(pos syntax.Pos, pkg *Package, name string, imported *Package) *PkgName {
235         return &PkgName{object{nil, pos, pkg, name, Typ[Invalid], 0, black, nopos}, imported, false}
236 }
237
238 // Imported returns the package that was imported.
239 // It is distinct from Pkg(), which is the package containing the import statement.
240 func (obj *PkgName) Imported() *Package { return obj.imported }
241
242 // A Const represents a declared constant.
243 type Const struct {
244         object
245         val constant.Value
246 }
247
248 // NewConst returns a new constant with value val.
249 // The remaining arguments set the attributes found with all Objects.
250 func NewConst(pos syntax.Pos, pkg *Package, name string, typ Type, val constant.Value) *Const {
251         return &Const{object{nil, pos, pkg, name, typ, 0, colorFor(typ), nopos}, val}
252 }
253
254 // Val returns the constant's value.
255 func (obj *Const) Val() constant.Value { return obj.val }
256
257 func (*Const) isDependency() {} // a constant may be a dependency of an initialization expression
258
259 // A TypeName represents a name for a (defined or alias) type.
260 type TypeName struct {
261         object
262 }
263
264 // NewTypeName returns a new type name denoting the given typ.
265 // The remaining arguments set the attributes found with all Objects.
266 //
267 // The typ argument may be a defined (Named) type or an alias type.
268 // It may also be nil such that the returned TypeName can be used as
269 // argument for NewNamed, which will set the TypeName's type as a side-
270 // effect.
271 func NewTypeName(pos syntax.Pos, pkg *Package, name string, typ Type) *TypeName {
272         return &TypeName{object{nil, pos, pkg, name, typ, 0, colorFor(typ), nopos}}
273 }
274
275 // NewTypeNameLazy returns a new defined type like NewTypeName, but it
276 // lazily calls resolve to finish constructing the Named object.
277 func NewTypeNameLazy(pos syntax.Pos, pkg *Package, name string, load func(named *Named) (tparams []*TypeParam, underlying Type, methods []*Func)) *TypeName {
278         obj := NewTypeName(pos, pkg, name, nil)
279         NewNamed(obj, nil, nil).loader = load
280         return obj
281 }
282
283 // IsAlias reports whether obj is an alias name for a type.
284 func (obj *TypeName) IsAlias() bool {
285         switch t := obj.typ.(type) {
286         case nil:
287                 return false
288         case *Basic:
289                 // unsafe.Pointer is not an alias.
290                 if obj.pkg == Unsafe {
291                         return false
292                 }
293                 // Any user-defined type name for a basic type is an alias for a
294                 // basic type (because basic types are pre-declared in the Universe
295                 // scope, outside any package scope), and so is any type name with
296                 // a different name than the name of the basic type it refers to.
297                 // Additionally, we need to look for "byte" and "rune" because they
298                 // are aliases but have the same names (for better error messages).
299                 return obj.pkg != nil || t.name != obj.name || t == universeByte || t == universeRune
300         case *Named:
301                 return obj != t.obj
302         case *TypeParam:
303                 return obj != t.obj
304         default:
305                 return true
306         }
307 }
308
309 // A Variable represents a declared variable (including function parameters and results, and struct fields).
310 type Var struct {
311         object
312         embedded bool // if set, the variable is an embedded struct field, and name is the type name
313         isField  bool // var is struct field
314         used     bool // set if the variable was used
315         origin   *Var // if non-nil, the Var from which this one was instantiated
316 }
317
318 // NewVar returns a new variable.
319 // The arguments set the attributes found with all Objects.
320 func NewVar(pos syntax.Pos, pkg *Package, name string, typ Type) *Var {
321         return &Var{object: object{nil, pos, pkg, name, typ, 0, colorFor(typ), nopos}}
322 }
323
324 // NewParam returns a new variable representing a function parameter.
325 func NewParam(pos syntax.Pos, pkg *Package, name string, typ Type) *Var {
326         return &Var{object: object{nil, pos, pkg, name, typ, 0, colorFor(typ), nopos}, used: true} // parameters are always 'used'
327 }
328
329 // NewField returns a new variable representing a struct field.
330 // For embedded fields, the name is the unqualified type name
331 // under which the field is accessible.
332 func NewField(pos syntax.Pos, pkg *Package, name string, typ Type, embedded bool) *Var {
333         return &Var{object: object{nil, pos, pkg, name, typ, 0, colorFor(typ), nopos}, embedded: embedded, isField: true}
334 }
335
336 // Anonymous reports whether the variable is an embedded field.
337 // Same as Embedded; only present for backward-compatibility.
338 func (obj *Var) Anonymous() bool { return obj.embedded }
339
340 // Embedded reports whether the variable is an embedded field.
341 func (obj *Var) Embedded() bool { return obj.embedded }
342
343 // IsField reports whether the variable is a struct field.
344 func (obj *Var) IsField() bool { return obj.isField }
345
346 // Origin returns the canonical Var for its receiver, i.e. the Var object
347 // recorded in Info.Defs.
348 //
349 // For synthetic Vars created during instantiation (such as struct fields or
350 // function parameters that depend on type arguments), this will be the
351 // corresponding Var on the generic (uninstantiated) type. For all other Vars
352 // Origin returns the receiver.
353 func (obj *Var) Origin() *Var {
354         if obj.origin != nil {
355                 return obj.origin
356         }
357         return obj
358 }
359
360 func (*Var) isDependency() {} // a variable may be a dependency of an initialization expression
361
362 // A Func represents a declared function, concrete method, or abstract
363 // (interface) method. Its Type() is always a *Signature.
364 // An abstract method may belong to many interfaces due to embedding.
365 type Func struct {
366         object
367         hasPtrRecv_ bool  // only valid for methods that don't have a type yet; use hasPtrRecv() to read
368         origin      *Func // if non-nil, the Func from which this one was instantiated
369 }
370
371 // NewFunc returns a new function with the given signature, representing
372 // the function's type.
373 func NewFunc(pos syntax.Pos, pkg *Package, name string, sig *Signature) *Func {
374         // don't store a (typed) nil signature
375         var typ Type
376         if sig != nil {
377                 typ = sig
378         }
379         return &Func{object{nil, pos, pkg, name, typ, 0, colorFor(typ), nopos}, false, nil}
380 }
381
382 // FullName returns the package- or receiver-type-qualified name of
383 // function or method obj.
384 func (obj *Func) FullName() string {
385         var buf bytes.Buffer
386         writeFuncName(&buf, obj, nil)
387         return buf.String()
388 }
389
390 // Scope returns the scope of the function's body block.
391 // The result is nil for imported or instantiated functions and methods
392 // (but there is also no mechanism to get to an instantiated function).
393 func (obj *Func) Scope() *Scope { return obj.typ.(*Signature).scope }
394
395 // Origin returns the canonical Func for its receiver, i.e. the Func object
396 // recorded in Info.Defs.
397 //
398 // For synthetic functions created during instantiation (such as methods on an
399 // instantiated Named type or interface methods that depend on type arguments),
400 // this will be the corresponding Func on the generic (uninstantiated) type.
401 // For all other Funcs Origin returns the receiver.
402 func (obj *Func) Origin() *Func {
403         if obj.origin != nil {
404                 return obj.origin
405         }
406         return obj
407 }
408
409 // Pkg returns the package to which the function belongs.
410 //
411 // The result is nil for methods of types in the Universe scope,
412 // like method Error of the error built-in interface type.
413 func (obj *Func) Pkg() *Package { return obj.object.Pkg() }
414
415 // hasPtrRecv reports whether the receiver is of the form *T for the given method obj.
416 func (obj *Func) hasPtrRecv() bool {
417         // If a method's receiver type is set, use that as the source of truth for the receiver.
418         // Caution: Checker.funcDecl (decl.go) marks a function by setting its type to an empty
419         // signature. We may reach here before the signature is fully set up: we must explicitly
420         // check if the receiver is set (we cannot just look for non-nil obj.typ).
421         if sig, _ := obj.typ.(*Signature); sig != nil && sig.recv != nil {
422                 _, isPtr := deref(sig.recv.typ)
423                 return isPtr
424         }
425
426         // If a method's type is not set it may be a method/function that is:
427         // 1) client-supplied (via NewFunc with no signature), or
428         // 2) internally created but not yet type-checked.
429         // For case 1) we can't do anything; the client must know what they are doing.
430         // For case 2) we can use the information gathered by the resolver.
431         return obj.hasPtrRecv_
432 }
433
434 func (*Func) isDependency() {} // a function may be a dependency of an initialization expression
435
436 // A Label represents a declared label.
437 // Labels don't have a type.
438 type Label struct {
439         object
440         used bool // set if the label was used
441 }
442
443 // NewLabel returns a new label.
444 func NewLabel(pos syntax.Pos, pkg *Package, name string) *Label {
445         return &Label{object{pos: pos, pkg: pkg, name: name, typ: Typ[Invalid], color_: black}, false}
446 }
447
448 // A Builtin represents a built-in function.
449 // Builtins don't have a valid type.
450 type Builtin struct {
451         object
452         id builtinId
453 }
454
455 func newBuiltin(id builtinId) *Builtin {
456         return &Builtin{object{name: predeclaredFuncs[id].name, typ: Typ[Invalid], color_: black}, id}
457 }
458
459 // Nil represents the predeclared value nil.
460 type Nil struct {
461         object
462 }
463
464 func writeObject(buf *bytes.Buffer, obj Object, qf Qualifier) {
465         var tname *TypeName
466         typ := obj.Type()
467
468         switch obj := obj.(type) {
469         case *PkgName:
470                 fmt.Fprintf(buf, "package %s", obj.Name())
471                 if path := obj.imported.path; path != "" && path != obj.name {
472                         fmt.Fprintf(buf, " (%q)", path)
473                 }
474                 return
475
476         case *Const:
477                 buf.WriteString("const")
478
479         case *TypeName:
480                 tname = obj
481                 buf.WriteString("type")
482                 if isTypeParam(typ) {
483                         buf.WriteString(" parameter")
484                 }
485
486         case *Var:
487                 if obj.isField {
488                         buf.WriteString("field")
489                 } else {
490                         buf.WriteString("var")
491                 }
492
493         case *Func:
494                 buf.WriteString("func ")
495                 writeFuncName(buf, obj, qf)
496                 if typ != nil {
497                         WriteSignature(buf, typ.(*Signature), qf)
498                 }
499                 return
500
501         case *Label:
502                 buf.WriteString("label")
503                 typ = nil
504
505         case *Builtin:
506                 buf.WriteString("builtin")
507                 typ = nil
508
509         case *Nil:
510                 buf.WriteString("nil")
511                 return
512
513         default:
514                 panic(fmt.Sprintf("writeObject(%T)", obj))
515         }
516
517         buf.WriteByte(' ')
518
519         // For package-level objects, qualify the name.
520         if obj.Pkg() != nil && obj.Pkg().scope.Lookup(obj.Name()) == obj {
521                 buf.WriteString(packagePrefix(obj.Pkg(), qf))
522         }
523         buf.WriteString(obj.Name())
524
525         if typ == nil {
526                 return
527         }
528
529         if tname != nil {
530                 switch t := typ.(type) {
531                 case *Basic:
532                         // Don't print anything more for basic types since there's
533                         // no more information.
534                         return
535                 case *Named:
536                         if t.TypeParams().Len() > 0 {
537                                 newTypeWriter(buf, qf).tParamList(t.TypeParams().list())
538                         }
539                 }
540                 if tname.IsAlias() {
541                         buf.WriteString(" =")
542                 } else if t, _ := typ.(*TypeParam); t != nil {
543                         typ = t.bound
544                 } else {
545                         // TODO(gri) should this be fromRHS for *Named?
546                         typ = under(typ)
547                 }
548         }
549
550         // Special handling for any: because WriteType will format 'any' as 'any',
551         // resulting in the object string `type any = any` rather than `type any =
552         // interface{}`. To avoid this, swap in a different empty interface.
553         if obj == universeAny {
554                 assert(Identical(typ, &emptyInterface))
555                 typ = &emptyInterface
556         }
557
558         buf.WriteByte(' ')
559         WriteType(buf, typ, qf)
560 }
561
562 func packagePrefix(pkg *Package, qf Qualifier) string {
563         if pkg == nil {
564                 return ""
565         }
566         var s string
567         if qf != nil {
568                 s = qf(pkg)
569         } else {
570                 s = pkg.Path()
571         }
572         if s != "" {
573                 s += "."
574         }
575         return s
576 }
577
578 // ObjectString returns the string form of obj.
579 // The Qualifier controls the printing of
580 // package-level objects, and may be nil.
581 func ObjectString(obj Object, qf Qualifier) string {
582         var buf bytes.Buffer
583         writeObject(&buf, obj, qf)
584         return buf.String()
585 }
586
587 func (obj *PkgName) String() string  { return ObjectString(obj, nil) }
588 func (obj *Const) String() string    { return ObjectString(obj, nil) }
589 func (obj *TypeName) String() string { return ObjectString(obj, nil) }
590 func (obj *Var) String() string      { return ObjectString(obj, nil) }
591 func (obj *Func) String() string     { return ObjectString(obj, nil) }
592 func (obj *Label) String() string    { return ObjectString(obj, nil) }
593 func (obj *Builtin) String() string  { return ObjectString(obj, nil) }
594 func (obj *Nil) String() string      { return ObjectString(obj, nil) }
595
596 func writeFuncName(buf *bytes.Buffer, f *Func, qf Qualifier) {
597         if f.typ != nil {
598                 sig := f.typ.(*Signature)
599                 if recv := sig.Recv(); recv != nil {
600                         buf.WriteByte('(')
601                         if _, ok := recv.Type().(*Interface); ok {
602                                 // gcimporter creates abstract methods of
603                                 // named interfaces using the interface type
604                                 // (not the named type) as the receiver.
605                                 // Don't print it in full.
606                                 buf.WriteString("interface")
607                         } else {
608                                 WriteType(buf, recv.Type(), qf)
609                         }
610                         buf.WriteByte(')')
611                         buf.WriteByte('.')
612                 } else if f.pkg != nil {
613                         buf.WriteString(packagePrefix(f.pkg, qf))
614                 }
615         }
616         buf.WriteString(f.name)
617 }