Giter Club home page Giter Club logo

pratt's Introduction

pratt

A Pratt parser builder.

Pratt parsers are top-down operator precedence (TDOP) parsers, and they are awesome. They operate off of a few simple principles, and make expression parsing simple.

Read more about Pratt parsers:

  • here (TDOP by Douglas Crockford)
  • here (Pratt Parsers: Expression Parsing Made Easy)
  • and here (Top Down Operator Precedence [the original paper by Vaughan R. Pratt])

Installation

npm install --save pratt
# or
yarn add pratt

Usage

This README merely serves as an example. Be sure to read the API documentation.

Make a simple calculator:

import * as perplex from 'perplex'
import {Parser} from 'pratt'

const lex = perplex('1 + -2 * 3^4')
	.token('NUM', /\d+/)
	.token('+', /\+/)
	.token('-', /-/)
	.token('*', /\*/)
	.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(bp - 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

License (ISC)

ISC License (ISC) Copyright 2017 Jonathan Apodaca [email protected]

Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

pratt's People

Contributors

jrop avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

pratt's Issues

Action required: Greenkeeper could not be activated 🚨

🚨 You need to enable Continuous Integration on all branches of this repository. 🚨

To enable Greenkeeper, you need to make sure that a commit status is reported on all branches. This is required by Greenkeeper because we are using your CI build statuses to figure out when to notify you about breaking changes.

Since we did not receive a CI status on the greenkeeper/initial branch, we assume that you still need to configure it.

If you have already set up a CI for this repository, you might need to check your configuration. Make sure it will run on all new branches. If you don’t want it to run on every branch, you can whitelist branches starting with greenkeeper/.

We recommend using Travis CI, but Greenkeeper will work with every other CI service as well.

Once you have installed CI on this repository, you’ll need to re-trigger Greenkeeper’s initial Pull Request. To do this, please delete the greenkeeper/initial branch in this repository, and then remove and re-add this repository to the Greenkeeper integration’s white list on Github. You'll find this list on your repo or organiszation’s settings page, under Installed GitHub Apps.

Example fails after 'Cannot create property 'stop' on number '30''

Trying to get the example and tests running.

The led and nud functions supplied to the builder now have the signature

export declare type NudFunction<T> = (inf: NudInfo<T>) => any;
export declare type LedFunction<T> = (inf: LedInfo<T>) => any;

so I can fix up the examples, e.g.:

-  .led('+', 30, (left, t, bp) => left + parser.parse(bp))
+  .led('+', 30, ({ left, t, bp }) => left + parser.parse(bp))

However, parser.parse only takes a ParseOpts, not a BP.

parse(opts?: ParseOpts<T>): any;

export declare type ParseOpts<T> = {
    ctx?: any;
    stop?: StopFunction;
    terminals?: (number | T)[];
};

Unfortunately, the code fails with:

Cannot create property 'stop' on number '30'

because we're explicitly passing parser.parse(bp?: BP) in all operator functions. Should you be passing in a parser which has a parse(bp: BP) method into the operator functions?

Very happy to submit a PR for documentation changes, but I don't thing I understand the parser enough to make implement the fixes.

Please adivse. Thank you so much.

Code

import { test } from 'tap';

import Lexer from 'perplex'
import { Parser } from 'pratt'

const lex = new Lexer('1 + -2 * 3^4')
  .token('NUM', /\d+/)
  .token('+', /\+/)
  .token('-', /-/)
  .token('*', /\*/)
  .token('/', /\//)
  .token('^', /\^/)
  .token('(', /\(/)
  .token(')', /\)/)
  .token('$SKIP_WS', /\s+/, true)

const parser = new Parser(lex)
  .builder()
  .nud('NUM', 100, ({ token }) => parseInt(token.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(bp - 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()

test('example works', t => {
  t.equal(-161, parser.parse());
  t.end();
});

Stacktrace:

    TAP version 13
    not ok 1 TypeError: Cannot create property 'stop' on number '30'
      ---
        type:    TypeError
        message: Cannot create property 'stop' on number '30'
        code:    ~
        errno:   ~
        file:    events.js
        line:    202
        column:  15
        stack:
          - |
            Parser.parse (webpack:///./node_modules/pratt/lib/index.js?:127:31)
          - |
            _pratt.Parser.builder.nud.nud.nud.bp.led.led (webpack:///./test/parser/test-pratt-example.js?:19:135)
          - |
            Parser.led (webpack:///./node_modules/pratt/lib/index.js?:117:16)
          - |
            Parser.parse (webpack:///./node_modules/pratt/lib/index.js?:153:25)
          - |
            Test.t (webpack:///./test/parser/test-pratt-example.js?:22:24)
          - |
            Test.emit (events.js:202:15)
          - |
            Test.eval [as emit] (webpack:///./node_modules/tap/lib/tap-test.js?:104:8)
          - |
            GlobalHarness.Harness.process (webpack:///./node_modules/tap/lib/tap-harness.js?:87:13)
          - |
            processTicksAndRejections (internal/process/next_tick.js:74:9)
          - |
            process.runNextTicks [as _tickCallback] (internal/process/next_tick.js:51:3)
        thrown:  true
      ...

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.