~mna/snow unlisted

snow/pkg/semantic/type.go -rw-r--r-- 22.6 KiB
424066c5Martin Angers doc: v0.0.5 1 year, 7 months ago
                                                                                
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
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
package semantic

import (
	"fmt"
	"reflect"
	"strings"

	"git.sr.ht/~mna/snow/pkg/token"
)

// Type represents a type of value. All types implement the Type interface.
type Type interface {
	// AssignableTo returns true if a value of the current type can be
	// assigned to a variable of type T.
	AssignableTo(T Type) bool
	// IdenticalTo returns true if the current type is identical to type T.
	IdenticalTo(T Type) bool
	// Valid indicates if the type is valid. Unresolved types are invalid.
	Valid() bool
	// ResolveGeneric returns a Type where all generic types present in the
	// resolve map provided and resolved to their matching type.
	ResolveGeneric(map[*GenericType]Type) Type

	fmt.Stringer
}

// typeContainer is an optional interface that must be implemented by Types that
// contain other identifiers. It defines the typeof method that must return
// the type of the selected identifier inside the container type. It returns nil
// as Type and Invalid as TypeContext if the selector does not exist.
type typeContainer interface {
	Type
	typeof(sel *Ident, ctxHint TypeContext) (Type, TypeContext)
}

// List of types implementing the Type interface.
type (
	// BasicType represents a basic type such as int, bool or string. All basic types
	// are predeclared and part of the Universe scope.
	BasicType struct {
		Kind BasicKind
	}

	// SignatureType represents the type of functions and methods.
	SignatureType struct {
		Params []Type
		Return Type
	}

	// TupleType represents the type of a tuple literal.
	TupleType struct {
		Fields []Type
	}

	// StructType represents a named struct type.
	StructType struct {
		// Decl represents the struct declaration of this type.
		Decl *Struct
		// Inst is the list of types used in a generic instantiation, if the
		// struct declaration is generic.
		Inst []Type
		// Ctx is the type context associated with the value that has that type.
		// It only plays a role in one specific case: when the value associated
		// with that type is assigned to an interface type, to check if ref
		// functions can be used to satisfy that type (if Ctx is mutable).
		Ctx TypeContext

		// lookup cache of GenericType to instantiated type, nil until the first
		// call to typeOfSel.
		lookup map[*GenericType]Type
	}

	// InterfaceType represents an interface type.
	InterfaceType struct {
		// Decl represents the interface declaration of this type.
		Decl *Interface
		// Inst is the list of types used in a generic instantiation, if the
		// interface declaration is generic.
		Inst []Type

		// lookup cache of GenericType to instantiated type, nil until the first
		// call to typeOfSel.
		lookup map[*GenericType]Type
	}

	// GenericType is the type of a generic placeholder, e.g. $T.
	GenericType struct {
		Name    string
		ScopeID int
	}

	// marker type for "unresolved", e.g. when an identifier is encountered before
	// its symbol is resolved (possible for top-level declarations and other order-
	// independent scopes).
	unresolvedType struct{}
)

func AsStructType(T Type) *StructType {
	if st, ok := T.(*StructType); ok {
		return st
	}
	return nil
}

func AsInterfaceType(T Type) *InterfaceType {
	if it, ok := T.(*InterfaceType); ok {
		return it
	}
	return nil
}

func AsBasicType(T Type) *BasicType {
	if bt, ok := T.(*BasicType); ok {
		return bt
	}
	return nil
}

func AsSignatureType(T Type) *SignatureType {
	if st, ok := T.(*SignatureType); ok {
		return st
	}
	return nil
}

func AsTupleType(T Type) *TupleType {
	if tt, ok := T.(*TupleType); ok {
		return tt
	}
	return nil
}

func AsGenericType(T Type) *GenericType {
	if gt, ok := T.(*GenericType); ok {
		return gt
	}
	return nil
}

var typeType = reflect.TypeOf((*Type)(nil)).Elem()

