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