-
Notifications
You must be signed in to change notification settings - Fork 6
/
types.go
718 lines (627 loc) · 18 KB
/
types.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
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
package modver
import (
"fmt"
"go/ast"
"go/types"
"reflect"
"regexp"
"strings"
"golang.org/x/tools/go/packages"
)
type (
comparer struct {
stack []typePair
cache map[typePair]Result
identicache map[typePair]bool
}
typePair struct{ a, b types.Type }
)
func newComparer() *comparer {
return &comparer{
cache: make(map[typePair]Result),
identicache: make(map[typePair]bool),
}
}
func (c *comparer) compareTypes(older, newer types.Type) (res Result) {
pair := typePair{a: older, b: newer}
if res, ok := c.cache[pair]; ok {
if res == nil {
// Break an infinite regress,
// e.g. when checking type Node struct { children []*Node }
return None
}
return res
}
c.cache[pair] = nil
defer func() {
c.cache[pair] = res
}()
switch older := older.(type) {
case *types.Array:
if newer, ok := newer.(*types.Array); ok {
if res = c.compareTypes(older.Elem(), newer.Elem()); res.Code() != None {
return rwrapf(res, "%s went from array of %s to array of %s", older, older.Elem(), newer.Elem())
}
if older.Len() != newer.Len() {
return rwrapf(Major, "%s went from length %d array to length %d", older, older.Len(), newer.Len())
}
return None
}
return rwrapf(Major, "%s went from array to non-array", older)
case *types.Chan:
if newer, ok := newer.(*types.Chan); ok {
if res = c.compareTypes(older.Elem(), newer.Elem()); res.Code() != None {
return rwrapf(res, "%s went from channel of %s to channel of %s", older, older.Elem(), newer.Elem())
}
if older.Dir() == newer.Dir() {
return None
}
if older.Dir() == types.SendRecv {
return rwrapf(Minor, "%s went from send/receive channel to %s", older, describeDirection(newer.Dir()))
}
return rwrapf(Major, "%s went from %s channel to %s", older, describeDirection(older.Dir()), describeDirection(newer.Dir()))
}
return rwrapf(Major, "%s went from channel to non-channel", older)
case *types.Pointer:
if newer, ok := newer.(*types.Pointer); ok {
return c.compareTypes(older.Elem(), newer.Elem())
}
return rwrapf(Major, "%s went from pointer to non-pointer", older)
case *types.Named:
if newer, ok := newer.(*types.Named); ok {
return c.compareNamed(older, newer)
}
if older.TypeParams().Len() > 0 {
return rwrapf(Major, "%s went from generic named type to unnamed %s", older, newer)
}
return c.compareTypes(older.Underlying(), newer)
case *types.Struct:
if newer, ok := newer.(*types.Struct); ok {
return c.compareStructs(older, newer)
}
return rwrapf(Major, "%s went from struct to non-struct", older)
case *types.Interface:
if newer, ok := newer.(*types.Interface); ok {
return c.compareInterfaces(older, newer)
}
return rwrapf(Major, "%s went from interface to non-interface", older)
case *types.Signature:
if newer, ok := newer.(*types.Signature); ok {
return c.compareSignatures(older, newer)
}
return rwrapf(Major, "%s went from function to non-function", older)
case *types.Map:
if newer, ok := newer.(*types.Map); ok {
kres := c.compareTypes(older.Key(), newer.Key())
vres := c.compareTypes(older.Elem(), newer.Elem())
if kres.Code() > vres.Code() {
return rwrapf(kres, "in the map-key type of %s", older)
}
return rwrapf(vres, "in the map-value type of %s", older)
}
return rwrapf(Major, "%s went from map to non-map", older)
case *types.Slice:
if newer, ok := newer.(*types.Slice); ok {
return c.compareTypes(older.Elem(), newer.Elem())
}
return rwrapf(Major, "%s went from slice to non-slice", older)
default:
if !c.assignableTo(newer, older) {
return rwrapf(Major, "%s is not assignable to %s", newer, older)
}
return None
}
}
func describeDirection(dir types.ChanDir) string {
switch dir {
case types.SendRecv:
return "send/receive"
case types.SendOnly:
return "send"
case types.RecvOnly:
return "receive"
default:
return fmt.Sprintf("[invalid direction %v]", dir)
}
}
func (c *comparer) compareNamed(older, newer *types.Named) Result {
res := c.compareTypeParamLists(older.TypeParams(), newer.TypeParams())
if r := c.compareTypes(older.Underlying(), newer.Underlying()); r.Code() > res.Code() {
res = r
}
if w, ok := res.(wrapped); ok {
var replaced bool
for i, arg := range w.whyargs {
if _, ok := arg.(types.Type); !ok {
continue
}
if reflect.DeepEqual(arg, older.Underlying()) {
w.whyargs[i] = older
replaced = true
} else if reflect.DeepEqual(arg, newer.Underlying()) {
w.whyargs[i] = newer
replaced = true
}
}
if replaced {
return w
}
}
return rwrapf(res, "in type %s", older)
}
func (c *comparer) compareStructs(older, newer *types.Struct) Result {
var (
olderMap = structMap(older)
newerMap = structMap(newer)
)
var res Result = None
for i := 0; i < older.NumFields(); i++ {
field := older.Field(i)
if !ast.IsExported(field.Name()) {
// Changes in unexported struct fields don't count.
continue
}
newFieldIndex, ok := newerMap[field.Name()]
if !ok {
return rwrapf(Major, "old struct field %s was removed from %s", field.Name(), older)
}
newField := newer.Field(newFieldIndex)
if r := c.compareTypes(field.Type(), newField.Type()); r.Code() > res.Code() {
res = rwrapf(r, "struct field %s changed in %s", field.Name(), older)
if res.Code() == Major {
return res
}
}
var (
tag = older.Tag(i)
newTag = newer.Tag(newFieldIndex)
)
if r := c.compareStructTags(tag, newTag); r.Code() == Major {
return rwrapf(r, "tag change in field %s of %s", field.Name(), older)
}
}
for i := 0; i < newer.NumFields(); i++ {
field := newer.Field(i)
if !ast.IsExported(field.Name()) {
// Changes in unexported struct fields don't count.
continue
}
oldFieldIndex, ok := olderMap[field.Name()]
if !ok {
return rwrapf(Minor, "struct field %s was added to %s", field.Name(), newer)
}
var (
oldTag = older.Tag(oldFieldIndex)
tag = newer.Tag(i)
)
if res := c.compareStructTags(oldTag, tag); res.Code() == Minor {
return rwrapf(res, "tag change in field %s of %s", field.Name(), older)
}
}
if !c.identical(older, newer) {
return rwrapf(Patchlevel, "old and new versions of %s are not identical", older)
}
return None
}
func (c *comparer) compareInterfaces(older, newer *types.Interface) Result {
var res Result = None
if c.implements(newer, older) {
if !c.implements(older, newer) {
switch {
case anyUnexportedMethods(older):
res = rwrapf(Minor, "new interface %s is a superset of older, with unexported methods", newer)
case anyInternalTypes(older):
res = rwrapf(Minor, "new interface %s is a superset of older, using internal types", newer)
default:
res = rwrapf(Major, "new interface %s is a superset of older", newer)
}
}
} else {
return rwrapf(Major, "new interface %s does not implement old", newer)
}
if isNonEmptyMethodSet(older) {
if isNonEmptyMethodSet(newer) {
return res
}
return rwrap(Major, "new interface is a constraint, old one is not")
}
if isNonEmptyMethodSet(newer) {
return rwrap(Major, "old interface is a constraint, new one is not")
}
olderTerms, newerTerms := termsOf(older), termsOf(newer)
if len(olderTerms) == 0 {
if len(newerTerms) == 0 {
if older.IsComparable() {
if newer.IsComparable() {
return res
}
return rwrap(Minor, "constraint went from comparable to any")
}
if newer.IsComparable() {
return rwrap(Major, "constraint went from any to comparable")
}
}
if older.IsComparable() {
if newer.IsComparable() {
return rwrap(Major, "constraint went from all to some comparable types")
}
return rwrap(Major, "constraint went from comparable to (some) non-comparable types")
}
if newer.IsComparable() {
return rwrap(Major, "constraint went from any to (some) comparable types")
}
return res
}
if len(newerTerms) == 0 {
if older.IsComparable() {
if newer.IsComparable() {
return rwrap(Minor, "constraint went from some to all comparable types")
}
return rwrap(Minor, "constraint went from some comparable types to any")
}
if newer.IsComparable() {
return rwrap(Major, "constraint went from (some) non-comparable types to comparable")
}
return rwrap(Major, "new constraint removes type union")
}
if c.termListSubset(olderTerms, newerTerms) {
if c.termListSubset(newerTerms, olderTerms) {
return res
}
return rwrapf(Minor, "older constraint type union is a subset of newer (constraint has relaxed)")
}
if c.termListSubset(newerTerms, olderTerms) {
return rwrapf(Major, "newer constraint type union is a subset of older (constraint has tightened)")
}
return rwrapf(Major, "constraint type unions differ")
}
func anyUnexportedMethods(intf *types.Interface) bool {
for i := 0; i < intf.NumMethods(); i++ {
if !ast.IsExported(intf.Method(i).Name()) {
return true
}
}
return false
}
// Do any of the types in the method args or results have "internal" in their pkgpaths?
func anyInternalTypes(intf *types.Interface) bool {
for i := 0; i < intf.NumMethods(); i++ {
sig, ok := intf.Method(i).Type().(*types.Signature)
if !ok {
// Should be impossible.
continue
}
if anyInternalTypesInTuple(sig.Params()) || anyInternalTypesInTuple(sig.Results()) {
return true
}
if recv := sig.Recv(); recv != nil && isInternalType(recv.Type()) {
return true
}
}
return false
}
func anyInternalTypesInTuple(tup *types.Tuple) bool {
for i := 0; i < tup.Len(); i++ {
if isInternalType(tup.At(i).Type()) {
return true
}
}
return false
}
func isInternalType(typ types.Type) bool {
s := types.TypeString(typ, nil)
if strings.HasPrefix(s, "internal.") {
return true
}
if strings.Contains(s, "/internal.") {
return true
}
if strings.Contains(s, "/internal/") {
return true
}
if strings.HasPrefix(s, "main.") {
return true
}
return strings.Contains(s, "/main.")
}
// This takes an interface and flattens its typelists by traversing embeds.
func termsOf(typ types.Type) []*types.Term {
var res []*types.Term
switch typ := typ.(type) {
case *types.Interface:
for i := 0; i < typ.NumEmbeddeds(); i++ {
emb := typ.EmbeddedType(i)
res = append(res, termsOf(emb)...)
}
case *types.Named:
res = append(res, termsOf(typ.Underlying())...)
case *types.Union:
for i := 0; i < typ.Len(); i++ {
term := typ.Term(i)
sub := termsOf(term.Type())
// TODO: Check this is the right logic for distributing term.Tilde() over the members of sub.
if term.Tilde() {
for _, s := range sub {
res = append(res, types.NewTerm(true, s.Type()))
}
} else {
res = append(res, sub...)
}
}
default:
return []*types.Term{types.NewTerm(false, typ)}
}
return res
}
func (c *comparer) compareSignatures(older, newer *types.Signature) Result {
var (
typeParamsRes = c.compareTypeParamLists(older.TypeParams(), newer.TypeParams())
paramsRes = c.compareTuples(older.Params(), newer.Params(), !older.Variadic() && newer.Variadic())
resultsRes = c.compareTuples(older.Results(), newer.Results(), false)
)
res := rwrapf(typeParamsRes, "in type parameters of %s", older)
if paramsRes.Code() > res.Code() {
res = rwrapf(paramsRes, "in parameters of %s", older)
}
if resultsRes.Code() > res.Code() {
res = rwrapf(resultsRes, "in results of %s", older)
}
return res
}
func (c *comparer) compareTuples(older, newer *types.Tuple, variadicCheck bool) Result {
la, lb := older.Len(), newer.Len()
maybeVariadic := variadicCheck && (la+1 == lb)
if la != lb && !maybeVariadic {
return rwrapf(Major, "%d param(s) to %d", la, lb)
}
var res Result = None
for i := 0; i < la; i++ {
va, vb := older.At(i), newer.At(i)
thisRes := c.compareTypes(va.Type(), vb.Type())
if thisRes.Code() == Major {
return thisRes
}
if thisRes.Code() > res.Code() {
res = thisRes
}
}
if res.Code() < Minor && maybeVariadic {
return rwrap(Minor, "added optional parameters")
}
return res
}
func (c *comparer) compareTypeParamLists(older, newer *types.TypeParamList) Result {
if older.Len() != newer.Len() {
return rwrapf(Major, "went from %d type parameter(s) to %d", older.Len(), newer.Len())
}
var res Result = None
for i := 0; i < older.Len(); i++ {
thisRes := c.compareTypes(older.At(i).Constraint(), newer.At(i).Constraint())
if thisRes.Code() > res.Code() {
res = thisRes
if res.Code() == Major {
break
}
}
}
return res
}
func (c *comparer) compareStructTags(a, b string) Result {
if a == b {
return None
}
var (
amap = tagMap(a)
bmap = tagMap(b)
)
for k, av := range amap {
if bv, ok := bmap[k]; ok {
if av != bv {
return rwrapf(Major, `struct tag changed the value for key "%s" from "%s" to "%s"`, k, av, bv)
}
} else {
return rwrapf(Major, "struct tag %s was removed", k)
}
}
for k := range bmap {
if _, ok := amap[k]; !ok {
return rwrapf(Minor, "struct tag %s was added", k)
}
}
return None
}
// https://golang.org/ref/spec#Assignability
func (c *comparer) assignableTo(v, t types.Type) bool {
if types.AssignableTo(v, t) {
return true
}
// "x's type is identical to T"
if c.identical(v, t) {
return true
}
// "x's type V and T have identical underlying types
// and at least one of V or T is not a defined type"
uv, ut := v.Underlying(), t.Underlying()
if c.identical(uv, ut) {
if _, ok := v.(*types.Named); !ok {
return true
}
if _, ok := t.(*types.Named); !ok {
return true
}
}
// "T is an interface type and x implements T"
if intf, ok := ut.(*types.Interface); ok {
if c.implements(v, intf) {
return true
}
}
if c.assignableChan(v, t, uv, ut) {
return true
}
return c.assignableBasic(v, t, uv, ut)
}
func (c *comparer) assignableChan(v, t, uv, ut types.Type) bool {
// "x is a bidirectional channel value,
// T is a channel type,
// x's type V and T have identical element types,
// and at least one of V or T is not a defined type"
if chv, ok := uv.(*types.Chan); ok && chv.Dir() == types.SendRecv {
if cht, ok := ut.(*types.Chan); ok && c.identical(chv.Elem(), cht.Elem()) {
if _, ok := v.(*types.Named); !ok {
return true
}
if _, ok := t.(*types.Named); !ok {
return true
}
}
}
return false
}
func (c *comparer) assignableBasic(v, t, uv, ut types.Type) bool {
b, ok := v.(*types.Basic)
if !ok {
return false
}
// "x is the predeclared identifier nil
// and T is a pointer, function, slice, map, channel, or interface type"
if b.Kind() == types.UntypedNil {
switch ut.(type) {
case *types.Pointer:
return true
case *types.Signature:
return true
case *types.Slice:
return true
case *types.Map:
return true
case *types.Chan:
return true
case *types.Interface:
return true
}
}
// "x is an untyped constant representable by a value of type T"
switch b.Kind() {
case types.UntypedBool, types.UntypedInt, types.UntypedRune, types.UntypedFloat, types.UntypedComplex, types.UntypedString:
return representable(b, t)
}
return false
}
// https://golang.org/ref/spec#Method_sets
func (c *comparer) implements(v types.Type, t *types.Interface) bool {
if types.Implements(v, t) {
return true
}
mv, mt := methodMap(v), methodMap(t)
for tname, tfn := range mt {
vfn, ok := mv[tname]
if !ok {
return false
}
if !c.identical(vfn.Type(), tfn.Type()) {
return false
}
}
return true
}
func (c *comparer) samePackage(a, b *types.Package) bool {
return a.Path() == b.Path()
}
// https://golang.org/ref/spec#Representability
// TODO: Add range checking of literals.
func representable(x *types.Basic, t types.Type) bool {
tb, ok := t.Underlying().(*types.Basic)
if !ok {
return false
}
switch x.Kind() {
case types.UntypedBool:
return (tb.Info() & types.IsBoolean) == types.IsBoolean
case types.UntypedInt:
return (tb.Info() & types.IsNumeric) == types.IsNumeric
case types.UntypedRune:
switch tb.Kind() {
case types.Int8, types.Int16, types.Uint8, types.Uint16:
return false
}
return (tb.Info() & types.IsNumeric) == types.IsNumeric
case types.UntypedFloat:
if (tb.Info() & types.IsInteger) == types.IsInteger {
return false
}
return (tb.Info() & types.IsNumeric) == types.IsNumeric
case types.UntypedComplex:
return (tb.Info() & types.IsComplex) == types.IsComplex
case types.UntypedString:
return (tb.Info() & types.IsString) == types.IsString
}
return false
}
func methodMap(t types.Type) map[string]types.Object {
ms := types.NewMethodSet(t)
result := make(map[string]types.Object)
for i := 0; i < ms.Len(); i++ {
fnobj := ms.At(i).Obj()
result[fnobj.Name()] = fnobj
}
return result
}
func makePackageMap(pkgs []*packages.Package) map[string]*packages.Package {
result := make(map[string]*packages.Package)
for _, pkg := range pkgs {
result[pkg.PkgPath] = pkg
}
return result
}
func makeTopObjs(pkg *packages.Package) map[string]types.Object {
res := make(map[string]types.Object)
for _, file := range pkg.Syntax {
for _, decl := range file.Decls {
switch decl := decl.(type) {
case *ast.GenDecl:
for _, spec := range decl.Specs {
switch spec := spec.(type) {
case *ast.ValueSpec:
for _, name := range spec.Names {
res[name.Name] = pkg.TypesInfo.Defs[name]
}
case *ast.TypeSpec:
res[spec.Name.Name] = pkg.TypesInfo.Defs[spec.Name]
}
}
case *ast.FuncDecl:
// If decl is a method, qualify the name with the receiver type.
name := decl.Name.Name
if decl.Recv != nil && len(decl.Recv.List) > 0 {
recv := decl.Recv.List[0].Type
if info := pkg.TypesInfo.Types[recv]; info.Type != nil {
name = types.TypeString(info.Type, types.RelativeTo(pkg.Types)) + "." + name
}
}
res[name] = pkg.TypesInfo.Defs[decl.Name]
}
}
}
return res
}
func structMap(t *types.Struct) map[string]int {
result := make(map[string]int)
for i := 0; i < t.NumFields(); i++ {
f := t.Field(i)
result[f.Name()] = i
}
return result
}
var tagRE = regexp.MustCompile(`([^ ":[:cntrl:]]+):"(([^"]|\\")*)"`)
func tagMap(inp string) map[string]string {
res := make(map[string]string)
matches := tagRE.FindAllStringSubmatch(inp, -1)
for _, match := range matches {
res[match[1]] = match[2]
}
return res
}
func isNonEmptyMethodSet(intf *types.Interface) bool {
return intf.IsMethodSet() && intf.NumMethods() > 0
}