项目作者: bwrrp

项目描述 :
Tiny parser combinators library
高级语言: TypeScript
项目地址: git://github.com/bwrrp/prsc.js.git
创建时间: 2019-11-01T10:10:16Z
项目社区:https://github.com/bwrrp/prsc.js

开源协议:MIT License

下载


prsc

NPM version
CI

Tiny parser combinators library for JavaScript and TypeScript. Heavily
inspired by nom.

Installation

The prsc library can be installed using npm or yarn:

  1. npm install --save prsc

or

  1. yarn add prsc

The package includes both a UMD bundle (dist/prsc.js), compatible with
Node.js, and an ES6 module (dist/prsc.mjs). TypeScript typings are included
(dist/prsc.d.ts) and should work automatically in most cases.

Usage

This library exports a number of functions that make it
easy to build parsers for input represented as a string. Start from primitive
parsers such as token or your own functions matching the Parser type,
transform results using map and filter and combine them using the other
functions such as then and star.

Example

The following parser accepts a simple arithmetic language consisting of the
+ and * operators:

  1. // Create a primitive parser that accepts a single digit
  2. const digit = (input, offset) => {
  3. if (/^[0-9]$/.test(input[offset])) {
  4. return ok(offset + 1);
  5. }
  6. return error(offset, ['digit']);
  7. };
  8. // Use that to accept a string of one or more digits
  9. const digits = plus(digit);
  10. // Then use recognize to get the matching string and use map to parse that into a number
  11. const number = map(recognize(digits), (str) => parseInt(str, 10));
  12. // Multiplication
  13. const term = then(
  14. number,
  15. star(preceded(token('*'), number)),
  16. // Multiply everything together
  17. (num, factors) => factors.reduce((product, factor) => product * factor, num)
  18. );
  19. // Addition
  20. const expression = then(term, star(preceded(token('+'), term)), (num, terms) =>
  21. terms.reduce((sum, term) => sum + term, num)
  22. );
  23. // Parsing some input
  24. console.log(expression('2*3+4*5', 0));
  25. // > { success: true, offset: 7, value: 26 }

Tips

Use functions to provide a layer of indirection for recursive definitions:

  1. const term = then(number, optional(preceded(token('*'), termIndirect)), ...);
  2. function termIndirect(input, offset) {
  3. return term(input, offset);
  4. }

Use the typings when working in TypeScript for strongly-typed parsers:

  1. const digit: Parser<string> = ...;
  2. const digits = plus(digit); // Parser<string[]>
  3. const number = map(
  4. digits,
  5. strs => parseInt(strs.join(''), 10)
  6. ); // Parser<number>