pratt-parser
TypeScript icon, indicating that this package has built-in type declarations

10.0.2 • Public • Published

npm License Typed with TypeScript bundlejs downloads GitHub Issues Build Status Styled with prettier Commitizen friendly Known Vulnerabilities Coverage Status

pratt-parser

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);

API

Table of Contents

ParsePosition

Type: Object

Properties

Token

Type: Object

Properties

RootToken

Base object for all tokens

parseString

Parses from chunk of PrasePosition and delivers next token Modifies ParsePosition so that it points behind the detected token.

Parameters

Returns Token

WhiteSpaceToken

skip white space

LineCommentToken

skips until end of line

EOFToken

Token representing 'end of file'

Parser

Creates a grammar for later parsing

Parameters

error

Forwards error to the tokenizer

Parameters

  • args ...any

Returns Object error

parse

Parses the input and delivers the outermoost expression.

Parameters

  • chunk string input text
  • context Object object transparently passed to tokenizer

Returns Object evaluated input

Tokenizer

Creates a tokenizer for later parsing.

Parameters

  • grammar Object definition of the grammar with operators...

tokens

delivers tokens from the input.

Parameters

  • chunk string the input to be processed
  • context Object additional info to be used by the actual token types

error

Parameters

Returns Object error

install

With npm do:

npm install pratt-parser

license

BSD-2-Clause

Package Sidebar

Install

npm i pratt-parser

Weekly Downloads

983

Version

10.0.2

License

BSD-2-Clause

Unpacked Size

26.2 kB

Total Files

9

Last publish

Collaborators

  • arlac77