]> Cypherpunks.ru repositories - gostls13.git/blob - src/cmd/compile/internal/types2/object.go
[dev.typeparams] merge master (2f0da6d) into dev.typeparams
[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 //
20 type Object interface {
21         Parent() *Scope  // scope in which this object is declared; nil for methods and struct fields
22         Pos() syntax.Pos // position of object identifier in declaration
23         Pkg() *Package   // package to which this object belongs; nil for labels and objects in the Universe scope
24         Name() string    // package local object name
25         Type() Type      // object type
26         Exported() bool  // reports whether the name starts with a capital letter
27         Id() string      // object name if exported, qualified name if not exported (see func Id)
28
29         // String returns a human-readable string of the object.
30         String() string
31
32         // order reflects a package-level object's source order: if object
33         // a is before object b in the source, then a.order() < b.order().
34         // order returns a value > 0 for package-level objects; it returns
35         // 0 for all other objects (including objects in file scopes).
36         order() uint32
37
38         // color returns the object's color.
39         color() color
40
41         // setType sets the type of the object.
42         setType(Type)
43
44         // setOrder sets the order number of the object. It must be > 0.
45         setOrder(uint32)
46
47         // setColor sets the object's color. It must not be white.
48         setColor(color color)
49
50         // setParent sets the parent scope of the object.
51         setParent(*Scope)
52
53         // sameId reports whether obj.Id() and Id(pkg, name) are the same.
54         sameId(pkg *Package, name string) bool
55
56         // scopePos returns the start position of the scope of this Object
57         scopePos() syntax.Pos
58
59         // setScopePos sets the start position of the scope for this Object.
60         setScopePos(pos syntax.Pos)
61 }
62
63 func isExported(name string) bool {
64         ch, _ := utf8.DecodeRuneInString(name)
65         return unicode.IsUpper(ch)
66 }
67
68 // Id returns name if it is exported, otherwise it
69 // returns the name qualified with the package path.
70 func Id(pkg *Package, name string) string {
71         if isExported(name) {
72                 return name
73         }
74         // unexported names need the package path for differentiation
75         // (if there's no package, make sure we don't start with '.'
76         // as that may change the order of methods between a setup
77         // inside a package and outside a package - which breaks some
78         // tests)
79         path := "_"
80         // pkg is nil for objects in Universe scope and possibly types
81         // introduced via Eval (see also comment in object.sameId)
82         if pkg != nil && pkg.path != "" {
83                 path = pkg.path
84         }
85         return path + "." + name
86 }
87
88 // An object implements the common parts of an Object.
89 type object struct {
90         parent    *Scope
91         pos       syntax.Pos
92         pkg       *Package
93         name      string
94         typ       Type
95         order_    uint32
96         color_    color
97         scopePos_ syntax.Pos
98 }
99
100 // color encodes the color of an object (see Checker.objDecl for details).
101 type color uint32
102
103 // An object may be painted in one of three colors.
104 // Color values other than white or black are considered grey.
105 const (
106         white color = iota
107         black
108         grey // must be > white and black
109 )
110
111 func (c color) String() string {
112         switch c {
113         case white:
114                 return "white"
115         case black:
116                 return "black"
117         default:
118                 return "grey"
119         }
120 }
121
122 // colorFor returns the (initial) color for an object depending on
123 // whether its type t is known or not.
124 func colorFor(t Type) color {
125         if t != nil {
126                 return black
127         }
128         return white
129 }
130
131 // Parent returns the scope in which the object is declared.
132 // The result is nil for methods and struct fields.
133 func (obj *object) Parent() *Scope { return obj.parent }
134
135 // Pos returns the declaration position of the object's identifier.
136 func (obj *object) Pos() syntax.Pos { return obj.pos }
137
138 // Pkg returns the package to which the object belongs.
139 // The result is nil for labels and objects in the Universe scope.
140 func (obj *object) Pkg() *Package { return obj.pkg }
141
142 // Name returns the object's (package-local, unqualified) name.
143 func (obj *object) Name() string { return obj.name }
144
145 // Type returns the object's type.
146 func (obj *object) Type() Type { return obj.typ }
147
148 // Exported reports whether the object is exported (starts with a capital letter).
149 // It doesn't take into account whether the object is in a local (function) scope
150 // or not.
151 func (obj *object) Exported() bool { return isExported(obj.name) }
152
153 // Id is a wrapper for Id(obj.Pkg(), obj.Name()).
154 func (obj *object) Id() string { return Id(obj.pkg, obj.name) }
155
156 func (obj *object) String() string       { panic("abstract") }
157 func (obj *object) order() uint32        { return obj.order_ }
158 func (obj *object) color() color         { return obj.color_ }
159 func (obj *object) scopePos() syntax.Pos { return obj.scopePos_ }
160
161 func (obj *object) setParent(parent *Scope)    { obj.parent = parent }
162 func (obj *object) setType(typ Type)           { obj.typ = typ }
163 func (obj *object) setOrder(order uint32)      { assert(order > 0); obj.order_ = order }
164 func (obj *object) setColor(color color)       { assert(color != white); obj.color_ = color }
165 func (obj *object) setScopePos(pos syntax.Pos) { obj.scopePos_ = pos }
166
167 func (obj *object) sameId(pkg *Package, name string) bool {
168         // spec:
169         // "Two identifiers are different if they are spelled differently,
170         // or if they appear in different packages and are not exported.
171         // Otherwise, they are the same."
172         if name != obj.name {
173                 return false
174         }
175         // obj.Name == name
176         if obj.Exported() {
177                 return true
178         }
179         // not exported, so packages must be the same (pkg == nil for
180         // fields in Universe scope; this can only happen for types
181         // introduced via Eval)
182         if pkg == nil || obj.pkg == nil {
183                 return pkg == obj.pkg
184         }
185         // pkg != nil && obj.pkg != nil
186         return pkg.path == obj.pkg.path
187 }
188
189 // A PkgName represents an imported Go package.
190 // PkgNames don't have a type.
191 type PkgName struct {
192         object
193         imported *Package
194         used     bool // set if the package was used
195 }
196
197 // NewPkgName returns a new PkgName object representing an imported package.
198 // The remaining arguments set the attributes found with all Objects.
199 func NewPkgName(pos syntax.Pos, pkg *Package, name string, imported *Package) *PkgName {
200         return &PkgName{object{nil, pos, pkg, name, Typ[Invalid], 0, black, nopos}, imported, false}
201 }
202
203 // Imported returns the package that was imported.
204 // It is distinct from Pkg(), which is the package containing the import statement.
205 func (obj *PkgName) Imported() *Package { return obj.imported }
206
207 // A Const represents a declared constant.
208 type Const struct {
209         object
210         val constant.Value
211 }
212
213 // NewConst returns a new constant with value val.
214 // The remaining arguments set the attributes found with all Objects.
215 func NewConst(pos syntax.Pos, pkg *Package, name string, typ Type, val constant.Value) *Const {
216         return &Const{object{nil, pos, pkg, name, typ, 0, colorFor(typ), nopos}, val}
217 }
218
219 // Val returns the constant's value.
220 func (obj *Const) Val() constant.Value { return obj.val }
221
222 func (*Const) isDependency() {} // a constant may be a dependency of an initialization expression
223
224 // A TypeName represents a name for a (defined or alias) type.
225 type TypeName struct {
226         object
227 }
228
229 // NewTypeName returns a new type name denoting the given typ.
230 // The remaining arguments set the attributes found with all Objects.
231 //
232 // The typ argument may be a defined (Named) type or an alias type.
233 // It may also be nil such that the returned TypeName can be used as
234 // argument for NewNamed, which will set the TypeName's type as a side-
235 // effect.
236 func NewTypeName(pos syntax.Pos, pkg *Package, name string, typ Type) *TypeName {
237         return &TypeName{object{nil, pos, pkg, name, typ, 0, colorFor(typ), nopos}}
238 }
239
240 // IsAlias reports whether obj is an alias name for a type.
241 func (obj *TypeName) IsAlias() bool {
242         switch t := obj.typ.(type) {
243         case nil:
244                 return false
245         case *Basic:
246                 // unsafe.Pointer is not an alias.
247                 if obj.pkg == Unsafe {
248                         return false
249                 }
250                 // Any user-defined type name for a basic type is an alias for a
251                 // basic type (because basic types are pre-declared in the Universe
252                 // scope, outside any package scope), and so is any type name with
253                 // a different name than the name of the basic type it refers to.
254                 // Additionally, we need to look for "byte" and "rune" because they
255                 // are aliases but have the same names (for better error messages).
256                 return obj.pkg != nil || t.name != obj.name || t == universeByte || t == universeRune
257         case *Named:
258                 return obj != t.obj
259         default:
260                 return true
261         }
262 }
263
264 // A Variable represents a declared variable (including function parameters and results, and struct fields).
265 type Var struct {
266         object
267         embedded bool // if set, the variable is an embedded struct field, and name is the type name
268         isField  bool // var is struct field
269         used     bool // set if the variable was used
270 }
271
272 // NewVar returns a new variable.
273 // The arguments set the attributes found with all Objects.
274 func NewVar(pos syntax.Pos, pkg *Package, name string, typ Type) *Var {
275         return &Var{object: object{nil, pos, pkg, name, typ, 0, colorFor(typ), nopos}}
276 }
277
278 // NewParam returns a new variable representing a function parameter.
279 func NewParam(pos syntax.Pos, pkg *Package, name string, typ Type) *Var {
280         return &Var{object: object{nil, pos, pkg, name, typ, 0, colorFor(typ), nopos}, used: true} // parameters are always 'used'
281 }
282
283 // NewField returns a new variable representing a struct field.
284 // For embedded fields, the name is the unqualified type name
285 /// under which the field is accessible.
286 func NewField(pos syntax.Pos, pkg *Package, name string, typ Type, embedded bool) *Var {
287         return &Var{object: object{nil, pos, pkg, name, typ, 0, colorFor(typ), nopos}, embedded: embedded, isField: true}
288 }
289
290 // Anonymous reports whether the variable is an embedded field.
291 // Same as Embedded; only present for backward-compatibility.
292 func (obj *Var) Anonymous() bool { return obj.embedded }
293
294 // Embedded reports whether the variable is an embedded field.
295 func (obj *Var) Embedded() bool { return obj.embedded }
296
297 // IsField reports whether the variable is a struct field.
298 func (obj *Var) IsField() bool { return obj.isField }
299
300 func (*Var) isDependency() {} // a variable may be a dependency of an initialization expression
301
302 // A Func represents a declared function, concrete method, or abstract
303 // (interface) method. Its Type() is always a *Signature.
304 // An abstract method may belong to many interfaces due to embedding.
305 type Func struct {
306         object
307         hasPtrRecv bool // only valid for methods that don't have a type yet
308 }
309
310 // NewFunc returns a new function with the given signature, representing
311 // the function's type.
312 func NewFunc(pos syntax.Pos, pkg *Package, name string, sig *Signature) *Func {
313         // don't store a (typed) nil signature
314         var typ Type
315         if sig != nil {
316                 typ = sig
317         }
318         return &Func{object{nil, pos, pkg, name, typ, 0, colorFor(typ), nopos}, false}
319 }
320
321 // FullName returns the package- or receiver-type-qualified name of
322 // function or method obj.
323 func (obj *Func) FullName() string {
324         var buf bytes.Buffer
325         writeFuncName(&buf, obj, nil)
326         return buf.String()
327 }
328
329 // Scope returns the scope of the function's body block.
330 func (obj *Func) Scope() *Scope { return obj.typ.(*Signature).scope }
331
332 // Less reports whether function a is ordered before function b.
333 //
334 // Functions are ordered exported before non-exported, then by name,
335 // and finally (for non-exported functions) by package path.
336 //
337 // TODO(gri) The compiler also sorts by package height before package
338 //           path for non-exported names.
339 func (a *Func) less(b *Func) bool {
340         if a == b {
341                 return false
342         }
343
344         // Exported functions before non-exported.
345         ea := isExported(a.name)
346         eb := isExported(b.name)
347         if ea != eb {
348                 return ea
349         }
350
351         // Order by name and then (for non-exported names) by package.
352         if a.name != b.name {
353                 return a.name < b.name
354         }
355         if !ea {
356                 return a.pkg.path < b.pkg.path
357         }
358
359         return false
360 }
361
362 func (*Func) isDependency() {} // a function may be a dependency of an initialization expression
363
364 // A Label represents a declared label.
365 // Labels don't have a type.
366 type Label struct {
367         object
368         used bool // set if the label was used
369 }
370
371 // NewLabel returns a new label.
372 func NewLabel(pos syntax.Pos, pkg *Package, name string) *Label {
373         return &Label{object{pos: pos, pkg: pkg, name: name, typ: Typ[Invalid], color_: black}, false}
374 }
375
376 // A Builtin represents a built-in function.
377 // Builtins don't have a valid type.
378 type Builtin struct {
379         object
380         id builtinId
381 }
382
383 func newBuiltin(id builtinId) *Builtin {
384         return &Builtin{object{name: predeclaredFuncs[id].name, typ: Typ[Invalid], color_: black}, id}
385 }
386
387 // Nil represents the predeclared value nil.
388 type Nil struct {
389         object
390 }
391
392 func writeObject(buf *bytes.Buffer, obj Object, qf Qualifier) {
393         var tname *TypeName
394         typ := obj.Type()
395
396         switch obj := obj.(type) {
397         case *PkgName:
398                 fmt.Fprintf(buf, "package %s", obj.Name())
399                 if path := obj.imported.path; path != "" && path != obj.name {
400                         fmt.Fprintf(buf, " (%q)", path)
401                 }
402                 return
403
404         case *Const:
405                 buf.WriteString("const")
406
407         case *TypeName:
408                 tname = obj
409                 buf.WriteString("type")
410
411         case *Var:
412                 if obj.isField {
413                         buf.WriteString("field")
414                 } else {
415                         buf.WriteString("var")
416                 }
417
418         case *Func:
419                 buf.WriteString("func ")
420                 writeFuncName(buf, obj, qf)
421                 if typ != nil {
422                         WriteSignature(buf, typ.(*Signature), qf)
423                 }
424                 return
425
426         case *Label:
427                 buf.WriteString("label")
428                 typ = nil
429
430         case *Builtin:
431                 buf.WriteString("builtin")
432                 typ = nil
433
434         case *Nil:
435                 buf.WriteString("nil")
436                 return
437
438         default:
439                 panic(fmt.Sprintf("writeObject(%T)", obj))
440         }
441
442         buf.WriteByte(' ')
443
444         // For package-level objects, qualify the name.
445         if obj.Pkg() != nil && obj.Pkg().scope.Lookup(obj.Name()) == obj {
446                 writePackage(buf, obj.Pkg(), qf)
447         }
448         buf.WriteString(obj.Name())
449
450         if typ == nil {
451                 return
452         }
453
454         if tname != nil {
455                 // We have a type object: Don't print anything more for
456                 // basic types since there's no more information (names
457                 // are the same; see also comment in TypeName.IsAlias).
458                 if _, ok := typ.(*Basic); ok {
459                         return
460                 }
461                 if tname.IsAlias() {
462                         buf.WriteString(" =")
463                 } else {
464                         typ = typ.Under()
465                 }
466         }
467
468         buf.WriteByte(' ')
469         WriteType(buf, typ, qf)
470 }
471
472 func writePackage(buf *bytes.Buffer, pkg *Package, qf Qualifier) {
473         if pkg == nil {
474                 return
475         }
476         var s string
477         if qf != nil {
478                 s = qf(pkg)
479         } else {
480                 s = pkg.Path()
481         }
482         if s != "" {
483                 buf.WriteString(s)
484                 buf.WriteByte('.')
485         }
486 }
487
488 // ObjectString returns the string form of obj.
489 // The Qualifier controls the printing of
490 // package-level objects, and may be nil.
491 func ObjectString(obj Object, qf Qualifier) string {
492         var buf bytes.Buffer
493         writeObject(&buf, obj, qf)
494         return buf.String()
495 }
496
497 func (obj *PkgName) String() string  { return ObjectString(obj, nil) }
498 func (obj *Const) String() string    { return ObjectString(obj, nil) }
499 func (obj *TypeName) String() string { return ObjectString(obj, nil) }
500 func (obj *Var) String() string      { return ObjectString(obj, nil) }
501 func (obj *Func) String() string     { return ObjectString(obj, nil) }
502 func (obj *Label) String() string    { return ObjectString(obj, nil) }
503 func (obj *Builtin) String() string  { return ObjectString(obj, nil) }
504 func (obj *Nil) String() string      { return ObjectString(obj, nil) }
505
506 func writeFuncName(buf *bytes.Buffer, f *Func, qf Qualifier) {
507         if f.typ != nil {
508                 sig := f.typ.(*Signature)
509                 if recv := sig.Recv(); recv != nil {
510                         buf.WriteByte('(')
511                         if _, ok := recv.Type().(*Interface); ok {
512                                 // gcimporter creates abstract methods of
513                                 // named interfaces using the interface type
514                                 // (not the named type) as the receiver.
515                                 // Don't print it in full.
516                                 buf.WriteString("interface")
517                         } else {
518                                 WriteType(buf, recv.Type(), qf)
519                         }
520                         buf.WriteByte(')')
521                         buf.WriteByte('.')
522                 } else if f.pkg != nil {
523                         writePackage(buf, f.pkg, qf)
524                 }
525         }
526         buf.WriteString(f.name)
527 }