Skip to content
parser combinators for typescript and javascript
Branch: master
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
.vscode
dist
s
src
.gitignore
.npmignore
LICENSE
README.md
package.json
test.js
tsconfig.json

README.md

Parsinator

Parsinator is a TypeScript/JavaScript library that lets you build small well-defined parsers which can be combined together to accomplish just about any parsing task.

Installation

npm install parsinator

Documentation

Technical documentation is a bit light, so your best bet is to look at the docstrings in the typescript declaration files: dist/es5-bundle/parsinator-amd.d.ts

Usage

TypeScript

import * as Parser from 'parsinator';

var parseNaturalNumber: Parser.Parser<number> = Parser.map<string,number>(
    Parser.regex(/[1-9][0-9]*|0/),
    (str: string): number => parseInt(str, 10)
);

var parseSum: Parser.Parser<number> = Parser.fromGenerator(function *() {
    var left = yield parseNaturalNumber;
    yield Parser.str("+");
    var right = yield parseNaturalNumber;
    return left + right;
});

Parser.run(parseSum, "123+456"); // evaluates to: 579
Parser.run(parseSum, "23.5+92"); // throws error:
// Error: Parse failure at 1:3: "+" not found
// -> "23.5+92"
//       ^

JavaScript (ES2015)

import * as Parser from 'parsinator';

var parseNaturalNumber = Parser.map(
    Parser.regex(/[1-9][0-9]*|0/),
    (str) => parseInt(str, 10)
);

var parseSum = Parser.fromGenerator(function *() {
    var left = yield parseNaturalNumber;
    yield Parser.str("+");
    var right = yield parseNaturalNumber;
    return left + right;
});

Parser.run(parseSum, "123+456"); // evaluates to: 579
Parser.run(parseSum, "23.5+92"); // throws error:
// Error: Parse failure at 1:3: "+" not found
// -> "23.5+92"
//       ^

JavaScript (ES5+commonjs)

Unfortunately, generator functions aren't in ES5, so you lose the monadic interface and must rely on a more manual approach.

var Parser = require('parsinator');

var parseNaturalNumber = Parser.map(
    Parser.regex(/[1-9][0-9]*|0/),
    function (str) {
        return parseInt(str, 10);
    }
);

var parseSum = Parser.map(Parser.sequence([
    parseNaturalNumber,
    Parser.str("+"),
    parseNaturalNumber
]), function (items) {
    return items[0] + items[2];
});

Parser.run(parseSum, "123+456"); // -> 579
Parser.run(parseSum, "23.5+92"); // throws error:
// Error: Parse failure at 1:3: "+" not found
// -> "23.5+92"
//       ^
You can’t perform that action at this time.