-
Notifications
You must be signed in to change notification settings - Fork 21
/
parser.go
2294 lines (1951 loc) · 55.8 KB
/
parser.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 (
"errors"
"fmt"
"regexp"
"strconv"
)
/*
stat ::= assign | if | for | funDecl | ret | funCall
statlist ::= stat [statlist]
if ::= 'if' exp '{' [statlist] '}' [else '{' [statlist] '}']
for ::= 'for' [assign] ';' [explist] ';' [assign] '{' [statlist] '}'
type ::= 'int' | 'float' | 'bool'
typelist ::= type [',' typelist]
paramlist ::= var type [',' paramlist]
funDecl ::= 'fun' Name '(' [paramlist] ')' [typelist] '{' [statlist] '}'
ret ::= 'return' [explist]
assign ::= varlist ‘=’ explist | postIncr | postDecr
postIncr ::= varDecl '++'
postDecr ::= varDecl '--'
varlist ::= varDecl [‘,’ varlist]
explist ::= exp [‘,’ explist]
exp ::= Numeral | String | var | '(' exp ')' | exp binop exp | unop exp | funCall
funCall ::= Name '(' [explist] ')'
varDecl ::= [shadow] var
var ::= Name
binop ::= '+' | '-' | '*' | '/' | '%' | '==' | '!=' | '<=' | '>=' | '<' | '>' | '&&' | '||'
unop ::= '-' | '!'
Operator priority (Descending priority!):
0: '-', '!'
1: '*', '/', '%'
2: '+', '-'
3: '==', '!=', '<=', '>=', '<', '>'
4: '&&', '||'
*/
/////////////////////////////////////////////////////////////////////////////////////////////////
// CONST
/////////////////////////////////////////////////////////////////////////////////////////////////
const (
TYPE_UNKNOWN = iota
TYPE_INT
TYPE_STRING
TYPE_CHAR
TYPE_FLOAT
TYPE_BOOL
// TYPE_FUNCTION ?
TYPE_ARRAY
TYPE_STRUCT
// This type will always be considered equal to any other type when compared!
// Used for variadic functions.
TYPE_WHATEVER
)
const (
OP_PLUS = iota
OP_MINUS
OP_MULT
OP_DIV
OP_MOD
OP_NEGATIVE
OP_NOT
OP_EQ
OP_NE
OP_LE
OP_GE
OP_LESS
OP_GREATER
OP_AND
OP_OR
OP_UNKNOWN
)
/////////////////////////////////////////////////////////////////////////////////////////////////
// INTERFACES
/////////////////////////////////////////////////////////////////////////////////////////////////
var (
ErrCritical = errors.New("")
ErrNormal = errors.New("error - ")
)
type SymbolVarEntry struct {
sType ComplexType
// Refers to the name used in the final assembler
varName string
offset int
// In case the variable is indexing an array (see sType), we need this second underlaying type as well!
isIndexed bool
//arrayType Type
// ... more information
}
// This is needed when code for function calls is generated
// and we need to know how many and what kind of variables are
// pushed onto the stack or popped from afterwards.
type SymbolFunEntry struct {
paramTypes []ComplexType
returnTypes []ComplexType
jumpLabel string
epilogueLabel string
returnStackPointerOffset int
inline bool
isUsed bool
}
type SymbolTypeEntry struct {
members []StructMem
offset int
}
type SymbolTable struct {
varTable map[string]SymbolVarEntry
funTable map[string][]SymbolFunEntry
typeTable map[string]SymbolTypeEntry
// activeFunctionReturn references the function return types, if we are within a function, otherwise nil
// This is required to check validity and code generation of return statements
activeFunctionName string
activeFunctionParams []ComplexType
activeFunctionReturn []ComplexType
activeLoop bool
activeLoopBreakLabel string
activeLoopContinueLabel string
parent *SymbolTable
}
type AST struct {
block Block
globalSymbolTable *SymbolTable
}
type ComplexType struct {
t Type
// iff t is a struct, we need the qualified type name to query the symbol table!
tName string
subType *ComplexType
}
type Type int
type Operator int
type Node interface {
// Notes the start position in the actual source code!
// (lineNr, columnNr)
startPos() (int, int)
generateCode(asm *ASM, s *SymbolTable)
}
//
// Interface types
//
type Statement interface {
Node
statement()
}
type Expression interface {
Node
expression()
getExpressionTypes(s *SymbolTable) []ComplexType
getResultCount() int
isDirectlyAccessed() bool
getDirectAccess() []DirectAccess
}
/////////////////////////////////////////////////////////////////////////////////////////////////
// EXPRESSIONS
/////////////////////////////////////////////////////////////////////////////////////////////////
// This can either be an index access or a struct . access
type DirectAccess struct {
indexed bool
// If indexed, this is the index expression
indexExpression Expression
// If struct access by qualified name, this is the qualified name
accessName string
// If struct, we also need the offset within the struct!
structOffset int
line, column int
}
type Variable struct {
vType ComplexType
vName string
vShadow bool
directAccess []DirectAccess
line, column int
}
type Constant struct {
cType Type
cValue string
line, column int
}
type Array struct {
aType ComplexType
aCount int
aExpressions []Expression
directAccess []DirectAccess
line, column int
}
type BinaryOp struct {
operator Operator
leftExpr Expression
rightExpr Expression
opType ComplexType
// fixed means, that the whole binary operation is in '(' ')' and should not be combined differently
// independent on operator priority!
fixed bool
line, column int
}
type UnaryOp struct {
operator Operator
expr Expression
opType ComplexType
line, column int
}
type FunCall struct {
funName string
// as struct creation and funCalls have the same syntax, we set this flag, whether we have a
// function call or a struct creation. Analysis and code generation may differ.
createStruct bool
args []Expression
retTypes []ComplexType
directAccess []DirectAccess
line, column int
}
func (_ Variable) expression() {}
func (_ Constant) expression() {}
func (_ Array) expression() {}
func (_ BinaryOp) expression() {}
func (_ UnaryOp) expression() {}
func (_ FunCall) expression() {}
func (e Variable) startPos() (int, int) {
return e.line, e.column
}
func (e Constant) startPos() (int, int) {
return e.line, e.column
}
func (e Array) startPos() (int, int) {
return e.line, e.column
}
func (e BinaryOp) startPos() (int, int) {
return e.line, e.column
}
func (e UnaryOp) startPos() (int, int) {
return e.line, e.column
}
func (e FunCall) startPos() (int, int) {
return e.line, e.column
}
func getAccessedType(c ComplexType, access []DirectAccess, s *SymbolTable) ComplexType {
for _, da := range access {
if da.indexed {
c = *c.subType
} else {
entry, _ := s.getType(c.tName)
for _, m := range entry.members {
if da.accessName == m.memName {
c = m.memType
break
}
}
}
}
return c
}
func (e Constant) getExpressionTypes(s *SymbolTable) []ComplexType {
return []ComplexType{ComplexType{e.cType, "", nil}}
}
func (e Array) getExpressionTypes(s *SymbolTable) []ComplexType {
return []ComplexType{getAccessedType(e.aType, e.directAccess, s)}
}
func (e Variable) getExpressionTypes(s *SymbolTable) []ComplexType {
return []ComplexType{getAccessedType(e.vType, e.directAccess, s)}
}
func (e UnaryOp) getExpressionTypes(s *SymbolTable) []ComplexType {
return []ComplexType{e.opType}
}
func (e BinaryOp) getExpressionTypes(s *SymbolTable) []ComplexType {
return []ComplexType{e.opType}
}
func (e FunCall) getExpressionTypes(s *SymbolTable) []ComplexType {
if len(e.retTypes) != 1 {
return e.retTypes
}
return []ComplexType{getAccessedType(e.retTypes[0], e.directAccess, s)}
}
func (e Constant) getResultCount() int {
return 1
}
func (e Array) getResultCount() int {
return 1
}
func (e Variable) getResultCount() int {
return 1
}
func (e UnaryOp) getResultCount() int {
return 1
}
func (e BinaryOp) getResultCount() int {
return 1
}
func (e FunCall) getResultCount() int {
return len(e.retTypes)
}
func (e Constant) isDirectlyAccessed() bool {
return false
}
func (e Array) isDirectlyAccessed() bool {
return len(e.directAccess) > 0
}
func (e Variable) isDirectlyAccessed() bool {
return len(e.directAccess) > 0
}
func (e UnaryOp) isDirectlyAccessed() bool {
return false
}
func (e BinaryOp) isDirectlyAccessed() bool {
return false
}
func (e FunCall) isDirectlyAccessed() bool {
return len(e.directAccess) > 0
}
func (e Constant) getDirectAccess() []DirectAccess {
return nil
}
func (e Array) getDirectAccess() []DirectAccess {
return e.directAccess
}
func (e Variable) getDirectAccess() []DirectAccess {
return e.directAccess
}
func (e UnaryOp) getDirectAccess() []DirectAccess {
return nil
}
func (e BinaryOp) getDirectAccess() []DirectAccess {
return nil
}
func (e FunCall) getDirectAccess() []DirectAccess {
return e.directAccess
}
/////////////////////////////////////////////////////////////////////////////////////////////////
// STATEMENTS
/////////////////////////////////////////////////////////////////////////////////////////////////
type StructMem struct {
memName string
offset int
memType ComplexType
}
type StructDef struct {
name string
members []StructMem
line, column int
}
type Block struct {
statements []Statement
symbolTable *SymbolTable
line, column int
}
type Assignment struct {
variables []Variable
expressions []Expression
line, column int
}
type Condition struct {
expression Expression
block Block
elseBlock Block
line, column int
}
type Case struct {
// When comparing values, a nil expressions list means: 'default'
// In a general switch, default is just 'true'
expressions []Expression
block Block
}
type Switch struct {
// nil for a general switch
expression Expression
cases []Case
line, column int
}
type Loop struct {
assignment Assignment
expressions []Expression
incrAssignment Assignment
block Block
line, column int
}
type RangedLoop struct {
counter Variable
elem Variable
rangeExpression Expression
block Block
line, column int
}
type Function struct {
fName string
parameters []Variable
returnTypes []ComplexType
block Block
line, column int
}
type Return struct {
expressions []Expression
line, column int
}
type Break struct {
line, column int
}
type Continue struct {
line, column int
}
func (_ StructDef) statement() {}
func (_ Block) statement() {}
func (_ Assignment) statement() {}
func (_ Condition) statement() {}
func (_ Switch) statement() {}
func (_ Loop) statement() {}
func (_ Function) statement() {}
func (_ Return) statement() {}
func (_ FunCall) statement() {}
func (_ RangedLoop) statement() {}
func (_ Break) statement() {}
func (_ Continue) statement() {}
func (s StructDef) startPos() (int, int) {
return s.line, s.column
}
func (s Block) startPos() (int, int) {
return s.line, s.column
}
func (s Assignment) startPos() (int, int) {
return s.line, s.column
}
func (s Condition) startPos() (int, int) {
return s.line, s.column
}
func (s Switch) startPos() (int, int) {
return s.line, s.column
}
func (s Loop) startPos() (int, int) {
return s.line, s.column
}
func (s Function) startPos() (int, int) {
return s.line, s.column
}
func (s Return) startPos() (int, int) {
return s.line, s.column
}
func (s RangedLoop) startPos() (int, int) {
return s.line, s.column
}
func (s Break) startPos() (int, int) {
return s.line, s.column
}
func (s Continue) startPos() (int, int) {
return s.line, s.column
}
/////////////////////////////////////////////////////////////////////////////////////////////////
// AST, OPS STRING
/////////////////////////////////////////////////////////////////////////////////////////////////
func (ast AST) String() string {
s := fmt.Sprintln("AST:")
for _, st := range ast.block.statements {
s += fmt.Sprintf("%v\n", st)
}
return s
}
func (o Operator) String() string {
switch o {
case OP_PLUS:
return "+"
case OP_MINUS:
return "-"
case OP_MULT:
return "*"
case OP_DIV:
return "/"
case OP_MOD:
return "%"
case OP_NEGATIVE:
return "-"
case OP_EQ:
return "=="
case OP_NE:
return "!="
case OP_LE:
return "<="
case OP_GE:
return ">="
case OP_LESS:
return "<"
case OP_GREATER:
return ">"
case OP_AND:
return "&&"
case OP_OR:
return "||"
case OP_NOT:
return "!"
case OP_UNKNOWN:
return "?"
}
return "?"
}
/////////////////////////////////////////////////////////////////////////////////////////////////
// EXPRESSION STRING
/////////////////////////////////////////////////////////////////////////////////////////////////
func (c ComplexType) String() string {
switch c.t {
case TYPE_ARRAY:
return fmt.Sprintf("array[%v]", c.subType)
case TYPE_STRUCT:
return fmt.Sprintf("struct[%v]", c.tName)
}
return fmt.Sprintf("%v", c.t.String())
}
func (v Variable) String() string {
if !v.isDirectlyAccessed() {
shadowString := ""
if v.vShadow {
shadowString = "shadow "
}
return fmt.Sprintf("%v%v(%v)", shadowString, v.vType.t, v.vName)
}
return fmt.Sprintf("%v(%v[%v])", v.vType.subType, v.vName, v.directAccess)
}
func (c Constant) String() string {
return fmt.Sprintf("%v(%v)", c.cType, c.cValue)
}
func (b BinaryOp) String() string {
start, end := "", ""
if b.fixed {
start = "("
end = ")"
}
return fmt.Sprintf("%v%v %v %v%v", start, b.leftExpr, b.operator, b.rightExpr, end)
}
func (u UnaryOp) String() string {
return fmt.Sprintf("%v(%v)", u.operator, u.expr)
}
func (a Array) String() string {
return fmt.Sprintf("[](%v, %v)", a.aType, a.aCount)
}
func (v Type) String() string {
switch v {
case TYPE_INT:
return "int"
case TYPE_STRING:
return "string"
case TYPE_CHAR:
return "char"
case TYPE_FLOAT:
return "float"
case TYPE_BOOL:
return "bool"
case TYPE_ARRAY:
return "array"
case TYPE_STRUCT:
return "struct"
case TYPE_WHATEVER:
return "anything"
}
return "?"
}
func stringToType(s string) Type {
switch s {
case "int":
return TYPE_INT
case "float":
return TYPE_FLOAT
case "bool":
return TYPE_BOOL
case "char":
return TYPE_CHAR
case "string":
return TYPE_STRING
case "array":
return TYPE_ARRAY
}
return TYPE_UNKNOWN
}
func isTypeString(s string) bool {
t := stringToType(s)
return t == TYPE_INT ||
t == TYPE_FLOAT ||
t == TYPE_BOOL ||
t == TYPE_ARRAY ||
t == TYPE_CHAR ||
t == TYPE_STRING
}
func (s SymbolFunEntry) String() string {
st := "SymbolFunEntry: ("
st += fmt.Sprintf("params: [")
for i, p := range s.paramTypes {
st += p.String()
if i < len(s.paramTypes)-1 {
st += " "
}
}
st += fmt.Sprintf("], returns: [")
for i, p := range s.returnTypes {
st += p.String()
if i < len(s.returnTypes)-1 {
st += " "
}
}
st += "])"
return st
}
/////////////////////////////////////////////////////////////////////////////////////////////////
// STATEMENT STRING
/////////////////////////////////////////////////////////////////////////////////////////////////
func (a Assignment) String() (s string) {
for i, v := range a.variables {
s += fmt.Sprintf("%v", v)
if i != len(a.variables)-1 {
s += fmt.Sprintf(", ")
}
}
s += fmt.Sprintf(" = ")
for i, v := range a.expressions {
s += fmt.Sprintf("%v", v)
if i != len(a.expressions)-1 {
s += ", "
}
}
return
}
func (st StructDef) String() (s string) {
s += "struct " + st.name + " {\n"
for _, m := range st.members {
s += fmt.Sprintf(" %v %v\n", m.memName, m.memType)
}
s += "}"
return
}
func (c Condition) String() (s string) {
s += fmt.Sprintf("if %v {\n", c.expression)
for _, st := range c.block.statements {
s += fmt.Sprintf("\t%v\n", st)
}
s += "}"
if c.elseBlock.statements != nil {
s += " else {\n"
for _, st := range c.elseBlock.statements {
s += fmt.Sprintf("\t%v\n", st)
}
s += "}"
}
return
}
func (c Case) String() (s string) {
s += "case "
for i, e := range c.expressions {
s += fmt.Sprintf("%v", e)
if i != len(c.expressions)-1 {
s += ", "
}
}
s += ":\n"
s += fmt.Sprintf("%v\n", c.block)
return
}
func (sw Switch) String() (s string) {
s = "switch "
if sw.expression != nil {
s += fmt.Sprintf("%v ", sw.expression)
}
s += "{\n"
for _, c := range sw.cases {
s += c.String()
}
s += "}"
return
}
func (l Loop) String() (s string) {
s += fmt.Sprintf("for %v; ", l.assignment)
for i, e := range l.expressions {
s += fmt.Sprintf("%v", e)
if i != len(l.expressions)-1 {
s += ", "
}
}
s += fmt.Sprintf("; %v", l.incrAssignment)
s += " {\n"
for _, st := range l.block.statements {
s += fmt.Sprintf("\t%v\n", st)
}
s += "}"
return
}
func (l RangedLoop) String() (s string) {
s += fmt.Sprintf("for %v, %v : %v {\n", l.counter, l.elem, l.rangeExpression)
for _, st := range l.block.statements {
s += fmt.Sprintf("\t%v\n", st)
}
s += "}"
return
}
func (s Return) String() string {
return fmt.Sprintf("return %v", s.expressions)
}
func (s Break) String() string {
return "break"
}
func (s Continue) String() string {
return "continue"
}
/////////////////////////////////////////////////////////////////////////////////////////////////
// TOKEN CHANNEL
/////////////////////////////////////////////////////////////////////////////////////////////////
// Implements a channel with one cache/lookahead, that can be pushed back in (logically)
type TokenChannel struct {
c chan Token
cached []Token
}
func (tc *TokenChannel) next() Token {
if len(tc.cached) > 0 {
t := tc.cached[len(tc.cached)-1]
tc.cached = tc.cached[:len(tc.cached)-1]
return t
}
v, ok := <-tc.c
if !ok {
panic("Error: Channel closed unexpectedly.")
}
return v
}
func (tc *TokenChannel) createToken(t TokenType, v string, line, column int) Token {
return Token{t, v, line, column}
}
func (tc *TokenChannel) pushBack(t Token) {
tc.cached = append(tc.cached, t)
}
/////////////////////////////////////////////////////////////////////////////////////////////////
// PARSER IMPLEMENTATION
/////////////////////////////////////////////////////////////////////////////////////////////////
// Sometimes, we are OK with non strict equality, i.e. if we only need an array and don't care about
// the actual type.
func equalType(c1, c2 ComplexType, strict bool) bool {
if c1.t != TYPE_WHATEVER && c2.t != TYPE_WHATEVER && c1.t != c2.t {
return false
}
if c1.tName != c2.tName {
return false
}
if c1.subType != nil && c2.subType != nil {
return equalType(*c1.subType, *c2.subType, strict)
}
return !strict || c1.subType == nil && c2.subType == nil
}
func equalTypes(l1, l2 []ComplexType, strict bool) bool {
if len(l1) != len(l2) {
return false
}
for i, c1 := range l1 {
if !equalType(c1, l2[i], strict) {
return false
}
}
return true
}
func (c ComplexType) typeIsGeneric() bool {
if c.t == TYPE_WHATEVER {
return true
}
if c.subType == nil {
return false
}
return c.subType.typeIsGeneric()
}
func (c ComplexType) getMemTypes(symbolTable *SymbolTable) []Type {
if c.t == TYPE_STRUCT {
types := make([]Type, 0)
entry, _ := symbolTable.getType(c.tName)
for _, m := range entry.members {
types = append(types, m.memType.getMemTypes(symbolTable)...)
}
return types
}
return []Type{c.t}
}
func (c ComplexType) getMemCount(symbolTable *SymbolTable) int {
return len(c.getMemTypes(symbolTable))
}
func typesToMemCount(ct []ComplexType, symbolTable *SymbolTable) (count int) {
for _, t := range ct {
count += t.getMemCount(symbolTable)
}
return
}
// Operator priority (Descending priority!):
// 0: '-', '!'
// 1: '*', '/', '%'
// 2: '+', '-'
// 3: '==', '!=', '<=', '>=', '<', '>'
// 4: '&&'
// 5: '||'
func (o Operator) priority() int {
switch o {
case OP_NEGATIVE, OP_NOT:
return 0
case OP_MULT, OP_DIV, OP_MOD:
return 1
case OP_PLUS, OP_MINUS:
return 2
case OP_EQ, OP_NE, OP_LE, OP_GE, OP_LESS, OP_GREATER:
return 3
case OP_AND:
return 4
case OP_OR:
return 5
default:
fmt.Printf("Unknown operator: %v\n", o)
}
return 100
}
func getOperatorType(o string) Operator {
switch o {
case "+":
return OP_PLUS
case "-":
return OP_MINUS
case "*":
return OP_MULT
case "/":
return OP_DIV
case "%":
return OP_MOD
case "==":
return OP_EQ
case "!=":
return OP_NE
case "<=":
return OP_LE
case ">=":
return OP_GE
case "<":
return OP_LESS
case ">":
return OP_GREATER
case "&&":
return OP_AND
case "||":
return OP_OR
case "!":
return OP_NOT
}
return OP_UNKNOWN
}
// expectType checks the next token against a given expected type and returns the token string
// with corresponding line and column numbers
func (tokens *TokenChannel) expectType(ttype TokenType) (string, int, int, bool) {
t := tokens.next()
//fmt.Println(" ", t)
if t.tokenType != ttype {
tokens.pushBack(t)
return t.value, t.line, t.column, false
}
return t.value, t.line, t.column, true
}
// expect checks the next token against a given expected type and value and returns true, if the
// check was valid.
func (tokens *TokenChannel) expect(ttype TokenType, value string) (int, int, bool) {
t := tokens.next()
//fmt.Println(" ", t)
if t.tokenType != ttype || t.value != value {
tokens.pushBack(t)
return t.line, t.column, false
}
return t.line, t.column, true
}
func parseDirectAccess(tokens *TokenChannel) (indexExpressions []DirectAccess, err error) {
// If it comes to it, we parse infinite [] expressions :)
for {
// Parse indexed expressions ...[..]
if row, col, ok := tokens.expect(TOKEN_SQUARE_OPEN, "["); ok {
e, parseErr := parseExpression(tokens)
if errors.Is(parseErr, ErrCritical) {
err = parseErr
return
}
if row, col, ok := tokens.expect(TOKEN_SQUARE_CLOSE, "]"); !ok {
err = fmt.Errorf("%w[%v:%v] - Expected ']' after array index expression",
ErrCritical, row, col,
)
return
}
indexExpressions = append(indexExpressions, DirectAccess{true, e, "", 0, row, col})
} else {
// Parse struct access with qualified name.
if _, _, ok := tokens.expect(TOKEN_DOT, "."); ok {