CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-parsimmon

A monadic LL(infinity) parser combinator library

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

core-parsers.mddocs/

Core Parser Construction

Fundamental parser creation and execution functionality. These are the building blocks for all parsing operations in Parsimmon.

Capabilities

Parsimmon Constructor

Creates a parser from a parsing function. This is the fundamental building block for all parsers.

/**
 * Creates a parser from a parsing function
 * @param {Function} action - Function that takes (input, index) and returns parse result
 * @returns {Parser} A new parser instance
 */
function Parsimmon(action);

Usage Examples:

// Custom parser that matches a specific word
const hello = Parsimmon(function(input, i) {
  const target = "hello";
  if (input.slice(i, i + target.length) === target) {
    return Parsimmon.makeSuccess(i + target.length, target);
  }
  return Parsimmon.makeFailure(i, `'${target}'`);
});

String Parser

Parses an exact string match. Case-sensitive.

/**
 * Creates a parser that matches an exact string
 * @param {string} str - The string to match
 * @returns {Parser} Parser that succeeds when input matches str
 */
Parsimmon.string(str);

Usage Examples:

const hello = Parsimmon.string("hello");
hello.parse("hello"); // { status: true, value: "hello" }
hello.parse("Hello"); // { status: false, ... }

// Case insensitive matching using regexp
const caseInsensitiveHello = Parsimmon.regexp(/hello/i);

Regular Expression Parser

Creates a parser from a regular expression pattern.

/**
 * Creates a parser that matches a regular expression
 * @param {RegExp} re - Regular expression to match
 * @param {number} [group=0] - Capture group to return (default: 0 for full match)
 * @returns {Parser} Parser that succeeds when regex matches
 */
Parsimmon.regexp(re, group);

// Alias for regexp
Parsimmon.regex(re, group);

Usage Examples:

// Match digits
const digits = Parsimmon.regexp(/[0-9]+/);
digits.parse("123"); // { status: true, value: "123" }

// Extract capture groups
const wordAndNumber = Parsimmon.regexp(/([a-z]+)([0-9]+)/, 1);
wordAndNumber.parse("abc123"); // { status: true, value: "abc" }

// Full match with all groups
const fullMatch = Parsimmon.regexp(/([a-z]+)([0-9]+)/);
fullMatch.parse("abc123"); // { status: true, value: "abc123" }

Success Parser

Always succeeds with a given value, consuming no input.

/**
 * Creates a parser that always succeeds with the given value
 * @param {any} value - Value to return on success
 * @returns {Parser} Parser that always succeeds
 */
Parsimmon.succeed(value);

// Alias for succeed
Parsimmon.of(value);

Usage Examples:

const alwaysTrue = Parsimmon.succeed(true);
alwaysTrue.parse("anything"); // { status: true, value: true }

// Useful for providing default values
const optionalName = Parsimmon.string("name").fallback("anonymous");

Failure Parser

Always fails with a given error message.

/**
 * Creates a parser that always fails
 * @param {string} message - Error message for the failure
 * @returns {Parser} Parser that always fails
 */
Parsimmon.fail(message);

Usage Examples:

const alwaysFails = Parsimmon.fail("This always fails");
alwaysFails.parse("anything"); // { status: false, expected: ["This always fails"] }

// Useful for conditional parsing
const validator = Parsimmon.regexp(/[0-9]+/).chain(function(numStr) {
  const num = parseInt(numStr);
  return num > 0 ? Parsimmon.succeed(num) : Parsimmon.fail("positive number");
});

Custom Parser

Creates a parser using a custom parsing function with access to success/failure constructors.

/**
 * Creates a custom parser with access to success/failure constructors
 * @param {Function} fn - Function receiving (succeed, fail) => (input, i) => result
 * @returns {Parser} Custom parser
 */
Parsimmon.custom(fn);

Usage Examples:

// Custom parser for balanced parentheses
const balanced = Parsimmon.custom(function(succeed, fail) {
  return function(input, i) {
    let depth = 0;
    let j = i;
    
    while (j < input.length) {
      if (input[j] === "(") depth++;
      else if (input[j] === ")") depth--;
      else if (depth === 0) break;
      j++;
    }
    
    if (depth === 0 && j > i) {
      return succeed(j, input.slice(i, j));
    }
    return fail(i, "balanced parentheses");
  };
});

Parser Execution Methods

Methods for executing parsers on input strings.

/**
 * Parses input and returns detailed result object
 * @param {string|Buffer} input - Input to parse
 * @returns {ParseResult} Result with status, value, and error information
 */
parser.parse(input);

/**
 * Parses input and returns value or throws error
 * @param {string|Buffer} input - Input to parse
 * @returns {any} Parsed value
 * @throws {Error} Formatted parsing error
 */
parser.tryParse(input);

Usage Examples:

const number = Parsimmon.regexp(/[0-9]+/).map(Number);

// Using parse() - returns result object
const result = number.parse("42");
if (result.status) {
  console.log("Success:", result.value); // Success: 42
} else {
  console.log("Error:", result.expected);
}

// Using tryParse() - throws on error
try {
  const value = number.tryParse("42");
  console.log("Success:", value); // Success: 42
} catch (err) {
  console.log("Error:", err.message);
}

Utility Functions

Helper functions for working with parse results.

/**
 * Check if an object is a parser
 * @param {any} obj - Object to test
 * @returns {boolean} True if obj is a parser
 */
Parsimmon.isParser(obj);

/**
 * Create a success result object
 * @param {number} index - Position after successful parse
 * @param {any} value - Parsed value
 * @returns {ParseResult} Success result
 */
Parsimmon.makeSuccess(index, value);

/**
 * Create a failure result object
 * @param {number} index - Position where parsing failed
 * @param {string|string[]} expected - Expected input description
 * @returns {ParseResult} Failure result
 */
Parsimmon.makeFailure(index, expected);

/**
 * Format a parse error for display
 * @param {string} input - Original input
 * @param {ParseResult} error - Error result from parse()
 * @returns {string} Formatted error message
 */
Parsimmon.formatError(input, error);

Usage Examples:

// Check if something is a parser
const isParser = Parsimmon.isParser(Parsimmon.string("test")); // true
const notParser = Parsimmon.isParser("test"); // false

// Format errors nicely
const parser = Parsimmon.string("hello");
const result = parser.parse("hi there");
if (!result.status) {
  const errorMsg = Parsimmon.formatError("hi there", result);
  console.log(errorMsg); // Shows formatted error with position
}

Install with Tessl CLI

npx tessl i tessl/npm-parsimmon

docs

binary-parsing.md

combinators.md

core-parsers.md

index.md

language-creation.md

string-parsers.md

transformation.md

tile.json