-
Notifications
You must be signed in to change notification settings - Fork 153
/
export.go
462 lines (397 loc) · 8.74 KB
/
export.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
// Copyright 2013 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package importer
import (
"bytes"
"encoding/binary"
"fmt"
"go/ast"
"strings"
"github.com/mailgun/godebug/Godeps/_workspace/src/golang.org/x/tools/go/exact"
"github.com/mailgun/godebug/Godeps/_workspace/src/golang.org/x/tools/go/types"
)
const (
debug = false // debugging support
// emit debugging data
trace = false // print emitted data
)
// format returns a byte indicating the low-level encoding/decoding format
// (debug vs product).
func format() byte {
if debug {
return 'd'
}
return 'p'
}
// ExportData serializes the interface (exported package objects)
// of package pkg and returns the corresponding data. The export
// format is described elsewhere (TODO).
func ExportData(pkg *types.Package) []byte {
p := exporter{
data: append([]byte(magic), format()),
pkgIndex: make(map[*types.Package]int),
typIndex: make(map[types.Type]int),
}
// populate typIndex with predeclared types
for _, t := range predeclared {
p.typIndex[t] = len(p.typIndex)
}
if trace {
p.tracef("export %s\n", pkg.Name())
defer p.tracef("\n")
}
p.string(version)
p.pkg(pkg)
// collect exported objects from package scope
var list []types.Object
scope := pkg.Scope()
for _, name := range scope.Names() {
if exported(name) {
list = append(list, scope.Lookup(name))
}
}
// write objects
p.int(len(list))
for _, obj := range list {
p.obj(obj)
}
return p.data
}
type exporter struct {
data []byte
pkgIndex map[*types.Package]int
typIndex map[types.Type]int
// tracing support
indent string
}
func (p *exporter) pkg(pkg *types.Package) {
if trace {
p.tracef("package { ")
defer p.tracef("} ")
}
if pkg == nil {
panic("unexpected nil pkg")
}
// if the package was seen before, write its index (>= 0)
if i, ok := p.pkgIndex[pkg]; ok {
p.int(i)
return
}
p.pkgIndex[pkg] = len(p.pkgIndex)
// otherwise, write the package tag (< 0) and package data
p.int(packageTag)
p.string(pkg.Name())
p.string(pkg.Path())
}
func (p *exporter) obj(obj types.Object) {
if trace {
p.tracef("object %s {\n", obj.Name())
defer p.tracef("}\n")
}
switch obj := obj.(type) {
case *types.Const:
p.int(constTag)
p.string(obj.Name())
p.typ(obj.Type())
p.value(obj.Val())
case *types.TypeName:
p.int(typeTag)
// name is written by corresponding named type
p.typ(obj.Type().(*types.Named))
case *types.Var:
p.int(varTag)
p.string(obj.Name())
p.typ(obj.Type())
case *types.Func:
p.int(funcTag)
p.string(obj.Name())
p.typ(obj.Type())
default:
panic(fmt.Sprintf("unexpected object type %T", obj))
}
}
func (p *exporter) value(x exact.Value) {
if trace {
p.tracef("value { ")
defer p.tracef("} ")
}
switch kind := x.Kind(); kind {
case exact.Bool:
tag := falseTag
if exact.BoolVal(x) {
tag = trueTag
}
p.int(tag)
case exact.Int:
if i, ok := exact.Int64Val(x); ok {
p.int(int64Tag)
p.int64(i)
return
}
p.int(floatTag)
p.float(x)
case exact.Float:
p.int(fractionTag)
p.fraction(x)
case exact.Complex:
p.int(complexTag)
p.fraction(exact.Real(x))
p.fraction(exact.Imag(x))
case exact.String:
p.int(stringTag)
p.string(exact.StringVal(x))
default:
panic(fmt.Sprintf("unexpected value kind %d", kind))
}
}
func (p *exporter) float(x exact.Value) {
sign := exact.Sign(x)
p.int(sign)
if sign == 0 {
return
}
p.ufloat(x)
}
func (p *exporter) fraction(x exact.Value) {
sign := exact.Sign(x)
p.int(sign)
if sign == 0 {
return
}
p.ufloat(exact.Num(x))
p.ufloat(exact.Denom(x))
}
// ufloat writes abs(x) in form of a binary exponent
// followed by its mantissa bytes; x must be != 0.
func (p *exporter) ufloat(x exact.Value) {
mant := exact.Bytes(x)
exp8 := -1
for i, b := range mant {
if b != 0 {
exp8 = i
break
}
}
if exp8 < 0 {
panic(fmt.Sprintf("%s has no mantissa", x))
}
p.int(exp8 * 8)
p.bytes(mant[exp8:])
}
func (p *exporter) typ(typ types.Type) {
if trace {
p.tracef("type {\n")
defer p.tracef("}\n")
}
// if the type was seen before, write its index (>= 0)
if i, ok := p.typIndex[typ]; ok {
p.int(i)
return
}
p.typIndex[typ] = len(p.typIndex)
// otherwise, write the type tag (< 0) and type data
switch t := typ.(type) {
case *types.Array:
p.int(arrayTag)
p.int64(t.Len())
p.typ(t.Elem())
case *types.Slice:
p.int(sliceTag)
p.typ(t.Elem())
case *types.Struct:
p.int(structTag)
n := t.NumFields()
p.int(n)
for i := 0; i < n; i++ {
p.field(t.Field(i))
p.string(t.Tag(i))
}
case *types.Pointer:
p.int(pointerTag)
p.typ(t.Elem())
case *types.Signature:
p.int(signatureTag)
p.signature(t)
case *types.Interface:
p.int(interfaceTag)
// write embedded interfaces
m := t.NumEmbeddeds()
p.int(m)
for i := 0; i < m; i++ {
p.typ(t.Embedded(i))
}
// write methods
n := t.NumExplicitMethods()
p.int(n)
for i := 0; i < n; i++ {
m := t.ExplicitMethod(i)
p.qualifiedName(m.Pkg(), m.Name())
p.typ(m.Type())
}
case *types.Map:
p.int(mapTag)
p.typ(t.Key())
p.typ(t.Elem())
case *types.Chan:
p.int(chanTag)
p.int(int(t.Dir()))
p.typ(t.Elem())
case *types.Named:
p.int(namedTag)
// write type object
obj := t.Obj()
p.string(obj.Name())
p.pkg(obj.Pkg())
// write underlying type
p.typ(t.Underlying())
// write associated methods
n := t.NumMethods()
p.int(n)
for i := 0; i < n; i++ {
m := t.Method(i)
p.string(m.Name())
p.typ(m.Type())
}
default:
panic("unreachable")
}
}
func (p *exporter) field(f *types.Var) {
// anonymous fields have "" name
name := ""
if !f.Anonymous() {
name = f.Name()
}
// qualifiedName will always emit the field package for
// anonymous fields because "" is not an exported name.
p.qualifiedName(f.Pkg(), name)
p.typ(f.Type())
}
func (p *exporter) qualifiedName(pkg *types.Package, name string) {
p.string(name)
// exported names don't need package
if !exported(name) {
if pkg == nil {
panic(fmt.Sprintf("nil package for unexported qualified name %s", name))
}
p.pkg(pkg)
}
}
func (p *exporter) signature(sig *types.Signature) {
// We need the receiver information (T vs *T)
// for methods associated with named types.
// We do not record interface receiver types in the
// export data because 1) the importer can derive them
// from the interface type and 2) they create cycles
// in the type graph.
if recv := sig.Recv(); recv != nil {
if _, ok := recv.Type().Underlying().(*types.Interface); !ok {
// 1-element tuple
p.int(1)
p.param(recv)
} else {
// 0-element tuple
p.int(0)
}
} else {
// 0-element tuple
p.int(0)
}
p.tuple(sig.Params())
p.tuple(sig.Results())
if sig.Variadic() {
p.int(1)
} else {
p.int(0)
}
}
func (p *exporter) param(v *types.Var) {
p.string(v.Name())
p.typ(v.Type())
}
func (p *exporter) tuple(t *types.Tuple) {
n := t.Len()
p.int(n)
for i := 0; i < n; i++ {
p.param(t.At(i))
}
}
// ----------------------------------------------------------------------------
// encoders
func (p *exporter) string(s string) {
p.bytes([]byte(s)) // (could be inlined if extra allocation matters)
}
func (p *exporter) int(x int) {
p.int64(int64(x))
}
func (p *exporter) int64(x int64) {
if debug {
p.marker('i')
}
if trace {
p.tracef("%d ", x)
}
p.rawInt64(x)
}
func (p *exporter) bytes(b []byte) {
if debug {
p.marker('b')
}
if trace {
p.tracef("%q ", b)
}
p.rawInt64(int64(len(b)))
if len(b) > 0 {
p.data = append(p.data, b...)
}
}
// marker emits a marker byte and position information which makes
// it easy for a reader to detect if it is "out of sync". Used for
// debug format only.
func (p *exporter) marker(m byte) {
if debug {
p.data = append(p.data, m)
p.rawInt64(int64(len(p.data)))
}
}
// rawInt64 should only be used by low-level encoders
func (p *exporter) rawInt64(x int64) {
var tmp [binary.MaxVarintLen64]byte
n := binary.PutVarint(tmp[:], x)
p.data = append(p.data, tmp[:n]...)
}
// utility functions
func (p *exporter) tracef(format string, args ...interface{}) {
// rewrite format string to take care of indentation
const indent = ". "
if strings.IndexAny(format, "{}\n") >= 0 {
var buf bytes.Buffer
for i := 0; i < len(format); i++ {
// no need to deal with runes
ch := format[i]
switch ch {
case '{':
p.indent += indent
case '}':
p.indent = p.indent[:len(p.indent)-len(indent)]
if i+1 < len(format) && format[i+1] == '\n' {
buf.WriteByte('\n')
buf.WriteString(p.indent)
buf.WriteString("} ")
i++
continue
}
}
buf.WriteByte(ch)
if ch == '\n' {
buf.WriteString(p.indent)
}
}
format = buf.String()
}
fmt.Printf(format, args...)
}
func exported(name string) bool {
return ast.IsExported(name)
}