~mna/snow

ref: wip-post-ast snow/pkg/semantic/type.go -rw-r--r-- 13.7 KiB
81715ef3Martin Angers pkg/{codegen,semantic}: OMG all codegen tests pass, all is good 2 years 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
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

	fmt.Stringer
}

// 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
	}

	// 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 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
}

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" }

// ========> 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) 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
}

// ========> 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
}

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

func (s *StructType) AssignableTo(T Type) bool { return s.IdenticalTo(T) }
func (s *StructType) Valid() bool              { return true }
func (s *StructType) String() string           { return "struct " + s.Decl.Ident() }
func (s *StructType) IdenticalTo(T Type) bool {
	s2 := AsStructType(T)
	if s2 == nil {
		return false
	}
	return s.Decl == s2.Decl
}

// ========> 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
}