Parser
A Pratt parser.
Example:
const lex = new perplex.Lexer('1 + -2 * 3^4')
.token('NUM', /\d+/)
.token('+', /\+/)
.token('-', /-/)
.token('*', new RegExp('*'))
.token('/', /\//)
.token('^', /\^/)
.token('(', /\(/)
.token(')', /\)/)
.token('$SKIP_WS', /\s+/)
const parser = new Parser(lex)
.builder()
.nud('NUM', 100, t => parseInt(t.match))
.nud('-', 10, (t, bp) => -parser.parse(bp))
.nud('(', 10, (t, bp) => {
const expr = parser.parse(bp)
lex.expect(')')
return expr
})
.bp(')', 0)
.led('^', 20, (left, t, bp) => Math.pow(left, parser.parse(20 - 1)))
.led('+', 30, (left, t, bp) => left + parser.parse(bp))
.led('-', 30, (left, t, bp) => left - parser.parse(bp))
.led('*', 40, (left, t, bp) => left * parser.parse(bp))
.led('/', 40, (left, t, bp) => left / parser.parse(bp))
.build()
parser.parse()
// => 161
Constructor Summary
Public Constructor | ||
public |
constructor(lexer: ILexer<T>) Constructs a Parser instance |
Member Summary
Public Members | ||
public |
lexer: ILexer<T> The lexer that this parser is operating on. |
Method Summary
Public Methods | ||
public |
Define binding power for a token-type |
|
public |
builder(): ParserBuilder<T> Create a ParserBuilder |
|
public |
led(info: LedInfo<T>): any Computes a token's |
|
public |
nud(info: NudInfo<T>): any Computes the token's |
|
public |
parse(opts: ParseOpts<T>): any Kicks off the Pratt parser, and returns the result |
Public Constructors
public constructor(lexer: ILexer<T>) source
Constructs a Parser instance
Params:
Name | Type | Attribute | Description |
lexer | ILexer<T> | The lexer to obtain tokens from |
Public Members
Public Methods
public bp(tokenOrType: IToken<T> | T): number source
Define binding power for a token-type
Params:
Name | Type | Attribute | Description |
tokenOrType | IToken<T> | T | The token type to define the binding power for |
public led(info: LedInfo<T>): any source
Computes a token's led
value and returns it
Params:
Name | Type | Attribute | Description |
info | LedInfo<T> | The info to compute the |
Return:
any | The result of invoking the pertinent |
public nud(info: NudInfo<T>): any source
Computes the token's nud
value and returns it
Params:
Name | Type | Attribute | Description |
info | NudInfo<T> | The info to compute the |
Return:
any | The result of invoking the pertinent |
public parse(opts: ParseOpts<T>): any source
Kicks off the Pratt parser, and returns the result
Params:
Name | Type | Attribute | Description |
opts | ParseOpts<T> | The parse options |
Return:
any |