TypeScript Parser Combinators (parser-ts)

0.7.0 · active · verified Tue Apr 21

`parser-ts` is a library providing string parser combinators for TypeScript, heavily influenced by the `purescript-eulalie` library and built upon the foundational `fp-ts` functional programming toolkit. It enables developers to construct complex parsers by combining simpler parsing functions in a declarative manner, leveraging `fp-ts`'s algebraic data types and functional patterns. The current stable version is 0.7.0, with releases occurring periodically to address bugs, introduce new combinators, and align with `fp-ts` peer dependency updates. Its key differentiators include its strong TypeScript typing, functional purity, and close integration with the `fp-ts` ecosystem, making it suitable for applications requiring robust and composable parsing logic within a functional TypeScript codebase. The library primarily focuses on string parsing and is often used for creating DSLs, configuration file parsers, or simple language frontends.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to define a parser for a comma-separated list of integers using basic combinators like `char`, `many1`, `recognize`, `map`, and `sepBy`, and then run it against various inputs.

import { pipe } from 'fp-ts/function';
import * as P from 'parser-ts/Parser';
import * as S from 'parser-ts/string';
import * as C from 'parser-ts/char';
import * as E from 'fp-ts/Either';

// Define a parser for one or more digits, then convert to an integer
const integerParser = pipe(
  S.recognize(C.many1(C.digit)), // `recognize` captures the matched string
  P.map(parseInt)              // `map` transforms the parsed string to a number
);

// Define a parser for a literal comma character
const commaParser = C.char(',');

// Define a parser for a list of integers separated by commas
// `sepBy` applies `integerParser`, consuming `commaParser` in between
const commaSeparatedIntegersParser = pipe(
  integerParser,
  P.sepBy(commaParser)
);

// Helper function to run the parser and log results
const parseNumbers = (input: string) => {
  console.log(`\nAttempting to parse: "${input}"`);
  const result = P.run(commaSeparatedIntegersParser, input);
  E.match(
    (error) => console.error('Parse Error:', error.message, 'at position', error.offset),
    ([value, remaining]) => console.log('Parsed Value:', value, '| Remaining Input:', remaining.length === 0 ? 'None' : `"${remaining}"`) 
  )(result);
};

// Example Usage
parseNumbers('1,2,3,4');
parseNumbers('100');
parseNumbers('1, 2, 3'); // Fails due to unexpected space
parseNumbers('abc');
parseNumbers('1,2,abc');

view raw JSON →