Pratt Parser
Based on Top Down Operator Precedence and Douglas Crockford TDOP
import { Parser, WhiteSpaceToken, NumberToken } from "pratt-parser";
function Value(value) {
return Object.create(null, {
value: {
value: value
}
});
}
const myGrammar = new Parser({
tokens: [WhiteSpaceToken, NumberToken],
prefix: {
"(": {
nud(grammar) {
const e = grammar.expression(0);
grammar.advance(")");
return e;
}
}
},
infix: {
")": {},
"+": {
precedence: 50,
combine: (left, right) => Value(left.value + right.value)
},
"-": {
precedence: 50,
combine: (left, right) => Value(left.value - right.value)
},
"*": {
precedence: 60,
combine: (left, right) => Value(left.value * right.value)
},
"/": {
precedence: 60,
combine: (left, right) => Value(left.value / right.value)
}
}
});
console.log(myGrammar.parse("(1 + (1 + 4 * 3)) * (2 + 1)").value);
Type: Object
Type: Object
Base object for all tokens
Parses from chunk of PrasePosition and delivers next token Modifies ParsePosition so that it points behind the detected token.
Returns Token
skip white space
skips until end of line
Token representing 'end of file'
Creates a grammar for later parsing
grammar
anyoptions
Object?
Forwards error to the tokenizer
args
...any
Returns Object error
Parses the input and delivers the outermoost expression.
Returns Object evaluated input
Creates a tokenizer for later parsing.
grammar
Object definition of the grammar with operators...
delivers tokens from the input.
chunk
string the input to be processedcontext
Object additional info to be used by the actual token types
Returns Object error
With npm do:
npm install pratt-parser
BSD-2-Clause