initial commit
This commit is contained in:
24
modules/lexer.js
Normal file
24
modules/lexer.js
Normal file
@@ -0,0 +1,24 @@
|
||||
function tokenize(expr) {
|
||||
// NOTE: not handling whitespace
|
||||
// NOTE: currently ends early if string doesn't match token
|
||||
// FIXME: need to handle unary minus (e.g. on parentheses)
|
||||
const regexp = /-?[0-9]+|[-+*/^]|\(|\)/gy;
|
||||
const matches = expr.matchAll(regexp);
|
||||
|
||||
const tokens = [];
|
||||
for (const match of matches) {
|
||||
if (/[0-9]+/.test(match[0])) {
|
||||
tokens.push(BigInt(match[0]));
|
||||
} else if (/[-+*^/]/.test(match[0])) {
|
||||
tokens.push(match[0])
|
||||
} else if (match[0] == "(") {
|
||||
tokens.push("(");
|
||||
} else if (match[0] == ")") {
|
||||
tokens.push(")");
|
||||
}
|
||||
}
|
||||
|
||||
return tokens;
|
||||
}
|
||||
|
||||
export { tokenize };
|
||||
69
modules/parser.js
Normal file
69
modules/parser.js
Normal file
@@ -0,0 +1,69 @@
|
||||
function isLeftAssociative(op) {
|
||||
return op === "+" || op === "-" || op === "*" || op === "/";
|
||||
}
|
||||
|
||||
function popOps(opstack, queue, op) {
|
||||
const prec = {"+": 1, "-": 1, "*": 2, "/": 2, "^": 3}
|
||||
while (true) {
|
||||
const op2 = opstack.at(-1);
|
||||
if (op2 === undefined) {
|
||||
break;
|
||||
} else if (op2 === "(") {
|
||||
break;
|
||||
}
|
||||
|
||||
if ((prec[op2] > prec[op]) || (prec[op2] === prec[op] && isLeftAssociative(op))) {
|
||||
opstack.pop();
|
||||
queue.push(op2);
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
opstack.push(op);
|
||||
}
|
||||
|
||||
function popBetweenParens(opstack, queue) {
|
||||
while (opstack.at(-1) !== "(") {
|
||||
if (opstack.length === 0) {
|
||||
throw new Error("mismatched parentheses");
|
||||
}
|
||||
|
||||
const op = opstack.pop();
|
||||
queue.push(op);
|
||||
}
|
||||
|
||||
opstack.pop();
|
||||
}
|
||||
|
||||
function empty(opstack, queue) {
|
||||
while (opstack.length !== 0) {
|
||||
const op = opstack.pop();
|
||||
if (op === "(") {
|
||||
throw new Error("mismatched parentheses");
|
||||
}
|
||||
|
||||
queue.push(op);
|
||||
}
|
||||
}
|
||||
|
||||
function shunt(tokens) {
|
||||
const queue = [];
|
||||
const opstack = [];
|
||||
for (const token of tokens) {
|
||||
if (typeof token === "bigint") {
|
||||
queue.push(token);
|
||||
} else if (/[-+*/^]/.test(token)) {
|
||||
popOps(opstack, queue, token);
|
||||
} else if (token === "(") {
|
||||
opstack.push(token);
|
||||
} else if (token === ")") {
|
||||
popBetweenParens(opstack, queue);
|
||||
}
|
||||
}
|
||||
|
||||
empty(opstack, queue);
|
||||
return queue;
|
||||
}
|
||||
|
||||
export { shunt };
|
||||
Reference in New Issue
Block a user