-
Notifications
You must be signed in to change notification settings - Fork 11
/
littlelang.ll
1133 lines (1044 loc) · 28.1 KB
/
littlelang.ll
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
// A littlelang interpreter, written in littlelang
// ------------------------------------------------------------------
// Tokenizer
// ------------------------------------------------------------------
// Stop tokens
ILLEGAL = "ILLEGAL"
EOF = "EOF"
// Keywords
AND = "and"
ELSE = "else"
FALSE = "false"
FOR = "for"
FUNC = "func"
IF = "if"
IN = "in"
NIL = "nil"
NOT = "not"
OR = "or"
RETURN = "return"
TRUE = "true"
WHILE = "while"
// Single-character tokens
ASSIGN = "="
COLON = ":"
COMMA = ","
DIVIDE = "/"
DOT = "."
GT = ">"
LBRACE = "{"
LBRACKET = "["
LPAREN = "("
LT = "<"
MINUS = "-"
MODULO = "%"
PLUS = "+"
RBRACE = "}"
RBRACKET = "]"
RPAREN = ")"
TIMES = "*"
single_only_tokens = {}
for tok in [
COLON, COMMA, DIVIDE, LBRACE, LBRACKET, LPAREN, MINUS, MODULO, PLUS,
RBRACE, RBRACKET, RPAREN, TIMES,
] {
single_only_tokens[tok] = true
}
// Two-character tokens
EQUAL = "=="
GTE = ">="
LTE = "<="
NOTEQUAL = "!="
// Three-character tokens
ELLIPSIS = "..."
// Literals and identifiers
INT = "int"
NAME = "name"
STR = "str"
keyword_tokens = {
"and": true,
"else": true,
"false": true,
"for": true,
"func": true,
"if": true,
"in": true,
"nil": true,
"not": true,
"or": true,
"return": true,
"true": true,
"while": true,
}
func Pos(line, col) {
self = {}
self.line = line
self.col = col
return self
}
func Token(tok, val, pos) {
self = {}
self.tok = tok
self.val = val
self.pos = pos
return self
}
func is_name_start(ch) {
return ch == "_" or (ch >= "a" and ch <= "z") or (ch >= "A" and ch <= "Z")
}
// Tokenize source string and return list of Token objects
func tokenize(source) {
t = {}
t.offset = 0
t.line = 1
t.col = 1
t.nextLine = 1
t.nextCol = 1
t.ch = nil
func next() {
t.line = t.nextLine
t.col = t.nextCol
if t.offset >= len(source) {
t.ch = nil
return nil
}
t.ch = source[t.offset]
t.offset = t.offset + 1
if t.ch == "\n" {
t.nextLine = t.nextLine + 1
t.nextCol = 1
} else {
t.nextCol = t.nextCol + 1
}
}
func skip_whitespace_and_comments() {
while true {
while t.ch == " " or t.ch == "\t" or t.ch == "\r" or t.ch == "\n" {
next()
}
if not (t.ch == "/" and t.offset < len(source) and source[t.offset] == "/") {
return nil
}
// Skip //-prefixed comment (to end of line or end of input)
next()
next()
while t.ch != "\n" and t.ch != nil {
next()
}
next()
}
}
// Kick things off
tokens = []
next()
func end(tok, val, line, col) {
append(tokens, Token(tok, val, Pos(line, col)))
return tokens
}
while true {
skip_whitespace_and_comments()
if t.ch == nil {
return end(EOF, "", t.line, t.col)
}
val = ""
line = t.line
col = t.col
ch = t.ch
next()
if is_name_start(ch) {
chars = [ch]
while t.ch != nil and (is_name_start(t.ch) or (t.ch >= "0" and t.ch <= "9")) {
append(chars, t.ch)
next()
}
tok = join(chars, "")
if not tok in keyword_tokens {
val = tok
tok = NAME
}
} else if ch in single_only_tokens {
tok = ch
} else if ch == "=" {
if t.ch == "=" {
next()
tok = EQUAL
} else {
tok = ASSIGN
}
} else if ch == "!" {
if t.ch == "=" {
next()
tok = NOTEQUAL
} else {
return end(ILLEGAL, "expected != instead of !" + t.ch, line, col)
}
} else if ch == "<" {
if t.ch == "=" {
next()
tok = LTE
} else {
tok = LT
}
} else if ch == ">" {
if t.ch == "=" {
next()
tok = GTE
} else {
tok = GT
}
} else if ch == "." {
if t.ch == "." {
next()
if t.ch != "." {
return end(ILLEGAL, "unexpected ..", line, col)
}
next()
tok = ELLIPSIS
} else {
tok = DOT
}
} else if ch >= "0" and ch <= "9" {
chars = [ch]
while t.ch != nil and t.ch >= "0" and t.ch <= "9" {
append(chars, t.ch)
next()
}
tok = INT
val = int(join(chars, ""))
} else if ch == "\"" {
chars = []
while t.ch != "\"" {
c = t.ch
if c == nil {
return end(ILLEGAL, "didn't find end quote in string", line, col)
}
if c == "\r" or c == "\n" {
return end(ILLEGAL, "can't have newline in string", line, col)
}
if c == "\\" {
next()
if t.ch == "\"" or t.ch == "\\" {
c = t.ch
} else if t.ch == "t" {
c = "\t"
} else if t.ch == "r" {
c = "\r"
} else if t.ch == "n" {
c = "\n"
} else {
return end(ILLEGAL, "invalid string escape \\" + t.ch, line, col)
}
}
append(chars, c)
next()
}
next()
tok = STR
val = join(chars, "")
} else {
return end(ILLEGAL, "unexpected " + ch, line, col)
}
append(tokens, Token(tok, val, Pos(line, col)))
}
}
// ------------------------------------------------------------------
// AST node help functions (node.str() converts node back to source string)
// ------------------------------------------------------------------
func indent(s) {
lines = split(s, "\n")
output = []
for line in lines {
append(output, " " + line)
}
return join(output, "\n")
}
func Node(type, pos) {
self = {}
self.type = type
self.pos = pos
return self
}
func Program(pos, body) {
self = Node("Program", pos)
self.body = body
self.str = func() {
return self.body.str()
}
return self
}
func Block(pos, statements) {
self = Node("Block", pos)
self.statements = statements
self.str = func() {
lines = []
for statement in self.statements {
append(lines, statement.str())
}
return join(lines, "\n")
}
return self
}
func Assign(pos, target, value) {
self = Node("Assign", pos)
self.target = target
self.value = value
self.str = func() {
return self.target.str() + " = " + self.value.str()
}
return self
}
func If(pos, condition, body, else_body) {
self = Node("If", pos)
self.condition = condition
self.body = body
self.else_body = else_body
self.str = func() {
s = "if " + self.condition.str() + " {\n" + indent(self.body.str()) + "\n}"
if self.else_body != nil {
s = s + " else {\n" + indent(self.else_body.str()) + "\n}"
}
return s
}
return self
}
func While(pos, condition, body) {
self = Node("While", pos)
self.condition = condition
self.body = body
self.str = func() {
return "while " + self.condition.str() + " {\n" + indent(self.body.str()) + "\n}"
}
return self
}
func For(pos, name, iterable, body) {
self = Node("For", pos)
self.name = name
self.iterable = iterable
self.body = body
self.str = func() {
return "for " + self.name + " in " + self.iterable.str() + " {\n" + indent(self.body.str()) + "\n}"
}
return self
}
func Return(pos, result) {
self = Node("Return", pos)
self.result = result
self.str = func() {
return "return " + self.result.str()
}
return self
}
func ExpressionStatement(pos, expr) {
self = Node("ExpressionStatement", pos)
self.expr = expr
self.str = func() {
return self.expr.str()
}
return self
}
func FunctionDefinition(pos, name, params, ellipsis, body) {
self = Node("FunctionDefinition", pos)
self.name = name
self.params = params
self.ellipsis = ellipsis
self.body = body
self.str = func() {
ellipsis_str = ""
if self.ellipsis {
ellipsis_str = "..."
}
body_str = ""
if len(self.body) != 0 {
body_str = "\n" + indent(self.body.str()) + "\n"
}
return "func " + self.name + "(" + join(self.params, ", ") + ellipsis_str + ") {" + body_str + "}"
}
return self
}
func Binary(pos, left, op, right) {
self = Node("Binary", pos)
self.left = left
self.op = op
self.right = right
self.str = func() {
return "(" + self.left.str() + " " + self.op + " " + self.right.str() + ")"
}
return self
}
func Unary(pos, operator, operand) {
self = Node("Unary", pos)
self.operator = operator
self.operand = operand
self.str = func() {
space = ""
if self.operator == NOT {
space = " "
}
return "(" + self.operator + space + self.operand.str() + ")"
}
return self
}
func Call(pos, function, args, ellipsis) {
self = Node("Call", pos)
self.function = function
self.args = args
self.ellipsis = ellipsis
self.str = func() {
args = []
for arg in self.args {
append(args, arg.str())
}
ellipsis_str = ""
if self.ellipsis {
ellipsis_str = "..."
}
return self.function.str() + "(" + join(args, ", ") + ellipsis_str + ")"
}
return self
}
func Literal(pos, value) {
self = Node("Literal", pos)
self.value = value
self.str = func() {
if type(self.value) == "str" {
quoted = str([self.value])
quoted = slice(quoted, 1, len(quoted)-1)
return quoted
}
return str(self.value)
}
return self
}
func List(pos, values) {
self = Node("List", pos)
self.values = values
self.str = func() {
values = []
for value in self.values {
append(values, value.str())
}
return "[" + join(values, ", ") + "]"
}
return self
}
func Map(pos, items) {
self = Node("Map", pos)
self.items = items
self.str = func() {
items = []
for item in self.items {
append(items, item[0].str() + ": " + item[1].str())
}
return "{" + join(items, ", ") + "}"
}
return self
}
func FunctionExpression(pos, params, ellipsis, body) {
self = Node("FunctionExpression", pos)
self.params = params
self.ellipsis = ellipsis
self.body = body
self.str = func() {
ellipsis_str = ""
if self.ellipsis {
ellipsis_str = "..."
}
body_str = ""
if len(self.body) != 0 {
body_str = "\n" + indent(self.body.str()) + "\n"
}
return "func(" + join(self.params, ", ") + ellipsis_str + ") {" + body_str + "}"
}
return self
}
func Subscript(pos, container, subscript) {
self = Node("Subscript", pos)
self.container = container
self.subscript = subscript
self.str = func() {
return self.container.str() + "[" + self.subscript.str() + "]"
}
return self
}
func Variable(pos, name) {
self = Node("Variable", pos)
self.name = name
self.str = func() {
return self.name
}
return self
}
// ------------------------------------------------------------------
// Parser
// ------------------------------------------------------------------
// Parse source string and return a Program node
func parse(source) {
p = {}
p.tokens = tokenize(source)
p.offset = 0
p.tok = nil
p.val = nil
p.pos = nil
func error(msg) {
print("parse error at " + str(p.pos.line) + ":" + str(p.pos.col) + ": " + msg)
exit(1)
}
func next() {
token = p.tokens[p.offset]
p.offset = p.offset + 1
p.tok = token.tok
p.val = token.val
p.pos = token.pos
if p.tok == ILLEGAL {
error(p.val)
}
}
func expect(tok) {
if p.tok != tok {
error("expected " + tok + " and not " + p.tok)
}
next()
}
func matches(operators...) {
for operator in operators {
if p.tok == operator {
return true
}
}
return false
}
func program() {
pos = p.pos
return Program(pos, statements(EOF))
}
func statements(end) {
pos = p.pos
statement_list = []
while p.tok != end and p.tok != EOF {
append(statement_list, statement())
}
return Block(pos, statement_list)
}
func statement() {
if p.tok == IF {
return if_()
} else if p.tok == WHILE {
return while_()
} else if p.tok == FOR {
return for_()
} else if p.tok == RETURN {
return return_()
} else if p.tok == FUNC {
return func_()
}
pos = p.pos
expr = expression()
if p.tok == ASSIGN {
pos = p.pos
if expr.type == "Variable" or expr.type == "Subscript" {
next()
value = expression()
return Assign(pos, expr, value)
} else {
error("expected name, subscript, or dot expression on left side of =")
}
}
return ExpressionStatement(pos, expr)
}
func block() {
expect(LBRACE)
body = statements(RBRACE)
expect(RBRACE)
return body
}
func if_() {
pos = p.pos
expect(IF)
condition = expression()
body = block()
else_body = nil
if p.tok == ELSE {
next()
if p.tok == LBRACE {
else_body = block()
} else if p.tok == IF {
else_body = Block(p.pos, [if_()])
} else {
error("expected { or if after else, not " + p.tok)
}
}
return If(pos, condition, body, else_body)
}
func while_() {
pos = p.pos
expect(WHILE)
condition = expression()
body = block()
return While(pos, condition, body)
}
func for_() {
pos = p.pos
expect(FOR)
name = p.val
expect(NAME)
expect(IN)
iterable = expression()
body = block()
return For(pos, name, iterable, body)
}
func return_() {
pos = p.pos
expect(RETURN)
result = expression()
return Return(pos, result)
}
func func_() {
pos = p.pos
expect(FUNC)
if p.tok == NAME {
name = p.val
next()
params_ellipsis = params()
body = block()
return FunctionDefinition(pos, name, params_ellipsis[0], params_ellipsis[1], body)
} else {
params_ellipsis = params()
body = block()
expr = FunctionExpression(pos, params_ellipsis[0], params_ellipsis[1], body)
return ExpressionStatement(pos, expr)
}
}
func params() {
expect(LPAREN)
params = []
got_comma = true
got_ellipsis = false
while p.tok != RPAREN and p.tok != EOF and not got_ellipsis {
if not got_comma {
error("expected , between parameters")
}
param = p.val
expect(NAME)
append(params, param)
if p.tok == ELLIPSIS {
got_ellipsis = true
next()
}
if p.tok == COMMA {
got_comma = true
next()
} else {
got_comma = false
}
}
if p.tok != RPAREN and got_ellipsis {
error("can only have ... after last parameter")
}
expect(RPAREN)
return [params, got_ellipsis]
}
func binary(parse_expr, operators...) {
expr = parse_expr()
while matches(operators...) {
op = p.tok
pos = p.pos
next()
right = parse_expr()
expr = Binary(pos, expr, op, right)
}
return expr
}
func expression() {
return binary(and_, OR)
}
func and_() {
return binary(not_, AND)
}
func not_() {
if p.tok == NOT {
pos = p.pos
next()
operand = not_()
return Unary(pos, NOT, operand)
}
return equality()
}
func equality() {
return binary(comparison, EQUAL, NOTEQUAL)
}
func comparison() {
return binary(addition, LT, LTE, GT, GTE, IN)
}
func addition() {
return binary(multiply, PLUS, MINUS)
}
func multiply() {
return binary(negative, TIMES, DIVIDE, MODULO)
}
func negative() {
if p.tok == MINUS {
pos = p.pos
next()
operand = negative()
return Unary(pos, MINUS, operand)
}
return call()
}
func call() {
expr = primary()
while matches(LPAREN, LBRACKET, DOT) {
if p.tok == LPAREN {
pos = p.pos
next()
args = []
got_comma = true
got_ellipsis = false
while p.tok != RPAREN and p.tok != EOF and not got_ellipsis {
if not got_comma {
error("expected , between arguments")
}
arg = expression()
append(args, arg)
if p.tok == ELLIPSIS {
got_ellipsis = true
next()
}
if p.tok == COMMA {
got_comma = true
next()
} else {
got_comma = false
}
}
if p.tok != RPAREN and got_ellipsis {
error("can only have ... after last argument")
}
expect(RPAREN)
expr = Call(pos, expr, args, got_ellipsis)
} else if p.tok == LBRACKET {
pos = p.pos
next()
subscript = expression()
expect(RBRACKET)
expr = Subscript(pos, expr, subscript)
} else {
pos = p.pos
next()
subscript = Literal(p.pos, p.val)
expect(NAME)
expr = Subscript(pos, expr, subscript)
}
}
return expr
}
func primary() {
if p.tok == NAME {
name = p.val
pos = p.pos
next()
return Variable(pos, name)
} else if p.tok == INT or p.tok == STR {
val = p.val
pos = p.pos
next()
return Literal(pos, val)
} else if p.tok == TRUE {
pos = p.pos
next()
return Literal(pos, true)
} else if p.tok == FALSE {
pos = p.pos
next()
return Literal(pos, false)
} else if p.tok == NIL {
pos = p.pos
next()
return Literal(pos, nil)
} else if p.tok == LBRACKET {
return list()
} else if p.tok == LBRACE {
return map()
} else if p.tok == FUNC {
pos = p.pos
next()
params_ellipsis = params()
body = block()
return FunctionExpression(pos, params_ellipsis[0], params_ellipsis[1], body)
} else if p.tok == LPAREN {
next()
expr = expression()
expect(RPAREN)
return expr
} else {
error("expected expression, not " + p.tok)
}
}
func list() {
pos = p.pos
expect(LBRACKET)
values = []
got_comma = true
while p.tok != RBRACKET and p.tok != EOF {
if not got_comma {
error("expected , between list elements")
}
value = expression()
append(values, value)
if p.tok == COMMA {
got_comma = true
next()
} else {
got_comma = false
}
}
expect(RBRACKET)
return List(pos, values)
}
func map() {
pos = p.pos
expect(LBRACE)
items = []
got_comma = true
while p.tok != RBRACE and p.tok != EOF {
if not got_comma {
error("expected , between map items")
}
key = expression()
expect(COLON)
value = expression()
append(items, [key, value])
if p.tok == COMMA {
got_comma = true
next()
} else {
got_comma = false
}
}
expect(RBRACE)
return Map(pos, items)
}
next()
return program()
}
// ------------------------------------------------------------------
// Interpreter
// ------------------------------------------------------------------
binary_funcs = {
DIVIDE: func(l, r) { return l / r },
EQUAL: func(l, r) { return l == r },
GT: func(l, r) { return l > r },
GTE: func(l, r) { return l >= r },
IN: func(l, r) { return l in r },
LT: func(l, r) { return l < r },
LTE: func(l, r) { return l <= r },
MINUS: func(l, r) { return l - r },
MODULO: func(l, r) { return l % r },
NOTEQUAL: func(l, r) { return l != r },
PLUS: func(l, r) { return l + r },
TIMES: func(l, r) { return l * r },
}
unary_funcs = {
MINUS: func(v) { return -v },
NOT: func(v) { return not v },
}
// Remove the first arg (source filename) from target's args()
_args = args()
func args() {
return slice(_args, 1, len(_args))
}
builtins = {
"append": append,
"args": args,
"char": char,
"exit": exit,
"find": find,
"int": int,
"join": join,
"len": len,
"lower": lower,
"print": print,
"range": range,
"read": read,
"rune": rune,
"slice": slice,
"sort": sort,
"split": split,
"str": str,
"type": type,
"upper": upper,
}
func execute(program) {
interp = {}
interp.vars = []
func error(msg) {
print("execute error : " + msg)
exit(1)
}
func push_scope(scope) {
append(interp.vars, scope)
}
func pop_scope() {
interp.vars = slice(interp.vars, 0, len(interp.vars)-1)
}
func assign(name, value) {
interp.vars[len(interp.vars)-1][name] = value
}
func lookup(name) {
i = len(interp.vars) - 1
while i >= 0 {
vars = interp.vars[i]
if name in vars {
return [vars[name], true]
}
i = i - 1
}
return [nil, false]
}
func user_function(name, params, ellipsis, body, closure) {
f = func(args...) {
if ellipsis {
ellipsis_args = slice(args, len(params)-1, len(args))
new_args = slice(args, 0, len(params)-1)
append(new_args, ellipsis_args)
args = new_args
}
push_scope(closure)
push_scope({})
for i in range(len(args)) {
assign(params[i], args[i])
}
r = execute_block(body)
pop_scope()
pop_scope()
if r != nil {
return r[0]
}
}