// AsType returns true if the Type is of the type provided in v, which must be
// a pointer to the actual type. If this is the case, the value pointed to by v
// is set to the type's value, otherwise it returns false.
func AsType(T Type, v interface{}) bool {
	val := reflect.ValueOf(v)
	typ := val.Type()
	targetType := typ.Elem()
	if targetType != typeType && !targetType.Implements(typeType) {
		panic("*v must be Type or implement Type")
	}

	if !reflect.TypeOf(T).AssignableTo(targetType) {
		return false
	}
	val.Elem().Set(reflect.ValueOf(T))
	return true
}

// ========> implement Type for unresolvedType

func (u unresolvedType) AssignableTo(Type) bool                            { return false }
func (u unresolvedType) IdenticalTo(T Type) bool                           { _, ok := T.(unresolvedType); return ok }
func (u unresolvedType) Valid() bool                                       { return false }
func (u unresolvedType) String() string                                    { return "unresolved" }
func (u unresolvedType) ResolveGeneric(resolve map[*GenericType]Type) Type { return u }

// ========> implement Type for BasicType

func (b *BasicType) String() string                                    { return b.Kind.String() }
func (b *BasicType) IdenticalTo(T Type) bool                           { return IsBasicOfKind(T, b.Kind) }
func (b *BasicType) Valid() bool                                       { return b.Kind >= Void && b.Kind < kindEnd }
func (b *BasicType) ResolveGeneric(resolve map[*GenericType]Type) Type { return b }
func (b *BasicType) AssignableTo(T Type) bool {
	// implicit type coercion works when all values of the type can be
	// represented by the target type, i.e. the target is a superset
	// of the values of the source.
	switch b.Kind {
	case Void:
		// void can only be assigned to void
		return IsBasicOfKind(T, Void)
	case Bool:
		return IsBasicOfKind(T, Bool)
	case I8:
		return IsBasicOfKind(T, I8, I16, I32, I64, Int)
	case I16:
		return IsBasicOfKind(T, I16, I32, I64, Int)
	case I32:
		return IsBasicOfKind(T, I32, I64, Int)
	case I64:
		// Int might be only 32 bits
		return IsBasicOfKind(T, I64)
	case Int:
		// Int cannot be more than I64
		return IsBasicOfKind(T, I64, Int)
	case U8:
		return IsBasicOfKind(T, U8, U16, U32, U64, Uint, I16, I32, I64, Int)
	case U16:
		return IsBasicOfKind(T, U16, U32, U64, Uint, I32, I64, Int)
	case U32:
		return IsBasicOfKind(T, U32, U64, Uint, I64)
	case U64:
		// Uint might be only 32 bits
		return IsBasicOfKind(T, U64)
	case Uint:
		// Uint cannot be more than U64
		return IsBasicOfKind(T, U64, Uint)
	case Float:
		// Float cannot be more than F64
		return IsBasicOfKind(T, Float, F64)
	case F32:
		return IsBasicOfKind(T, Float, F32, F64)
	case F64:
		// Float might be only 32 bits
		return IsBasicOfKind(T, F64)
	case String:
		return IsBasicOfKind(T, String)
	default:
		panic(fmt.Sprintf("invalid basic type: %s", b.Kind))
	}
}

// ========> implement Type for SignatureType

func (s *SignatureType) String() string {
	var b strings.Builder
	b.WriteByte('(')
	for i, p := range s.Params {
		if i > 0 {
			b.WriteString(", ")
		}
		b.WriteString(p.String())
	}
	b.WriteString(") -> ")
	b.WriteString(s.Return.String())
	return b.String()
}

func (s *SignatureType) AssignableTo(T Type) bool {
	// A function value can only be assigned to a variable with the exact same type,
	// that is, parameters' types all match exactly, and return value too.
	return s.IdenticalTo(T)
}

