-
Notifications
You must be signed in to change notification settings - Fork 57
/
Copy pathSema.fu
2366 lines (2249 loc) · 74.4 KB
/
Sema.fu
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
// Sema.fu - semantic analysis of Fusion
//
// Copyright (C) 2011-2025 Piotr Fusik
//
// This file is part of Fusion Transpiler,
// see https://github.com/fusionlanguage/fut
//
// Fusion Transpiler is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Fusion Transpiler is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Fusion Transpiler. If not, see http://www.gnu.org/licenses/
public abstract class FuSemaHost : FuParserHost
{
internal virtual int GetResourceLength!(string name, FuPrefixExpr expr) => 0;
}
public class FuSema
{
FuSemaHost! Host;
FuMethodBase!? CurrentMethod = null;
FuScope!? CurrentScope;
HashSet<FuMethod>() CurrentPureMethods;
Dictionary<FuVar, FuExpr#>() CurrentPureArguments;
FuType# Poison = new FuType { Name = "poison" };
public void SetHost!(FuSemaHost! host)
{
this.Host = host;
}
void ReportError(FuStatement statement, string message)
{
this.Host.ReportStatementError(statement, message);
}
FuType# PoisonError(FuStatement statement, string message)
{
ReportError(statement, message);
return this.Poison;
}
void ResolveBase!(FuClass! klass)
{
if (klass.HasBaseClass()) {
this.CurrentScope = klass;
if (this.Host.Program.TryLookup(klass.BaseClass.Name, true) is FuClass! baseClass) {
if (klass.IsPublic && !baseClass.IsPublic)
ReportError(klass.BaseClass, "Public class cannot derive from an internal class");
klass.BaseClass.Symbol = baseClass;
baseClass.HasSubclasses = true;
klass.Parent = baseClass;
}
else
ReportError(klass.BaseClass, $"Base class '{klass.BaseClass.Name}' not found");
}
this.Host.Program.Classes.Add(klass);
}
void CheckBaseCycle!(FuClass! klass)
{
// Floyd's tortoise and hare cycle-finding algorithm
FuSymbol? hare = klass;
FuSymbol tortoise = klass;
do {
hare = hare.Parent;
if (hare == null)
return;
if (hare.Id == FuId.ExceptionClass)
klass.Id = FuId.ExceptionClass;
hare = hare.Parent;
if (hare == null)
return;
if (hare.Id == FuId.ExceptionClass)
klass.Id = FuId.ExceptionClass;
tortoise = tortoise.Parent;
} while (tortoise != hare);
this.CurrentScope = klass;
ReportError(klass, $"Circular inheritance for class '{klass.Name}'");
}
static void TakePtr(FuExpr expr)
{
if (expr.Type is FuArrayStorageType! arrayStg)
arrayStg.PtrTaken = true;
}
bool Coerce(FuExpr expr, FuType type)
{
if (expr == this.Poison || type == this.Poison)
return false;
if (!type.IsAssignableFrom(expr.Type)) {
ReportError(expr, $"Cannot convert '{expr.Type}' to '{type}'");
return false;
}
if (expr is FuPrefixExpr prefix && prefix.Op == FuToken.New && !(type is FuDynamicPtrType)) {
assert expr.Type is FuDynamicPtrType newType;
string kind = newType.Class.Id == FuId.ArrayPtrClass ? "array" : "object";
ReportError(expr, $"Dynamically allocated {kind} must be assigned to a '{expr.Type}' reference");
return false;
}
TakePtr(expr);
return true;
}
bool CoercePermanent(FuExpr expr, FuType type)
{
bool ok = Coerce(expr, type);
if (ok && type.Id == FuId.StringPtrType && expr.IsNewString(true)) {
ReportError(expr, "New string must be assigned to 'string()'");
return false;
}
return ok;
}
FuExpr# VisitInterpolatedString!(FuInterpolatedString# expr)
{
int partsCount = 0;
string() s = "";
for (int partsIndex = 0; partsIndex < expr.Parts.Count; partsIndex++) {
FuInterpolatedPart part = expr.Parts[partsIndex];
s += part.Prefix;
FuExpr# arg = VisitExpr(part.Argument);
if (Coerce(arg, this.Host.Program.System.PrintableType)) {
switch (arg.Type) {
case FuIntegerType:
switch (part.Format) {
case ' ':
if (arg is FuLiteralLong literalLong && part.WidthExpr == null) {
s += $"{literalLong.Value}";
continue;
}
break;
case 'D':
case 'd':
case 'X':
case 'x':
if (part.WidthExpr != null && part.Precision >= 0)
ReportError(part.WidthExpr, "Cannot format an integer with both width and precision");
break;
default:
ReportError(arg, "Invalid format");
break;
}
break;
case FuFloatingType:
switch (part.Format) {
case ' ':
case 'F':
case 'f':
case 'E':
case 'e':
break;
default:
ReportError(arg, "Invalid format");
break;
}
break;
default:
if (part.Format != ' ')
ReportError(arg, "Invalid format");
else if (arg is FuLiteralString literalString && part.WidthExpr == null) {
s += literalString.Value;
continue;
}
break;
}
}
FuInterpolatedPart! targetPart = expr.Parts[partsCount++];
targetPart.Prefix = s;
targetPart.Argument = arg;
targetPart.WidthExpr = part.WidthExpr;
targetPart.Width = part.WidthExpr != null ? FoldConstInt(part.WidthExpr) : 0;
targetPart.Format = part.Format;
targetPart.Precision = part.Precision;
s = "";
}
s += expr.Suffix;
if (partsCount == 0)
return this.Host.Program.System.NewLiteralString(s, expr.Loc);
expr.Type = this.Host.Program.System.StringStorageType;
expr.Parts.RemoveRange(partsCount, expr.Parts.Count - partsCount);
expr.Suffix = s;
return expr;
}
FuExpr# Lookup!(FuSymbolReference# expr, FuScope scope)
{
if (expr.Symbol == null) {
expr.Symbol = scope.TryLookup(expr.Name, expr.Left == null);
if (expr.Symbol == null)
return PoisonError(expr, $"'{expr.Name}' not found");
expr.Type = expr.Symbol.Type;
}
if (!(scope is FuEnum) && expr.Symbol is FuConst! konst) {
ResolveConst(konst);
if (konst.Value is FuLiteral || konst.Value is FuSymbolReference) {
if (konst.Type is FuFloatingType && konst.Value is FuLiteralLong intValue)
return ToLiteralDouble(expr, intValue.Value);
return konst.Value;
}
}
return expr;
}
FuContainerType! GetCurrentContainer() // TODO: refactor to this.CurrentMethod.Parent ?
{
for (FuScope!? scope = this.CurrentScope; scope != null; scope = scope.Parent) {
if (scope is FuContainerType! container)
return container;
}
assert false;
}
FuExpr# VisitSymbolReference!(FuSymbolReference# expr)
{
if (expr.Left == null) {
FuExpr# resolved = Lookup(expr, this.CurrentScope);
if (expr.Symbol is FuMember nearMember) {
if (nearMember.Visibility == FuVisibility.Private
&& nearMember.Parent is FuClass memberClass // not local const
&& memberClass != GetCurrentContainer())
ReportError(expr, $"Cannot access private member '{expr.Name}'");
if (!nearMember.IsStatic()
&& (this.CurrentMethod == null || this.CurrentMethod.IsStatic()))
ReportError(expr, $"Cannot use instance member '{expr.Name}' from static context");
}
if (resolved is FuSymbolReference symbol) {
if (symbol.Symbol is FuVar v) {
if (v.Parent is FuFor! loop)
loop.IsIndVarUsed = true;
else if (this.CurrentPureArguments.ContainsKey(v)) // TryGetValue
return this.CurrentPureArguments[v];
}
else if (symbol.Symbol.Id == FuId.RegexOptionsEnum)
this.Host.Program.RegexOptionsEnum = true;
}
return resolved;
}
FuExpr# left = VisitExpr(expr.Left, true);
if (left == this.Poison)
return left;
FuScope scope;
bool isBase = left is FuSymbolReference baseSymbol && baseSymbol.Symbol.Id == FuId.BasePtr;
if (isBase) {
if (this.CurrentMethod == null)
return PoisonError(left, "'base' invalid outside methods");
if (this.CurrentMethod.IsStatic())
return PoisonError(left, "'base' invalid in static context");
if (!(this.CurrentMethod.Parent.Parent is FuClass baseClass))
return PoisonError(left, "No base class");
scope = baseClass;
}
else if (left is FuSymbolReference leftSymbol && leftSymbol.Symbol is FuScope obj)
scope = obj;
else {
scope = left.Type;
if (scope is FuClassType klass)
scope = klass.Class;
}
FuExpr# result = Lookup(expr, scope);
if (expr.Symbol is FuMember member) {
switch (member.Visibility) {
case FuVisibility.Private:
if (member.Parent != this.CurrentMethod.Parent
|| this.CurrentMethod.Parent != scope) // enforced by Java, but not C++/C#/TS
ReportError(expr, $"Cannot access private member '{expr.Name}'");
break;
case FuVisibility.Protected:
if (isBase)
break;
assert this.CurrentMethod.Parent is FuClass currentClass;
assert scope is FuClass scopeClass;
if (!currentClass.IsSameOrBaseOf(scopeClass)) // enforced by C++/C#/TS but not Java
ReportError(expr, $"Cannot access protected member '{expr.Name}'");
break;
case FuVisibility.NumericElementType:
if (left.Type is FuClassType klass && !(klass.GetElementType() is FuNumericType))
ReportError(expr, "Method restricted to collections of numbers");
break;
case FuVisibility.FinalValueType: // DictionaryAdd
if (!left.Type.AsClassType().GetValueType().IsFinal())
ReportError(expr, "Method restricted to dictionaries with storage values");
break;
default:
switch (expr.Symbol.Id) {
case FuId.ArrayLength:
if (left.Type is FuArrayStorageType arrayStorage)
return ToLiteralLong(expr, arrayStorage.Length);
break;
case FuId.StringLength:
if (left is FuLiteralString leftLiteral) {
int length = leftLiteral.GetAsciiLength();
if (length >= 0)
return ToLiteralLong(expr, length);
}
break;
default:
break;
}
break;
}
if (!(member is FuMethodGroup)) {
if (left is FuSymbolReference leftType && leftType.Symbol is FuType) {
if (!member.IsStatic())
ReportError(expr, $"Cannot use instance member '{expr.Name}' without an object");
}
else if (member.IsStatic())
ReportError(expr, $"'{expr.Name}' is static");
}
}
if (result != expr)
return result;
return new FuSymbolReference { Loc = expr.Loc, Left = left, Name = expr.Name, Symbol = expr.Symbol, Type = expr.Type };
}
static FuRangeType# Union(FuRangeType# left, FuRangeType#? right)
{
if (right == null)
return left;
if (right.Min < left.Min) {
if (right.Max >= left.Max)
return right;
return FuRangeType.New(right.Min, left.Max);
}
if (right.Max > left.Max)
return FuRangeType.New(left.Min, right.Max);
return left;
}
FuType# GetIntegerType(FuExpr left, FuExpr right)
{
FuType# type = this.Host.Program.System.PromoteIntegerTypes(left.Type, right.Type);
Coerce(left, type);
Coerce(right, type);
return type;
}
FuType# GetShiftType(FuExpr left, FuExpr right)
{
FuIntegerType# intType = this.Host.Program.System.IntType;
Coerce(left, intType);
Coerce(right, intType);
return left.Type is FuRangeType ? intType : left.Type;
}
FuType# GetNumericType(FuExpr left, FuExpr right)
{
FuType# type = this.Host.Program.System.PromoteNumericTypes(left.Type, right.Type);
Coerce(left, type);
Coerce(right, type);
return type;
}
static int SaturatedNeg(int a)
{
if (a == int.MinValue)
return int.MaxValue;
return -a;
}
static int SaturatedAdd(int a, int b)
{
int c = a + b;
if (c >= 0) {
if (a < 0 && b < 0)
return int.MinValue;
}
else if (a > 0 && b > 0)
return int.MaxValue;
return c;
}
static int SaturatedSub(int a, int b)
{
if (b == int.MinValue)
return a < 0 ? a ^ b : int.MaxValue;
return SaturatedAdd(a, -b);
}
static int SaturatedMul(int a, int b)
{
if (a == 0 || b == 0)
return 0;
if (a == int.MinValue)
return b >> 31 ^ a;
if (b == int.MinValue)
return a >> 31 ^ b;
if (int.MaxValue / Math.Abs(a) < Math.Abs(b))
return (a ^ b) >> 31 ^ int.MaxValue;
return a * b;
}
static int SaturatedDiv(int a, int b)
{
if (a == int.MinValue && b == -1)
return int.MaxValue;
return a / b;
}
static int SaturatedShiftRight(int a, int b) => a >> (b >= 31 || b < 0 ? 31 : b);
static FuRangeType# BitwiseUnsignedOp(FuRangeType left, FuToken op, FuRangeType right)
{
int leftVariableBits = left.GetVariableBits();
int rightVariableBits = right.GetVariableBits();
int min;
int max;
switch (op) {
case FuToken.And:
min = left.Min & right.Min & ~FuRangeType.GetMask(~left.Min & ~right.Min & (leftVariableBits | rightVariableBits));
// Calculate upper bound with variable bits set
max = (left.Max | leftVariableBits) & (right.Max | rightVariableBits);
// The upper bound will never exceed the input
if (max > left.Max)
max = left.Max;
if (max > right.Max)
max = right.Max;
break;
case FuToken.Or:
min = (left.Min & ~leftVariableBits) | (right.Min & ~rightVariableBits);
max = left.Max | right.Max | FuRangeType.GetMask(left.Max & right.Max & FuRangeType.GetMask(leftVariableBits | rightVariableBits));
// The lower bound will never be less than the input
if (min < left.Min)
min = left.Min;
if (min < right.Min)
min = right.Min;
break;
case FuToken.Xor:
int variableBits = leftVariableBits | rightVariableBits;
min = (left.Min ^ right.Min) & ~variableBits;
max = (left.Max ^ right.Max) | variableBits;
break;
default:
assert false;
}
if (min > max)
return FuRangeType.New(max, min); // FIXME: this is wrong! e.g. min=0 max=0x8000000_00000000 then 5 should be in range
return FuRangeType.New(min, max);
}
bool IsEnumOp(FuExpr left, FuExpr right)
{
if (left.Type is FuEnum) {
if (left.Type.Id != FuId.BoolType && !(left.Type is FuEnumFlags))
ReportError(left, $"Define flags enumeration as 'enum* {left.Type}'");
Coerce(right, left.Type);
return true;
}
return false;
}
FuType# BitwiseOp(FuExpr left, FuToken op, FuExpr right)
{
if (left.Type is FuRangeType# leftRange && right.Type is FuRangeType# rightRange) {
FuRangeType#? range = null;
FuRangeType#? rightNegative;
FuRangeType#? rightPositive;
if (rightRange.Min >= 0) {
rightNegative = null;
rightPositive = rightRange;
}
else if (rightRange.Max < 0) {
rightNegative = rightRange;
rightPositive = null;
}
else {
rightNegative = FuRangeType.New(rightRange.Min, -1);
rightPositive = FuRangeType.New(0, rightRange.Max);
}
if (leftRange.Min < 0) {
FuRangeType leftNegative = leftRange.Max < 0 ? leftRange : FuRangeType.New(leftRange.Min, -1);
if (rightNegative != null)
range = BitwiseUnsignedOp(leftNegative, op, rightNegative);
if (rightPositive != null)
range = Union(BitwiseUnsignedOp(leftNegative, op, rightPositive), range);
}
if (leftRange.Max >= 0) {
FuRangeType leftPositive = leftRange.Min >= 0 ? leftRange : FuRangeType.New(0, leftRange.Max);
if (rightNegative != null)
range = Union(BitwiseUnsignedOp(leftPositive, op, rightNegative), range);
if (rightPositive != null)
range = Union(BitwiseUnsignedOp(leftPositive, op, rightPositive), range);
}
return range;
}
if (IsEnumOp(left, right))
return left.Type;
return GetIntegerType(left, right);
}
static FuRangeType# NewRangeType(int a, int b, int c, int d)
{
if (a > b) {
int t = a;
a = b;
b = t;
}
if (c > d) {
int t = c;
c = d;
d = t;
}
return FuRangeType.New(a <= c ? a : c, b >= d ? b : d);
}
FuLiteral# ToLiteralBool(FuExpr expr, bool value)
{
FuLiteral# result = value ? new FuLiteralTrue() : new FuLiteralFalse();
result.Loc = expr.Loc;
result.Type = this.Host.Program.System.BoolType;
return result;
}
FuLiteralLong# ToLiteralLong(FuExpr expr, long value) => this.Host.Program.System.NewLiteralLong(value, expr.Loc);
FuLiteralDouble# ToLiteralDouble(FuExpr expr, double value) => new FuLiteralDouble { Loc = expr.Loc, Type = this.Host.Program.System.DoubleType, Value = value };
void CheckLValue(FuExpr expr)
{
switch (expr) {
case FuSymbolReference symbol:
switch (symbol.Symbol) {
case FuVar! def:
def.IsAssigned = true;
switch (symbol.Symbol.Parent) {
case FuFor! forLoop:
forLoop.IsRange = false;
break;
case FuForeach:
ReportError(expr, "Cannot assign a foreach iteration variable");
break;
default:
break;
}
for (FuScope! scope = this.CurrentScope; !(scope is FuClass); scope = scope.Parent) {
if (scope is FuFor! forLoop
&& forLoop.IsRange
&& forLoop.Cond is FuBinaryExpr binaryCond
&& binaryCond.Right.IsReferenceTo(symbol.Symbol))
forLoop.IsRange = false;
}
break;
case FuField:
if (symbol.Left == null) {
if (!this.CurrentMethod.IsMutator())
ReportError(expr, "Cannot modify field in a non-mutating method");
}
else {
switch (symbol.Left.Type) {
case FuStorageType:
// TODO
break;
case FuReadWriteClassType:
break;
case FuClassType:
ReportError(expr, "Cannot modify field through a read-only reference");
break;
default:
assert false;
}
}
break;
default:
ReportError(expr, "Cannot modify this");
break;
}
break;
case FuBinaryExpr indexing when indexing.Op == FuToken.LeftBracket:
switch (indexing.Left.Type) {
case FuStorageType:
// TODO
break;
case FuReadWriteClassType:
break;
case FuClassType:
ReportError(expr, "Cannot modify collection through a read-only reference");
break;
default:
assert false;
}
break;
default:
ReportError(expr, "Cannot modify this");
break;
}
}
FuInterpolatedString# Concatenate(FuInterpolatedString left, FuInterpolatedString right)
{
FuInterpolatedString# result = new FuInterpolatedString { Loc = left.Loc, Type = this.Host.Program.System.StringStorageType };
result.Parts.AddRange(left.Parts);
if (right.Parts.Count == 0)
result.Suffix = left.Suffix + right.Suffix;
else {
result.Parts.AddRange(right.Parts);
FuInterpolatedPart! middle = result.Parts[left.Parts.Count];
middle.Prefix = left.Suffix + middle.Prefix;
result.Suffix = right.Suffix;
}
return result;
}
FuInterpolatedString# ToInterpolatedString(FuExpr# expr)
{
if (expr is FuInterpolatedString# interpolated)
return interpolated;
FuInterpolatedString# result = new FuInterpolatedString { Loc = expr.Loc, Type = this.Host.Program.System.StringStorageType };
if (expr is FuLiteral literal)
result.Suffix = literal.GetLiteralString();
else {
result.AddPart("", expr);
result.Suffix = "";
}
return result;
}
void CheckComparison(FuExpr left, FuExpr right)
{
if (left.Type is FuEnum)
Coerce(right, left.Type);
else {
FuType doubleType = this.Host.Program.System.DoubleType;
Coerce(left, doubleType);
Coerce(right, doubleType);
}
}
void OpenScope!(FuScope! scope)
{
scope.Parent = this.CurrentScope;
this.CurrentScope = scope;
}
void CloseScope!()
{
this.CurrentScope = this.CurrentScope.Parent;
}
FuExpr# ResolveNew!(FuPrefixExpr# expr)
{
if (expr.Type != null)
return expr;
FuType# type;
if (expr.Inner is FuBinaryExpr binaryNew && binaryNew.Op == FuToken.LeftBrace) {
type = ToType(binaryNew.Left, true);
if (!(type is FuClassType klass) || klass is FuReadWriteClassType)
return PoisonError(expr, "Invalid argument to new");
assert binaryNew.Right is FuAggregateInitializer# init;
ResolveObjectLiteral(klass, init);
expr.Type = new FuDynamicPtrType { Loc = expr.Loc, Class = klass.Class };
expr.Inner = init;
return expr;
}
type = ToType(expr.Inner, true);
switch (type) {
case FuArrayStorageType array:
expr.Type = new FuDynamicPtrType { Loc = expr.Loc, Class = this.Host.Program.System.ArrayPtrClass, TypeArg0 = array.GetElementType() };
expr.Inner = array.LengthExpr;
return expr;
case FuStorageType klass:
expr.Type = new FuDynamicPtrType { Loc = expr.Loc, Class = klass.Class, TypeArg0 = klass.TypeArg0, TypeArg1 = klass.TypeArg1 };
expr.Inner = null;
return expr;
default:
return PoisonError(expr, "Invalid argument to new");
}
}
FuExpr# VisitPrefixExpr!(FuPrefixExpr# expr)
{
FuExpr# inner;
FuType# type;
switch (expr.Op) {
case FuToken.Increment:
case FuToken.Decrement:
inner = VisitExpr(expr.Inner);
if (inner == this.Poison)
return inner;
CheckLValue(inner);
Coerce(inner, this.Host.Program.System.DoubleType);
if (inner.Type is FuRangeType xcrementRange) {
int delta = expr.Op == FuToken.Increment ? 1 : -1;
type = FuRangeType.New(xcrementRange.Min + delta, xcrementRange.Max + delta); // FIXME: overflow
}
else
type = inner.Type;
expr.Inner = inner;
expr.Type = type;
return expr;
case FuToken.Minus:
inner = VisitExpr(expr.Inner);
if (inner == this.Poison)
return inner;
Coerce(inner, this.Host.Program.System.DoubleType);
if (inner.Type is FuRangeType negRange) {
if (negRange.Min == negRange.Max)
return ToLiteralLong(expr, -negRange.Min);
type = FuRangeType.New(SaturatedNeg(negRange.Max), SaturatedNeg(negRange.Min));
}
else if (inner is FuLiteralDouble d)
return ToLiteralDouble(expr, -d.Value);
else if (inner is FuLiteralLong l)
return ToLiteralLong(expr, -l.Value);
else
type = inner.Type;
break;
case FuToken.Tilde:
inner = VisitExpr(expr.Inner);
if (inner == this.Poison)
return inner;
if (inner.Type is FuEnumFlags)
type = inner.Type;
else {
Coerce(inner, this.Host.Program.System.IntType);
if (inner.Type is FuRangeType notRange)
type = FuRangeType.New(~notRange.Max, ~notRange.Min);
else
type = inner.Type;
}
break;
case FuToken.ExclamationMark:
inner = ResolveBool(expr.Inner);
type = this.Host.Program.System.BoolType;
break;
case FuToken.New:
return ResolveNew(expr);
case FuToken.Resource:
if (!(FoldConst(expr.Inner) is FuLiteralString# resourceName))
return PoisonError(expr.Inner, "Resource name must be a string");
inner = resourceName;
type = new FuArrayStorageType { Class = this.Host.Program.System.ArrayStorageClass, TypeArg0 = this.Host.Program.System.ByteType, Length = this.Host.GetResourceLength(resourceName.Value, expr) };
break;
default:
assert false;
}
return new FuPrefixExpr { Loc = expr.Loc, Op = expr.Op, Inner = inner, Type = type };
}
FuExpr# VisitPostfixExpr!(FuPostfixExpr# expr)
{
expr.Inner = VisitExpr(expr.Inner);
switch (expr.Op) {
case FuToken.Increment:
case FuToken.Decrement:
CheckLValue(expr.Inner);
Coerce(expr.Inner, this.Host.Program.System.DoubleType);
expr.Type = expr.Inner.Type;
return expr;
default:
return PoisonError(expr, $"Unexpected {FuLexer.TokenToString(expr.Op)}");
}
}
static bool CanCompareEqual(FuType left, FuType right)
{
switch (left) {
case FuNumericType:
return right is FuNumericType;
case FuEnum:
return left == right;
case FuClassType leftClass:
if (left.Nullable && right.Id == FuId.NullType)
return true;
if ((left is FuStorageType && right is FuOwningType)
|| (left is FuDynamicPtrType && right is FuStorageType))
return false;
return right is FuClassType rightClass
&& (leftClass.Class.IsSameOrBaseOf(rightClass.Class) || rightClass.Class.IsSameOrBaseOf(leftClass.Class))
&& leftClass.EqualTypeArguments(rightClass);
default:
return left.Id == FuId.NullType && right.Nullable;
}
}
FuExpr# ResolveEquality(FuBinaryExpr expr, FuExpr# left, FuExpr# right)
{
if (!CanCompareEqual(left.Type, right.Type))
return PoisonError(expr, $"Cannot compare '{left.Type}' with '{right.Type}'");
if (left.Type is FuRangeType leftRange && right.Type is FuRangeType rightRange) {
if (leftRange.Min == leftRange.Max && leftRange.Min == rightRange.Min && leftRange.Min == rightRange.Max)
return ToLiteralBool(expr, expr.Op == FuToken.Equal);
if (leftRange.Max < rightRange.Min || leftRange.Min > rightRange.Max)
return ToLiteralBool(expr, expr.Op == FuToken.NotEqual);
}
else {
switch (left) {
case FuLiteralLong leftLong when right is FuLiteralLong rightLong:
return ToLiteralBool(expr, (expr.Op == FuToken.NotEqual) ^ (leftLong.Value == rightLong.Value));
case FuLiteralDouble leftDouble when right is FuLiteralDouble rightDouble:
return ToLiteralBool(expr, (expr.Op == FuToken.NotEqual) ^ (leftDouble.Value == rightDouble.Value));
case FuLiteralString leftString when right is FuLiteralString rightString:
return ToLiteralBool(expr, (expr.Op == FuToken.NotEqual) ^ (leftString.Value == rightString.Value));
case FuLiteralNull when right is FuLiteralNull:
case FuLiteralFalse when right is FuLiteralFalse:
case FuLiteralTrue when right is FuLiteralTrue:
return ToLiteralBool(expr, expr.Op == FuToken.Equal);
case FuLiteralFalse when right is FuLiteralTrue:
case FuLiteralTrue when right is FuLiteralFalse:
return ToLiteralBool(expr, expr.Op == FuToken.NotEqual);
default:
break;
}
if (left.IsConstEnum() && right.IsConstEnum())
return ToLiteralBool(expr, (expr.Op == FuToken.NotEqual) ^ (left.IntValue() == right.IntValue()));
}
TakePtr(left);
TakePtr(right);
return new FuBinaryExpr { Loc = expr.Loc, Left = left, Op = expr.Op, Right = right, Type = this.Host.Program.System.BoolType };
}
void SetSharedAssign(FuExpr left, FuExpr right)
{
if (left.Type is FuDynamicPtrType && !right.IsUnique()) {
left.SetShared();
right.SetShared();
}
}
void CheckIsHierarchy(FuClassType leftPtr, FuExpr left, FuClass rightClass, FuExpr expr, string op, string alwaysMessage, string neverMessage)
{
if (rightClass.IsSameOrBaseOf(leftPtr.Class))
ReportError(expr, $"'{left}' is '{leftPtr.Class.Name}', '{op} {rightClass.Name}' would {alwaysMessage}");
else if (!leftPtr.Class.IsSameOrBaseOf(rightClass))
ReportError(expr, $"'{leftPtr.Class.Name}' is not base class of '{rightClass.Name}', '{op} {rightClass.Name}' would {neverMessage}");
}
void CheckIsVar(FuExpr left, FuVar def, FuExpr expr, string op, string alwaysMessage, string neverMessage)
{
if (!(def.Type is FuClassType! rightPtr) || rightPtr is FuStorageType)
ReportError(def.TypeExpr, $"'{op}' with non-reference type");
else{
assert left.Type is FuClassType leftPtr;
if (rightPtr is FuReadWriteClassType
&& !(leftPtr is FuDynamicPtrType)
&& (rightPtr is FuDynamicPtrType || !(leftPtr is FuReadWriteClassType)))
ReportError(def.TypeExpr, $"'{leftPtr}' cannot be casted to '{rightPtr}'");
else {
// TODO: outside assert NotSupported(expr, "'is' operator", "c", "py", "swift", "cl");
CheckIsHierarchy(leftPtr, left, rightPtr.Class, expr, op, alwaysMessage, neverMessage);
if (rightPtr is FuDynamicPtrType! dynamic) {
left.SetShared();
dynamic.Unique = false;
}
}
}
}
FuExpr# ResolveIs(FuBinaryExpr# expr, FuExpr# left, FuExpr right)
{
if (!(left.Type is FuClassType leftPtr) || left.Type is FuStorageType)
return PoisonError(expr, "Left hand side of the 'is' operator must be an object reference");
switch (right) {
case FuSymbolReference symbol when symbol.Symbol is FuClass klass:
CheckIsHierarchy(leftPtr, left, klass, expr, "is", "always equal 'true'", "always equal 'false'");
break;
case FuVar def:
CheckIsVar(left, def, expr, "is", "always equal 'true'", "always equal 'false'");
break;
default:
return PoisonError(expr, "Right hand side of the 'is' operator must be a class name");
}
expr.Left = left;
expr.Type = this.Host.Program.System.BoolType;
return expr;
}
FuExpr# VisitBinaryExpr!(FuBinaryExpr# expr)
{
FuExpr# left = VisitExpr(expr.Left);
FuExpr# right = VisitExpr(expr.Right, expr.Op == FuToken.Is);
if (left == this.Poison || left.Type == this.Poison || right == this.Poison || right.Type == this.Poison)
return this.Poison;
FuType# type;
switch (expr.Op) {
case FuToken.LeftBracket:
if (!(left.Type is FuClassType klass))
return PoisonError(expr, "Cannot index this object");
switch (klass.Class.Id) {
case FuId.StringClass:
Coerce(right, this.Host.Program.System.IntType);
if (right.Type is FuRangeType stringIndexRange && stringIndexRange.Max < 0)
ReportError(right, "Negative index");
else if (left is FuLiteralString stringLiteral && right is FuLiteralLong indexLiteral) {
long i = indexLiteral.Value;
if (i >= 0 && i <= int.MaxValue) {
int c = stringLiteral.GetAsciiAt(i);
if (c >= 0)
return FuLiteralChar.New(c, expr.Loc);
}
}
type = this.Host.Program.System.CharType;
break;
case FuId.ArrayPtrClass:
case FuId.ArrayStorageClass:
case FuId.ListClass:
Coerce(right, this.Host.Program.System.IntType);
if (right.Type is FuRangeType indexRange) {
if (indexRange.Max < 0)
ReportError(right, "Negative index");
else if (klass is FuArrayStorageType array && indexRange.Min >= array.Length)
ReportError(right, "Array index out of bounds");
}
type = klass.GetElementType();
break;
case FuId.DictionaryClass:
case FuId.SortedDictionaryClass:
case FuId.OrderedDictionaryClass:
Coerce(right, klass.GetKeyType());
type = klass.GetValueType();
break;
default:
return PoisonError(expr, "Cannot index this object");
}
break;
case FuToken.Plus:
if (left.Type is FuRangeType leftAdd && right.Type is FuRangeType rightAdd) {
type = FuRangeType.New(
SaturatedAdd(leftAdd.Min, rightAdd.Min),
SaturatedAdd(leftAdd.Max, rightAdd.Max));
}
else if (left.Type is FuStringType) {
Coerce(right, this.Host.Program.System.StringPtrType);
if (left is FuLiteral leftLiteral && right is FuLiteral rightLiteral)
return this.Host.Program.System.NewLiteralString(leftLiteral.GetLiteralString() + rightLiteral.GetLiteralString(), expr.Loc);
if (left is FuInterpolatedString || right is FuInterpolatedString)
return Concatenate(ToInterpolatedString(left), ToInterpolatedString(right));
type = this.Host.Program.System.StringStorageType;
}
else
type = GetNumericType(left, right);
break;
case FuToken.Minus:
if (left.Type is FuRangeType leftSub && right.Type is FuRangeType rightSub) {
type = FuRangeType.New(
SaturatedSub(leftSub.Min, rightSub.Max),
SaturatedSub(leftSub.Max, rightSub.Min));
}
else
type = GetNumericType(left, right);
break;
case FuToken.Asterisk:
if (left.Type is FuRangeType leftMul && right.Type is FuRangeType rightMul) {
type = NewRangeType(
SaturatedMul(leftMul.Min, rightMul.Min),
SaturatedMul(leftMul.Min, rightMul.Max),
SaturatedMul(leftMul.Max, rightMul.Min),
SaturatedMul(leftMul.Max, rightMul.Max));
}
else
type = GetNumericType(left, right);
break;
case FuToken.Slash:
if (left.Type is FuRangeType leftDiv && right.Type is FuRangeType rightDiv) {
int denMin = rightDiv.Min;
if (denMin == 0)
denMin = 1;
int denMax = rightDiv.Max;
if (denMax == 0)
denMax = -1;
type = NewRangeType(
SaturatedDiv(leftDiv.Min, denMin),
SaturatedDiv(leftDiv.Min, denMax),
SaturatedDiv(leftDiv.Max, denMin),
SaturatedDiv(leftDiv.Max, denMax));
}
else
type = GetNumericType(left, right);
break;
case FuToken.Mod:
if (left.Type is FuRangeType leftMod && right.Type is FuRangeType rightMod) {
int den = ~Math.Min(rightMod.Min, -rightMod.Max); // max(abs(rightRange))-1
if (den < 0)
return PoisonError(expr, "Mod zero");
type = FuRangeType.New(
leftMod.Min >= 0 ? 0 : Math.Max(leftMod.Min, -den),
leftMod.Max < 0 ? 0 : Math.Min(leftMod.Max, den));
}
else
type = GetIntegerType(left, right);
break;
case FuToken.And:
case FuToken.Or:
case FuToken.Xor:
type = BitwiseOp(left, expr.Op, right);
break;
case FuToken.ShiftLeft: