/
typer.go
2397 lines (2067 loc) · 59 KB
/
typer.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
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
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Negotiate and validate types in an AST.
package have
import (
"fmt"
"strings"
)
// Generic instantiation key.
type InstKey string
func NewInstKey(g Generic, params []Type) InstKey {
name, _ := g.Signature()
strParams := make([]string, 0, len(params))
for _, p := range params {
strParams = append(strParams, p.String())
}
return InstKey(name + "[" + strings.Join(strParams, ", ") + "]")
}
type TypesContext struct {
// Stores negotiated types of expression.
types map[Expr]Type
// Stores strings that should be used in place of expressions for code generation.
// Useful e.g. for instantiations of generics.
goNames map[Expr]string
// Stores instantiations of generics.
instantiations map[InstKey]*Instantiation
}
func (tc *TypesContext) SetType(e Expr, typ Type) { tc.types[e] = typ }
func (tc *TypesContext) GetType(e Expr) Type { return nonilTyp(tc.types[e]) }
func (tc *TypesContext) IsTypeSet(e Expr) bool { _, ok := tc.types[e]; return ok }
func NewTypesContext() *TypesContext {
return &TypesContext{
types: map[Expr]Type{},
goNames: map[Expr]string{},
instantiations: map[InstKey]*Instantiation{},
}
}
// Provides a type checking context to typed expressions.
type ExprToProcess interface {
Expr
NegotiateTypes(tc *TypesContext) error
}
type TypedExpr interface {
Expr
// Infers type of the expression based on facts that are certain - no guessing should
// happen at this point.
// Errors returned from Type() are reported as compilation errors.
// Type() MUSTN'T return GenericType in any case, but the underlying type instead.
Type(tc *TypesContext) (Type, error)
// Called by the type checker when it wants this expression to be of a particular type.
// If all goes well, this should affect the result of further calls to Type().
// If applying the given type is impossible, appropriate error should be returned (it
// doesn't always mean the end of negotiation - further calls to Type/ApplyType/GuessType can
// be expected).
ApplyType(tc *TypesContext, typ Type) error
// Tries to guess the most appropriate type for this expression.
// GuessType(tc *TypesContext) MUSTN'T return GenericType in any case, but the underlying type instead.
GuessType(tc *TypesContext) (ok bool, typ Type)
}
func unNilType(t *Type) Type {
if *t == nil {
*t = &UnknownType{}
}
return *t
}
func nonilTyp(t Type) Type {
if t == nil {
return &UnknownType{}
}
return t
}
func RootType(t Type) Type {
if at, ok := t.(DeclaredType); ok {
return at.RootType()
}
//if t.Kind() == KIND_CUSTOM {
// return t.(*CustomType).RootType()
//}
return t
}
// Implements the definition of underlying types from the Go spec.
func UnderlyingType(t Type) Type {
if t.Kind() == KIND_CUSTOM {
return t.(*CustomType).Decl.AliasedType
}
return t
}
// Implements the definition of named types from the Go spec.
func IsNamed(t Type) bool {
return t.Kind() == KIND_CUSTOM || t.Kind() == KIND_SIMPLE
}
// Implements the definition of unnamed types from the Go spec.
func IsUnnamed(t Type) bool {
return !IsNamed(t)
}
// Can be used to check if a type is an interface. Works with
// interfaces aliased by named types.
func IsInterface(t Type) bool {
return RootType(t).Kind() == KIND_INTERFACE
}
func IsIdentincal(to, what Type) bool {
return to.String() == what.String()
}
// Implements the definition of assignability from the Go spec.
func IsAssignable(to, what Type) bool {
if IsInterface(to) {
return Implements(to, what)
}
if IsNamed(to) && IsNamed(what) {
return to.String() == what.String()
}
return UnderlyingType(to).String() == UnderlyingType(what).String()
}
// Tells whether value's methods are a subset of iface's methods.
func Implements(iface, value Type) bool {
i := RootType(iface).(*IfaceType)
ptr := false
if value.Kind() == KIND_POINTER {
value = value.(*PointerType).To
ptr = true
}
var valueMethods map[string]*FuncDecl
switch value.Kind() {
case KIND_CUSTOM:
valueMethods = value.(*CustomType).Decl.Methods
case KIND_INTERFACE:
valueMethods = value.(*IfaceType).Methods
case KIND_GENERIC_INST:
gen, ok := value.(*GenericType)
if !ok {
return false
}
valueMethods = gen.Struct.Methods
default:
// Other types can't have methods, but they still can satsifty
// the empty interface.
valueMethods = map[string]*FuncDecl{}
}
for _, imet := range i.Methods {
found := false
for _, met := range valueMethods {
if met.name != imet.name {
continue
}
if met.PtrReceiver != ptr {
continue
}
if met.typ.String() != imet.typ.String() {
continue
}
found = true
break
}
if !found {
return false
}
}
return true
}
func IsPackage(e TypedExpr) bool {
ident, isIdent := e.(*Ident)
return isIdent && ident.object.ObjectType() == OBJECT_PACKAGE
}
func IsBlank(e TypedExpr) bool {
ident, isIdent := e.(*Ident)
return isIdent && ident.name == Blank
}
// Given an expression, returns a function referred by it or nil otherwise.
func funcUnderneath(expr Expr) *FuncDecl {
if oe, ok := expr.(ObjectExpr); ok {
vr, ok := oe.ReferedObject().(*Variable)
if !ok {
return nil
}
fd, ok := vr.init.(*FuncDecl)
if !ok {
return nil
}
return fd
}
return nil
}
func (vs *VarStmt) NegotiateTypes(tc *TypesContext) error {
for _, v := range vs.Vars {
err := v.NegotiateTypes(tc)
if err != nil {
return err
}
}
return nil
}
func (td *ImportStmt) NegotiateTypes(tc *TypesContext) error { return nil }
func (td *TypeDecl) NegotiateTypes(tc *TypesContext) error { return nil }
func (bs *BranchStmt) NegotiateTypes(tc *TypesContext) error { return nil }
func (ls *LabelStmt) NegotiateTypes(tc *TypesContext) error { return nil }
func (ls *GenericFunc) NegotiateTypes(tc *TypesContext) error { return nil }
func (ls *GenericStruct) NegotiateTypes(tc *TypesContext) error { return nil }
func (ws *WhenStmt) NegotiateTypes(tc *TypesContext) error {
for _, branch := range ws.Branches {
fail := false
loop:
for i, pred := range branch.Predicates {
switch pred.Kind {
case WHEN_KIND_IS:
if !IsIdentincal(pred.Target, ws.Args[i]) {
fail = true
break loop
}
case WHEN_KIND_IMPLEMENTS:
_, ok := RootType(pred.Target).(*IfaceType)
if !ok {
return ExprErrorf(branch, "Not an interface: %s", pred.Target)
}
if !Implements(pred.Target, ws.Args[i]) {
fail = true
break loop
}
case WHEN_KIND_DEFAULT:
}
}
branch.True = !fail
if branch.True {
return branch.Code.CheckTypes(tc)
}
}
return nil
}
func (rs *ReturnStmt) NegotiateTypes(tc *TypesContext) error {
if rs.Func.Results.countVars() != len(rs.Values) {
return ExprErrorf(rs, "Different number of return values")
}
i, err := 0, error(nil)
rs.Func.Results.eachPair(func(v *Variable, init Expr) {
if err != nil {
return
}
err = NegotiateExprType(tc, &v.Type, rs.Values[i].(TypedExpr))
i++
})
return err
}
func (ls *SendStmt) NegotiateTypes(tc *TypesContext) error {
ltyp, rtyp := Type(&UnknownType{}), Type(&UnknownType{})
if err := NegotiateExprType(tc, <yp, ls.Lhs.(TypedExpr)); err != nil {
return err
}
if err := NegotiateExprType(tc, &rtyp, ls.Rhs.(TypedExpr)); err != nil {
return err
}
lroot := RootType(ltyp)
if lroot.Kind() != KIND_CHAN {
return ExprErrorf(ls.Lhs, "Not a chan used for sending")
}
channel := lroot.(*ChanType)
if channel.Dir == CHAN_DIR_RECEIVE {
return ExprErrorf(ls.Lhs, "Channel is receive-only")
}
if !IsAssignable(channel.Of, rtyp) {
return ExprErrorf(ls.Rhs, "Send value has to be assignable to channel's base type")
}
return nil
}
func (ss *StructStmt) NegotiateTypes(tc *TypesContext) error {
for _, m := range ss.Struct.Methods {
if err := m.Code.CheckTypes(tc); err != nil {
return err
}
}
return nil
}
func (is *IfaceStmt) NegotiateTypes(tc *TypesContext) error {
return nil
}
// This will overwrite the type pointer by varType.
func NegotiateExprType(tc *TypesContext, varType *Type, value TypedExpr) error {
*varType = nonilTyp(*varType)
valueTyp, err := value.Type(tc)
if err != nil {
return err
}
typ := firstKnown(*varType, valueTyp)
if typ == nil {
// Try guessing. Literals like "1", or "{1, 2}" can be used
// to initialize variables of many types (int/double/etc,
// array/slice/struct), but if type of the variable is
// not known, we try to guess it (for these examples,
// it would be "int" and "[]int").
ok, guessedType := value.GuessType(tc)
if !ok || !guessedType.Known() {
return ExprErrorf(value, "Too little information to infer types")
}
typ = guessedType
}
*varType = typ
valueTyp, err = value.Type(tc)
if err != nil {
return err
}
if !valueTyp.Known() {
// Don't always run ApplyType for interfaces - lhs and rhs expressions
// might have different types and that is on purpose.
if IsInterface(typ) {
// If we're dealing with interfaces then we don't want to apply that
// interface type to the value (unless that's explicitly specified).
// But we don't know the type of the value. But, we still haven't run
// GuessType(tc *TypesContext) on it, so we still have a chance.
// Example where this is used: assigning builtin types to the empty interface.
ok, guessedType := value.GuessType(tc)
if ok {
if !IsAssignable(typ, guessedType) {
return ExprErrorf(value, "Types %s and %s are not assignable", typ, guessedType)
}
return value.ApplyType(tc, guessedType)
}
}
return value.ApplyType(tc, typ)
} else {
if !IsAssignable(typ, valueTyp) {
return ExprErrorf(value, "Types %s and %s are not assignable", typ, valueTyp)
}
// Run value.ApplyType with value's own type - seems unnecessary,
// but ApplyType might do some extra checks as side effects.
return value.ApplyType(tc, valueTyp)
}
}
func CheckCondition(tc *TypesContext, expr TypedExpr) error {
var boolTyp Type = &SimpleType{SIMPLE_TYPE_BOOL}
err := NegotiateExprType(tc, &boolTyp, expr)
if err != nil {
return err
}
if !IsBoolAssignable(boolTyp) {
return ExprErrorf(expr, "Error while negotiating types")
}
return nil
}
func negotiateScopedVar(tc *TypesContext, scopedVar Stmt) error {
if scopedVar == nil {
return nil
}
switch scoped := scopedVar.(type) {
case *VarStmt:
// ok
case *AssignStmt:
if scoped.Token.Type != TOKEN_ASSIGN {
return CompileErrorf(scoped.Token, "Only `=` assignment allowed in scoped declarations")
}
default:
return ExprErrorf(scopedVar, "Not a var declaration or assignment")
}
return scopedVar.(ExprToProcess).NegotiateTypes(tc)
}
func (is *IfStmt) NegotiateTypes(tc *TypesContext) error {
for _, b := range is.Branches {
if err := negotiateScopedVar(tc, b.ScopedVar); err != nil {
return err
}
if b.Condition != nil {
if err := CheckCondition(tc, b.Condition.(TypedExpr)); err != nil {
return err
}
}
if err := b.Code.CheckTypes(tc); err != nil {
return err
}
}
return nil
}
func (ss *SwitchStmt) NegotiateTypes(tc *TypesContext) error {
if err := negotiateScopedVar(tc, ss.ScopedVar); err != nil {
return err
}
var valExpr TypedExpr = &BasicLit{token: &Token{Type: TOKEN_TRUE}}
typeSwitch, assertion := false, (*TypeAssertion)(nil)
if ss.Value != nil {
switch val := ss.Value.(type) {
case *VarStmt:
typeSwitch = true
init := val.Vars[0].Inits[0]
var ok bool
assertion, ok = init.(*TypeAssertion)
if !ok {
return ExprErrorf(ss.Value, "Variable not initialized with type assertion")
}
if !assertion.ForSwitch {
return ExprErrorf(ss.Value, "Type switch should use v.(type)")
}
case *ExprStmt:
var ok bool
if assertion, ok = val.Expression.(*TypeAssertion); ok {
typeSwitch = true
} else {
err := val.NegotiateTypes(tc)
if err != nil {
return err
}
valExpr = val.Expression.(TypedExpr)
}
}
}
// Determine type of the switch value. It is done independently from values in switch branches.
valType, err := valExpr.Type(tc)
if err != nil {
return err
}
if !valType.Known() {
var ok bool
ok, valType = valExpr.GuessType(tc)
if !ok {
return ExprErrorf(valExpr, "Couldn't determine type of switch expression")
}
}
err = valExpr.ApplyType(tc, valType)
if err != nil {
return err
}
wasDefault := false
for i, b := range ss.Branches {
if len(b.Values) > 0 {
if typeSwitch {
if len(b.Values) != 1 {
return ExprErrorf(b.Values[0], "More than 1 value in a branch of type switch")
}
typ, err := ExprToTypeName(tc, b.Values[0])
if err != nil {
return err
}
if typ == nil {
return ExprErrorf(b.Values[0], "Not a type name in type switch")
}
if b.TypeSwitchVar != nil {
b.TypeSwitchVar.Type = typ
}
if err := CheckTypeAssert(tc, assertion.Left.(TypedExpr), typ); err != nil {
return err
}
} else {
if ss.Value == nil && len(b.Values) > 1 {
return ExprErrorf(b.Values[0], "List of values in freeform switch")
}
for _, val := range b.Values {
err := NegotiateExprType(tc, &valType, val.(TypedExpr))
if err != nil {
return ExprErrorf(b.Values[0], "Error with switch clause: %s", i+1, err)
}
if !AreComparable(tc, valExpr, val.(TypedExpr)) {
return ExprErrorf(b.Values[0], "Error with switch clause, values are not comparable")
}
}
}
} else {
if wasDefault {
return ExprErrorf(b, "Error - more than one `default` clause")
}
wasDefault = true
}
err := b.Code.CheckTypes(tc)
if err != nil {
return err
}
}
return nil
}
func (p *PassStmt) NegotiateTypes(tc *TypesContext) error {
return nil
}
func (c *compilerMacro) NegotiateTypes(tc *TypesContext) error {
c.Active = true
return nil
}
// For convenience, always returns TupleType, even for one type (chans).
func iteratorType(containerType Type) (*TupleType, error) {
ct := RootType(containerType)
switch ct.Kind() {
case KIND_ARRAY:
return &TupleType{[]Type{&SimpleType{SIMPLE_TYPE_INT}, ct.(*ArrayType).Of}}, nil
case KIND_SLICE:
return &TupleType{[]Type{&SimpleType{SIMPLE_TYPE_INT}, ct.(*SliceType).Of}}, nil
case KIND_MAP:
mapType := ct.(*MapType)
return &TupleType{[]Type{mapType.By, mapType.Of}}, nil
case KIND_CHAN:
chanType := ct.(*ChanType)
if chanType.Dir == CHAN_DIR_SEND {
return nil, fmt.Errorf("Can't read from %s (%s)", containerType, ct)
}
return &TupleType{[]Type{chanType.Of}}, nil
default:
return nil, fmt.Errorf("Type %s is not iterable", containerType)
}
}
func (fs *ForRangeStmt) NegotiateTypes(tc *TypesContext) error {
seriesTyp, err := fs.Series.(TypedExpr).Type(tc)
if err != nil {
return err
}
if !seriesTyp.Known() {
var ok bool
ok, seriesTyp = fs.Series.(TypedExpr).GuessType(tc)
if !ok || !seriesTyp.Known() {
return ExprErrorf(fs.Series, "Couldn't determine the type")
}
}
err = fs.Series.(TypedExpr).ApplyType(tc, seriesTyp)
if err != nil {
return err
}
iterType, err := iteratorType(seriesTyp)
if err != nil {
return ExprErrorf(fs.Series, err.Error())
}
if fs.ScopedVars != nil {
if len(iterType.Members) < len(fs.ScopedVars.Vars) {
return ExprErrorf(fs.Series, "Wrong number of iterator vars, max %d", len(iterType.Members))
}
// All vars are new, just assign them their types.
for i, v := range fs.ScopedVars.Vars {
v.Type = iterType.Members[i]
}
} else if fs.OutsideVars != nil {
if len(iterType.Members) < len(fs.OutsideVars) {
return ExprErrorf(fs.OutsideVars[0], "Wrong number of iterator vars, max %d", len(iterType.Members))
}
// TODO: Check if fs.OutsideVars are addressable
for i, v := range fs.OutsideVars {
if IsBlank(v.(TypedExpr)) {
continue
}
varType, err := v.(TypedExpr).Type(tc)
if err != nil {
return err
}
if !IsAssignable(varType, iterType.Members[i]) {
return ExprErrorf(v, "Can't use %s for iteration, it's not assignable to %s",
varType, iterType.Members[i])
}
}
} else {
panic("niemożliwe")
}
if err := fs.Code.CheckTypes(tc); err != nil {
return err
}
return nil
}
func (fs *ForStmt) NegotiateTypes(tc *TypesContext) error {
if err := negotiateScopedVar(tc, fs.ScopedVar); err != nil {
return err
}
if fs.Condition != nil {
if err := CheckCondition(tc, fs.Condition.(TypedExpr)); err != nil {
return err
}
}
if fs.RepeatStmt != nil {
err := fs.RepeatStmt.(ExprToProcess).NegotiateTypes(tc)
if err != nil {
return err
}
}
if err := fs.Code.CheckTypes(tc); err != nil {
return err
}
return nil
}
// Helper function useful for situations where an expression returning
// more than one result is assigned to multiple variables.
// In some situations only func calls unpacking works. Type assertions or map
// inclusion testing doesn't work in non-assignment situtations, examples:
//
// func x() int, bool:
// return someMap[7] // Doesn't work (in Golang as well)
//
// func x(int, bool):
// pass
// x(someMap[7]) // Doesn't work (in Golang as well)
//
// UseonlyFuncCalls argument to control this.
func NegotiateTupleUnpackAssign(tc *TypesContext, onlyFuncCalls bool, lhsTypes []*Type, rhs TypedExpr) error {
var tuple *TupleType
switch rhs.(type) {
case *FuncCallExpr:
rhsType, err := rhs.Type(tc)
if err != nil {
return err
}
if rhsType.Kind() != KIND_TUPLE {
return ExprErrorf(rhs, "Too few values on the right side (function call returns only 1 result)")
}
tuple = rhsType.(*TupleType)
default:
// In other cases (non-function-calls), tuples aren't returned explicitly - extra
// boolean is returned only if two variables are in the lhs expression.
if onlyFuncCalls {
// Tuples cannot be stored explicitly at the moment.
return ExprErrorf(rhs, "Too few values")
}
leftTyp, err := rhs.Type(tc)
if err != nil {
return err
}
var ok = true
if !leftTyp.Known() {
ok, leftTyp = rhs.GuessType(tc)
}
if !ok || !leftTyp.Known() {
return ExprErrorf(rhs, "Couldn't determine type of the right side of the assignment")
}
tuple = &TupleType{Members: []Type{
leftTyp,
&SimpleType{SIMPLE_TYPE_BOOL},
}}
if err := rhs.ApplyType(tc, tuple); err != nil {
return err
}
}
for i, t := range lhsTypes {
typ := firstKnown(*t, tuple.Members[i])
if typ == nil {
return ExprErrorf(rhs, "Too little information to infer types")
}
if !tuple.Members[i].Known() {
return ExprErrorf(rhs, "Unknown type in a tuple")
}
if (*t).Kind() == KIND_UNKNOWN {
*t = typ
} else if !IsAssignable(*t, tuple.Members[i]) {
return ExprErrorf(rhs, "Types %s and %s aren't assignable", *t, tuple.Members[i])
}
}
return nil
}
func (as *AssignStmt) NegotiateTypes(tc *TypesContext) error {
if len(as.Lhs) != len(as.Rhs) {
if len(as.Rhs) == 1 {
// We might be dealing with tuple unpacking
types := make([]*Type, len(as.Lhs))
for i, v := range as.Lhs {
var typ Type
var err error
if IsBlank(v.(TypedExpr)) {
typ = &UnknownType{}
} else {
typ, err = v.(TypedExpr).Type(tc)
if err != nil {
return err
}
}
types[i] = &typ
}
return NegotiateTupleUnpackAssign(tc, false, types, as.Rhs[0].(TypedExpr))
} else {
return ExprErrorf(as, "Different number of items on the left and right hand side")
}
}
for i := range as.Lhs {
leftExpr := as.Lhs[i].(TypedExpr)
var leftType Type
var err error
if IsBlank(leftExpr) {
leftType = &UnknownType{}
} else {
leftType, err = as.Lhs[i].(TypedExpr).Type(tc)
if err != nil {
return err
}
}
err = NegotiateExprType(tc, &leftType, as.Rhs[i].(TypedExpr))
if err != nil {
return err
}
// TODO: check addressability, "_" for ==, and if type is numeric for +=, -=,...
}
return nil
}
type varInitPair struct {
v *Variable
init Expr
}
func (p *varInitPair) NegotiateTypes(tc *TypesContext) error {
if p.init == nil {
p.init = NewBlankExpr()
}
return NegotiateExprType(tc, &p.v.Type, p.init.(TypedExpr))
}
func (vd *VarDecl) NegotiateTypes(tc *TypesContext) error {
if len(vd.Vars) > 1 && len(vd.Inits) == 1 {
// Mutliple variables initialized with a single function call - we need to unpack a tuple
types := make([]*Type, len(vd.Vars))
for i, v := range vd.Vars {
types[i] = &v.Type
}
return NegotiateTupleUnpackAssign(tc, false, types, vd.Inits[0].(TypedExpr))
}
var err error
vd.eachPair(func(v *Variable, init Expr) {
if err == nil {
if init == nil {
init = NewBlankExpr()
}
err = NegotiateExprType(tc, &v.Type, init.(TypedExpr))
}
})
return err
}
func (es *ExprStmt) NegotiateTypes(tc *TypesContext) error {
te := es.Expression.(TypedExpr)
typ, err := te.Type(tc)
if err != nil {
return err
}
if !typ.Known() {
ok, typ_ := te.GuessType(tc)
if ok {
typ = typ_
}
}
if !typ.Known() {
fc, ok := es.Expression.(*FuncCallExpr)
if ok && fc.IsNullResult(tc) {
return nil
}
return ExprErrorf(es, "Couldn't infer types")
}
return es.Expression.(TypedExpr).ApplyType(tc, typ)
}
func (ex *BlankExpr) Type(tc *TypesContext) (Type, error) { return &UnknownType{}, nil }
func (ex *BlankExpr) ApplyType(tc *TypesContext, typ Type) error { return nil }
func (ex *BlankExpr) GuessType(tc *TypesContext) (ok bool, typ Type) { return false, nil }
// Implements convertability definition from Go spec
// https://golang.org/ref/spec#Conversions
func IsConvertable(tc *TypesContext, what TypedExpr, to Type) bool {
wt, err := what.Type(tc)
if err != nil {
panic("BUG: Type() errors should be dealt with before IsConvertable")
}
if IsAssignable(to, wt) {
return true
}
if UnderlyingType(to).String() == UnderlyingType(wt).String() {
return true
}
if to.Kind() == KIND_POINTER && wt.Kind() == KIND_POINTER &&
UnderlyingType(wt.(*PointerType).To).String() == UnderlyingType(to.(*PointerType).To).String() {
return true
}
// TODO cases:
// x's type and T are both integer or floating point types.
// x's type and T are both complex types.
// x is an integer or a slice of bytes or runes and T is a string type.
// x is a string and T is a slice of bytes or runes.
return false
}
// Sometimes it is not immediately obvious if a piece of code is
// an actual expression or a name of a type.
// That can happen during during type conversions, for example in
// the line below we don't know whether 'blah' is a type name or
// a function during parsing:
//
// blah(123)
//
// This function tells if an expression is really a type name, and
// returns that type if the answer was yes (nil otherwise).
// Additionaly, if it encounters an error it returns it, usually
// they are non-recoverable and can be printed out as compilation errors.
func ExprToTypeName(tc *TypesContext, e Expr) (t Type, err error) {
switch e := e.(type) {
case *TypeExpr:
return e.typ, nil
case *UnaryOp:
subType, err := ExprToTypeName(tc, e.Right)
if err != nil {
return nil, err
}
if subType == nil {
return nil, nil
}
return &PointerType{To: subType}, nil
case *Ident:
if e.object == nil {
return nil, ExprErrorf(e, "Unknown identifier: %s", e.name)
}
if e.object.ObjectType() == OBJECT_TYPE {
return e.object.(*TypeDecl).Type(), nil
}
case *DotSelector:
if IsPackage(e.Left.(TypedExpr)) {
importStmt := e.Left.(*Ident).object.(*ImportStmt)
decl := importStmt.pkg.GetType(e.Right.name)
if decl != nil {
return &CustomType{Decl: decl, Name: decl.name, Package: importStmt}, nil
}
}
}
// No error found, but the expression is not a type.
return nil, nil
}
// Just like ExprToTypeName, but for generics.
func ExprToGeneric(e Expr) (t Generic, err error) {
switch e := e.(type) {
case *Ident:
if e.object == nil {
return nil, ExprErrorf(e, "Unknown identifier: %s", e.name)
}
if e.object.ObjectType() == OBJECT_GENERIC {
return e.object.(Generic), nil
}
case *DotSelector:
if IsPackage(e.Left.(TypedExpr)) {
importStmt := e.Left.(*Ident).object.(*ImportStmt)
obj := importStmt.pkg.GetObject(e.Right.name)
if obj != nil && obj.ObjectType() == OBJECT_GENERIC {
return obj.(Generic), nil
}
}
}
// No error found, but the expression is no a generic.
return nil, nil
}
func (ex *FuncCallExpr) inferGeneric(tc *TypesContext) (*Variable, string, error) {
generic, err := ExprToGeneric(ex.Left)
if err != nil {
return nil, "", err
}
if generic == nil {
return nil, "", nil
}
// Generic function call with indirect generic params
_, params := generic.Signature()
genericFn, isFn := generic.(*GenericFunc)
if !isFn {
return nil, "", ExprErrorf(ex.Left, "Expression is not a function")
}
var argTypes []Type
genericFn.Func.Args.eachPair(func(v *Variable, init Expr) {
argTypes = append(argTypes, v.Type)
})
gnParams, err := deduceGenericParams(tc, params, argTypes, ex.Args, genericFn.Func.Ellipsis && !ex.Ellipsis)
if err != nil {
return nil, "", ExprErrorf(ex, err.Error())
}
obj, goName, errors := generic.Instantiate(tc, gnParams...)
if len(errors) > 0 {
// TODO: return all errors
return nil, "", errors[0]
}
if obj.ObjectType() != OBJECT_VAR {
return nil, "", ExprErrorf(ex, "Result of a generic is not a value")
}
return obj.(*Variable), goName, nil
}
func (ex *FuncCallExpr) getCalleeType(tc *TypesContext) (Type, error) {
generic, goName, err := ex.inferGeneric(tc)
if err != nil {
return nil, err
}