func (s *SignatureType) IdenticalTo(T Type) bool {
	target := AsSignatureType(T)
	if target == nil {
		return false
	}

	if len(s.Params) != len(target.Params) {
		return false
	}
	for i := range s.Params {
		if !s.Params[i].IdenticalTo(target.Params[i]) {
			return false
		}
	}
	if (s.Return == nil) != (target.Return == nil) {
		return false
	}
	if s.Return != nil {
		return s.Return.IdenticalTo(target.Return)
	}
	return true
}

func (s *SignatureType) Valid() bool {
	for _, param := range s.Params {
		if !param.Valid() {
			return false
		}
	}
	if s.Return != nil && !s.Return.Valid() {
		return false
	}
	return true
}

func (s *SignatureType) ResolveGeneric(resolve map[*GenericType]Type) Type {
	var diff bool

	sigt := &SignatureType{
		Params: make([]Type, len(s.Params)),
	}
	for i, pt := range s.Params {
		if gt := AsGenericType(pt); gt != nil {
			if newt := resolve[gt]; newt != nil {
				sigt.Params[i] = newt
				diff = true
				continue
			}
		}
		sigt.Params[i] = pt
	}
	sigt.Return = s.Return
	if gt := AsGenericType(s.Return); gt != nil {
		if newt := resolve[gt]; newt != nil {
			sigt.Return = newt
			diff = true
		}
	}
	if diff {
		return sigt
	}
	return s
}

// ========> implement Type for TupleType

func (t *TupleType) Valid() bool {
	for _, f := range t.Fields {
		if !f.Valid() {
			return false
		}
	}
	return true
}

func (t *TupleType) String() string {
	var b strings.Builder
	b.WriteByte('(')
	for i, f := range t.Fields {
		if i > 0 {
			b.WriteString(", ")
		}
		b.WriteString(f.String())
	}
	b.WriteByte(')')
	return b.String()
}

func (t *TupleType) AssignableTo(T Type) bool {
	// tuple is assignable if each of the elements are assignable to
	// the target.
	t2 := AsTupleType(T)
	if t2 == nil {
		return false
	}
	if len(t.Fields) != len(t2.Fields) {
		return false
	}
	for i, f := range t.Fields {
		if !f.AssignableTo(t2.Fields[i]) {
			return false
		}
	}
	return true
}

func (t *TupleType) IdenticalTo(T Type) bool {
	t2 := AsTupleType(T)
	if t2 == nil {
		return false
	}
	if len(t.Fields) != len(t2.Fields) {
		return false
	}
	for i, f := range t.Fields {
		if !f.IdenticalTo(t2.Fields[i]) {
			return false
		}
	}
	return true
}

func (t *TupleType) ResolveGeneric(resolve map[*GenericType]Type) Type {
	var diff bool

	tt := &TupleType{
		Fields: make([]Type, len(t.Fields)),
	}
	for i, ft := range t.Fields {
		if gt := AsGenericType(ft); gt != nil {
			if newt := resolve[gt]; newt != nil {
				tt.Fields[i] = newt
				diff = true
				continue
			}
		}
		tt.Fields[i] = ft
	}
	if diff {
		return tt
	}
	return t
}

func (t *TupleType) typeof(sel *Ident, ctxHint TypeContext) (Type, TypeContext) {
	if sel.Index < 0 || sel.Index >= len(t.Fields) {
		return nil, Invalid
	}
	return t.Fields[sel.Index], ctxHint
}

// ========> implement Type for StructType

func (s *StructType) AssignableTo(T Type) bool {
	switch T := T.(type) {
	case *StructType:
		return s.IdenticalTo(T)
	case *InterfaceType:
		return T.isSatisfiedBy(s)
	}
	return false
}

func (s *StructType) Valid() bool { return true }

func (s *StructType) String() string {
	var buf strings.Builder
	buf.WriteString("struct " + s.Decl.Ident())
	if len(s.Inst) > 0 {
		buf.WriteString("[")
		for i, t := range s.Inst {
			if i > 0 {
				buf.WriteString(", ")
			}
			buf.WriteString(t.String())
		}
		buf.WriteString("]")
	}
	return buf.String()
}

