-
Notifications
You must be signed in to change notification settings - Fork 0
/
obi.ts
1918 lines (1737 loc) · 51.2 KB
/
obi.ts
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 { delay as DenoDelay } from "https://deno.land/[email protected]/async/mod.ts";
import * as path from "https://deno.land/[email protected]/path/mod.ts";
import { createHash } from "https://deno.land/[email protected]/hash/mod.ts";
import { expr } from "./ast.ts";
import * as runtime from "./runtime.ts";
class WaitGroup {
count: number = 0;
doneCount: number = 0;
add(n: number) {
this.count += n;
}
done() {
this.doneCount += 1;
}
async wait(): Promise<void> {
const self = this;
return new Promise((resolve) => {
(function wait_() {
if (self.doneCount >= self.count) resolve();
else setTimeout(wait_, 0);
})();
});
}
}
type Expr = expr.Expr;
export enum TokenType {
// Single-character tokens.
LEFT_PAREN,
RIGHT_PAREN,
LEFT_BRACE,
RIGHT_BRACE,
LEFT_BRACKET,
RIGHT_BRACKET,
COMMA,
DOT,
PLUS,
SEMICOLON,
SLASH,
STAR,
PERCENT,
TILDE,
UNDERSCORE,
// One or two character tokens.
BANG,
BANG_EQUAL,
EQUAL,
EQUAL_EQUAL,
GREATER,
GREATER_EQUAL,
LESS,
LESS_EQUAL,
COLON,
COLON_COLON,
COLON_EQUAL,
MINUS,
MINUS_LESS,
// Literals.
IDENTIFIER,
STRING,
NUMBER,
COMMENT,
// Keywords.
AND,
ELSE,
FALSE,
FUN,
FOR,
IF,
MATCH,
MOD,
NIL,
OR,
PUB,
RETURN,
TRUE,
VAR,
TEE,
TAP,
TYPE,
NEWLINE,
EOF,
}
export const TT = TokenType;
export class Token {
type: TokenType;
lexeme: string;
literal: any; // Value | null;
line: number;
column: number;
constructor(
type: TokenType,
lexeme: string,
literal: any,
line: number,
column: number,
) {
this.type = type;
this.lexeme = lexeme;
this.literal = literal;
this.line = line;
this.column = column;
}
public toString(): string {
const lexeme: string = this.lexeme === "\n" ? "<newline>" : this.lexeme;
return `[${this.line}:${this.column}] ${
TokenType[this.type]
} '${lexeme}' ${this.literal && this.literal.toString()}`;
}
}
export class Environment {
enclosing: Environment | null;
values: Map<string, any> = new Map<string, any>();
published: Map<string, boolean> = new Map<string, boolean>();
constructor(enclosing?: Environment) {
if (enclosing) {
this.enclosing = enclosing;
} else {
this.enclosing = null;
}
}
define(name: string, value: any, published?: boolean) {
this.values.set(name, value);
if (published) this.published.set(name, true);
}
ancestor(distance: number): Environment {
let environment: Environment = this;
for (let i = 0; i < distance; i++) {
environment = environment.enclosing as Environment;
}
return environment;
}
getAt(distance: number, name: string) {
return this.ancestor(distance).values.get(name);
}
assignAt(distance: number, name: Token, value: any) {
this.ancestor(distance).values.set(name.lexeme, value);
}
get(name: Token): any {
if (this.values.has(name.lexeme)) {
return this.values.get(name.lexeme);
}
if (this.enclosing !== null) {
return this.enclosing.get(name);
}
throw new RuntimeError(name, `Undefined variable '${name.lexeme}'.`);
}
assign(name: Token, value: any): any {
if (this.values.has(name.lexeme)) {
this.values.set(name.lexeme, value);
return;
}
if (this.enclosing !== null) {
return this.enclosing.assign(name, value);
}
throw new RuntimeError(name, `Undefined variable '${name.lexeme}'.`);
}
}
export type ObiCallable = {
arity(): number;
call(interpreter: Interpreter, args: any[]): any;
};
enum FunctionType {
NONE,
FUNCTION,
METHOD,
INITIALIZER,
}
export class ObiFunction implements ObiCallable {
private declaration: expr.Function;
private closure: Environment;
isInitializer: boolean;
published: boolean;
constructor(
declaration: expr.Function,
closure: Environment,
isInitializer: boolean,
published: boolean,
) {
this.declaration = declaration;
this.closure = closure;
this.isInitializer = isInitializer;
this.published = published;
}
call(interpreter: Interpreter, args: any[]): any {
const environment = new Environment(this.closure);
for (let i = 0; i < this.declaration.parameters.length; i++) {
environment.define(this.declaration.parameters[i].lexeme, args[i]);
}
try {
return interpreter.executeBlock(this.declaration.body, environment, this);
} catch (err) {
if (err instanceof Return) {
return (err as Return).value;
} else {
throw err;
}
}
return null;
}
arity(): number {
return this.declaration.parameters.length;
}
toString(): string {
if (null !== this.declaration.name) {
return `<lambda ${this.declaration.name.lexeme}>`;
} else {
return `<lambda>`;
}
}
getDeclaration(): expr.Function {
return this.declaration;
}
}
export class ObiTable {
private fields: Map<string, any> = new Map<string, any>();
toString() {
let f = "";
for (const k of this.fields.keys()) {
f += `${k}:${this.fields.get(k)};`;
}
return `<table (${f})>`;
// return "<table>";
}
get(name: Token): any {
return this.getDyn(name.lexeme);
}
getDyn(name: any): any {
if (this.fields.has(name)) {
return this.fields.get(name);
}
return null;
}
set(name: Token, value: any) {
this.setDyn(name.lexeme, value);
}
setDyn(name: any, value: any): any {
this.fields.set(name, value);
}
getFields(): Map<string, any> {
return this.fields;
}
}
export class RuntimeError extends Error {
token: Token;
constructor(token: Token, message: string) {
super(message);
this.token = token;
}
}
class Return extends Error {
value: any;
constructor(value: any) {
super();
this.value = value;
}
}
class Resolver implements expr.Visitor<void> {
private interpreter: Interpreter;
private scopes: Map<string, boolean>[] = [];
private currentFunction: FunctionType = FunctionType.NONE;
constructor(interpreter: Interpreter) {
this.interpreter = interpreter;
}
resolveExpr(exp: Expr) {
exp.accept(this);
}
resolveExprs(expressions: Expr[]) {
for (const expression of expressions) {
this.resolveExpr(expression);
}
}
resolveFunction(func: expr.Function, type: FunctionType) {
const enclosingFunction = this.currentFunction;
this.currentFunction = type;
this.beginScope();
for (const param of func.parameters) {
this.declare(param);
this.define(param);
}
this.resolveExprs(func.body);
this.endScope();
this.currentFunction = enclosingFunction;
}
beginScope() {
this.scopes.push(new Map<string, boolean>());
}
endScope() {
this.scopes.pop();
}
declare(name: Token) {
if (this.scopes.length < 1) return;
const scope = this.scopes[this.scopes.length - 1];
if (scope.has(name.lexeme)) {
Obi.errorToken(name, "Already a variable with this name in this scope.");
}
scope.set(name.lexeme, false);
}
define(name: Token) {
if (this.scopes.length < 1) return;
const scope = this.scopes[this.scopes.length - 1];
scope.set(name.lexeme, true);
}
count: number = 0;
resolveLocal(exp: Expr, name: Token) {
for (let i = this.scopes.length - 1; i >= 0; i--) {
if (this.scopes[i].has(name.lexeme)) {
this.interpreter.resolve(exp, this.scopes.length - 1 - i);
return;
}
}
}
resolveLocalTable(exp: Expr, name: Token) {
for (let i = this.scopes.length - 1; i >= 0; i--) {
if (this.scopes[i].has(name.lexeme)) {
this.interpreter.resolve(exp, this.scopes.length - i);
return;
}
}
}
visitAssignExpr(exp: expr.Assign) {
this.resolveExpr(exp.value);
this.resolveLocal(exp, exp.name);
}
visitBinaryExpr(exp: expr.Binary) {
this.resolveExpr(exp.left);
this.resolveExpr(exp.right);
}
visitBlockExpr(exp: expr.Block) {
this.beginScope();
this.resolveExprs(exp.expressions);
this.endScope();
}
visitCallExpr(exp: expr.Call) {
this.resolveExpr(exp.callee);
for (const arg of exp.args) {
this.resolveExpr(arg);
}
}
visitFunctionExpr(exp: expr.Function) {
if (null !== exp.name) {
this.declare(exp.name);
this.define(exp.name);
}
this.resolveFunction(exp, FunctionType.FUNCTION);
}
visitGetExpr(exp: expr.Get) {
this.resolveExpr(exp.object);
}
visitGetDynExpr(exp: expr.GetDyn) {
this.resolveExpr(exp.object);
this.resolveExpr(exp.name);
}
visitGroupingExpr(exp: expr.Grouping) {
this.resolveExpr(exp.expression);
}
visitSetExpr(exp: expr.Set) {
this.resolveExpr(exp.value);
this.resolveExpr(exp.object);
}
visitSetDynExpr(exp: expr.SetDyn) {
this.resolveExpr(exp.value);
this.resolveExpr(exp.name);
this.resolveExpr(exp.object);
}
visitLiteralExpr(exp: expr.Literal) {}
visitLogicalExpr(exp: expr.Logical) {
this.resolveExpr(exp.left);
this.resolveExpr(exp.right);
}
visitMatchExpr(exp: expr.Match) {
this.resolveExpr(exp.against);
for (let i = 0; i < exp.cases.length; i++) {
const case_ = exp.cases[i];
if (case_.isDefault && i !== exp.cases.length - 1) {
Obi.errorToken(
exp.where,
"Match branches after default case will never be reached.",
);
}
if (null !== case_.pattern) this.resolveExpr(case_.pattern);
this.resolveExpr(case_.branch);
}
}
visitReturnExpr(exp: expr.Return) {
if (this.currentFunction === FunctionType.NONE) {
Obi.errorToken(exp.keyword, "Can't return from top-level code.");
}
if (exp.value !== null) {
if (this.currentFunction === FunctionType.INITIALIZER) {
Obi.errorToken(
exp.keyword,
"Can't return a value from an initializer.",
);
}
this.resolveExpr(exp.value);
}
}
visitTableExpr(exp: expr.Table) {
this.beginScope();
for (const value of exp.values) {
this.resolveExpr(value);
}
this.endScope();
}
visitUnaryExpr(exp: expr.Unary) {
this.resolveExpr(exp.right);
}
visitVariableExpr(exp: expr.Variable) {
if (
!(this.scopes.length < 1) &&
(this.scopes[this.scopes.length - 1]).get(exp.name.lexeme) === false
) {
Obi.errorToken(
exp.name,
"Can't read local variable in its own initializer.",
);
}
this.resolveLocal(exp, exp.name);
}
visitVarExpr(exp: expr.Var) {
this.declare(exp.name);
if (exp.initializer !== null) {
this.resolveExpr(exp.initializer);
}
this.define(exp.name);
}
}
const PRELUDE = `
fun List() {
self := [
items = [],
len = 0,
add = fun(item) {
self.items.(self.len) = item;
self.len = self.len + 1;
},
get = fun(i) {
return self.items.(i);
},
size = fun() {
return self.len;
},
];
return self;
}
fun Map() {
self := [
defined = [],
items = [],
get = fun(key) {
return match (self.defined.(key)) {
true -> self.items.(key);
_ -> nil;
};
},
set = fun(key, value) {
// print(self.items);
self.items.(key) = value;
self.defined.(key) = true;
},
has = fun(key) {
return match (self.defined.(key)) {
true -> true;
_ -> false;
};
},
unset = fun(key) {
self.items.(key) = nil;
self.defined.(key) = false;
},
keys = fun() {
result := [];
itemKeys := keys(self.items);
size := len(self.items);
resultLen := 0;
i := 0; while() { i < size; } {
match (self.defined.(itemKeys.(i))) {
true -> {
result.(resultLen) = itemKeys.(i);
resultLen = resultLen + 1;
}
_ -> ();
};
i = i + 1;
};
return result;
}
];
return self;
}
fun while(p, f) {
match (p()) {
false -> return;
_ -> ();
};
f();
while(p, f);
}
fun each(list, fn) {
i := 0;
while(fun (){ i < list.len; }) {
fn(list.get(i));
i = i + 1;
};
}`;
export class Interpreter implements expr.Visitor<any> {
entryFile: string = "";
globals: Environment = new Environment();
environment: Environment = this.globals;
private locals: Map<Expr, number> = new Map<Expr, number>();
waitGroup: WaitGroup = new WaitGroup();
timers: Map<number, number> = new Map<number, number>();
modules: Map<string, ObiTable> = new Map<string, ObiTable>();
constructor() {
this.globals.define("mod", new runtime.RtMod());
this.globals.define("print", new runtime.RtPrint());
this.globals.define("clock", new runtime.RtClock());
this.globals.define("random", new runtime.RtRandom());
this.globals.define("delay", new runtime.RtDelay());
this.globals.define("clear_delay", new runtime.RtClearDelay());
this.globals.define("type", new runtime.RtType());
this.globals.define("keys", new runtime.RtKeys());
this.globals.define("str", new runtime.RtStr());
this.globals.define("strlen", new runtime.RtStrlen());
this.globals.define("strcharcode", new runtime.RtStrcharcode());
this.globals.define("strslice", new runtime.RtStrslice());
this.globals.define("parse_float", new runtime.RtParseFloat());
this.globals.define("listen_tcp", new runtime.RtListenTcp());
this.globals.define("readdir", new runtime.RtReadDir());
this.globals.define("writefile", new runtime.RtWritefile());
this.globals.define("readfile", new runtime.RtReadfile());
this.globals.define("readfile_bytes", new runtime.RtReadfileBytes());
this.globals.define("bytes_concat", new runtime.RtBytesConcat());
this.globals.define("text_encode", new runtime.RtTextEncode());
this.globals.define("text_decode", new runtime.RtTextDecode());
this.globals.define("len", new runtime.RtLen());
this.globals.define("load_wasm", new runtime.RtLoadWasm());
this.globals.define("array_make", new runtime.RtArrayMake());
this.globals.define("atob", new runtime.RtAtob());
this.globals.define("btoa", new runtime.RtBtoa());
this.globals.define("fd_open", new runtime.RtFdOpen());
this.globals.define("fd_close", new runtime.RtFdClose());
this.globals.define("fd_seek", new runtime.RtFdSeek());
this.globals.define("fd_read", new runtime.RtFdRead());
this.globals.define("fd_write", new runtime.RtFdWrite());
this.globals.define("fd_fdatasync", new runtime.RtFdFdatasync());
this.globals.define("fd_size", new runtime.RtFdSize());
this.globals.define("file_exists", new runtime.RtFileExists());
this.globals.define("ensure_dir", new runtime.RtEnsureDir());
this.globals.define("fetch", new runtime.RtFetch());
this.globals.define("process_args", new runtime.RtProcessArgs());
this.globals.define("process_exit", new runtime.RtProcessExit());
this.globals.define("process_run", new runtime.RtProcessRun());
this.globals.define("process_env", new runtime.RtProcessEnv());
this.globals.define("list_sort", new runtime.RtListSort());
}
setEntryFile(entryFile: string) {
this.entryFile = entryFile;
}
loadModule(source: string): ObiTable {
const key = createHash("md5").update(source).toString();
const cached = this.modules.get(key);
if (cached) return cached;
const module = new ObiTable();
this.modules.set(key, module);
const scanner = new Scanner(source);
const tokens = scanner.scanTokens();
const parser = new Parser(tokens);
const expressions = parser.parse();
const wrapped = new expr.Block(expressions);
if (Obi.hadError) {
throw new Error("Failed to load module");
}
const resolver = new Resolver(this);
resolver.resolveExprs([wrapped]);
const moduleEnvironment = new Environment(this.environment);
if (Obi.hadError) {
throw new Error("Failed to resolve prelude");
}
const result = this.executeBlock(expressions, moduleEnvironment);
moduleEnvironment.published.forEach((val, key) => {
const value = moduleEnvironment.values.get(key);
module.setDyn(key, value);
});
return module;
}
async interpret(expressions: Expr[]) {
try {
for (const expression of expressions) {
const _ = this.evaluate(expression);
}
} catch (err) {
if (err instanceof RuntimeError) {
Obi.runtimeError(err);
} else {
throw err;
}
}
await DenoDelay(0);
await this.waitGroup.wait();
}
private evaluate(expr: Expr): any {
return expr.accept(this);
}
resolve(exp: Expr, depth: number) {
this.locals.set(exp, depth);
}
executeBlock(
expressions: Expr[],
environment: Environment,
func?: ObiFunction | null,
): any {
const previous = this.environment;
let returnValue = null;
try {
this.environment = environment;
if (this.isTailCall(expressions, func)) {
while (true) {
for (
const expression of expressions.slice(0, expressions.length - 1)
) {
returnValue = this.evaluate(expression);
}
}
} else {
for (const expression of expressions) {
returnValue = this.evaluate(expression);
}
}
} finally {
this.environment = previous;
}
return returnValue;
}
isTailCall(expressions: Expr[], func?: ObiFunction | null): boolean {
if (!func) return false;
if (expressions.length < 1) {
return false;
}
const lastExpr = expressions[expressions.length - 1];
if (!(lastExpr instanceof expr.Call)) {
return false;
}
const lastCall = lastExpr as expr.Call;
if (lastCall.callee instanceof expr.Variable) {
const varName = (lastCall.callee as expr.Variable).name;
try {
const variable = this.lookupVariable(varName, lastCall);
if (variable === func) return true;
} catch (err) {
// Ignore if not found.
if (err instanceof RuntimeError) return false;
else throw err;
}
}
return false;
}
visitAssignExpr(exp: expr.Assign): any {
const value = this.evaluate(exp.value);
const distance = this.locals.get(exp);
if (distance !== null && distance !== undefined) {
this.environment.assignAt(distance, exp.name, value);
} else {
this.globals.assign(exp.name, value);
}
return value;
}
visitBinaryExpr(exp: expr.Binary): any {
const left = this.evaluate(exp.left);
const right = this.evaluate(exp.right);
switch (exp.operator.type) {
case TT.BANG_EQUAL:
return !this.isEqual(left, right);
case TT.EQUAL_EQUAL:
return this.isEqual(left, right);
case TT.GREATER:
this.checkNumberOperands(exp.operator, left, right);
return (left as number) > (right as number);
case TT.GREATER_EQUAL:
this.checkNumberOperands(exp.operator, left, right);
return (left as number) >= (right as number);
case TT.LESS:
this.checkNumberOperands(exp.operator, left, right);
return (left as number) < (right as number);
case TT.LESS_EQUAL:
this.checkNumberOperands(exp.operator, left, right);
return (left as number) <= (right as number);
case TT.MINUS:
this.checkNumberOperands(exp.operator, left, right);
return (left as number) - (right as number);
case TT.PLUS:
if (typeof left === "number" && typeof right === "number") {
return (left as number) + (right as number);
}
if (typeof left === "string" && typeof right === "string") {
return (left as string) + (right as string);
}
console.log(left, right);
throw new RuntimeError(
exp.operator,
"Operands must be two numbers or two strings.",
);
case TT.SLASH:
this.checkNumberOperands(exp.operator, left, right);
return (left as number) / (right as number);
case TT.STAR:
this.checkNumberOperands(exp.operator, left, right);
return (left as number) * (right as number);
case TT.PERCENT:
this.checkNumberOperands(exp.operator, left, right);
return (left as number) % (right as number);
}
// Unreachable.
return null;
}
visitBlockExpr(exp: expr.Block): any {
return this.executeBlock(
exp.expressions,
new Environment(this.environment),
);
}
visitCallExpr(exp: expr.Call): any {
let callee = this.evaluate(exp.callee);
const args: any[] = [];
for (const arg of exp.args) {
args.push(this.evaluate(arg));
}
if (
!(callee && (typeof callee === "object") && "arity" in callee &&
"call" in callee)
) {
throw new RuntimeError(exp.paren, "Can only call functions.");
}
const func = callee as ObiCallable;
if (args.length !== func.arity()) {
throw new RuntimeError(
exp.paren,
`Expected ${func.arity()} arguments but got ${args.length}.`,
);
}
return func.call(this, args);
}
visitFunctionExpr(exp: expr.Function): any {
const func = new ObiFunction(exp, this.environment, false, exp.publish);
if (null !== exp.name) {
this.environment.define(exp.name.lexeme, func, exp.publish);
}
return func;
}
visitGetExpr(exp: expr.Get): any {
const object = this.evaluate(exp.object);
if (object instanceof ObiTable) {
return (object as ObiTable).get(exp.name);
}
if (object instanceof Uint8Array) {
const name = exp.name;
if (name.lexeme === "len") {
return (object as Uint8Array).length;
} else if (typeof (name.literal) === "number") {
return (object as Uint8Array)[exp.name.literal];
}
}
throw new RuntimeError(exp.name, "Only instances have properties.");
}
visitGetDynExpr(exp: expr.GetDyn): any {
const object = this.evaluate(exp.object);
const name = this.evaluate(exp.name);
if (object instanceof ObiTable) {
return (object as ObiTable).getDyn(name);
}
if (object instanceof Uint8Array) {
if (name === "len") {
return (object as Uint8Array).length;
} else if (typeof (name) === "number") {
return (object as Uint8Array)[name];
}
}
throw new RuntimeError(exp.dot, "Only instances have properties.");
}
visitGroupingExpr(exp: expr.Grouping): any {
const value = this.evaluate(exp.expression);
return value;
}
visitLiteralExpr(exp: expr.Literal): any {
return exp.value;
}
visitLogicalExpr(exp: expr.Logical): any {
const left = this.evaluate(exp.left);
if (exp.operator.type == TT.OR) {
if (this.isTruthy(left)) return left;
} else {
if (!this.isTruthy(left)) return left;
}
return this.evaluate(exp.right);
}
visitReturnExpr(exp: expr.Return) {
let value = null;
if (exp.value !== null) value = this.evaluate(exp.value);
throw new Return(value);
}
visitSetExpr(exp: expr.Set): any {
const object = this.evaluate(exp.object);
if (!(object instanceof ObiTable)) {
throw new RuntimeError(exp.name, "Only instances have fields.");
}
const value = this.evaluate(exp.value);
if (object instanceof ObiTable) {
(object as ObiTable).set(exp.name, value);
}
return value;
}
visitSetDynExpr(exp: expr.SetDyn): any {
const object = this.evaluate(exp.object);
if (
!(object instanceof ObiTable ||
object instanceof Uint8Array)
) {
throw new RuntimeError(exp.dot, "Only instances have fields.");
}
const name = this.evaluate(exp.name);
const value = this.evaluate(exp.value);
if (object instanceof ObiTable) {
(object as ObiTable).setDyn(name, value);
} else if ((object as any) instanceof Uint8Array) {
if (typeof name === "number") {
(object as Uint8Array)[name] = value;
}
}
return value;
}
visitMatchExpr(exp: expr.Match): any {
const against = this.evaluate(exp.against);
for (let i = 0; i < exp.cases.length; i++) {
const case_ = exp.cases[i];
if (case_.isDefault) {
return this.evaluate(case_.branch);
}
if (!case_.pattern) continue; // obi error
const pattern = this.evaluate(case_.pattern);
if (this.isEqual(pattern, against)) {
return this.evaluate(case_.branch);
}
}
Obi.errorToken(exp.where, "Un-matched match block.");
return null;
}
visitTableExpr(exp: expr.Table): any {
const table = new ObiTable();
let index = 0;
this.environment = new Environment(this.environment);
for (const value_ of exp.values) {
if (value_ instanceof expr.Assign) {
const assign = value_ as expr.Assign;
const value = this.evaluate(assign.value);
table.setDyn(assign.name.lexeme, value);
} else {
const value = this.evaluate(value_);
table.setDyn(index as any, value);
index += 1;
}
}
this.environment = this.environment.enclosing as Environment;
return table;
}
visitUnaryExpr(exp: expr.Unary): any {
const right = this.evaluate(exp.right);
switch (exp.operator.type) {
case TT.BANG:
return !this.isTruthy(right);
case TT.MINUS:
if (typeof right !== "number") {
throw new RuntimeError(exp.operator, "Operand must be a number.");
}
return -(right as number);
}
// :notsureif:
return null;
}
visitVariableExpr(exp: expr.Variable): any {
return this.lookupVariable(exp.name, exp);
}
visitVarExpr(exp: expr.Var): any {
let value = null;
if (exp.initializer != null) {
value = this.evaluate(exp.initializer);
}
this.environment.define(exp.name.lexeme, value, exp.publish);
return value;
}
lookupVariable(name: Token, exp: Expr): any {
const distance = this.locals.get(exp);
if (distance !== null && distance !== undefined) {
return this.environment.getAt(distance, name.lexeme);
} else {
return this.globals.get(name);
}
}
private checkNumberOperands(op: Token, left: any, right: any) {
if (typeof left === "number" && typeof right === "number") return;
console.log(left, right, op);
throw new RuntimeError(op, "Operands must be numbers.");
}
private isTruthy(object: any): boolean {
if (null === object || undefined === object || false === object) {
return false;
}
if (object instanceof Boolean) return object as boolean;
return true;
}
public isEqual(a: any, b: any): boolean {
if (null == a && null == b) return true;
else if (null == a) return false;
return a === b;
}
static stringify(object: any) {
if (null === object) return "nil";
if (typeof object === "number") {
if (object === 0) {
const bytes = Interpreter.doubleToByteArray(object);
// Not really sure why this is expected...
if (bytes[0] === -128) return "-0";
}
return JSON.stringify(object);
}
if (typeof object === "string") {
return object;
}
if (object && object.toString) {
return object.toString();
}