-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
582 lines (582 loc) · 16.9 KB
/
Copy pathindex.js
File metadata and controls
582 lines (582 loc) · 16.9 KB
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
const { readFileSync } = require("fs");
const TOKEN_TYPES = {
START_PROGRAM: /^GRRRRRRR!/,
END_PROGRAM: /^HSSSSSSS!/,
DECLARE: /^RAAAWR!/,
ASSIGN: /^RAAAWR\./,
RAAWR_KEYWORD: /^RAAWR\b/,
FUNCTION_DEFINE: /^DEFINE_TERRITORY/,
FUNCTION_END: /^END_TERRITORY/,
FUNCTION_RETURN: /^RETURN_PREY/,
FUNCTION_CALL: /^CALL_TERRITORY/,
IF: /^IF_ROAR/,
THEN: /^THEN_CHOMP/,
ELSE: /^ELSE_STOMP/,
END_IF: /^END_HUNT/,
WHILE: /^WHILE_ROAR/,
LOOP: /^KEEP_MIGRATING/,
END_LOOP: /^END_MIGRATION/,
OUTPUT: /^ROAR/,
INPUT: /^SNIFF/,
PLUS: /^RAAWR\+/,
MINUS: /^RAAWR\-/,
MUL: /^RAAWR\*/,
DIV: /^RAAWR\//,
MOD: /^RAAWR%/,
EQ: /^RAAWR==/,
GT: /^RAAWR>/,
LT: /^RAAWR</,
CONCAT: /^ROOOOAAR/,
LPAREN: /^\(/,
RPAREN: /^\)/,
COMMA: /^,/,
STRING: /^"([^"]*)"/,
BOOLEAN_TRUE: /^GRRR/,
BOOLEAN_FALSE: /^HISS/,
NUMBER: /^\d+(\.\d+)?/,
IDENTIFIER: /^[A-Za-z_][A-Za-z0-9_]*/,
COMMENT: /^\/\/.*/,
NEWLINE: /^\n+/,
WHITESPACE: /^[ \t\r]+/,
};
const orderedTokenTypes = [
"START_PROGRAM",
"END_PROGRAM",
"DECLARE",
"ASSIGN",
"FUNCTION_DEFINE",
"FUNCTION_END",
"FUNCTION_RETURN",
"FUNCTION_CALL",
"IF",
"THEN",
"ELSE",
"END_IF",
"WHILE",
"LOOP",
"END_LOOP",
"OUTPUT",
"INPUT",
"PLUS",
"MINUS",
"MUL",
"DIV",
"MOD",
"EQ",
"GT",
"LT",
"CONCAT",
"RAAWR_KEYWORD",
"LPAREN",
"RPAREN",
"COMMA",
"STRING",
"BOOLEAN_TRUE",
"BOOLEAN_FALSE",
"NUMBER",
"IDENTIFIER",
"COMMENT",
"NEWLINE",
"WHITESPACE",
];
function tokenize(code) {
let tokens = [],
line = 1;
while (code.length > 0) {
let matched = false;
for (const type of orderedTokenTypes) {
const regex = TOKEN_TYPES[type];
const match = regex.exec(code);
if (match) {
matched = true;
const value = match[0];
if (type === "NEWLINE") line += (value.match(/\n/g) || []).length;
if (!["WHITESPACE", "COMMENT", "NEWLINE"].includes(type)) {
tokens.push({
type,
value: type === "STRING" ? match[1] : value,
line,
});
}
code = code.slice(value.length);
break;
}
}
if (!matched)
throw new Error(`ROOOAAARRR! Unrecognized '${code[0]}' at line ${line}.`);
}
return tokens;
}
function parse(tokens) {
let i = 0;
function peek() {
return tokens[i];
}
function consume(expected) {
const tok = tokens[i++];
if (!tok)
throw new Error(
`CRUNCH! (Syntax Error: Unexpected end of code, expected ${
expected || "token"
}.)`
);
if (expected && tok.type !== expected)
throw new Error(
`ROOOAAARRR! (Syntax Error: Expected '${expected}', but found '${tok.type}' ('${tok.value}') at line ${tok.line}.)`
);
return tok;
}
function match(type) {
return tokens[i] && tokens[i].type === type;
}
function parseProgram() {
const node = { type: "Program", body: [], line: peek().line };
consume("START_PROGRAM");
while (!match("END_PROGRAM")) node.body.push(parseStatement());
consume("END_PROGRAM");
return node;
}
function parseStatement() {
if (match("DECLARE")) return parseVariableDeclaration();
if (match("ASSIGN")) return parseAssignment();
if (match("OUTPUT")) return parseOutput();
if (match("INPUT")) return parseInput();
if (match("IF")) return parseIf();
if (match("WHILE")) return parseWhile();
if (match("FUNCTION_DEFINE")) return parseFunctionDef();
if (match("FUNCTION_CALL")) return parseFunctionCall();
if (match("FUNCTION_RETURN")) return parseReturn();
throw new Error(
`ROOOAAARRR! (Syntax Error: Unexpected statement '${
peek().value
}' at line ${peek().line}.)`
);
}
function parseVariableDeclaration() {
const line = peek().line;
consume("DECLARE");
const name = consume("IDENTIFIER").value;
consume("RAAWR_KEYWORD");
const value = parseExpression();
return { type: "VariableDeclaration", name, value, line };
}
function parseAssignment() {
const line = peek().line;
consume("ASSIGN");
const name = consume("IDENTIFIER").value;
consume("RAAWR_KEYWORD");
const value = parseExpression();
return { type: "Assignment", name, value, line };
}
function parseOutput() {
const line = peek().line;
consume("OUTPUT");
const value = parseExpression();
return { type: "Output", value, line };
}
function parseInput() {
const line = peek().line;
consume("INPUT");
const name = consume("IDENTIFIER").value;
return { type: "Input", name, line };
}
function parseIf() {
const line = peek().line;
consume("IF");
const cond = parseExpression();
consume("THEN");
const thenBranch = [];
while (!match("ELSE") && !match("END_IF"))
thenBranch.push(parseStatement());
let elseBranch = [];
if (match("ELSE")) {
consume("ELSE");
while (!match("END_IF")) elseBranch.push(parseStatement());
}
consume("END_IF");
return { type: "If", condition: cond, thenBranch, elseBranch, line };
}
function parseWhile() {
const line = peek().line;
consume("WHILE");
const cond = parseExpression();
consume("LOOP");
const body = [];
while (!match("END_LOOP")) body.push(parseStatement());
consume("END_LOOP");
return { type: "While", condition: cond, body, line };
}
function parseFunctionDef() {
const line = peek().line;
consume("FUNCTION_DEFINE");
const name = consume("IDENTIFIER").value;
consume("LPAREN");
const params = [];
if (!match("RPAREN")) {
params.push(consume("IDENTIFIER").value);
while (match("RAAWR_KEYWORD")) {
consume("RAAWR_KEYWORD");
params.push(consume("IDENTIFIER").value);
}
}
consume("RPAREN");
const body = [];
let returnValue = null;
while (!match("FUNCTION_END")) {
if (match("FUNCTION_RETURN")) returnValue = parseReturn().value;
else body.push(parseStatement());
}
consume("FUNCTION_END");
return {
type: "FunctionDeclaration",
name,
params,
body,
returnValue,
line,
};
}
function parseReturn() {
const line = peek().line;
consume("FUNCTION_RETURN");
const value = parseExpression();
return { type: "Return", value, line };
}
function parseFunctionCall() {
const line = peek().line;
consume("FUNCTION_CALL");
const name = consume("IDENTIFIER").value;
consume("LPAREN");
const args = [];
if (!match("RPAREN")) {
args.push(parseExpression());
while (match("RAAWR_KEYWORD")) {
consume("RAAWR_KEYWORD");
args.push(parseExpression());
}
}
consume("RPAREN");
return { type: "FunctionCall", name, args, line };
}
function parseExpression() {
let left = parsePrimaryExpression();
while (
[
"PLUS",
"MINUS",
"MUL",
"DIV",
"MOD",
"EQ",
"GT",
"LT",
"CONCAT",
].includes(peek()?.type)
) {
const op = consume().type;
const right = parsePrimaryExpression();
left = {
type: "BinaryExpression",
operator: op,
left,
right,
line: left.line,
};
}
return left;
}
function parsePrimaryExpression() {
const tok = peek();
if (!tok)
throw new Error(`CRUNCH! (Syntax Error: Unexpected end in expression.)`);
if (tok.type === "NUMBER") {
consume("NUMBER");
return { type: "Literal", value: parseFloat(tok.value), line: tok.line };
}
if (tok.type === "STRING") {
consume("STRING");
return { type: "Literal", value: tok.value, line: tok.line };
}
if (tok.type === "BOOLEAN_TRUE") {
consume("BOOLEAN_TRUE");
return { type: "Literal", value: true, line: tok.line };
}
if (tok.type === "BOOLEAN_FALSE") {
consume("BOOLEAN_FALSE");
return { type: "Literal", value: false, line: tok.line };
}
if (tok.type === "FUNCTION_CALL") {
return parseFunctionCall();
}
if (tok.type === "IDENTIFIER") {
consume("IDENTIFIER");
return { type: "Identifier", name: tok.value, line: tok.line };
}
if (tok.type === "LPAREN") {
consume("LPAREN");
const expr = parseExpression();
consume("RPAREN");
return expr;
}
throw new Error(
`ROOOAAARRR! (Syntax Error: Unexpected token '${tok.value}' at line ${tok.line}.)`
);
}
return parseProgram();
}
class Environment {
constructor(parent = null) {
this.vars = new Map();
this.functions = new Map();
this.parent = parent;
}
declareVar(name, value) {
if (this.vars.has(name))
throw new Error(
`CRUNCH! (Runtime Error: Variable '${name}' already declared.)`
);
this.vars.set(name, value);
}
setVar(name, value) {
if (this.vars.has(name)) return this.vars.set(name, value);
if (this.parent) return this.parent.setVar(name, value);
throw new Error(
`CRUNCH! (Runtime Error: Variable '${name}' not declared.)`
);
}
getVar(name) {
if (this.vars.has(name)) return this.vars.get(name);
if (this.parent) return this.parent.getVar(name);
throw new Error(
`CRUNCH! (Runtime Error: Variable '${name}' not declared.)`
);
}
declareFunction(name, def) {
this.functions.set(name, def);
}
getFunction(name, line) {
if (this.functions.has(name)) return this.functions.get(name);
if (this.parent) return this.parent.getFunction(name, line);
throw new Error(
`CRUNCH! (Runtime Error: Function '${name}' not found at line ${line}.)`
);
}
}
async function interpret(ast, getInput) {
const globalEnv = new Environment();
async function evaluate(node, env) {
if (node.type === "Literal") return node.value;
if (node.type === "Identifier") return env.getVar(node.name);
if (node.type === "BinaryExpression") {
const l = await evaluate(node.left, env);
const r = await evaluate(node.right, env);
if (["PLUS", "MINUS", "MUL", "DIV", "MOD"].includes(node.operator)) {
if (typeof l !== "number" || typeof r !== "number") {
throw new Error(
`CRUNCH! (Runtime Error: ${
node.operator
} expects numbers, got ${typeof l} and ${typeof r} at line ${
node.line
}.)`
);
}
}
if (["EQ", "GT", "LT"].includes(node.operator)) {
}
if (node.operator === "CONCAT") {
}
switch (node.operator) {
case "PLUS":
return l + r;
case "MINUS":
return l - r;
case "MUL":
return l * r;
case "DIV":
if (r === 0)
throw new Error(
`CRUNCH! (Runtime Error: Division by zero at line ${node.line}. The Raptor just ate your data.)`
);
return l / r;
case "MOD":
if (r === 0)
throw new Error(
`CRUNCH! (Runtime Error: Modulo by zero at line ${node.line}. Even dinosaurs can't divide by zero!)`
);
return l % r;
case "EQ":
return l === r;
case "GT":
return l > r;
case "LT":
return l < r;
case "CONCAT":
return String(l) + String(r);
default:
throw new Error(
`CRUNCH! (Runtime Error: Unknown operator '${node.operator}' at line ${node.line}.)`
);
}
}
if (node.type === "FunctionCall") {
const def = env.getFunction(node.name, node.line);
if (def.params.length !== node.args.length)
throw new Error(
`CRUNCH! (Runtime Error: Function '${node.name}' expects ${def.params.length} arguments, but got ${node.args.length} at line ${node.line}.)`
);
const fnEnv = new Environment(env);
for (let i = 0; i < def.params.length; i++)
fnEnv.declareVar(def.params[i], await evaluate(node.args[i], env));
for (const stmt of def.body) {
const res = await execute(stmt, fnEnv);
if (res && res.type === "Return")
return await evaluate(res.value, fnEnv);
}
if (def.returnValue) return await evaluate(def.returnValue, fnEnv);
return;
}
throw new Error(
`CRUNCH! (Runtime Error: Unknown expression type '${node.type}' at line ${node.line}.)`
);
}
async function execute(node, env) {
switch (node.type) {
case "VariableDeclaration":
env.declareVar(node.name, await evaluate(node.value, env));
break;
case "Assignment":
env.setVar(node.name, await evaluate(node.value, env));
break;
case "Output":
console.log(await evaluate(node.value, env));
break;
case "Input":
env.setVar(node.name, await getInput());
break;
case "If": {
const cond = await evaluate(node.condition, env);
if (typeof cond !== "boolean")
throw new Error(
`CRUNCH! (Runtime Error: IF_ROAR condition must be boolean, got ${typeof cond} at line ${
node.line
}.)`
);
const branch = cond ? node.thenBranch : node.elseBranch;
for (const stmt of branch) await execute(stmt, env);
break;
}
case "While":
const conditionValue = await evaluate(node.condition, env);
if (typeof conditionValue !== "boolean")
throw new Error(
`CRUNCH! (Runtime Error: WHILE_ROAR condition must be boolean, got ${typeof conditionValue} at line ${
node.line
}.)`
);
while (await evaluate(node.condition, env)) {
for (const stmt of node.body) await execute(stmt, env);
}
break;
case "FunctionDeclaration":
env.declareFunction(node.name, node);
break;
case "Return":
return node;
case "FunctionCall":
await evaluate(node, env);
break;
default:
throw new Error(
`CRUNCH! (Runtime Error: Unknown node type '${node.type}' in execute.)`
);
}
}
for (const stmt of ast.body) await execute(stmt, globalEnv);
}
async function runRaaawr(code) {
try {
const tokens = tokenize(code);
const ast = parse(tokens);
const readline = require("readline");
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
const getInput = () =>
new Promise((res) => rl.question("", (ans) => res(ans)));
console.log("--- Raaawr Execution Started ---");
await interpret(ast, getInput);
console.log("--- Raaawr Execution Finished ---");
rl.close();
} catch (e) {
console.error("FATAL ERROR:", e.message);
}
}
const raaawrCode = `
GRRRRRRR!
RAAAWR! DINO_NAME RAAWR ""
ROAR "Welcome to the Jurassic Jungle!"
ROAR "What's your name, brave dinosaur?"
SNIFF DINO_NAME
ROAR "RAAAWR! " ROOOOAAR DINO_NAME ROOOOAAR " has entered the jungle."
RAAAWR! IS_HUNGRY RAAWR GRRR
RAAAWR! PREY_COUNT RAAWR 0
RAAAWR! ENERGY RAAWR 50
RAAAWR! MAX_ENERGY RAAWR 100
DEFINE_TERRITORY HUNT_PREY ()
ROAR "Looking for prey..."
RAAAWR. PREY_COUNT RAAWR (PREY_COUNT RAAWR+ 1)
RAAAWR. ENERGY RAAWR (ENERGY RAAWR- 10)
ROAR "Caught one prey! Total prey: " ROOOOAAR PREY_COUNT
END_TERRITORY
DEFINE_TERRITORY EAT_PREY ()
IF_ROAR (PREY_COUNT RAAWR> 0) THEN_CHOMP
RAAAWR. PREY_COUNT RAAWR (PREY_COUNT RAAWR- 1)
RAAAWR. ENERGY RAAWR (ENERGY RAAWR+ 20)
ROAR "Yum! Ate a prey! Energy: " ROOOOAAR ENERGY
ELSE_STOMP
ROAR "No prey to eat!"
END_HUNT
END_TERRITORY
DEFINE_TERRITORY NEED_REST ()
IF_ROAR (ENERGY RAAWR< 30) THEN_CHOMP
RETURN_PREY GRRR
ELSE_STOMP
RETURN_PREY HISS
END_HUNT
END_TERRITORY
RAAAWR! ACTION RAAWR ""
RAAAWR! NEEDS_REST RAAWR HISS
WHILE_ROAR (ENERGY RAAWR< MAX_ENERGY) KEEP_MIGRATING
ROAR "Energy level: " ROOOOAAR ENERGY
ROAR "Do you want to hunt or eat? (hunt/eat)"
SNIFF ACTION
IF_ROAR (ACTION RAAWR== "hunt") THEN_CHOMP
CALL_TERRITORY HUNT_PREY ()
ELSE_STOMP
CALL_TERRITORY EAT_PREY ()
END_HUNT
RAAAWR. NEEDS_REST RAAWR CALL_TERRITORY NEED_REST ()
IF_ROAR (NEEDS_REST RAAWR== GRRR) THEN_CHOMP
ROAR "You feel tired and need to rest."
RAAAWR. ENERGY RAAWR (ENERGY RAAWR+ 15)
ROAR "You rested and regained some energy."
END_HUNT
END_MIGRATION
ROAR "Well done, " ROOOOAAR DINO_NAME ROOOOAAR "! You survived the jungle!"
ROAR "Total prey caught: " ROOOOAAR PREY_COUNT
ROAR "Final energy: " ROOOOAAR ENERGY
ROAR "RAAAWR-some adventure ends here!"
DEFINE_TERRITORY Calculate_Energy_Cost (distance RAAWR terrain_difficulty)
RAAAWR! base_cost RAAWR (distance RAAWR* 2)
RAAAWR! terrain_modifier RAAWR (terrain_difficulty RAAWR% 3)
RAAAWR! total_cost RAAWR (base_cost RAAWR+ terrain_modifier)
RETURN_PREY total_cost
END_TERRITORY
RAAAWR! travel_distance RAAWR 15
RAAAWR! current_terrain RAAWR 7
RAAAWR! hunt_cost RAAWR CALL_TERRITORY Calculate_Energy_Cost(travel_distance RAAWR current_terrain)
ROAR "Calculated hunt energy cost: " ROOOOAAR hunt_cost
HSSSSSSS!
`;
runRaaawr(raaawrCode);