func (s *StructType) IdenticalTo(T Type) bool {
	s2 := AsStructType(T)
	if s2 == nil {
		return false
	}
	if s.Decl != s2.Decl {
		return false
	}
	if len(s.Inst) != len(s2.Inst) {
		return false
	}
	for i, t1 := range s.Inst {
		t2 := s2.Inst[i]
		if !t1.IdenticalTo(t2) {
			return false
		}
	}
	return true
}

func (s *StructType) ResolveGeneric(resolve map[*GenericType]Type) Type {
	var diff bool
	strt := &StructType{
		Decl: s.Decl,
		Inst: make([]Type, len(s.Inst)),
	}
	for i, it := range s.Inst {
		if gt := AsGenericType(it); gt != nil {
			if newt := resolve[gt]; newt != nil {
				strt.Inst[i] = newt
				diff = true
				continue
			}
		}
		strt.Inst[i] = it
	}
	if diff {
		return strt
	}
	return s
}

func (s *StructType) typeof(sel *Ident, _ TypeContext) (Type, TypeContext) {
	decl := s.Decl.BodyScope.Lookup(sel.Name)
	if decl == nil {
		return nil, Invalid
	}
	sel.Ref = decl
	return s.typeOfSel(decl.Type()), decl.TypeContext()
}

// typeOfSel returns the actual type of a selection inside the struct.
// If the struct is not generic, then T is returned unchanged, otherwise
// if T is a GenericType it is replaced by the type of its corresponding
// instantiation.
func (s *StructType) typeOfSel(T Type) Type {
	if !s.Decl.IsGeneric() {
		return T
	}

	if s.lookup == nil {
		s.lookup = makeGenericResolveMap(s.Decl.GenericParams, s.Inst)
	}
	return T.ResolveGeneric(s.lookup)
}

func makeGenericResolveMap(gc *GenericClause, types []Type) map[*GenericType]Type {
	resolve := make(map[*GenericType]Type, len(types))
	for i, elem := range gc.Elems {
		if i >= len(types) {
			break
		}
		resolve[AsGenericType(elem.Type())] = types[i]
	}
	return resolve
}

// ========> implement Type for InterfaceType

// Assignable to any interface type that is a subset of this interface (or
// identical).
func (i *InterfaceType) AssignableTo(T Type) bool {
	if i2 := AsInterfaceType(T); i2 != nil {
		return i2.isSatisfiedBy(i)
	}
	return false
}

// an interface type is valid if all of its methods' types are valid.
func (i *InterfaceType) Valid() bool {
	for _, m := range i.Decl.Methods {
		if !m.Type().Valid() {
			return false
		}
	}
	return true
}

func (i *InterfaceType) String() string {
	var buf strings.Builder
	buf.WriteString("interface " + i.Decl.Ident())
	if len(i.Inst) > 0 {
		buf.WriteString("[")
		for i, t := range i.Inst {
			if i > 0 {
				buf.WriteString(", ")
			}
			buf.WriteString(t.String())
		}
		buf.WriteString("]")
	}
	return buf.String()
}

func (i *InterfaceType) IdenticalTo(T Type) bool {
	i2 := AsInterfaceType(T)
	if i2 == nil {
		return false
	}
	if i.Decl != i2.Decl {
		return false
	}
	if len(i.Inst) != len(i2.Inst) {
		return false
	}
	for i, t1 := range i.Inst {
		t2 := i2.Inst[i]
		if !t1.IdenticalTo(t2) {
			return false
		}
	}
	return true
}

func (i *InterfaceType) ResolveGeneric(resolve map[*GenericType]Type) Type {
	var diff bool
	ift := &InterfaceType{
		Decl: i.Decl,
		Inst: make([]Type, len(i.Inst)),
	}
	for i, it := range i.Inst {
		if gt := AsGenericType(it); gt != nil {
			if newt := resolve[gt]; newt != nil {
				ift.Inst[i] = newt
				diff = true
				continue
			}
		}
		ift.Inst[i] = it
	}
	if diff {
		return ift
	}
	return i
}

