-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
1773 lines (1579 loc) · 43.9 KB
/
main.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 (
"bufio"
"fmt"
"math"
"os"
"reflect"
"strconv"
"strings"
"time"
"github.com/fatih/color"
)
// loop stack overflow
const MAX_LOOPS = 50
// Setting global environment scope
func setUpGlobalEnvironmentScope(env Environment) {
// Environment variables
env.declareVar("true", MK_BOOL_VALUE(true), true)
env.declareVar("false", MK_BOOL_VALUE(false), true)
env.declareVar("nil", MK_NIL_VALUE(), true)
// Native functions
env.declareVar("print", MK_NATIVE_FN_VALUE(func(args []any, env Environment) any {
fmt.Print(color.GreenString(fmt.Sprintln(args...)))
return MK_NIL_VALUE()
}), true)
env.declareVar("getTime", MK_NATIVE_FN_VALUE(func(args []any, env Environment) any {
return MK_NUMBER_VALUE(float64(time.Now().Unix()))
}), true)
}
// making enum TokenType
type TokenType int
const (
// single-character
LEFT_PAREN TokenType = iota + 1
RIGHT_PAREN
LEFT_BRACE
RIGHT_BRACE
LEFT_SQUARE
RIGHT_SQUARE
COMMA
COLON
DOT
MINUS
PLUS
PERCENT
SEMICOLON
SLASH
STAR
// one or two character token
BANG
BANG_EQUAL
EQUAL
EQUAL_EQUAL
GREATER
GREATER_EQUAL
LESS
LESS_EQUAL
// literals
IDENTIFIER
STRING
NUMBER
// keywords
AND
BREAK
CLASS
CONST
CONTINUE
ELSE
ELIF
FALSE
FN
FOR
IF
LOOP
NIL
OR
RETURN
SUPER
THIS
TRUE
VAR
WHILE
// eof
EOF
)
func (t TokenType) EnumIndex() int {
return int(t)
}
func (t TokenType) String() string {
return [...]string{"LEFT_PAREN", "RIGHT_PAREN", "LEFT_BRACE", "RIGHT_BRACE", "LEFT_SQUARE", "RIGHT_SQUARE", "COMMA", "COLON", "DOT", "MINUS", "PLUS", "PERCENT", "SEMICOLON", "SLASH", "STAR", "BANG", "BANG_EQUAL", "EQUAL", "EQUAL_EQUAL", "GREATER", "GREATER_EQUAL", "LESS", "LESS_EQUAL", "IDENTIFIER", "STRING", "NUMBER", "AND", "BREAK", "CLASS", "CONST", "CONTINUE", "ELSE", "ELIF", "FALSE", "FN", "FOR", "IF", "LOOP", "NIL", "OR", "RETURN", "SUPER", "THIS", "TRUE", "VAR", "WHILE", "EOF"}[t-1]
}
var keywords map[string]TokenType = make(map[string]TokenType)
// making Token struct
type Token struct {
tokenType TokenType
lexeme string
literal string
line int
}
func (t Token) String() string {
return color.GreenString(t.tokenType.String()) + " " + t.lexeme + " " + t.literal
}
func main() {
// keyword initialisation
keywords["and"] = AND
keywords["break"] = BREAK
keywords["class"] = CLASS
keywords["const"] = CONST
keywords["continue"] = CONTINUE
keywords["else"] = ELSE
keywords["elif"] = ELIF
keywords["false"] = FALSE
keywords["for"] = FOR
keywords["fn"] = FN
keywords["if"] = IF
keywords["loop"] = LOOP
keywords["nil"] = NIL
keywords["or"] = OR
keywords["return"] = RETURN
keywords["super"] = SUPER
keywords["this"] = THIS
keywords["true"] = TRUE
keywords["var"] = VAR
keywords["while"] = WHILE
// Environment variables
env := Environment{parent: nil, variables: map[string]any{}, constants: map[string]void{}}
setUpGlobalEnvironmentScope(env)
if len(os.Args) > 2 {
fmt.Println()
fmt.Println(color.YellowString("USAGE : lexer [script]"))
fmt.Println()
os.Exit(64)
} else if len(os.Args) == 2 {
runFile(os.Args[1], env)
} else {
runPrompt(env)
}
}
// Error handling
func Error(line int, message string) {
report(line, message)
}
func report(line int, message string) {
fmt.Println(color.RedString("ERROR : [ Line"), color.RedString(strconv.Itoa(line)), color.RedString("]"))
fmt.Println(color.RedString(" :"), color.RedString(message))
fmt.Println()
os.Exit(1)
}
// Scanner object
type Scanner struct {
source string
tokens []Token
start int
current int
line int
}
func (sc Scanner) isAtEnd() bool {
return sc.current >= len(sc.source)
}
func (sc Scanner) scanTokens() []Token {
for !sc.isAtEnd() {
sc.start = sc.current
sc.scanToken()
}
eofToken := Token{EOF, "", "null", sc.line}
sc.tokens = append(sc.tokens, eofToken)
return sc.tokens
}
func (sc *Scanner) advance() byte {
ret := sc.source[sc.current]
sc.current = sc.current + 1
return ret
}
func (sc *Scanner) addToken(tokenType TokenType) {
sc.addTokenWithLiteral(tokenType, "null")
}
func (sc *Scanner) addTokenWithLiteral(tokenType TokenType, literal string) {
text := sc.source[sc.start:sc.current]
newToken := Token{tokenType, text, "null", sc.line}
sc.tokens = append(sc.tokens, newToken)
}
func (sc *Scanner) match(expected byte) bool {
if sc.isAtEnd() {
return false
}
if sc.source[sc.current] != expected {
return false
}
sc.current = sc.current + 1
return true
}
func (sc *Scanner) peek() byte {
if sc.isAtEnd() {
return '\x00'
}
return sc.source[sc.current]
}
func (sc *Scanner) peekNext() byte {
if sc.current+1 >= len(sc.source) {
return '\x00'
}
return sc.source[sc.current+1]
}
func (sc *Scanner) addString() {
for sc.peek() != '"' && !sc.isAtEnd() {
if sc.peek() == '\n' {
sc.line = sc.line + 1
}
sc.advance()
}
if sc.isAtEnd() {
Error(sc.line, "Unterminated string")
return
}
sc.advance()
value := sc.source[sc.start+1 : sc.current-1]
sc.addTokenWithLiteral(STRING, value)
}
func (sc *Scanner) isDigit(c byte) bool {
digit_list := []byte{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'}
for _, digit := range digit_list {
if digit == c {
return true
}
}
return false
}
func (sc *Scanner) isAlpha(c byte) bool {
return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_'
}
func (sc *Scanner) isAlphaNumeric(c byte) bool {
return sc.isAlpha(c) || sc.isDigit(c)
}
func (sc *Scanner) addWord() {
for sc.isAlphaNumeric(sc.peek()) {
sc.advance()
}
text := sc.source[sc.start:sc.current]
gotType, isFound := keywords[text]
if isFound {
sc.addToken(gotType)
} else {
sc.addToken(IDENTIFIER)
}
}
func (sc *Scanner) addNumber() {
for sc.isDigit(sc.peek()) {
sc.advance()
}
if sc.peek() == '.' && sc.isDigit(sc.peekNext()) {
sc.advance()
}
for sc.isDigit(sc.peek()) {
sc.advance()
}
value := sc.source[sc.start:sc.current]
sc.addTokenWithLiteral(NUMBER, value)
}
func (sc *Scanner) scanToken() {
var c byte = sc.advance()
switch c {
case '(':
sc.addToken(LEFT_PAREN)
case ')':
sc.addToken(RIGHT_PAREN)
case '{':
sc.addToken(LEFT_BRACE)
case '}':
sc.addToken(RIGHT_BRACE)
case '[':
sc.addToken(LEFT_SQUARE)
case ']':
sc.addToken(RIGHT_SQUARE)
case ',':
sc.addToken(COMMA)
case ':':
sc.addToken(COLON)
case '.':
sc.addToken(DOT)
case '-':
sc.addToken(MINUS)
case '+':
sc.addToken(PLUS)
case '%':
sc.addToken(PERCENT)
case ';':
sc.addToken(SEMICOLON)
case '*':
sc.addToken(STAR)
case '!':
if sc.match('=') {
sc.addToken(BANG_EQUAL)
} else {
sc.addToken(BANG)
}
case '=':
if sc.match('=') {
sc.addToken(EQUAL_EQUAL)
} else {
sc.addToken(EQUAL)
}
case '<':
if sc.match('=') {
sc.addToken(LESS_EQUAL)
} else {
sc.addToken(LESS)
}
case '>':
if sc.match('=') {
sc.addToken(GREATER_EQUAL)
} else {
sc.addToken(GREATER)
}
case '/':
if sc.match('/') {
for sc.peek() != '\n' && !sc.isAtEnd() {
sc.advance()
}
} else {
sc.addToken(SLASH)
}
case ' ', '\t':
case '\r':
sc.advance()
case '\n':
sc.line += 1
case '"':
sc.addString()
case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
sc.addNumber()
default:
if sc.isAlpha(c) {
sc.addWord()
} else {
Error(sc.line, "Unexpected character "+string(c))
}
}
}
// run functions
func run(source string, env Environment) {
// running code
p := Parser{make([]Token, 0)}
program := p.produceAST(source)
_ = evaluate(0, program, env)
// fmt.Printf(color.GreenString("%+v\n"), result)
}
func runFile(path string, env Environment) {
fmt.Println()
_, err := os.Stat(path)
if err != nil {
fmt.Println(color.RedString("ERROR : file not found at"), color.RedString(path))
fmt.Println()
return
}
data, err := os.ReadFile(path)
if err != nil {
fmt.Println(color.RedString("ERROR : file cannot be read at"), color.RedString(path))
fmt.Println()
return
}
fmt.Println(color.YellowString("Welcome to Toy Lang Source"))
fmt.Println(color.YellowString("File " + path + " running ..."))
fmt.Println()
run(string(data), env)
fmt.Println()
fmt.Println(color.YellowString("Thanks for using Source - by Pratik"))
fmt.Println()
}
func runPrompt(env Environment) {
reader := bufio.NewReader(os.Stdin)
fmt.Println()
fmt.Println(color.YellowString("Welcome to Toy Lang REPL"))
fmt.Println(color.YellowString("Enter 'quit' to exit"))
for {
fmt.Print(color.YellowString("\n>>> "))
line, err := reader.ReadString('\n')
fmt.Println()
if err != nil {
fmt.Println(color.RedString("ERROR : I/O error occured"))
}
line = line[:len(line)-2]
if strings.TrimSpace(line) == "quit" {
fmt.Println(color.YellowString("Thanks for using REPL - by Pratik"))
fmt.Println()
break
}
run(line, env)
}
}
// PARSER
type NodeType int
const (
// Statements
_PROGRAM NodeType = iota + 1
_VAR_DECLARE
_IF
_LOOP
_BREAK
_CONTINUE
// Expressions
_FUNCTION_EXPR
_ASSIGN_EXPR
_MEMBER_EXPR
_CALL_EXPR
//Literals
_PROPERTY
_ARRAY_LITERAL
_STRING_LITERAL
_OBJECT_LITERAL
_NUMERIC_LITERAL
_BOOL_LITERAL
_NIL_LITERAL
_IDENTIFIER
_BINARY_EXPR
_UNARY_EXPR
)
func (n NodeType) EnumIndex() int {
return int(n)
}
func (n NodeType) String() string {
return [...]string{"PROGRAM", "VAR_DECLARE", "IF", "LOOP", "BREAK", "CONTINUE", "FUNCTION_EXPR", "ASSIGN_EXPR", "MEMBER_EXPR", "CALL_EXPR", "PROPERTY", "ARRAY_LITERAL", "STRING_LITERAL", "OBJECT_LITERAL", "NUMERIC_LITERAL", "BOOL_LITERAL", "NIL_LITERAL", "IDENTIFIER", "BINARY_EXPR", "UNARY_EXPR"}[n-1]
}
type Stmt struct {
kind string
}
type VarDeclaration struct {
kind string
constant bool
identifier string
value any
}
type If struct {
kind string
ifCondition any
ifBody []any
countElif int
elifCondition []any
elifBody [][]any
isElse bool
elseBody []any
}
type Loop struct {
kind string
loopCondition any
loopBody []any
maxLoops int
}
type Break struct {
kind string
}
type Continue struct {
kind string
}
type Program struct {
kind string
body []any
}
type Expr struct {
kind NodeType
}
type FunctionExpr struct {
kind string
name string
parameters []string
body []any
}
type AssignmentExpr struct {
kind string
assignee any
value any
}
type BinaryExpr struct {
kind string
left any
right any
operator string
}
type UnaryExpr struct {
kind string
operator string
operand any
}
type CallExpr struct {
kind string
args []any
caller any
}
type MemberExpr struct {
kind string
object any
property any
computed bool
}
type Identifier struct {
kind string
symbol string
}
type NumericLiteral struct {
kind string
value float64
}
type ArrayLiteral struct {
kind string
value []any
}
type Property struct {
kind string
key string
value any
}
type StringLiteral struct {
kind string
value string
}
type ObjectLiteral struct {
kind string
properties []Property
}
type BoolLiteral struct {
kind string
value bool
}
type NilLiteral struct {
kind string
value string
}
type Parser struct {
tokens []Token
}
func (p *Parser) not_eof() bool {
return p.tokens[0].tokenType != EOF
}
func (p *Parser) at() Token {
return p.tokens[0]
}
func (p *Parser) eat() Token {
prev := p.tokens[0]
p.tokens = p.tokens[1:]
return prev
}
func (p *Parser) expect(tokenType TokenType, errMsg string) Token {
prev := p.tokens[0]
p.tokens = p.tokens[1:]
if prev.tokenType == EOF || prev.tokenType != tokenType {
Error(prev.line, errMsg)
os.Exit(1)
}
return prev
}
func (p *Parser) produceAST(source string) Program {
sc := Scanner{source, []Token{}, 0, 0, 1}
p.tokens = sc.scanTokens()
// fmt.Printf("token: %+v\n", p.tokens)
program := Program{
kind: _PROGRAM.String(),
body: make([]any, 0),
}
line := 1
for p.not_eof() {
program.body = append(program.body, p.parse_stmt(line))
line += 1
}
// fmt.Printf("%+v\n", program.body)
return program
}
func (p *Parser) parse_stmt(line int) any {
switch p.at().tokenType {
case VAR, CONST:
return p.parse_var_declare(line)
case IF:
return p.parse_if(line)
case LOOP:
return p.parse_loop(line)
case BREAK:
p.eat()
return Break{kind: _BREAK.String()}
case CONTINUE:
p.eat()
return Continue{kind: _CONTINUE.String()}
default:
return p.parse_expr(line)
}
}
func (p *Parser) parse_if(line int) any {
p.eat()
p.expect(LEFT_PAREN, "Expected ( after if")
ifCondition := p.parse_expr(line)
p.expect(RIGHT_PAREN, "Expected ) after expression")
p.expect(LEFT_BRACE, "Expected { after expression")
ifBody := make([]any, 0)
for p.at().tokenType != EOF && p.at().tokenType != RIGHT_BRACE {
ifBody = append(ifBody, p.parse_stmt(line))
}
p.expect(RIGHT_BRACE, "Expected } after if body")
countElif := 0
elifCondition := make([]any, 0)
elifBody := make([][]any, 0)
for p.at().tokenType == ELIF {
p.eat()
countElif += 1
p.expect(LEFT_PAREN, "Expected ( after elif")
elifCondition_i := p.parse_expr(line)
p.expect(RIGHT_PAREN, "Expected ) after expression")
p.expect(LEFT_BRACE, "Expected { after expression")
elifBody_i := make([]any, 0)
for p.at().tokenType != EOF && p.at().tokenType != RIGHT_BRACE {
elifBody_i = append(elifBody_i, p.parse_stmt(line))
}
p.expect(RIGHT_BRACE, "Expected } after elif body")
elifCondition = append(elifCondition, elifCondition_i)
elifBody = append(elifBody, elifBody_i)
}
isElse := false
elseBody := make([]any, 0)
if p.at().tokenType == ELSE {
p.eat()
isElse = true
p.expect(LEFT_BRACE, "Expected { after else")
for p.at().tokenType != EOF && p.at().tokenType != RIGHT_BRACE {
elseBody = append(elseBody, p.parse_stmt(line))
}
p.expect(RIGHT_BRACE, "Expected } after else body")
}
return If{
kind: _IF.String(),
ifCondition: ifCondition,
ifBody: ifBody,
countElif: countElif,
elifCondition: elifCondition,
elifBody: elifBody,
isElse: isElse,
elseBody: elseBody,
}
}
func (p *Parser) parse_loop(line int) any {
p.eat()
p.expect(LEFT_PAREN, "Expected ( after loop")
loopCondition := p.parse_expr(line)
p.expect(RIGHT_PAREN, "Expected ) after expression")
p.expect(LEFT_BRACE, "Expected { after expression")
loopBody := make([]any, 0)
for p.at().tokenType != EOF && p.at().tokenType != RIGHT_BRACE {
loopBody = append(loopBody, p.parse_stmt(line))
}
p.expect(RIGHT_BRACE, "Expected } after if body")
return Loop{
kind: _LOOP.String(),
loopCondition: loopCondition,
loopBody: loopBody,
maxLoops: MAX_LOOPS,
}
}
func (p *Parser) parse_var_declare(line int) any {
isConstant := (p.eat().tokenType == CONST)
identifier := p.expect(IDENTIFIER, "Expected identifier after var | const keyword").lexeme
if p.at().tokenType == SEMICOLON {
p.eat()
if isConstant {
Error(line, "Must assign value to const declared identifier "+identifier)
os.Exit(1)
}
return VarDeclaration{
kind: _VAR_DECLARE.String(),
constant: false,
identifier: identifier,
value: nil,
}
}
if isConstant {
p.expect(EQUAL, "Expected = following identifier "+identifier)
declaration := VarDeclaration{
kind: _VAR_DECLARE.String(),
constant: isConstant,
identifier: identifier,
value: p.parse_expr(line),
}
if p.at().tokenType == SEMICOLON {
p.eat()
}
return declaration
} else {
if p.at().tokenType == EQUAL {
p.eat()
declaration := VarDeclaration{
kind: _VAR_DECLARE.String(),
constant: isConstant,
identifier: identifier,
value: p.parse_expr(line),
}
if p.at().tokenType == SEMICOLON {
p.eat()
}
return declaration
} else {
return VarDeclaration{
kind: _VAR_DECLARE.String(),
constant: isConstant,
identifier: identifier,
value: NilLiteral{kind: _NIL_LITERAL.String(), value: "nil"},
}
}
}
}
func (p *Parser) parse_expr(line int) any {
return p.parse_assignment_expr(line)
}
func (p *Parser) parse_assignment_expr(line int) any {
left := p.parse_object_expr(line)
if p.at().tokenType == EQUAL {
p.eat()
value := p.parse_assignment_expr(line)
return AssignmentExpr{
kind: _ASSIGN_EXPR.String(),
assignee: left,
value: value,
}
}
return left
}
func (p *Parser) parse_object_expr(line int) any {
if p.at().tokenType != LEFT_BRACE {
return p.parse_array_expr(line)
}
p.eat()
properties := make([]Property, 0)
for p.not_eof() && p.at().tokenType != RIGHT_BRACE {
key := p.expect(IDENTIFIER, "Object key expected").lexeme
if p.at().tokenType == COMMA {
p.eat()
properties = append(properties, Property{kind: _PROPERTY.String(), key: key, value: nil})
continue
} else if p.at().tokenType == RIGHT_BRACE {
properties = append(properties, Property{kind: _PROPERTY.String(), key: key, value: nil})
continue
}
p.expect(COLON, "Object missing : after key")
value := p.parse_expr(line)
properties = append(properties, Property{kind: _PROPERTY.String(), key: key, value: value})
if p.at().tokenType != RIGHT_BRACE {
p.expect(COMMA, "Expected , or } after property")
}
}
p.expect(RIGHT_BRACE, "Object missing }")
return ObjectLiteral{
kind: _OBJECT_LITERAL.String(),
properties: properties,
}
}
func (p *Parser) parse_array_expr(line int) any {
if p.at().tokenType != LEFT_SQUARE {
return p.parse_function_expr(line)
}
p.eat()
arr := make([]any, 0)
for p.not_eof() && p.at().tokenType != RIGHT_SQUARE {
value := p.parse_expr(line)
arr = append(arr, value)
if p.at().tokenType != RIGHT_SQUARE {
p.expect(COMMA, "Expected , or ] after element")
}
}
p.expect(RIGHT_SQUARE, "Array missing ]")
return ArrayLiteral{
kind: _ARRAY_LITERAL.String(),
value: arr,
}
}
func (p *Parser) parse_function_expr(line int) any {
if p.at().tokenType != FN {
return p.parse_logical_not_expr(line)
}
p.eat()
name := p.expect(IDENTIFIER, "Expected identifier following fn").lexeme
args := p.parse_args(line)
params := make([]string, 0)
for _, arg := range args {
if reflect.TypeOf(arg).Name() != reflect.TypeOf(Identifier{}).Name() {
Error(line, "Inside function declaration expected parameter to be of type string")
os.Exit(1)
}
arg_typed := arg.(Identifier)
params = append(params, arg_typed.symbol)
}
p.expect(LEFT_BRACE, "Expected { after function indentifier")
body := make([]any, 0)
for p.at().tokenType != EOF && p.at().tokenType != RIGHT_BRACE {
body = append(body, p.parse_stmt(line))
}
p.expect(RIGHT_BRACE, "Expected } after function body")
fn := FunctionExpr{
kind: _FUNCTION_EXPR.String(),
name: name,
parameters: params,
body: body,
}
return fn
}
func (p *Parser) parse_logical_not_expr(line int) any {
if p.at().tokenType != BANG {
return p.parse_logical_and_or_expr(line)
}
var operator = p.eat().lexeme
var operand = p.parse_logical_and_or_expr(line)
return UnaryExpr{
kind: _BINARY_EXPR.String(),
operator: operator,
operand: operand,
}
}
func (p *Parser) parse_logical_and_or_expr(line int) any {
var left = p.parse_relational_equal_expr(line)
for p.at().tokenType == AND || p.at().tokenType == OR {
var operator string = p.eat().lexeme
var right = p.parse_relational_equal_expr(line)
left = BinaryExpr{
kind: _BINARY_EXPR.String(),
left: left,
right: right,
operator: operator,
}
}
return left
}
func (p *Parser) parse_relational_equal_expr(line int) any {
var left = p.parse_relational_greater_less_expr(line)
for p.at().tokenType == EQUAL_EQUAL || p.at().tokenType == BANG_EQUAL {
var operator string = p.eat().lexeme
var right = p.parse_relational_greater_less_expr(line)
left = BinaryExpr{
kind: _BINARY_EXPR.String(),
left: left,
right: right,
operator: operator,
}
}
return left
}
func (p *Parser) parse_relational_greater_less_expr(line int) any {
var left = p.parse_additive_expr(line)
for p.at().tokenType == GREATER || p.at().tokenType == GREATER_EQUAL || p.at().tokenType == LESS || p.at().tokenType == LESS_EQUAL || p.at().tokenType == LESS || p.at().tokenType == LESS_EQUAL {
var operator string = p.eat().lexeme
var right = p.parse_additive_expr(line)
left = BinaryExpr{
kind: _BINARY_EXPR.String(),
left: left,
right: right,
operator: operator,
}
}
return left
}
func (p *Parser) parse_additive_expr(line int) any {
var left = p.parse_multiplicative_expr(line)
for p.at().tokenType == PLUS || p.at().tokenType == MINUS {
var operator string = p.eat().lexeme
var right = p.parse_multiplicative_expr(line)
left = BinaryExpr{
kind: _BINARY_EXPR.String(),
left: left,
right: right,
operator: operator,
}
}
return left
}
func (p *Parser) parse_multiplicative_expr(line int) any {
var left = p.parse_call_member_expr(line)
for p.at().tokenType == STAR || p.at().tokenType == SLASH || p.at().tokenType == PERCENT {
var operator string = p.eat().lexeme
var right = p.parse_call_member_expr(line)
left = BinaryExpr{
kind: _BINARY_EXPR.String(),
left: left,
right: right,
operator: operator,
}
}
return left
}
func (p *Parser) parse_call_member_expr(line int) any {
member := p.parse_member_expr(line)
if p.at().tokenType == LEFT_PAREN {
member = p.parse_call_expr(line, member)
}
return member