Home Reference Source Repository
import {Parser} from 'pratt'
public class | source

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

bp(tokenOrType: IToken<T> | T): number

Define binding power for a token-type

public

Create a ParserBuilder

public

led(info: LedInfo<T>): any

Computes a token's led value and returns it

public

nud(info: NudInfo<T>): any

Computes the token's nud value and returns it

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:

NameTypeAttributeDescription
lexer ILexer<T>

The lexer to obtain tokens from

Public Members

public lexer: ILexer<T> source

The lexer that this parser is operating on.

Public Methods

public bp(tokenOrType: IToken<T> | T): number source

Define binding power for a token-type

Params:

NameTypeAttributeDescription
tokenOrType IToken<T> | T

The token type to define the binding power for

Return:

number

The binding power of the specified token type

public builder(): ParserBuilder<T> source

Create a ParserBuilder

Return:

ParserBuilder<T>

Returns the ParserBuilder

public led(info: LedInfo<T>): any source

Computes a token's led value and returns it

Params:

NameTypeAttributeDescription
info LedInfo<T>

The info to compute the led value for

Return:

any

The result of invoking the pertinent led operator

public nud(info: NudInfo<T>): any source

Computes the token's nud value and returns it

Params:

NameTypeAttributeDescription
info NudInfo<T>

The info to compute the nud from

Return:

any

The result of invoking the pertinent nud operator

public parse(opts: ParseOpts<T>): any source

Kicks off the Pratt parser, and returns the result

Params:

NameTypeAttributeDescription
opts ParseOpts<T>

The parse options

Return:

any