func (i *InterfaceType) typeof(sel *Ident, _ TypeContext) (Type, TypeContext) {
	for _, m := range i.Decl.Methods {
		if m.Ident() == sel.Name {
			sel.Ref = m
			return i.typeOfSel(m.Type()), m.TypeContext()
		}
	}
	return nil, Invalid
}

// typeOfSel returns the actual type of a selection inside the interface.
// If the method is not generic, then T is returned unchanged, otherwise
// if T is a GenericType it is replaced by the type of its corresponding
// instantiation.
func (i *InterfaceType) typeOfSel(T Type) Type {
	if !i.Decl.IsGeneric() {
		return T
	}

	if i.lookup == nil {
		i.lookup = makeGenericResolveMap(i.Decl.GenericParams, i.Inst)
	}
	return T.ResolveGeneric(i.lookup)
}

func (i *InterfaceType) isSatisfiedBy(T Type) bool {
	var (
		tfns     []*Fn
		resolve  func(Type) Type
		allowRef bool
	)

	switch T := T.(type) {
	case *StructType:
		tfns = T.Decl.Fns
		resolve = T.typeOfSel
		allowRef = T.Ctx == Mutable
	case *InterfaceType:
		tfns = T.Decl.Methods
		resolve = T.typeOfSel
		allowRef = false // cannot have ref methods on interface anyway
	default:
		return false
	}

	// build the map of required fn names to corresponding type
	req := make(map[string]Type, len(i.Decl.Methods))
	for _, m := range i.Decl.Methods {
		req[m.Ident()] = i.typeOfSel(m.Type())
	}

	for _, fn := range tfns {
		// if this fn is part of the required methods set, check if the types match
		if reqt := req[fn.Ident()]; reqt != nil {
			if fn.IsRef && !allowRef {
				// won't be able to satisfy this method
				return false
			}
			if !reqt.IdenticalTo(resolve(fn.Type())) {
				return false
			}
			delete(req, fn.Ident())
		}
	}
	return len(req) == 0
}

// ========> implement Type for GenericType

func (g *GenericType) String() string { return g.Name }
func (g *GenericType) ResolveGeneric(resolve map[*GenericType]Type) Type {
	if newt := resolve[g]; newt != nil {
		return newt
	}
	return g
}

// a generic type is always valid by itself (i.e. it is not unresolved)
func (g *GenericType) Valid() bool { return true }

func (g *GenericType) AssignableTo(T Type) bool { return g.IdenticalTo(T) }
func (g *GenericType) IdenticalTo(T Type) bool {
	g2 := AsGenericType(T)
	if g2 == nil {
		return false
	}
	return g2.Name == g.Name && g2.ScopeID == g.ScopeID
}

// ========> BasicKind

// BasicKind defines the basic, built-in kind of types.
type BasicKind int

const (
	kindStart BasicKind = iota

	Void // must be at this position
	Bool
	Int // Signed integers must stay ordered that way
	I8
	I16
	I32
	I64
	Uint // Unsigned integers must stay ordered that way
	U8
	U16
	U32
	U64
	Float // Floating points must stay ordered that way
	F32
	F64
	String

	kindEnd
)

var basicKindStrings = [...]string{
	Void:   "void",
	Bool:   "bool",
	Int:    "int", // guaranteed to be at least 32 bits.
	I8:     "i8",
	I16:    "i16",
	I32:    "i32",
	I64:    "i64",
	Uint:   "uint", // guaranteed to be at least 32 bits.
	U8:     "u8",
	U16:    "u16",
	U32:    "u32",
	U64:    "u64",
	Float:  "float", // really necessary?
	F32:    "f32",
	F64:    "f64",
	String: "string",
}

func IsBasicOfKind(T Type, kinds ...BasicKind) bool {
	target := AsBasicType(T)
	if target == nil {
		return false
	}
	k := target.Kind
	for _, kk := range kinds {
		if k == kk {
			return true
		}
	}
	return false
}

