-
Notifications
You must be signed in to change notification settings - Fork 21
/
semanticAnalyzer.go
1373 lines (1159 loc) · 41 KB
/
semanticAnalyzer.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
package main
import (
"fmt"
)
// getVar goes through all symbol varTables recursively and looks for an entry for the given variable name v
func (s *SymbolTable) getVar(v string) (SymbolVarEntry, bool) {
if s == nil {
return SymbolVarEntry{}, false
}
if variable, ok := s.varTable[v]; ok {
return variable, true
}
return s.parent.getVar(v)
}
// isLocalVar only searches the immediate local symbol varTable
func (s *SymbolTable) isLocalVar(v string) bool {
if s == nil {
return false
}
_, ok := s.varTable[v]
return ok
}
func (s *SymbolTable) getLocalVars() (keys []string) {
for k := range s.varTable {
keys = append(keys, k)
}
return
}
func (s *SymbolTable) setVar(v string, t ComplexType, isIndexed bool) {
s.varTable[v] = SymbolVarEntry{t, "", 0, isIndexed}
}
func (s *SymbolTable) setType(v string, members []StructMem) {
// Only set type definitions in the upper-most symbol table!
if s != nil && s.parent == nil {
s.typeTable[v] = SymbolTypeEntry{members, 0}
return
}
s.parent.setType(v, members)
}
func (s *SymbolTable) getType(v string) (SymbolTypeEntry, bool) {
// Only query type definitions from the upper-most symbol table!
if s != nil && s.parent == nil {
entry, ok := s.typeTable[v]
return entry, ok
}
return s.parent.getType(v)
}
func (s *SymbolTable) setFun(name string, argTypes, returnTypes []ComplexType, inline bool) {
l := s.funTable[name]
l = append(l, SymbolFunEntry{argTypes, returnTypes, "", "", 0, inline, false})
s.funTable[name] = l
}
func (s *SymbolTable) getLocalFun(name string, paramTypes []ComplexType, strict bool) (SymbolFunEntry, bool) {
if s == nil {
return SymbolFunEntry{}, false
}
l, ok := s.funTable[name]
if !ok {
return SymbolFunEntry{}, false
}
for _, le := range l {
if equalTypes(le.paramTypes, paramTypes, strict) {
return le, true
}
}
return SymbolFunEntry{}, false
}
func (s *SymbolTable) isLocalFun(name string, paramTypes []ComplexType) bool {
_, ok := s.getLocalFun(name, paramTypes, true)
return ok
}
func (s *SymbolTable) getFun(name string, paramTypes []ComplexType, strict bool) (SymbolFunEntry, bool) {
if s == nil {
return SymbolFunEntry{}, false
}
if localFun, ok := s.getLocalFun(name, paramTypes, strict); ok {
return localFun, true
}
return s.parent.getFun(name, paramTypes, strict)
}
func (s *SymbolTable) setVarAsmName(v string, asmName string) {
if s == nil {
panic("Could not set asm variable name in symbol table!")
return
}
if _, ok := s.varTable[v]; ok {
tmp := s.varTable[v]
tmp.varName = asmName
s.varTable[v] = tmp
return
}
s.parent.setVarAsmName(v, asmName)
}
func (s *SymbolTable) setVarAsmOffset(v string, offset int) {
if s == nil {
panic("Could not set asm variable name in symbol table!")
return
}
if _, ok := s.varTable[v]; ok {
tmp := s.varTable[v]
tmp.offset = offset
s.varTable[v] = tmp
return
}
s.parent.setVarAsmOffset(v, offset)
}
func (s *SymbolTable) setLoopJumpLabels(br, cont string) {
s.activeLoopBreakLabel = br
s.activeLoopContinueLabel = cont
}
func (s *SymbolTable) getLoopBreakLabel() string {
if s.activeLoopBreakLabel != "" {
return s.activeLoopBreakLabel
}
return s.parent.getLoopBreakLabel()
}
func (s *SymbolTable) getLoopContinueLabel() string {
if s.activeLoopContinueLabel != "" {
return s.activeLoopContinueLabel
}
return s.parent.getLoopContinueLabel()
}
func (s *SymbolTable) setFunAsmName(v string, asmName string, paramTypes []ComplexType, strict bool) {
if s == nil {
panic("Could not set asm function name in symbol table!")
}
l, ok := s.funTable[v]
if !ok {
panic("No such function in funTable. Can not set asm name")
}
for i, le := range l {
if equalTypes(le.paramTypes, paramTypes, strict) {
le.jumpLabel = asmName
l[i] = le
s.funTable[v] = l
return
}
}
s.parent.setFunAsmName(v, asmName, paramTypes, strict)
}
func (s *SymbolTable) funIsInline(name string, paramTypes []ComplexType, strict bool) bool {
if e, ok := s.getFun(name, paramTypes, strict); ok {
return e.inline
}
panic("No such function in funTable. Cannot query used status")
}
func (s *SymbolTable) funIsUsed(name string, paramTypes []ComplexType, strict bool) bool {
if e, ok := s.getFun(name, paramTypes, strict); ok {
return e.isUsed
}
panic("No such function in funTable. Cannot query used status")
}
func (s *SymbolTable) setFunEpilogueLabel(v string, label string, paramTypes []ComplexType) {
if s == nil {
panic("Could not set asm epilogue label in symbol table!")
return
}
l, ok := s.funTable[v]
if !ok {
panic("No such function in funTable. Can not set epilogue label.")
}
for i, le := range l {
if equalTypes(le.paramTypes, paramTypes, true) {
le.epilogueLabel = label
l[i] = le
s.funTable[v] = l
return
}
}
s.parent.setFunEpilogueLabel(v, label, paramTypes)
}
func (s *SymbolTable) setFunIsUsed(v string, paramTypes []ComplexType, isUsed bool) {
if s == nil {
panic("Could not set isUsed flag in symbol table!")
return
}
if l, ok := s.funTable[v]; ok {
for i, le := range l {
if equalTypes(le.paramTypes, paramTypes, false) {
le.isUsed = isUsed
l[i] = le
s.funTable[v] = l
return
}
}
}
s.parent.setFunIsUsed(v, paramTypes, isUsed)
}
func (s *SymbolTable) setFunReturnStackPointer(v string, offset int, paramTypes []ComplexType) {
if s == nil {
panic("Could not set asm return stack pointer in symbol table!")
return
}
l, ok := s.funTable[v]
if !ok {
panic("No such function in funTable. Can not set return stack pointer.")
}
for i, le := range l {
if equalTypes(le.paramTypes, paramTypes, true) {
le.returnStackPointerOffset = offset
l[i] = le
s.funTable[v] = l
return
}
}
s.parent.setFunReturnStackPointer(v, offset, paramTypes)
}
func analyzeUnaryOp(unaryOp UnaryOp, symbolTable *SymbolTable) (Expression, error) {
// Re-order expression, if the expression is not fixed and the priority is of the operator is not according to the priority
// The priority of an operator must be equal or higher in (right) sub-trees (as they are evaluated first).
if tmpE, ok := unaryOp.expr.(BinaryOp); ok {
if unaryOp.operator.priority() < tmpE.operator.priority() && !tmpE.fixed {
newChild := unaryOp
newChild.expr = tmpE.leftExpr
tmpE.leftExpr = newChild
var newRoot Expression
newRoot = tmpE
// The unary expression is now a binary, so we have to start over. The following checks won't be working any more.
expression, err := analyzeExpression(newRoot, symbolTable)
if err != nil {
return newRoot, err
}
newRoot = expression
return newRoot, nil
}
}
expression, err := analyzeExpression(unaryOp.expr, symbolTable)
if err != nil {
return unaryOp, err
}
unaryOp.expr = expression
if expression.getResultCount() != 1 {
return nil, fmt.Errorf("%w[%v:%v] - Unary expression can only handle one result", ErrCritical, unaryOp.line, unaryOp.column)
}
t := expression.getExpressionTypes(symbolTable)[0]
switch unaryOp.operator {
case OP_NEGATIVE:
if t.t != TYPE_FLOAT && t.t != TYPE_INT {
return nil, fmt.Errorf("%w[%v:%v] - Unary '-' expression must be float or int, but is: %v", ErrCritical, unaryOp.line, unaryOp.column, unaryOp)
}
unaryOp.opType = t
return unaryOp, nil
case OP_NOT:
if t.t != TYPE_BOOL {
return nil, fmt.Errorf("%w[%v:%v] - Unary '!' expression must be bool, but is: %v", ErrCritical, unaryOp.line, unaryOp.column, unaryOp)
}
unaryOp.opType = ComplexType{TYPE_BOOL, "", nil}
return unaryOp, nil
}
return nil, fmt.Errorf("%w[%v:%v] - Unknown unary expression: %v", ErrCritical, unaryOp.line, unaryOp.column, unaryOp)
}
func analyzeBinaryOp(binaryOp BinaryOp, symbolTable *SymbolTable) (Expression, error) {
// Re-order expression, if the expression is not fixed and the priority is of the operator is not according to the priority
// The priority of an operator must be equal or higher in (right) sub-trees (as they are evaluated first).
if tmpE, ok := binaryOp.rightExpr.(BinaryOp); ok {
if binaryOp.operator.priority() < tmpE.operator.priority() && !tmpE.fixed {
newChild := binaryOp
newChild.rightExpr = tmpE.leftExpr
tmpE.leftExpr = newChild
binaryOp = tmpE
}
}
leftExpression, err := analyzeExpression(binaryOp.leftExpr, symbolTable)
if err != nil {
return binaryOp, err
}
binaryOp.leftExpr = leftExpression
rightExpression, err := analyzeExpression(binaryOp.rightExpr, symbolTable)
if err != nil {
return binaryOp, err
}
binaryOp.rightExpr = rightExpression
if binaryOp.leftExpr.getResultCount() != binaryOp.rightExpr.getResultCount() || binaryOp.leftExpr.getResultCount() != 1 {
return nil, fmt.Errorf("%w[%v:%v] - BinaryOp %v expected two values, got %v and %v",
ErrCritical, binaryOp.line, binaryOp.column, binaryOp.operator,
binaryOp.leftExpr.getResultCount(), binaryOp.rightExpr.getResultCount(),
)
}
tLeft := binaryOp.leftExpr.getExpressionTypes(symbolTable)[0]
tRight := binaryOp.rightExpr.getExpressionTypes(symbolTable)[0]
// Check types only after we possibly rearranged the expression!
if binaryOp.leftExpr.getExpressionTypes(symbolTable)[0] != binaryOp.rightExpr.getExpressionTypes(symbolTable)[0] {
return binaryOp, fmt.Errorf(
"%w[%v:%v] - BinaryOp '%v' expected same type, got: '%v', '%v'",
ErrCritical, binaryOp.line, binaryOp.column, binaryOp.operator, tLeft, tRight,
)
}
// We match all types explicitely to make sure that this still works or create an error when we introduce new types
// that are not considered yet!
switch binaryOp.operator {
case OP_AND, OP_OR:
binaryOp.opType = ComplexType{TYPE_BOOL, "", nil}
// We know left and right are the same type, so only compare left here.
if tLeft.t != TYPE_BOOL {
return binaryOp, fmt.Errorf(
"%w[%v:%v] - BinaryOp '%v' needs bool, got: '%v'",
ErrCritical, binaryOp.line, binaryOp.column, binaryOp.operator, tLeft,
)
}
//return binaryOp, TYPE_BOOL, nil
case OP_MOD:
binaryOp.opType = ComplexType{TYPE_INT, "", nil}
if tLeft.t != TYPE_INT {
return binaryOp, fmt.Errorf(
"%w[%v:%v] - BinaryOp '%v' only works for int",
ErrCritical, binaryOp.line, binaryOp.column, binaryOp.operator,
)
}
case OP_PLUS, OP_MINUS, OP_MULT, OP_DIV:
if tLeft.t == TYPE_FLOAT {
binaryOp.opType = ComplexType{TYPE_FLOAT, "", nil}
} else {
binaryOp.opType = ComplexType{TYPE_INT, "", nil}
}
if tLeft.t != TYPE_FLOAT && tLeft.t != TYPE_INT {
return binaryOp, fmt.Errorf(
"%w[%v:%v] - BinaryOp '%v' needs int/float, got: '%v'",
ErrCritical, binaryOp.line, binaryOp.column, binaryOp.operator, tLeft,
)
}
//return binaryOp, tLeft, nil
case OP_LE, OP_GE, OP_LESS, OP_GREATER:
binaryOp.opType.t = TYPE_BOOL
if tLeft.t != TYPE_FLOAT && tLeft.t != TYPE_INT && tLeft.t != TYPE_STRING {
return binaryOp, fmt.Errorf(
"%w[%v:%v] - BinaryOp '%v' needs int/float/string, got: '%v'",
ErrCritical, binaryOp.line, binaryOp.column, binaryOp.operator, tLeft,
)
}
//return binaryOp, TYPE_BOOL, nil
case OP_EQ, OP_NE:
binaryOp.opType = ComplexType{TYPE_BOOL, "", nil}
// We can actually compare all data types. So there will be no missmatch in general!
default:
return binaryOp, fmt.Errorf(
"%w[%v:%v] - Invalid binary operator: '%v' for type '%v'",
ErrCritical, binaryOp.line, binaryOp.column, binaryOp.operator, tLeft,
)
}
return binaryOp, nil
}
func analyzeDirectAccess(t ComplexType, directAccess []DirectAccess, symbolTable *SymbolTable) ([]DirectAccess, error) {
// If any of the accesses are an Array, we switch to heap memory and have to negate the offset in memory!
isHeapMemory := false
for i, access := range directAccess {
if t.t == TYPE_ARRAY {
isHeapMemory = true
}
if access.indexed {
if t.t != TYPE_ARRAY {
row, col := access.indexExpression.startPos()
return nil, fmt.Errorf("%w[%v:%v] - Indexing only works on arrays, ... got %v",
ErrCritical, row, col, t.t,
)
}
if t.subType == nil {
row, col := access.indexExpression.startPos()
return nil, fmt.Errorf("%w[%v:%v] - Indexing only works on arrays, got %v",
ErrCritical, row, col, t.t,
)
}
newIndexExpression, tmpE := analyzeExpression(access.indexExpression, symbolTable)
if tmpE != nil {
return nil, tmpE
}
directAccess[i].indexExpression = newIndexExpression
ts := newIndexExpression.getExpressionTypes(symbolTable)
if len(ts) != 1 || ts[0].getMemCount(symbolTable) != 1 {
row, col := access.indexExpression.startPos()
return nil, fmt.Errorf("%w[%v:%v] - Index expression can only have one value",
ErrCritical, row, col,
)
}
if ts[0].t != TYPE_INT {
row, col := access.indexExpression.startPos()
return nil, fmt.Errorf("%w[%v:%v] - Index expression must be int",
ErrCritical, row, col,
)
}
t = *t.subType
} else {
if t.t != TYPE_STRUCT {
return nil, fmt.Errorf("%w[%v:%v] - Qualified name access only works on structs",
ErrCritical, access.line, access.column,
)
}
entry, ok := symbolTable.getType(t.tName)
if !ok {
return nil, fmt.Errorf("%w[%v:%v] - Struct type '%v' used before declaration",
ErrCritical, access.line, access.column, t.tName,
)
}
memberIndex := -1
memberOffset := 0
for j, m := range entry.members {
if m.memName == access.accessName {
memberIndex = j
// For stack memory, the offset is negative!
memberOffset = -m.offset
break
}
}
if memberIndex == -1 {
return nil, fmt.Errorf("%w[%v:%v] - '%v' is not a member of struct '%v'",
ErrCritical, access.line, access.column, access.accessName, t.tName,
)
}
if isHeapMemory {
memberOffset = -memberOffset
}
directAccess[i].structOffset = memberOffset
t = entry.members[memberIndex].memType
}
}
return directAccess, nil
}
// Sometimes we need a bit of special handling to work with system-side generic functions
// like 'append()', to keep our type system going on the programmer and semantic side ...
func analyzeFunCallReturnTypes(fun FunCall, args []ComplexType, symbolTable *SymbolTable) ([]ComplexType, error) {
funEntry, _ := symbolTable.getFun(fun.funName, args, false)
types := funEntry.returnTypes
if len(types) == 1 && types[0].typeIsGeneric() {
arrayType := ComplexType{TYPE_ARRAY, "", &ComplexType{TYPE_WHATEVER, "", nil}}
switch fun.funName {
case "extend":
if len(args) != 2 {
return nil, fmt.Errorf("%w[%v:%v] - Function '%v' needs two parameters",
ErrCritical, fun.line, fun.column, fun.funName,
)
}
if !equalType(args[0], arrayType, false) {
return nil, fmt.Errorf("%w[%v:%v] - Function '%v' needs array as first parameter",
ErrCritical, fun.line, fun.column, fun.funName,
)
}
// Both parameters to extend should be equal.
if !equalType(args[0], args[1], true) {
return nil, fmt.Errorf("%w[%v:%v] - Function '%v' can only be called with arrays (of the same type)",
ErrCritical, fun.line, fun.column, fun.funName,
)
}
// Whatever we dump into append, we get out again!
return []ComplexType{args[0]}, nil
case "append":
if len(args) != 2 {
return nil, fmt.Errorf("%w[%v:%v] - Function '%v' needs two parameters",
ErrCritical, fun.line, fun.column, fun.funName,
)
}
if !equalType(args[0], arrayType, false) {
return nil, fmt.Errorf("%w[%v:%v] - Function '%v' needs array as first parameter",
ErrCritical, fun.line, fun.column, fun.funName,
)
}
// We expect the append element function
// The element must have the same type as the array.
if !equalType(*args[0].subType, args[1], true) {
return nil, fmt.Errorf("%w[%v:%v] - Function '%v' type mismatch between array type and given element to append",
ErrCritical, fun.line, fun.column, fun.funName,
)
}
// Whatever we dump into append, we get out again!
return []ComplexType{args[0]}, nil
default:
return nil, fmt.Errorf("%w[%v:%v] - Unknown generic function %v", ErrCritical, fun.line, fun.column, fun.funName)
}
}
return types, nil
}
func structMemToTypeList(mems []StructMem) (types []ComplexType) {
for _, m := range mems {
types = append(types, m.memType)
}
return
}
func analyzeFunCall(fun FunCall, symbolTable *SymbolTable) (FunCall, error) {
// The parameters must be analyzed before we query the symbol table for the actual
// function because the argument types must be analyzed/determined by then!
// Basically unpacking expression list before providing it to the function
expressionTypes := []ComplexType{}
for i, e := range fun.args {
newE, parseErr := analyzeExpression(e, symbolTable)
if parseErr != nil {
return fun, parseErr
}
fun.args[i] = newE
expressionTypes = append(expressionTypes, newE.getExpressionTypes(symbolTable)...)
}
funEntry, funOk := symbolTable.getFun(fun.funName, expressionsToTypes(fun.args, symbolTable), false)
typeEntry, typeOk := symbolTable.getType(fun.funName)
if funOk && typeOk {
return fun, fmt.Errorf("%w[%v:%v] - Function name '%v' already in use as a Type", ErrCritical, fun.line, fun.column, fun.funName)
}
var paramTypes []ComplexType
switch {
case funOk:
paramTypes = funEntry.paramTypes
symbolTable.setFunIsUsed(fun.funName, expressionsToTypes(fun.args, symbolTable), true)
returnTypes, err := analyzeFunCallReturnTypes(fun, expressionsToTypes(fun.args, symbolTable), symbolTable)
if err != nil {
return fun, err
}
fun.retTypes = returnTypes
fun.createStruct = false
case typeOk:
paramTypes = structMemToTypeList(typeEntry.members)
// One well defined return type. That is this struct we expect!
fun.retTypes = []ComplexType{ComplexType{TYPE_STRUCT, fun.funName, nil}}
fun.createStruct = true
default:
return fun, fmt.Errorf("%w[%v:%v] - Function '%v' called before declaration", ErrCritical, fun.line, fun.column, fun.funName)
}
if len(expressionTypes) != len(paramTypes) {
return fun, fmt.Errorf("%w[%v:%v] - Function call to '%v' has %v parameters, but needs %v",
ErrCritical, fun.line, fun.column, fun.funName, len(expressionTypes), len(funEntry.paramTypes),
)
}
for i, t := range expressionTypes {
if !equalType(t, paramTypes[i], false) {
return fun, fmt.Errorf("%w[%v:%v] - Function call to '%v' got type %v as %v. parameter, but needs %v",
ErrCritical, fun.line, fun.column, fun.funName, t, i+1, paramTypes[i],
)
}
}
if len(fun.directAccess) > 0 {
if fun.getResultCount() != 1 {
return fun, fmt.Errorf("%w[%v:%v] - Indexing is only allowed for single return functions",
ErrCritical, fun.line, fun.column,
)
}
newDirectAccess, err := analyzeDirectAccess(fun.retTypes[0], fun.directAccess, symbolTable)
if err != nil {
return fun, err
}
fun.directAccess = newDirectAccess
}
return fun, nil
}
func analyzeArrayDecl(a Array, symbolTable *SymbolTable) (Array, error) {
var arrayType ComplexType = ComplexType{TYPE_UNKNOWN, "", nil}
arraySize := 0
for i, e := range a.aExpressions {
newE, err := analyzeExpression(e, symbolTable)
if err != nil {
return a, err
}
a.aExpressions[i] = newE
if i == 0 && a.aType.t == TYPE_UNKNOWN {
arrayType = ComplexType{TYPE_ARRAY, "", &newE.getExpressionTypes(symbolTable)[0]}
}
if !equalType(newE.getExpressionTypes(symbolTable)[0], *arrayType.subType, true) {
return a, fmt.Errorf("%w[%v:%v] - Not all expressions in array declaration have the same type",
ErrCritical, a.line, a.column,
)
}
arraySize += newE.getResultCount()
}
// If aCount is already set to something, we know, this value is correct!!!
if a.aCount == 0 && arraySize > 0 {
a.aCount = arraySize
}
// For an empty array declaration, the type is set explicitely!
if a.aType.t == TYPE_UNKNOWN {
a.aType = arrayType
}
if e := analyzeType(a.aType, symbolTable); e != nil {
return a, fmt.Errorf("%w[%v:%v] - %v", ErrCritical, a.line, a.column, e.Error())
}
if a.isDirectlyAccessed() {
newDirectAccess, err := analyzeDirectAccess(a.aType, a.directAccess, symbolTable)
if err != nil {
return a, err
}
a.directAccess = newDirectAccess
}
return a, nil
}
func analyzeVariable(e Variable, symbolTable *SymbolTable) (Variable, error) {
// Lookup variable type and annotate node.
if vTable, ok := symbolTable.getVar(e.vName); ok {
e.vType = vTable.sType
if e.isDirectlyAccessed() {
newDirectAccess, err := analyzeDirectAccess(e.vType, e.directAccess, symbolTable)
if err != nil {
return e, err
}
e.directAccess = newDirectAccess
}
} else {
return e, fmt.Errorf("%w[%v:%v] - Variable '%v' referenced before declaration", ErrCritical, e.line, e.column, e.vName)
}
// Always access the very last entry for variables!
return e, nil
}
func analyzeExpression(expression Expression, symbolTable *SymbolTable) (Expression, error) {
switch e := expression.(type) {
case Constant:
return e, nil
case Variable:
v, err := analyzeVariable(e, symbolTable)
if err == nil && v.vShadow {
err = fmt.Errorf("%w[%v:%v] - Variable used as expression can not use 'shadow' keyword", ErrCritical, v.line, v.column)
}
return v, err
case UnaryOp:
return analyzeUnaryOp(e, symbolTable)
case BinaryOp:
return analyzeBinaryOp(e, symbolTable)
case FunCall:
return analyzeFunCall(e, symbolTable)
case Array:
return analyzeArrayDecl(e, symbolTable)
default:
row, col := expression.startPos()
return expression, fmt.Errorf("%w[%v:%v] - Unknown type for expression '%v'", ErrCritical, row, col, expression)
}
}
// Returns newly created variables and variables that should shadow others!
// This is just for housekeeping and removing them later!!!!
// All new variables (and shadow ones) are updated/written to the symbol varTable
func analyzeAssignment(assignment Assignment, symbolTable *SymbolTable) (Assignment, error) {
expressionTypes := make([]ComplexType, 0)
// We need this temporary array to hold information about sub-types for arrays, so we can
// pass this information on for later usage in indexed variables!
for i, e := range assignment.expressions {
expression, err := analyzeExpression(e, symbolTable)
if err != nil {
return assignment, err
}
tmpTypes := expression.getExpressionTypes(symbolTable)
expressionTypes = append(expressionTypes, tmpTypes...)
assignment.expressions[i] = expression
}
// Populate/overwrite the dictionary of variables for futher statements :)
if len(assignment.variables) != len(expressionTypes) {
row, col := assignment.startPos()
if len(assignment.variables) > 0 {
row, col = assignment.variables[0].line, assignment.variables[0].column
}
return assignment, fmt.Errorf(
"%w[%v:%v] - Variables and expression count need to match", ErrCritical, row, col,
)
}
for i, v := range assignment.variables {
expressionType := expressionTypes[i]
// Shadowing is only allowed in a different block, not right after the first variable, to avoid confusion and complicated
// variable handling
if symbolTable.isLocalVar(v.vName) && v.vShadow {
return assignment, fmt.Errorf(
"%w[%v:%v] - Variable %v is shadowing another variable in the same block. This is not allowed",
ErrCritical, v.line, v.column, v.vName,
)
}
// Only, if the variable already exists and we're not trying to shadow it!
if vTable, ok := symbolTable.getVar(v.vName); ok {
if !v.vShadow {
variableType := getAccessedType(vTable.sType, v.directAccess, symbolTable)
if !equalType(variableType, expressionType, true) {
return assignment, fmt.Errorf(
"%w[%v:%v] - Assignment type missmatch between variable %v and expression %v",
ErrCritical, v.line, v.column, v.vType, expressionType,
)
}
} else {
if v.isDirectlyAccessed() {
return assignment, fmt.Errorf("%w[%v:%v] - An indexed array write can not shadow its source",
ErrCritical, v.line, v.column,
)
}
symbolTable.setVar(v.vName, expressionType, false)
}
} else {
symbolTable.setVar(v.vName, expressionType, v.isDirectlyAccessed())
}
assignment.variables[i].vType = expressionType
if v.isDirectlyAccessed() {
entry, _ := symbolTable.getVar(v.vName)
newDirectAccess, err := analyzeDirectAccess(entry.sType, v.directAccess, symbolTable)
if err != nil {
return assignment, err
}
assignment.variables[i].directAccess = newDirectAccess
}
}
return assignment, nil
}
func analyzeCondition(condition Condition, symbolTable *SymbolTable) (Condition, error) {
// This expression MUST come out as boolean!
e, err := analyzeExpression(condition.expression, symbolTable)
if err != nil {
return condition, err
}
if e.getResultCount() != 1 {
row, col := e.startPos()
return condition, fmt.Errorf("%w[%v:%v] - Condition accepts only one expression, got %v",
ErrCritical, row, col, e.getResultCount(),
)
}
t := e.getExpressionTypes(symbolTable)[0]
if t.t != TYPE_BOOL {
row, col := e.startPos()
return condition, fmt.Errorf(
"%w[%v:%v] - If expression expected boolean, got: %v --> <<%v>>",
ErrCritical, row, col, t, condition.expression,
)
}
condition.expression = e
block, err := analyzeBlock(condition.block, symbolTable, nil)
if err != nil {
return condition, err
}
condition.block = block
elseBlock, err := analyzeBlock(condition.elseBlock, symbolTable, nil)
if err != nil {
return condition, err
}
condition.elseBlock = elseBlock
return condition, nil
}
func analyzeSwitch(sc Switch, symbolTable *SymbolTable) (Switch, error) {
valueSwitch := sc.expression != nil
if valueSwitch {
e, err := analyzeExpression(sc.expression, symbolTable)
if err != nil {
return sc, err
}
sc.expression = e
}
for i, c := range sc.cases {
// Empty case is permitted (behaves just like a default) as the last case only!
// And only, if we have a value-switch! Otherwise the default will be 'true'
if len(c.expressions) == 0 && i != len(sc.cases)-1 && sc.expression != nil {
row, col := sc.startPos()
return sc, fmt.Errorf("%w[%v:%v] - empty/default case must be the last case or have an expression to match",
ErrCritical, row, col,
)
}
for j, ce := range c.expressions {
e, err := analyzeExpression(ce, symbolTable)
if err != nil {
return sc, err
}
if e.getResultCount() != 1 {
row, col := e.startPos()
return sc, fmt.Errorf("%w[%v:%v] - case expression can only have one result value",
ErrCritical, row, col,
)
}
if valueSwitch {
if e.getExpressionTypes(symbolTable)[0].t != TYPE_INT {
row, col := e.startPos()
return sc, fmt.Errorf("%w[%v:%v] - value switch only accepts integers as cases",
ErrCritical, row, col,
)
}
} else {
if e.getExpressionTypes(symbolTable)[0].t != TYPE_BOOL {
row, col := e.startPos()
return sc, fmt.Errorf("%w[%v:%v] - general switch only accepts bools as cases",
ErrCritical, row, col,
)
}
}
c.expressions[j] = e
}
block, err := analyzeBlock(c.block, symbolTable, nil)
if err != nil {
return sc, err
}
c.block = block
sc.cases[i] = c
}
return sc, nil
}
func analyzeLoop(loop Loop, symbolTable *SymbolTable) (Loop, error) {
nextSymbolTable := &SymbolTable{
make(map[string]SymbolVarEntry, 0),
make(map[string][]SymbolFunEntry, 0),
make(map[string]SymbolTypeEntry, 0),
symbolTable.activeFunctionName,
symbolTable.activeFunctionParams,
symbolTable.activeFunctionReturn,
true,
"",
"",
symbolTable,
}
assignment, err := analyzeAssignment(loop.assignment, nextSymbolTable)
if err != nil {
return loop, err
}
loop.assignment = assignment
for i, e := range loop.expressions {
expression, err := analyzeExpression(e, nextSymbolTable)
if err != nil {
return loop, err
}
for _, t := range expression.getExpressionTypes(symbolTable) {
if t.t != TYPE_BOOL {
row, col := expression.startPos()
return loop, fmt.Errorf(
"%w[%v:%v] - Loop expression expected boolean, got: %v (%v)",
ErrCritical, row, col, t, expression,
)
}
}
loop.expressions[i] = expression
}
incrAssignment, err := analyzeAssignment(loop.incrAssignment, nextSymbolTable)
if err != nil {
return loop, err
}
loop.incrAssignment = incrAssignment
statements, err := analyzeBlock(loop.block, symbolTable, nextSymbolTable)
if err != nil {
return loop, err
}
loop.block = statements
loop.block.symbolTable = nextSymbolTable
return loop, nil
}
func analyzeRangedLoop(loop RangedLoop, symbolTable *SymbolTable) (RangedLoop, error) {
nextSymbolTable := &SymbolTable{
make(map[string]SymbolVarEntry, 0),
make(map[string][]SymbolFunEntry, 0),
make(map[string]SymbolTypeEntry, 0),
symbolTable.activeFunctionName,
symbolTable.activeFunctionParams,
symbolTable.activeFunctionReturn,
true,
"",
"",
symbolTable,
}
rangeExpression, err := analyzeExpression(loop.rangeExpression, nextSymbolTable)
if err != nil {
return loop, err
}
if rangeExpression.getResultCount() != 1 {
return loop, fmt.Errorf("%w[%v:%v] - RangedLoop can only iterate one array at a time", ErrCritical, loop.line, loop.column)
}
rangeType := rangeExpression.getExpressionTypes(symbolTable)[0]