From 843842ebf58f52f38ebdb6f735024f7bce309eb3 Mon Sep 17 00:00:00 2001 From: elioat Date: Sun, 7 Jan 2024 13:09:14 -0500 Subject: I mean, it does not work...but perhaps that is fine --- js/scripting-lang/input.txt | 3 +++ js/scripting-lang/lang.js | 54 +++++++++++++++++++++++---------------------- 2 files changed, 31 insertions(+), 26 deletions(-) create mode 100644 js/scripting-lang/input.txt (limited to 'js') diff --git a/js/scripting-lang/input.txt b/js/scripting-lang/input.txt new file mode 100644 index 0000000..d343086 --- /dev/null +++ b/js/scripting-lang/input.txt @@ -0,0 +1,3 @@ +x : 10; +y : 20; +x + y; \ No newline at end of file diff --git a/js/scripting-lang/lang.js b/js/scripting-lang/lang.js index 11a7ee5..f91f842 100644 --- a/js/scripting-lang/lang.js +++ b/js/scripting-lang/lang.js @@ -11,6 +11,7 @@ const TokenType = { RIGHT_PAREN: 'RIGHT_PAREN', LEFT_BRACE: 'LEFT_BRACE', RIGHT_BRACE: 'RIGHT_BRACE', + SEMICOLON: 'SEMICOLON', }; // Lexer @@ -127,6 +128,12 @@ function lexer(input) { continue; } + if (char === ';') { + tokens.push({ type: TokenType.SEMICOLON }); + current++; + continue; + } + current++; } @@ -223,6 +230,11 @@ function parser(tokens) { return node; } + if (token.type === TokenType.SEMICOLON) { + current++; + return; + } + throw new TypeError(token.type); } @@ -286,33 +298,23 @@ function interpreter(ast) { } // Usage -const tokens = lexer('2 + 2'); -const ast = parser(tokens); -const result = interpreter(ast); -console.log(result); // 4 - -/* -// Define a variable -let a = 10; +// const tokens = lexer('2 + 2'); +// const ast = parser(tokens); +// const result = interpreter(ast); +// console.log(result); // 4 -// Assign a new value to a variable -a = 20; - -// Define a function -function add(x, y) { - return x + y; -} +// const tokens2 = lexer('x : 2 + 2'); +// const ast2 = parser(tokens2); +// const result2 = interpreter(ast2); +// console.log(result2); -// Call a function -let b = add(a, 5); +const fs = require('fs'); -// If statement -if (b == 25) { - b = b + 5; -} else { - b = b - 5; -} +// Read the input from a file +const input = fs.readFileSync('input.txt', 'utf-8'); -// Print the result -console.log(b); -*/ \ No newline at end of file +// Usage +const tokens = lexer(input); +const ast = parser(tokens); +const result = interpreter(ast); +console.log(result); \ No newline at end of file -- cgit 1.4.1-2-gfad0