// String returns the string representation of the basic kind.
func (b BasicKind) String() string {
	if b > kindStart && b < kindEnd {
		return basicKindStrings[b]
	}
	return fmt.Sprintf("Invalid(%d)", b)
}

// this is conceptual sizes, used to get relative ordering of type sizes, not
// to represent actual exact sizes.
var basicKindSizes = [...]int{
	Void:   0,
	Bool:   1,
	Int:    33,
	I8:     8,
	I16:    16,
	I32:    32,
	I64:    64,
	Uint:   33,
	U8:     8,
	U16:    16,
	U32:    32,
	U64:    64,
	Float:  33,
	F32:    32,
	F64:    64,
	String: -1,
}

// ========> TypeContext

// TypeContext indicates the context of a type in the AST.
type TypeContext int

const (
	Invalid   TypeContext = iota
	Typ                   // expression is a type
	Constant              // expression is a compile-time constant (literal)
	Value                 // expression is a computed value
	Mutable               // expression is a mutable variable (var)
	Immutable             // expression is an immutable variable (let)
)

func (t TypeContext) isAnyOf(ctxs ...TypeContext) bool {
	for _, ctx := range ctxs {
		if t == ctx {
			return true
		}
	}
	return false
}

var (
	// TypeContextValues is the context for any kind of value.
	TypeContextValues = []TypeContext{Constant, Value, Mutable, Immutable}

	typeContextStrings = [...]string{
		Invalid:   "invalid",
		Typ:       "type",
		Constant:  "const",
		Value:     "value",
		Mutable:   "var",
		Immutable: "let",
	}
)

func (t TypeContext) String() string {
	if t >= 0 && int(t) < len(typeContextStrings) {
		return typeContextStrings[t]
	}
	return fmt.Sprintf("<unknown typeContext: %d>", t)
}

// ========> Selector Expressions Type Context Table

// logic for the type context:
// - if both are types, type
// - if any are value or constant and the other is any value, value
// - if any is immutable and the other is any value, immutable
// - if both are mutable, mutable
// otherwise, invalid
var selectorTypeContext = map[TypeContext]map[TypeContext]TypeContext{
	Invalid: { // Invalid with anything is Invalid
		Invalid:   Invalid,
		Typ:       Invalid,
		Constant:  Invalid,
		Value:     Invalid,
		Mutable:   Invalid,
		Immutable: Invalid,
	},
	Typ: {
		Invalid:   Invalid,
		Typ:       Typ, // only valid combination for Typ
		Constant:  Invalid,
		Value:     Invalid,
		Mutable:   Invalid,
		Immutable: Invalid,
	},
	Constant: {
		Invalid:   Invalid,
		Typ:       Invalid,
		Constant:  Value,
		Value:     Value,
		Mutable:   Value,
		Immutable: Value,
	},
	Value: {
		Invalid:   Invalid,
		Typ:       Invalid,
		Constant:  Value,
		Value:     Value,
		Mutable:   Value,
		Immutable: Value,
	},
	Mutable: {
		Invalid:   Invalid,
		Typ:       Invalid,
		Constant:  Value,
		Value:     Value,
		Mutable:   Mutable,
		Immutable: Immutable,
	},
	Immutable: {
		Invalid:   Invalid,
		Typ:       Invalid,
		Constant:  Value,
		Value:     Value,
		Mutable:   Immutable,
		Immutable: Immutable,
	},
}

// ========> Implicit Conversion Rules

