-
Notifications
You must be signed in to change notification settings - Fork 3
/
Interpreter.java
1454 lines (1203 loc) · 46.1 KB
/
Interpreter.java
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
import java.util.ArrayList;
import java.util.HashMap;
/**
* @author Mikail Khan <mikail@mikail-khan.com>
* @version 0.1.0
*
* An Atom is any discrete variable, literal or not
*
* <p>
* It's worth noting that this is a significant reason why the
* interpreter is so slow; each Atom has a whole lot of space and time
* overhead because of how Java stores things. Because of this
* optimization is not a priority. To get around this, we could use a
* bytecode interpreter which would be orders of magnitude faster but a
* bit more complex.
* </p>
*/
abstract class Atom {
public static class Val extends Atom {
int val;
public Val(int val) {
this.val = val;
}
public String toString() {
return String.valueOf(val);
}
}
public static class Bool extends Atom {
boolean val;
public Bool(boolean val) {
this.val = val;
}
public String toString() {
return String.valueOf(val);
}
}
public static class Char extends Atom {
char val;
public Char(char val) {
this.val = val;
}
public String toString() {
return '\'' + String.valueOf(val) + '\'';
}
}
public static class List extends Atom {
ArrayList<Expr> list;
public List(ArrayList<Expr> list) {
this.list = list;
}
private boolean isCharArray() {
for(int i = 0; i < list.size(); i++) {
Expr e = list.get(i);
if (!(e instanceof Expr.AtomicExpr && ((Expr.AtomicExpr)e).val instanceof Atom.Char)) return false;
}
return true;
}
private String formatAsString() {
assert isCharArray();
String result = "\"";
for(int i = 0; i < list.size(); i++) {
result += ((Atom.Char)((Expr.AtomicExpr)list.get(i)).val).val;
}
return result + '"';
}
public String toString() {
if (isCharArray()) return formatAsString();
return list.toString();
}
}
public static class Str extends List {
private static ArrayList<Expr> split(String val) {
ArrayList<Expr> list = new ArrayList<Expr>();
for(int i = 0; i < val.length(); i++) {
list.add(new Expr.AtomicExpr(new Atom.Char(val.charAt(i))));
}
return list;
}
public Str(String val) {
super(split(val));
}
}
public static class Ident extends Atom {
String name;
public Ident(String name) {
this.name = name;
}
public String toString() {
return String.format("\"%s\"", name);
}
}
public static class Lambda extends Atom {
Expr expr;
ArrayList<String> argNames;
public Lambda(Expr expr, ArrayList<String> argNames) {
this.expr = expr;
this.argNames = argNames;
}
public String toString() {
return String.format("Lambda {expr: %s, argNames: %s}", expr.toString(), argNames.toString());
}
}
public static class Unit extends Atom {
public Unit() {
}
public String toString() {
return String.format("()");
}
}
public Atom add(Atom rhs) throws Exception {
if ((this instanceof Val) && (rhs instanceof Val)) {
return (Atom) new Val(((Val) this).val + ((Val) rhs).val);
} else if ((this instanceof List) && (rhs instanceof List)) {
List lArr = (List) this;
List rArr = (List) rhs;
List newList = new List(new ArrayList<Expr>());
newList.list.addAll(lArr.list);
newList.list.addAll(rArr.list);
return (Atom) newList;
} else {
throw new Exception("Badd");
}
}
public Atom sub(Atom rhs) throws Exception {
if ((this instanceof Val) && (rhs instanceof Val)) {
return (Atom) new Val(((Val) this).val - ((Val) rhs).val);
} else {
throw new Exception("Bad Sub");
}
}
public Atom mul(Atom rhs) throws Exception {
if ((this instanceof Val) && (rhs instanceof Val)) {
return (Atom) new Val(((Val) this).val * ((Val) rhs).val);
} else {
throw new Exception("Bad Mul");
}
}
public Atom div(Atom rhs) throws Exception {
if ((this instanceof Val) && (rhs instanceof Val)) {
return (Atom) new Val(((Val) this).val / ((Val) rhs).val);
} else {
throw new Exception("Bad Div");
}
}
public Atom mod(Atom rhs) throws Exception {
if ((this instanceof Val) && (rhs instanceof Val)) {
return (Atom) new Val(((Val) this).val % ((Val) rhs).val);
} else {
throw new Exception("Bad Mod");
}
}
public Atom lt(Atom rhs) throws Exception {
if ((this instanceof Val) && (rhs instanceof Val)) {
return (Atom) new Bool(((Val) this).val < ((Val) rhs).val);
} else {
throw new Exception("Bad Cmp");
}
}
public Atom gt(Atom rhs) throws Exception {
if ((this instanceof Val) && (rhs instanceof Val)) {
return (Atom) new Bool(((Val) this).val > ((Val) rhs).val);
} else {
throw new Exception("Bad Cmp");
}
}
public Atom eq(Atom rhs) throws Exception {
if ((this instanceof Val) && (rhs instanceof Val)) {
return (Atom) new Bool(((Val) this).val == ((Val) rhs).val);
}
else if (this instanceof Bool || rhs instanceof Bool) {
return (Atom) new Bool(this.isTruthy() == rhs.isTruthy());
}
else {
throw new Exception("Bad Cmp");
}
}
public Atom negate() throws Exception {
if (this instanceof Val) {
Val v = (Val) this;
return (Atom) new Val(-v.val);
}
else if (this instanceof Bool) {
Bool b = (Bool) this;
return (Atom) new Bool(!b.val);
}
else {
throw new Exception("Bad Negate");
}
}
public Atom head(HashMap<String, Atom> variables) throws Exception {
if (this instanceof List) {
List ls = (List) this;
return (Atom) ls.list.get(0).eval(variables);
} else {
throw new Exception("Bad Head");
}
}
public Atom tail(HashMap<String, Atom> variables) throws Exception {
if (this instanceof List) {
List ls = (List) this;
ArrayList<Expr> nls = new ArrayList<>(ls.list.subList(1, ls.list.size()));
return (Atom) new List(nls);
} else {
throw new Exception("Bad Tail");
}
}
public boolean isTruthy() throws Exception {
if (this instanceof Bool) {
Bool v = (Bool) this;
return v.val;
} else if (this instanceof List) {
List ls = (List) this;
return !ls.list.isEmpty();
} else {
throw new Exception(String.format("Can't coerce %s to a boolean", this.toString()));
}
}
public Atom and(Atom rhs) throws Exception {
if (this instanceof Bool && rhs instanceof Bool) {
Bool lhs = (Bool) this;
Bool other = (Bool) rhs;
return new Bool(lhs.val && other.val);
} else {
throw new Exception(String.format("Can't coerce %s to a boolean", this.toString()));
}
}
public Atom or(Atom rhs) throws Exception {
if (this instanceof Bool && rhs instanceof Bool) {
Bool lhs = (Bool) this;
Bool other = (Bool) rhs;
return new Bool(lhs.val || other.val);
} else {
throw new Exception(String.format("Can't coerce %s to a boolean", this.toString()));
}
}
}
/**
* @author Mikail Khan <mikail@mikail-khan.com>
* @version 0.1.0
*
* An expression, the AST of this language.
*
* <p>
* Because this is a functional expression based language, there are no
* statements, only expressions. In other words, everything returns
* something, even if it's just the unit type.
* </p>
*/
abstract class Expr {
abstract Atom eval(HashMap<String, Atom> variables) throws Exception;
public static class AtomicExpr extends Expr {
Atom val;
Atom eval(HashMap<String, Atom> variables) throws Exception {
if (val instanceof Atom.Ident) {
Atom.Ident v = (Atom.Ident) val;
var res = variables.get(v.name);
if (res == null) {
throw new Exception(String.format("Tried to access nonexistent variable %s", v.name));
}
return res;
} else if (val instanceof Atom.List) {
Atom.List ls = (Atom.List) val;
ArrayList<Expr> nls = new ArrayList<>();
for (Expr expr : ls.list) {
nls.add(new AtomicExpr(expr.eval(variables)));
}
return new Atom.List(nls);
} else {
return val;
}
}
public AtomicExpr(Atom val) {
this.val = val;
}
public String toString() {
return String.valueOf(val);
}
}
public static class PrefixExpr extends Expr {
PrefixOp op;
Expr rhs;
Atom eval(HashMap<String, Atom> variables) throws Exception {
return switch (op) {
case Negate -> rhs.eval(variables).negate();
case Head -> rhs.eval(variables).head(variables);
case Tail -> rhs.eval(variables).tail(variables);
};
}
public PrefixExpr(PrefixOp op, Expr rhs) {
this.op = op;
this.rhs = rhs;
}
public String toString() {
return String.format("%s (%s)", op.toString(), rhs.toString());
}
}
public static class BinaryExpr extends Expr {
BinOp op;
Expr lhs;
Expr rhs;
Atom eval(HashMap<String, Atom> variables) throws Exception {
return switch (op) {
case Add -> lhs.eval(variables).add(rhs.eval(variables));
case Sub -> lhs.eval(variables).sub(rhs.eval(variables));
case Mul -> lhs.eval(variables).mul(rhs.eval(variables));
case Div -> lhs.eval(variables).div(rhs.eval(variables));
case Mod -> lhs.eval(variables).mod(rhs.eval(variables));
case LT -> lhs.eval(variables).lt(rhs.eval(variables));
case GT -> lhs.eval(variables).gt(rhs.eval(variables));
case EQ -> lhs.eval(variables).eq(rhs.eval(variables));
case And -> lhs.eval(variables).and(rhs.eval(variables));
case Or -> lhs.eval(variables).or(rhs.eval(variables));
};
}
public BinaryExpr(BinOp op, Expr lhs, Expr rhs) {
this.op = op;
this.lhs = lhs;
this.rhs = rhs;
}
public BinaryExpr(BinOp op, Atom lhs, Atom rhs) {
this.op = op;
this.lhs = new AtomicExpr(lhs);
this.rhs = new AtomicExpr(rhs);
}
public String toString() {
return String.format("%s, (%s, %s)", op.toString(), lhs.toString(), rhs.toString());
}
}
public static class IfExpr extends Expr {
Expr cond;
Expr lhs;
Expr rhs;
Atom eval(HashMap<String, Atom> variables) throws Exception {
Atom condVal = cond.eval(variables);
if (condVal.isTruthy()) {
return lhs.eval(variables);
} else {
return rhs.eval(variables);
}
}
public IfExpr(Expr cond, Expr lhs, Expr rhs) {
this.cond = cond;
this.lhs = lhs;
this.rhs = rhs;
}
public String toString() {
return String.format("if (%s) then (%s) else (%s)", cond.toString(), lhs.toString(), rhs.toString());
}
}
public static class LambdaCall extends Expr {
String name;
ArrayList<Expr> variables;
Atom eval(HashMap<String, Atom> variables) throws Exception {
HashMap<String, Atom> evaledVariables = new HashMap<>();
evaledVariables.putAll(variables);
Atom.Lambda lambda = ((Atom.Lambda) evaledVariables.get(this.name));
if (lambda == null) {
throw new Exception(String.format("Undefined lambda '%s'", this.name));
}
ArrayList<String> argNames = lambda.argNames;
if (this.variables.size() != lambda.argNames.size()) {
throw new Exception(String.format("Expected %d arguments to call of lambda %s, got %d",
lambda.argNames.size(), name, this.variables.size()));
}
for (int i = 0; i < argNames.size(); i += 1) {
evaledVariables.put(argNames.get(i), this.variables.get(i).eval(variables));
}
Expr expr = lambda.expr;
return expr.eval(evaledVariables);
}
public LambdaCall(String name) {
this.name = name;
}
public LambdaCall(String name, ArrayList<Expr> variables) {
this.name = name;
this.variables = variables;
}
public String toString() {
return String.format("%s(%s)", name, variables.toString());
}
}
public static class AssignExpr extends Expr {
String lhs;
Expr rhs;
Atom eval(HashMap<String, Atom> variables) throws Exception {
variables.put(lhs, rhs.eval(variables));
return new Atom.Unit();
}
public AssignExpr(String lhs, Expr rhs) {
this.lhs = lhs;
this.rhs = rhs;
}
public String toString() {
return String.format("let %s = %s", lhs, rhs.toString());
}
}
public static void testExpr() throws Exception {
// all the eval methods are mutually recursive but since it's essentially a tree
// instead of a potentially cyclic graph it *is* possible to test them all
// individually
HashMap<String, Atom> emptyScope = new HashMap<>();
AtomicExpr e1 = new AtomicExpr(new Atom.Val(1));
assert ((Atom.Val) e1.eval(emptyScope)).val == 1;
HashMap<String, Atom> piScope = new HashMap<>();
piScope.put("pi", new Atom.Val(3));
AtomicExpr e2 = new AtomicExpr(new Atom.Ident("pi"));
assert ((Atom.Val) e2.eval(piScope)).val == 3;
PrefixExpr e3 = new PrefixExpr(PrefixOp.Negate, new AtomicExpr(new Atom.Val(3)));
assert ((Atom.Val) e3.eval(emptyScope)).val == -3;
BinaryExpr e4 = new BinaryExpr(BinOp.Add, new Atom.Val(10), new Atom.Val(20));
assert ((Atom.Val) e4.eval(emptyScope)).val == 30;
IfExpr e5 = new IfExpr(new AtomicExpr(new Atom.Bool(false)), new AtomicExpr(new Atom.Val(10)),
new AtomicExpr(new Atom.Val(20)));
assert ((Atom.Val) e5.eval(emptyScope)).val == 20;
IfExpr e6 = new IfExpr(new AtomicExpr(new Atom.Bool(true)), new AtomicExpr(new Atom.Val(10)),
new AtomicExpr(new Atom.Val(20)));
assert ((Atom.Val) e6.eval(emptyScope)).val == 10;
HashMap<String, Atom> lambdaScope = new HashMap<>();
AtomicExpr fib = (AtomicExpr) Parser.parseExpr("fn (n) => if (n < 2) then (1) else (fib(n - 1) + fib(n - 2))");
AtomicExpr add = (AtomicExpr) Parser.parseExpr("fn (start, end) => start + end");
lambdaScope.put("fib", fib.val);
lambdaScope.put("add", add.val);
LambdaCall e7 = (LambdaCall) Parser.parseExpr("fib(10)");
LambdaCall e8 = (LambdaCall) Parser.parseExpr("add(5, 10)");
assert ((Atom.Val) e7.eval(lambdaScope)).val == 89;
assert ((Atom.Val) e8.eval(lambdaScope)).val == 15;
HashMap<String, Atom> newScope = new HashMap<>();
AssignExpr e9 = (AssignExpr) Parser.parseExpr("let x = 15");
e9.eval(newScope);
assert ((Atom.Val) newScope.get("x")).val == 15;
AssignExpr e10 = (AssignExpr) Parser.parseExpr("let x = x * x");
e10.eval(newScope);
assert ((Atom.Val) newScope.get("x")).val == 15 * 15;
}
}
enum BinOp {
Add, Sub, Mul, Div,
LT, GT, EQ,
And, Or,
Mod,
}
enum PrefixOp {
Negate,
Head, Tail,
}
enum TokenTy {
LParen, RParen,
LBracket, RBracket,
Ident, Number, Character, String, True, False,
Add, Sub, Mul, Div, Mod,
EQ, LT, GT,
And, Or,
If, Then, Else,
Let, Assign, Comma,
Caret, Dollar,
Fn, Arrow,
For, In, DotDot,
EOF,
}
/**
* @author Mikail Khan <mikail@mikail-khan.com>
* @version 0.1.0
*
* A token
*
* <p>
* A token represents a basic building block of the flat structure of
* the language. They're easier to work with than characters.
* </p>
*/
class Token {
TokenTy ty;
String lexeme;
public Token(TokenTy ty, String lexeme) {
this.ty = ty;
this.lexeme = lexeme;
}
public static Token EOF() {
return new Token(TokenTy.EOF, null);
}
public String toString() {
return switch (ty) {
case Ident -> String.format("Ident '%s'", lexeme);
case Number -> String.format("Number %s", lexeme);
default -> String.format("%s", ty.toString());
};
}
}
/**
* @author Mikail Khan <mikail@mikail-khan.com>
* @version 0.1.0
*
* The Tokenizer takes a String and turns it into a flat list of
* Tokens.
*
*/
class Tokenizer {
private String input;
private int position;
private ArrayList<Token> output;
private Tokenizer(String input) {
this.input = input;
this.position = 0;
this.output = new ArrayList<Token>();
}
private boolean isFinished() {
return this.position >= this.input.length();
}
private char peek() {
return input.charAt(position);
}
private char eat() {
char ret = input.charAt(position);
position += 1;
return ret;
}
private boolean expect(char expected) {
char c = input.charAt(position);
if (c == expected) {
position += 1;
return true;
} else {
return false;
}
}
private void addToken(Token t) {
this.output.add(t);
}
private void addToken(TokenTy ty, char lexeme) {
addToken(new Token(ty, String.valueOf(lexeme)));
}
private void addToken(TokenTy ty, String lexeme) {
addToken(new Token(ty, lexeme));
}
private void scanIdent() {
int start = position;
while (!isFinished() && (Character.isAlphabetic(peek()) || Character.isDigit(peek()) || peek() == '_')) {
eat();
}
String lexeme = input.substring(start, position);
switch (lexeme) {
case "if" -> addToken(new Token(TokenTy.If, lexeme));
case "then" -> addToken(new Token(TokenTy.Then, lexeme));
case "else" -> addToken(new Token(TokenTy.Else, lexeme));
case "let" -> addToken(new Token(TokenTy.Let, lexeme));
case "fn" -> addToken(new Token(TokenTy.Fn, lexeme));
case "for" -> addToken(new Token(TokenTy.For, lexeme));
case "in" -> addToken(new Token(TokenTy.In, lexeme));
case "true" -> addToken(new Token(TokenTy.True, lexeme));
case "false" -> addToken(new Token(TokenTy.False, lexeme));
default -> addToken(new Token(TokenTy.Ident, lexeme));
}
}
private void scanNumber() {
int start = position;
while (!isFinished() && Character.isDigit(peek())) {
eat();
}
String lexeme = input.substring(start, position);
addToken(new Token(TokenTy.Number, lexeme));
}
private static boolean isHex(char c) {
return Character.isDigit(c) || (c >= 'A' && c <= 'F');
}
private static boolean isHex(String s) {
for(int i = 0; i < s.length(); i++) {
if (!isHex(s.charAt(i))) return false;
}
return true;
}
private String unescaper(String sequence) {
// TODO: Implement unescaper for: https://en.wikipedia.org/wiki/Escape_character
// * Octal (\1 to \377)
// * Unicode: https://en.wikipedia.org/wiki/List_of_Unicode_characters https://www.rapidtables.com/code/text/unicode-characters.html
// * Control characters: https://en.wikipedia.org/wiki/Control_character
// * Whitespace characters: https://en.wikipedia.org/wiki/Whitespace_character
String result = "";
for(int p = 0; p < sequence.length(); p++) {
char c = sequence.charAt(p);
if (c == '\\') {
p++;
String remaining = sequence.substring(p);
if (remaining.length() >= 5 && remaining.charAt(0) == 'u' && isHex(remaining.substring(1, 5))) {
char unicodeChar = (char)Integer.parseInt(remaining.substring(1, 5), 16);
result += unicodeChar;
p += 4; // p will increment before next iteration
}
else {
result += remaining.charAt(0);
}
}
else result += c;
}
return result;
}
private void scanCharacter() throws Exception {
expect('\''); // Will always match
int start = position;
boolean escaped;
while (!isFinished() && peek() != '\'') {
escaped = peek() == '\\';
eat();
if (escaped && (peek() == '\'' || peek() == '\\')) eat(); // eat escaped apostrophes or backslashes
}
if (start == position) throw new Exception("Missing character, '' is not valid.");
String lexeme = input.substring(start, position);
if (!isFinished() && peek() == '\'') eat();
else throw new Exception("Found character with a missing closing apostrophe, did you mean '" + lexeme + "'?");
String characters = unescaper(lexeme);
if (characters.length() > 1) throw new Exception("Found invalid character, did you mean \"" + characters + "\"?");
char character = characters.charAt(0);
addToken(new Token(TokenTy.Character, "" + character));
}
private void scanString() throws Exception {
expect('"'); // Will always match
int start = position;
boolean escaped;
while (!isFinished() && peek() != '"') {
escaped = peek() == '\\';
eat();
if (escaped && (peek() == '\"' || peek() == '\\')) eat(); // eat escaped apostrophes or backslashes
}
String lexeme = input.substring(start, position);
if (!isFinished() && peek() == '"') eat();
else throw new Exception("Found string with a missing closing quotation mark, did you mean \"" + lexeme + "\"?");
String string = unescaper(lexeme);
addToken(new Token(TokenTy.String, string));
}
private void addNextToken() throws Exception {
char c = eat();
switch (c) {
case ' ' -> addNextToken();
case '(' -> addToken(TokenTy.LParen, c);
case ')' -> addToken(TokenTy.RParen, c);
case '[' -> addToken(TokenTy.LBracket, c);
case ']' -> addToken(TokenTy.RBracket, c);
case '+' -> addToken(TokenTy.Add, c);
case '-' -> addToken(TokenTy.Sub, c);
case '*' -> addToken(TokenTy.Mul, c);
case '%' -> addToken(TokenTy.Mod, c);
case '/' -> addToken(TokenTy.Div, c);
case '<' -> addToken(TokenTy.LT, c);
case '>' -> addToken(TokenTy.GT, c);
case ',' -> addToken(TokenTy.Comma, c);
case '^' -> addToken(TokenTy.Caret, c);
case '$' -> addToken(TokenTy.Dollar, c);
case '|' -> {
if (expect('|')) {
addToken(TokenTy.Or, "||");
} else {
throw new Exception("Found a single '|', did you mean '||'?");
}
}
case '&' -> {
if (expect('&')) {
addToken(TokenTy.And, "&&");
} else {
throw new Exception("Found a single '&', did you mean '&&'?");
}
}
case '.' -> {
if (expect('.')) {
addToken(TokenTy.DotDot, "..");
} else {
throw new Exception("Found a single '.', did you mean '..'?");
}
}
case '=' -> {
if (expect('=')) {
addToken(TokenTy.EQ, "==");
} else if (expect('>')) {
addToken(TokenTy.Arrow, "=>");
} else {
addToken(TokenTy.Assign, "=");
}
}
default -> {
if (Character.isAlphabetic(c)) {
position -= 1;
scanIdent();
} else if (Character.isDigit(c)) {
position -= 1;
scanNumber();
} else if (c == '\'') {
position -= 1;
scanCharacter();
}else if (c == '"') {
position -= 1;
scanString();
} else {
throw new Exception(String.format("Unexpected character: %c", c));
}
}
};
}
public static ArrayList<Token> tokenize(String input) throws Exception {
Tokenizer t = new Tokenizer(input);
while (!t.isFinished()) {
t.addNextToken();
}
return t.output;
}
public static void testTokenizer() throws Exception {
{
// tests constructor and isFinished
var t = new Tokenizer("");
assert t.isFinished();
}
{
// tests scanIdent
// a non-keyword identifier
var t0 = new Tokenizer("valid_identifier");
t0.scanIdent();
assert t0.output.get(0).ty == TokenTy.Ident;
assert t0.output.get(0).lexeme.equals("valid_identifier");
// keywords
String keywords = "if then else let fn for in";
String[] keywordLS = keywords.split(" ");
TokenTy[] kwTokens = { TokenTy.If, TokenTy.Then, TokenTy.Else, TokenTy.Let, TokenTy.Fn, TokenTy.For,
TokenTy.In };
for (int i = 0; i < keywordLS.length; i += 1) {
var t1 = new Tokenizer(keywordLS[i]);
t1.scanIdent();
Token t = t1.output.get(0);
assert t.ty == kwTokens[i];
assert t.lexeme.equals(keywordLS[i]);
}
}
{
// tests scanNumber
String numbers = "5 10 20 30";
String[] numberLS = numbers.split(" ");
for (int i = 0; i < numberLS.length; i += 1) {
var t1 = new Tokenizer(numberLS[i]);
t1.scanNumber();
Token t = t1.output.get(0);
assert t.ty == TokenTy.Number;
assert t.lexeme.equals(numberLS[i]);
}
}
{
// tests addNextToken
String input = "for x in [10..12] 15 let";
Tokenizer t = new Tokenizer(input);
t.addNextToken();
assert t.output.get(t.output.size() - 1).ty == TokenTy.For;
assert t.output.get(t.output.size() - 1).lexeme.equals("for");
t.addNextToken();
assert t.output.get(t.output.size() - 1).ty == TokenTy.Ident;
assert t.output.get(t.output.size() - 1).lexeme.equals("x");
t.addNextToken();
assert t.output.get(t.output.size() - 1).ty == TokenTy.In;
assert t.output.get(t.output.size() - 1).lexeme.equals("in");
t.addNextToken();
assert t.output.get(t.output.size() - 1).ty == TokenTy.LBracket;
assert t.output.get(t.output.size() - 1).lexeme.equals("[");
t.addNextToken();
assert t.output.get(t.output.size() - 1).ty == TokenTy.Number;
assert t.output.get(t.output.size() - 1).lexeme.equals("10");
t.addNextToken();
assert t.output.get(t.output.size() - 1).ty == TokenTy.DotDot;
assert t.output.get(t.output.size() - 1).lexeme.equals("..");
t.addNextToken();
assert t.output.get(t.output.size() - 1).ty == TokenTy.Number;
assert t.output.get(t.output.size() - 1).lexeme.equals("12");
t.addNextToken();
assert t.output.get(t.output.size() - 1).ty == TokenTy.RBracket;
assert t.output.get(t.output.size() - 1).lexeme.equals("]");
t.addNextToken();
assert t.output.get(t.output.size() - 1).ty == TokenTy.Number;
assert t.output.get(t.output.size() - 1).lexeme.equals("15");
t.addNextToken();
assert t.output.get(t.output.size() - 1).ty == TokenTy.Let;
assert t.output.get(t.output.size() - 1).lexeme.equals("let");
}
{
// tests tokenize()
ArrayList<Token> tokens = tokenize("for x in [0..15]");
assert tokens.get(0).ty == TokenTy.For;
assert tokens.get(0).lexeme.equals("for");
assert tokens.get(1).ty == TokenTy.Ident;
assert tokens.get(1).lexeme.equals("x");
assert tokens.get(2).ty == TokenTy.In;
assert tokens.get(2).lexeme.equals("in");
assert tokens.get(3).ty == TokenTy.LBracket;
assert tokens.get(3).lexeme.equals("[");
assert tokens.get(4).ty == TokenTy.Number;
assert tokens.get(4).lexeme.equals("0");
assert tokens.get(5).ty == TokenTy.DotDot;
assert tokens.get(5).lexeme.equals("..");
assert tokens.get(6).ty == TokenTy.Number;
assert tokens.get(6).lexeme.equals("15");
assert tokens.get(7).ty == TokenTy.RBracket;
assert tokens.get(7).lexeme.equals("]");
}
}
}
class BindingPower {
public int left;
public int right;
public BindingPower(int left, int right) {
this.left = left;
this.right = right;
}
public BindingPower(BinOp op) {
switch (op) {
case Add, Sub -> {
this.left = 4;
this.right = 5;
}
case Mul, Div, Mod -> {
this.left = 6;
this.right = 7;
}
case LT, GT, EQ -> {
this.left = 2;
this.right = 3;
}
case And, Or -> {
this.left = 0;
this.right = 1;
}
}
}
}
class PrefixBindingPower {
public int right;
public PrefixBindingPower(int right) {
this.right = right;
}