-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.bundle.js
1472 lines (1471 loc) · 43.7 KB
/
index.bundle.js
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
// deno-fmt-ignore-file
// deno-lint-ignore-file
// This code was bundled using `deno bundle` and it's not recommended to edit it manually
class RuntimeError extends Error {
token;
constructor(token, msg){
super(msg);
this.token = token;
}
}
class LoxInstance {
_class;
fields = new Map();
constructor(_class){
this._class = _class;
}
get(name) {
if (this.fields.has(name.lexeme)) {
const val = this.fields.get(name.lexeme);
return val === undefined ? null : val;
}
const method = this._class.findMethod(name.lexeme);
if (method !== null) return method.bind(this);
throw new RuntimeError(name, `Undefined property ${name.lexeme}.`);
}
set(name, val) {
this.fields.set(name.lexeme, val);
}
toString() {
return this._class.name + " instance";
}
}
class LoxClass {
name;
methods;
superclass;
constructor(name, superclass, methods){
this.name = name;
this.methods = methods;
this.superclass = superclass;
}
findMethod(name) {
if (this.methods.has(name)) {
const method = this.methods.get(name);
return method === undefined ? null : method;
}
if (this.superclass !== null) {
return this.superclass.findMethod(name);
}
return null;
}
call(interpreter, args) {
const instance = new LoxInstance(this);
const initializer = this.findMethod("init");
if (initializer !== null) {
initializer.bind(instance).call(interpreter, args);
}
return instance;
}
toString() {
return this.name;
}
arity() {
const initializer = this.findMethod("init");
if (initializer === null) return 0;
return initializer.arity();
}
}
class Environment {
values = new Map();
enclosing;
constructor(enclosing){
if (enclosing) this.enclosing = enclosing;
}
define(name, value) {
this.values.set(name, value);
}
get(name) {
const value = this.values.has(name.lexeme) ? this.values.get(name.lexeme) : undefined;
if (value !== undefined) return value;
else if (this.enclosing) return this.enclosing.get(name);
else throw new RuntimeError(name, `Undefined variable '${name.lexeme}'.`);
}
getAt(distance, name) {
const ancestor = this.ancestor(distance);
if (ancestor) {
const val = ancestor.values.get(name);
return val === undefined ? null : val;
} else {
throw new Error(`Cannot access unresolved variable '${name}'.`);
}
}
ancestor(distance) {
let environment = this;
for(let i = 0; i < distance; i++){
environment = environment && environment.enclosing;
}
return environment;
}
assign(name, value) {
if (this.values.has(name.lexeme)) this.values.set(name.lexeme, value);
else if (this.enclosing) this.enclosing.assign(name, value);
else throw new RuntimeError(name, `Undefined variable '${name.lexeme}'.`);
}
assignAt(distance, name, value) {
const ancestor = this.ancestor(distance);
if (ancestor) {
ancestor.values.set(name.lexeme, value);
} else {
throw new Error(`Cannot access unresolved variable '${name.lexeme}'.`);
}
}
}
class ReturnException {
value;
constructor(value){
this.value = value;
}
}
class LoxFunction {
declaration;
closure;
isInitializer;
constructor(declaration, closure, isInitializer){
this.declaration = declaration;
this.closure = closure;
this.isInitializer = isInitializer;
}
bind(instance) {
const environment = new Environment(this.closure);
environment.define("this", instance);
return new LoxFunction(this.declaration, environment, this.isInitializer);
}
arity() {
return this.declaration.params.length;
}
call(interpreter, args) {
const environment = new Environment(this.closure);
for(let x = 0; x < this.declaration.params.length; x++){
environment.define(this.declaration.params[x].lexeme, args[x]);
}
try {
interpreter.executeBlock(this.declaration.body, environment);
} catch (err) {
if (this.isInitializer) {
return this.closure.getAt(0, "this");
}
if (err instanceof ReturnException) {
return err.value;
}
}
if (this.isInitializer) return this.closure.getAt(0, "this");
return null;
}
toString() {
return `<fn ${this.declaration.name.lexeme}>`;
}
}
class Block {
statements;
constructor(statements){
this.statements = statements;
}
accept(visitor) {
return visitor.visitBlockStmt(this);
}
}
class Class {
name;
superclass;
methods;
constructor(name, superclass, methods){
this.name = name;
this.superclass = superclass;
this.methods = methods;
}
accept(visitor) {
return visitor.visitClassStmt(this);
}
}
class Expression {
expression;
constructor(expression){
this.expression = expression;
}
accept(visitor) {
return visitor.visitExpressionStmt(this);
}
}
class Func {
name;
params;
body;
constructor(name, params, body){
this.name = name;
this.params = params;
this.body = body;
}
accept(visitor) {
return visitor.visitFuncStmt(this);
}
}
class If {
condition;
thenBranch;
elseBranch;
constructor(condition, thenBranch, elseBranch){
this.condition = condition;
this.thenBranch = thenBranch;
this.elseBranch = elseBranch;
}
accept(visitor) {
return visitor.visitIfStmt(this);
}
}
class Print {
expression;
constructor(expression){
this.expression = expression;
}
accept(visitor) {
return visitor.visitPrintStmt(this);
}
}
class Return {
keyword;
value;
constructor(keyword, value){
this.keyword = keyword;
this.value = value;
}
accept(visitor) {
return visitor.visitReturnStmt(this);
}
}
class Var {
name;
initializer;
constructor(name, initializer){
this.name = name;
this.initializer = initializer;
}
accept(visitor) {
return visitor.visitVarStmt(this);
}
}
class While {
condition;
body;
constructor(condition, body){
this.condition = condition;
this.body = body;
}
accept(visitor) {
return visitor.visitWhileStmt(this);
}
}
class Assign {
name;
value;
constructor(name, value){
this.name = name;
this.value = value;
}
accept(visitor) {
return visitor.visitAssignExpr(this);
}
}
class Binary {
left;
operator;
right;
constructor(left, operator, right){
this.left = left;
this.operator = operator;
this.right = right;
}
accept(visitor) {
return visitor.visitBinaryExpr(this);
}
}
class Call {
callee;
paren;
args;
constructor(callee, paren, args){
this.callee = callee;
this.paren = paren;
this.args = args;
}
accept(visitor) {
return visitor.visitCallExpr(this);
}
}
class Getter {
obj;
name;
constructor(obj, name){
this.obj = obj;
this.name = name;
}
accept(visitor) {
return visitor.visitGetterExpr(this);
}
}
class Grouping {
expression;
constructor(expression){
this.expression = expression;
}
accept(visitor) {
return visitor.visitGroupingExpr(this);
}
}
class Literal {
value;
constructor(value){
this.value = value;
}
accept(visitor) {
return visitor.visitLiteralExpr(this);
}
}
class Logical {
left;
operator;
right;
constructor(left, operator, right){
this.left = left;
this.operator = operator;
this.right = right;
}
accept(visitor) {
return visitor.visitLogicalExpr(this);
}
}
class Setter {
obj;
name;
val;
constructor(obj, name, val){
this.obj = obj;
this.name = name;
this.val = val;
}
accept(visitor) {
return visitor.visitSetterExpr(this);
}
}
class Super {
keyword;
method;
constructor(keyword, method){
this.keyword = keyword;
this.method = method;
}
accept(visitor) {
return visitor.visitSuperExpr(this);
}
}
class This {
keyword;
constructor(keyword){
this.keyword = keyword;
}
accept(visitor) {
return visitor.visitThisExpr(this);
}
}
class Unary {
operator;
right;
constructor(operator, right){
this.operator = operator;
this.right = right;
}
accept(visitor) {
return visitor.visitUnaryExpr(this);
}
}
class Variable {
name;
constructor(name){
this.name = name;
}
accept(visitor) {
return visitor.visitVariableExpr(this);
}
}
const Keywords = {
and: "AND",
class: "CLASS",
else: "ELSE",
false: "FALSE",
fun: "FUN",
for: "FOR",
if: "IF",
nil: "NIL",
or: "OR",
print: "PRINT",
return: "RETURN",
super: "SUPER",
this: "THIS",
true: "TRUE",
var: "VAR",
while: "WHILE"
};
class Token {
type;
lexeme;
literal;
line;
constructor(type, lexeme, literal, line){
this.type = type;
this.lexeme = lexeme;
this.literal = literal;
this.line = line;
}
toString() {
return `(Type: ${this.type} | Lexeme: ${this.lexeme})`;
}
}
class Interpreter {
globals;
environment;
locals = new Map();
constructor(){
this.globals = new Environment();
this.environment = this.globals;
this.globals.define("clock", {
arity () {
return 0;
},
call () {
return Date.now();
},
toString () {
return "<native fn>";
}
});
}
interpret(statements) {
try {
for (const statement of statements){
this.execute(statement);
}
} catch (err) {
Lox.runtimeError(err);
}
}
visitLiteralExpr(expr) {
return expr.value;
}
visitLogicalExpr(expr) {
const left = this.evaluate(expr.left);
if (expr.operator.type === "OR") {
if (this.isTruthy(left)) return left;
} else {
if (!this.isTruthy(left)) return left;
}
return this.evaluate(expr.right);
}
visitSetterExpr(expr) {
const obj = this.evaluate(expr.obj);
if (!(obj instanceof LoxInstance)) {
throw new RuntimeError(expr.name, "Only instances have fields.");
}
const val = this.evaluate(expr.val);
obj.set(expr.name, val);
return val;
}
visitSuperExpr(expr) {
const distance = this.locals.get(expr);
if (distance) {
const superclass = this.environment.getAt(distance, "super");
if (superclass instanceof LoxClass) {
const obj = this.environment.getAt(distance - 1, "this");
const method = superclass.findMethod(expr.method.lexeme);
if (method !== null) {
if (obj instanceof LoxInstance) {
return method.bind(obj);
} else {
throw new RuntimeError(expr.keyword, "'this' does not point to a LoxInstance in the superclass.");
}
} else {
throw new RuntimeError(expr.method, `Undefined property '${expr.method.lexeme}'.`);
}
} else {
throw new RuntimeError(expr.keyword, "'super' does not point to a class.");
}
} else {
throw new RuntimeError(expr.keyword, "Unresolved super expression.");
}
}
visitThisExpr(expr) {
return this.lookupVariable(expr.keyword, expr);
}
visitGroupingExpr(expr) {
return this.evaluate(expr.expression);
}
visitUnaryExpr(expr) {
const rightRaw = this.evaluate(expr.right);
const rightStr = rightRaw !== null ? rightRaw.toString() : "null";
switch(expr.operator.type){
case "MINUS":
this.checkNumberOperands(expr.operator, rightRaw);
return -parseFloat(rightStr);
case "BANG":
return !this.isTruthy(rightRaw);
}
return null;
}
visitVariableExpr(expr) {
return this.lookupVariable(expr.name, expr);
}
lookupVariable(name, expr) {
const distance = this.locals.get(expr);
if (distance !== undefined) {
return this.environment.getAt(distance, name.lexeme);
} else {
return this.globals.get(name);
}
}
visitBinaryExpr(expr) {
const left = this.evaluate(expr.left);
const right = this.evaluate(expr.right);
switch(expr.operator.type){
case "GREATER":
this.checkNumberOperands(expr.operator, left, right);
return left > right;
case "GREATER_EQUAL":
this.checkNumberOperands(expr.operator, left, right);
return left >= right;
case "LESS":
this.checkNumberOperands(expr.operator, left, right);
return left < right;
case "LESS_EQUAL":
this.checkNumberOperands(expr.operator, left, right);
return left <= right;
case "BANG_EQUAL":
this.checkNumberOperands(expr.operator, left, right);
return !this.isEqual(left, right);
case "EQUAL_EQUAL":
this.checkNumberOperands(expr.operator, left, right);
return this.isEqual(left, right);
case "MINUS":
this.checkNumberOperands(expr.operator, left, right);
return left - right;
case "PLUS":
if (typeof left === "number" && typeof right === "number") {
return left + right;
}
if (typeof left === "string" && typeof right === "string") {
return left + right;
}
throw new RuntimeError(expr.operator, "Operands must be strings or numbers");
case "SLASH":
this.checkNumberOperands(expr.operator, left, right);
return left / right;
case "STAR":
this.checkNumberOperands(expr.operator, left, right);
return left * right;
}
return null;
}
visitCallExpr(expr) {
const callee = this.evaluate(expr.callee);
const args = [];
for (const arg of expr.args){
args.push(this.evaluate(arg));
}
if (!isLoxCallable(callee)) {
throw new RuntimeError(expr.paren, "Can only call functions and classes.");
}
const fn = callee;
if (args.length != fn.arity()) {
throw new RuntimeError(expr.paren, `Expected ${fn.arity()} arguments but got ${args.length}.`);
}
return fn.call(this, args);
}
visitGetterExpr(expr) {
const obj = this.evaluate(expr.obj);
if (obj instanceof LoxInstance) {
return obj.get(expr.name);
}
throw new RuntimeError(expr.name, "Only instances have properties.");
}
checkNumberOperands(operator, ...operands) {
for (const operand of operands){
if (typeof operand !== "number") {
throw new RuntimeError(operator, "Operands must be numbers!");
}
}
}
evaluate(expr) {
return expr.accept(this);
}
execute(stmt) {
stmt.accept(this);
}
resolve(expr, depth) {
this.locals.set(expr, depth);
}
executeBlock(statements, environment) {
const { environment: previous } = this;
try {
this.environment = environment;
for (const statement of statements){
this.execute(statement);
}
} finally{
this.environment = previous;
}
}
visitBlockStmt(stmt) {
this.executeBlock(stmt.statements, new Environment(this.environment));
return null;
}
visitClassStmt(stmt) {
let superclass = null;
if (stmt.superclass !== null) {
superclass = this.evaluate(stmt.superclass);
if (!(superclass instanceof LoxClass)) {
throw new RuntimeError(stmt.superclass.name, "Superclass must be a class.");
}
}
this.environment.define(stmt.name.lexeme, null);
if (stmt.superclass !== null) {
this.environment = new Environment(this.environment);
this.environment.define("super", superclass);
}
const methods = new Map();
for (const method of stmt.methods){
const func = new LoxFunction(method, this.environment, method.name.lexeme === "init");
methods.set(method.name.lexeme, func);
}
const _class = new LoxClass(stmt.name.lexeme, superclass, methods);
if (superclass !== null) {
this.environment = this.environment.enclosing ? this.environment.enclosing : this.environment;
}
this.environment.assign(stmt.name, _class);
}
visitExpressionStmt(stmt) {
this.evaluate(stmt.expression);
}
visitFuncStmt(stmt) {
const func = new LoxFunction(stmt, this.environment, false);
this.environment.define(stmt.name.lexeme, func);
}
visitIfStmt(stmt) {
if (this.isTruthy(this.evaluate(stmt.condition))) {
this.execute(stmt.thenBranch);
} else if (stmt.elseBranch !== null) {
this.execute(stmt.elseBranch);
}
return null;
}
visitPrintStmt(stmt) {
const value = this.evaluate(stmt.expression);
console.log(value !== null ? value.toString() : "nil");
}
visitReturnStmt(stmt) {
let value = null;
if (stmt.value != null) {
value = this.evaluate(stmt.value);
}
throw new ReturnException(value);
}
visitVarStmt(stmt) {
let value = null;
if (stmt.initializer != null) {
value = this.evaluate(stmt.initializer);
}
this.environment.define(stmt.name.lexeme, value);
}
visitWhileStmt(stmt) {
while(this.isTruthy(this.evaluate(stmt.condition))){
this.execute(stmt.body);
}
}
visitAssignExpr(expr) {
const value = this.evaluate(expr.value);
const distance = this.locals.get(expr);
if (distance !== undefined) {
this.environment.assignAt(distance, expr.name, value);
} else {
this.globals.assign(expr.name, value);
}
return value;
}
isTruthy(val) {
if (val === null) return false;
if (window.toString.call(val) === "[object Boolean]") {
return !!val.valueOf();
}
return true;
}
isEqual(a, b) {
return a === b;
}
}
class Lox {
static interpreter = new Interpreter();
static hadError = false;
static hadRuntimeError = false;
static runFile(path) {
try {
const source = Deno.readTextFileSync(path);
if (source) this.run(source);
if (this.hadError) Deno.exit(64);
if (this.hadRuntimeError) Deno.exit(70);
} catch (err) {
console.error(`Error:\n\t${err.message}`);
Deno.exit(64);
}
}
static runPrompt() {
console.log("lox.ts REPL. Press Ctrl + C to exit.");
while(true){
const text = prompt("::");
const source = text ? text.trim() : "";
this.run(source);
this.hadError = false;
}
}
static run(source) {
const scanner = new Scanner(source);
const tokens = scanner.scanTokens();
const parser = new Parser(tokens);
const statements = parser.parse();
if (this.hadError) return;
if (statements === null) {
console.log("Program terminated due to error!");
} else {
const resolver = new Resolver(this.interpreter);
resolver.resolve(...statements);
if (this.hadError) return;
this.interpreter.interpret(statements);
}
}
static error(token, message) {
if (typeof token === "number") {
this.report(token, "", message);
} else {
if (token.type === "EOF") {
this.report(token.line, " at end", message);
} else {
this.report(token.line, ` at '${token.lexeme}'`, message);
}
}
}
static runtimeError(err) {
this.report(err.token.line, "", err.message);
this.hadRuntimeError = true;
}
static report(line, where, message) {
const msg = `[line ${line}] Error${where}: ${message}`;
console.error(msg);
this.hadError = true;
}
}
class Scanner {
source;
tokens = [];
start = 0;
current = 0;
line = 1;
constructor(source){
this.source = source;
}
scanTokens() {
while(!this.isAtEnd()){
this.start = this.current;
this.scanToken();
}
this.tokens.push(new Token("EOF", "[EOF]", null, this.line));
return this.tokens;
}
scanToken() {
const c = this.advance();
switch(c){
case "(":
this.addToken("LEFT_PAREN");
break;
case ")":
this.addToken("RIGHT_PAREN");
break;
case "{":
this.addToken("LEFT_BRACE");
break;
case "}":
this.addToken("RIGHT_BRACE");
break;
case ",":
this.addToken("COMMA");
break;
case ".":
this.addToken("DOT");
break;
case "-":
this.addToken("MINUS");
break;
case "+":
this.addToken("PLUS");
break;
case ";":
this.addToken("SEMICOLON");
break;
case "*":
this.addToken("STAR");
break;
case "!":
this.addToken(this.match("=") ? "BANG_EQUAL" : "BANG");
break;
case "=":
this.addToken(this.match("=") ? "EQUAL_EQUAL" : "EQUAL");
break;
case "<":
this.addToken(this.match("=") ? "LESS_EQUAL" : "LESS");
break;
case ">":
this.addToken(this.match("=") ? "GREATER_EQUAL" : "GREATER");
break;
case "/":
if (this.match("/")) {
while(this.peek() != "\n" && !this.isAtEnd()){
this.advance();
}
} else {
this.addToken("SLASH");
}
break;
case " ":
case "\r":
case "\t":
break;
case "\n":
this.line++;
break;
case '"':
this.handleString();
break;
default:
if (this.isDigit(c)) {
this.handleNumber();
} else if (this.isAlpha(c)) {
this.handleIdentifier();
} else {
Lox.error(this.line, `Unexpected character: ${c}`);
}
break;
}
}
handleIdentifier() {
while(this.isAlphaNumeric(this.peek())){
this.advance();
}
const lexeme = this.source.substring(this.start, this.current);
const type = Keywords[lexeme] || "IDENTIFIER";
this.addToken(type);
}
handleNumber() {
while(this.isDigit(this.peek())){
this.advance();
}
if (this.peek() === "." && this.isDigit(this.peekNext())) {
this.advance();
while(this.isDigit(this.peek())){
this.advance();
}
}
const val = parseFloat(this.source.substring(this.start, this.current));
this.addToken("NUMBER", val);
}
handleString() {
while(this.peek() != '"' && !this.isAtEnd()){
if (this.peek() === "\n") this.line++;
this.advance();
}
if (this.isAtEnd()) {
Lox.error(this.line, "Unterminated string!");
} else {
this.advance();
const val = this.source.substring(this.start + 1, this.current - 1);
this.addToken("STRING", val);
}
}
addToken(type, literal) {
literal = literal === undefined ? null : literal;
const lexeme = this.source.substring(this.start, this.current);
this.tokens.push(new Token(type, lexeme, literal, this.line));
}
advance() {
this.current++;
return this.source[this.current - 1];
}
isAtEnd() {
return this.current >= this.source.length;
}
match(expected) {
if (this.isAtEnd()) return false;
if (this.source[this.current] !== expected) return false;
this.current++;
return true;
}
peek() {
if (this.isAtEnd()) return "\0";
return this.source[this.current];
}
peekNext() {
if (this.current + 1 >= this.source.length) return "\0";
return this.source[this.current + 1];
}
isDigit(c) {
return /\d/.test(c);
}
isAlpha(c) {
return /[A-Za-z_]/.test(c);
}
isAlphaNumeric(c) {
return this.isAlpha(c) || this.isDigit(c);
}
}
class Parser {
tokens;
current = 0;
constructor(tokens){
this.tokens = tokens;
}
parse() {
try {
const statements = [];
while(!this.isAtEnd()){
statements.push(this.declaration());
}
return statements;
} catch (err) {
return null;
}
}
statement() {
if (this.match("PRINT")) return this.printStatement();
if (this.match("RETURN")) return this.returnStatement();
if (this.match("WHILE")) return this.whileStatement();
if (this.match("LEFT_BRACE")) return new Block(this.block());
if (this.match("IF")) return this.ifStatement();
if (this.match("FOR")) return this.forStatement();
return this.expressionStatement();
}
forStatement() {
this.consume("LEFT_PAREN", "Expect '(' after 'for'.");
let initializer = null;
if (this.match("SEMICOLON")) {
initializer = null;
} else if (this.match("VAR")) {
initializer = this.varDeclaration();
} else {
initializer = this.expressionStatement();
}
let condition = null;
if (!this.check("SEMICOLON")) {
condition = this.expression();
}
this.consume("SEMICOLON", "Expect ';' after loop condition.");
let increment = null;
if (!this.check("RIGHT_PAREN")) {
increment = this.expression();
}
this.consume("RIGHT_PAREN", "Expect ')' after for clauses.");
let body = this.statement();
if (increment != null) {
body = new Block([
body,
new Expression(increment)
]);
}
if (condition == null) condition = new Literal(true);
body = new While(condition, body);
if (initializer != null) {
body = new Block([
initializer,
body
]);
}
return body;
}
ifStatement() {
this.consume("LEFT_PAREN", "Expect '(' after 'if'.");
const condition = this.expression();
this.consume("RIGHT_PAREN", "Expect ')' after 'if' condition.");
const thenBranch = this.statement();
let elseBranch = null;
if (this.match("ELSE")) {
elseBranch = this.statement();
}
return new If(condition, thenBranch, elseBranch);
}
printStatement() {
const value = this.expression();