var (
	unaryOpsTable = map[token.Token][]BasicKind{
		token.Add: {Int, I8, I16, I32, I64, Uint, U8, U16, U32, U64, Float, F32, F64},
		token.Sub: {Int, I8, I16, I32, I64, Uint, U8, U16, U32, U64, Float, F32, F64},
		token.Not: {Bool},
	}

	intsWidening = map[BasicKind]map[BasicKind]BasicKind{
		Int: {Int: Int, I8: Int, I16: Int, I32: Int, I64: I64},
		I8:  {I8: I8, I16: I16, I32: I32, I64: I64},
		I16: {I16: I16, I32: I32, I64: I64},
		I32: {I32: I32, I64: I64},
		I64: {I64: I64},

		Uint: {Uint: Uint, U8: Uint, U16: Uint, U32: Uint, U64: U64},
		U8:   {U8: U8, U16: U16, U32: U32, U64: U64},
		U16:  {U16: U16, U32: U32, U64: U64},
		U32:  {U32: U32, U64: U64},
		U64:  {U64: U64},
	}

	intsCompare = map[BasicKind]map[BasicKind]BasicKind{
		Int: {Int: Bool, I8: Bool, I16: Bool, I32: Bool, I64: Bool},
		I8:  {I8: Bool, I16: Bool, I32: Bool, I64: Bool},
		I16: {I16: Bool, I32: Bool, I64: Bool},
		I32: {I32: Bool, I64: Bool},
		I64: {I64: Bool},

		Uint: {Uint: Bool, U8: Bool, U16: Bool, U32: Bool, U64: Bool},
		U8:   {U8: Bool, U16: Bool, U32: Bool, U64: Bool},
		U16:  {U16: Bool, U32: Bool, U64: Bool},
		U32:  {U32: Bool, U64: Bool},
		U64:  {U64: Bool},
	}

	floatsWidening = map[BasicKind]map[BasicKind]BasicKind{
		Float: {Float: Float, F32: Float, F64: F64},
		F32:   {F32: F32, F64: F64},
		F64:   {F64: F64},
	}

	floatsCompare = map[BasicKind]map[BasicKind]BasicKind{
		Float: {Float: Bool, F32: Bool, F64: Bool},
		F32:   {F32: Bool, F64: Bool},
		F64:   {F64: Bool},
	}

	stringsWidening = map[BasicKind]map[BasicKind]BasicKind{
		String: {String: String},
	}

	stringsCompare = map[BasicKind]map[BasicKind]BasicKind{
		String: {String: Bool},
	}

	boolsCompare = map[BasicKind]map[BasicKind]BasicKind{
		Bool: {Bool: Bool},
	}

	// expects the smallest kind to be on the left, indicates the resulting basic kind
	// from the two operand kinds.
	binaryOpsTable = map[token.Token]map[BasicKind]map[BasicKind]BasicKind{
		// arithmetic
		token.Add: mergeBinaryMaps(stringsWidening, intsWidening, floatsWidening),
		token.Sub: mergeBinaryMaps(intsWidening, floatsWidening),
		token.Mul: mergeBinaryMaps(intsWidening, floatsWidening),
		token.Div: mergeBinaryMaps(intsWidening, floatsWidening),
		token.Mod: mergeBinaryMaps(intsWidening),

		// comparison
		token.Eq:    mergeBinaryMaps(boolsCompare, stringsCompare, intsCompare, floatsCompare),
		token.NotEq: mergeBinaryMaps(boolsCompare, stringsCompare, intsCompare, floatsCompare),
		token.Lt:    mergeBinaryMaps(stringsCompare, intsCompare, floatsCompare),
		token.Lte:   mergeBinaryMaps(stringsCompare, intsCompare, floatsCompare),
		token.Gt:    mergeBinaryMaps(stringsCompare, intsCompare, floatsCompare),
		token.Gte:   mergeBinaryMaps(stringsCompare, intsCompare, floatsCompare),

		// logical
		token.Or:  {Bool: {Bool: Bool}},
		token.And: {Bool: {Bool: Bool}},
	}
)

func mergeBinaryMaps(ms ...map[BasicKind]map[BasicKind]BasicKind) map[BasicKind]map[BasicKind]BasicKind {
	res := make(map[BasicKind]map[BasicKind]BasicKind)
	for _, m := range ms {
		for k, v := range m {
			res[k] = v
		}
	}
	return res
}