### Create a Custom Parser with Parsimmon.custom Source: https://github.com/jneen/parsimmon/blob/master/API.md Use Parsimmon.custom to define a primitive parser. This example creates a parser that matches any character except a specified one. ```javascript function notChar(char) { return Parsimmon.custom(function(success, failure) { return function(input, i) { if (input.charAt(i) !== char) { return success(i + 1, input.charAt(i)); } return failure(i, 'anything different than "' + char + '"'); }; }); } ``` -------------------------------- ### Compose Custom Parsers with Parsimmon.seq Source: https://github.com/jneen/parsimmon/blob/master/API.md Demonstrates composing a custom parser with existing Parsimmon combinators. This example uses Parsimmon.seq to combine a string parser with a custom notChar parser. ```javascript var parser = Parsimmon.seq(Parsimmon.string("a"), notChar("b").times(5)); parser.parse("accccc"); // => { status: true, value: ['a', ['c', 'c', 'c', 'c', 'c']] } ``` -------------------------------- ### Contramap Input Transformation Caveat Source: https://github.com/jneen/parsimmon/blob/master/API.md Demonstrates a caveat where `contramap` can cause subsequent parsers in a sequence to fail due to input transformation. This example shows a failing case and a workaround. ```javascript Parsimmon.seq( Parsimmon.string("a"), Parsimmon.string("c").contramap(function(x) { return x.slice(1); }), Parsimmon.string("d") ) .tie() .parse("abcd"); //this will fail Parsimmon.seq( Parsimmon.string("a"), Parsimmon.seq(Parsimmon.string("c"), Parsimmon.string("d")) .tie() .contramap(function(x) { return x.slice(1); }) ) .tie() .parse("abcd"); // => {status: true, value: 'acd'} ``` -------------------------------- ### parser.lookahead(string) Source: https://github.com/jneen/parsimmon/blob/master/API.md Creates a parser that checks if the input starts with a specific `string` without consuming it. It yields the same result as the original parser. ```APIDOC ## parser.lookahead(string) ### Description Returns a parser that looks for `string` but does not consume it. Yields the same result as `parser`. Equivalent to `parser.skip(Parsimmon.lookahead(string))`. ``` -------------------------------- ### Using parser.mark() Source: https://github.com/jneen/parsimmon/blob/master/API.md The mark() method adds start and end position information to the parsed value. It returns an object with start, value, and end keys, where start and end contain offset, line, and column details. ```javascript var Identifier = Parsimmon.regexp(/[a-z]+/).mark(); Identifier.tryParse("hey"); // => { start: { offset: 0, line: 1, column: 1 }, // value: 'hey', // end: { offset: 3, line: 1, column: 4 } } ``` -------------------------------- ### Parse a Specific Byte with Parsimmon.Binary.byte Source: https://github.com/jneen/parsimmon/blob/master/API.md Parses binary content to yield a specific byte value. This example uses Parsimmon.Binary.byte to match the byte 0x3f. ```javascript var parser = Parsimmon.Binary.byte(0x3f); parser.parse(Buffer.from([0x3f])); // => { status: true, value: 63 } ``` -------------------------------- ### Map Regexp Parser Source: https://github.com/jneen/parsimmon/blob/master/GUIDE.md Transforms the yielded value of a regular expression parser. This example converts a matched digit string to a number and doubles it. ```javascript Parsimmon.regexp(/[0-9]+/).map(function(x) { return Number(x) * 2; }); ``` -------------------------------- ### Parse Delimited Strings with Parsimmon.takeWhile Source: https://github.com/jneen/parsimmon/blob/master/API.md This example defines a custom string parser that captures content between matching delimiters like %, [], (), {}, or <>. It uses takeWhile to consume characters until the closing delimiter is found. ```javascript var CustomString = Parsimmon.string("%") .then(Parsimmon.any) .chain(function(start) { var end = { "[": "]", "(": ")", "{": "}", "<": ">" }[start] || start; return Parsimmon.takeWhile(function(c) { return c !== end; }).skip(Parsimmon.string(end)); }); CustomString.parse("%:a string:"); // => {status: true, value: 'a string'} CustomString.parse("%[a string]"); // => {status: true, value: 'a string'} CustomString.parse("%{a string}"); // => {status: true, value: 'a string'} CustomString.parse("%(a string)"); // => {status: true, value: 'a string'} CustomString.parse("%"); // => {status: true, value: 'a string'} ``` -------------------------------- ### parser.node(name) Source: https://github.com/jneen/parsimmon/blob/master/API.md Yields an object with name, value, start, and end keys. The value is the original parser result, name is the provided argument, and start/end indicate the position in the input. ```APIDOC ## parser.node(name) ### Description Yields an object with `name`, `value`, `start`, and `end` keys, where `value` is the original value yielded by the parser, `name` is the argument passed in, and `start` and `end` are are objects with a 0-based `offset` and 1-based `line` and `column` properties that represent the position in the input that contained the parsed text. ### Method N/A (Method chaining on a parser object) ### Endpoint N/A ### Request Example ```js var Identifier = Parsimmon.regexp(/[a-z]+/).node("Identifier"); Identifier.tryParse("hey"); // => { name: 'Identifier', // value: 'hey', // start: { offset: 0, line: 1, column: 1 }, // end: { offset: 3, line: 1, column: 4 } } ``` ``` -------------------------------- ### Equivalent to wrap using then and skip Source: https://github.com/jneen/parsimmon/blob/master/API.md Illustrates how the `wrap` functionality can be implemented using `then` and `skip` with specified before and after parsers. ```javascript before.then(parser).skip(after); ``` -------------------------------- ### Equivalent to trim using then and skip Source: https://github.com/jneen/parsimmon/blob/master/API.md Demonstrates an alternative implementation of the `trim` functionality using a combination of `then` and `skip` parsers. ```javascript anotherParser.then(parser).skip(anotherParser); ``` -------------------------------- ### Create Alternative Parser with Parsimmon.alt Source: https://github.com/jneen/parsimmon/blob/master/API.md Use Parsimmon.alt to create a parser that tries multiple parsers in order and returns the value of the first one that succeeds. The order matters, and longer matches should come first. ```javascript Parsimmon.alt(Parsimmon.string("ab"), Parsimmon.string("a")).parse("ab"); // => {status: true, value: 'ab'} ``` ```javascript Parsimmon.alt(Parsimmon.string("a"), Parsimmon.string("ab")).parse("ab"); // => {status: false, ...} ``` -------------------------------- ### Parsimmon Constructors Source: https://github.com/jneen/parsimmon/blob/master/API.md Parsimmon provides a rich set of static methods for creating parsers, ranging from basic string and character matching to regular expressions and sequence/alternative combinators. ```APIDOC ## Parsimmon Constructors Parsimmon offers various static methods to create parser instances: - **Parsimmon.createLanguage(parsers)**: Creates a language object from a map of parsers. - **Parsimmon(fn)**: Creates a parser from a function. - **Parsimmon.Parser(fn)**: Constructor for creating a parser. - **Parsimmon.makeSuccess(index, value)**: Creates a successful parse result. - **Parsimmon.makeFailure(furthest, expectation)**: Creates a failed parse result. - **Parsimmon.isParser(obj)**: Checks if an object is a Parsimmon parser. - **Parsimmon.string(string)**: Creates a parser that matches a literal string. - **Parsimmon.oneOf(string)**: Creates a parser that matches any single character in the string. - **Parsimmon.noneOf(string)**: Creates a parser that matches any single character not in the string. - **Parsimmon.range(begin, end)**: Creates a parser that matches a single character within a given range. - **Parsimmon.regexp(regexp, [group])**: Creates a parser that matches a regular expression. Optionally captures a specific group. - **Parsimmon.regex**: Alias for Parsimmon.regexp. - **Parsimmon.notFollowedBy(parser)**: Creates a lookahead parser that fails if the given parser matches. - **Parsimmon.lookahead(parser | string | regexp)**: Creates a lookahead parser that succeeds if the given parser/string/regexp matches without consuming input. - **Parsimmon.succeed(result)**: Creates a parser that always succeeds with the given result without consuming input. - **Parsimmon.of(result)**: Creates a parser that always succeeds with the given result. - **Parsimmon.formatError(string, error)**: Formats a parse error for display. - **Parsimmon.seq(p1, p2, ...pn)**: Creates a parser that matches a sequence of parsers. - **Parsimmon.seqMap(p1, p2, ...pn, function(r1, r2, ...rn))**: Creates a parser that matches a sequence and maps the results using a function. - **Parsimmon.seqObj(...args)**: Creates a parser that matches a sequence of parsers and returns an object of results. - **Parsimmon.alt(p1, p2, ...pn)**: Creates a parser that tries parsers in order and succeeds with the first one that matches. - **Parsimmon.sepBy(content, separator)**: Creates a parser that matches zero or more occurrences of `content`, separated by `separator`. - **Parsimmon.sepBy1(content, separator)**: Creates a parser that matches one or more occurrences of `content`, separated by `separator`. - **Parsimmon.lazy(fn | description, fn)**: Creates a parser that defers its definition until it's needed, useful for recursive grammars. - **Parsimmon.fail(message)**: Creates a parser that always fails with the given message. - **Parsimmon.letter**: A parser that matches a single letter. - **Parsimmon.letters**: A parser that matches one or more letters. - **Parsimmon.digit**: A parser that matches a single digit. - **Parsimmon.digits**: A parser that matches one or more digits. - **Parsimmon.whitespace**: A parser that matches one or more whitespace characters. - **Parsimmon.optWhitespace**: A parser that matches zero or more whitespace characters. - **Parsimmon.cr**: A parser that matches a carriage return. - **Parsimmon.lf**: A parser that matches a line feed. - **Parsimmon.crlf**: A parser that matches a carriage return followed by a line feed. - **Parsimmon.newline**: A parser that matches a newline character. - **Parsimmon.end**: A parser that matches the end of the input. - **Parsimmon.any**: A parser that matches any single character. - **Parsimmon.all**: A parser that matches the entire input string. - **Parsimmon.eof**: A parser that matches the end of the input. - **Parsimmon.index**: A parser that returns the current index in the input. - **Parsimmon.test(predicate)**: Creates a parser that succeeds if the predicate function returns true for the next character. - **Parsimmon.takeWhile(predicate)**: Creates a parser that consumes characters as long as the predicate function returns true. - **Parsimmon.custom(fn)**: Creates a parser using a custom function. ``` -------------------------------- ### Creating a shortcut for the Parsimmon library Source: https://github.com/jneen/parsimmon/blob/master/API.md For improved readability, it's recommended to create a shortcut alias for the Parsimmon library, especially when using multiple Parsimmon functions or methods within your parser definitions. ```javascript var P = Parsimmon; var parser = P.digits.sepBy(P.whitespace); ``` -------------------------------- ### Equivalent to trim using seqMap Source: https://github.com/jneen/parsimmon/blob/master/API.md Shows how the `trim` functionality can be achieved using `seqMap` to combine three parsers and return the middle result. ```javascript Parsimmon.seqMap(anotherParser, parser, anotherParser, function(before, middle) { return middle; }); ``` -------------------------------- ### Get Current Parse Index with Parsimmon.index Source: https://github.com/jneen/parsimmon/blob/master/API.md Use Parsimmon.index within seqMap to capture the current offset, line, and column during parsing. This is useful for error reporting or context-aware parsing. ```javascript Parsimmon.seqMap( Parsimmon.oneOf("Q\n").many(), Parsimmon.string("B"), Parsimmon.index, function(_prefix, B, index) { console.log(index.offset); // => 8 console.log(index.line); // => 3 console.log(index.column); // => 5 return B; } ).parse("QQ\n\nQQQB"); ``` -------------------------------- ### Compose Parsers with Parsimmon.seq and Custom Parsers Source: https://github.com/jneen/parsimmon/blob/master/API.md Demonstrates composing a sequence of parsers, including a custom 'notChar' parser, to parse a specific string pattern. ```javascript var parser = Parsimmon.seq(Parsimmon.string("a"), notChar("b").times(5)); parser.parse("accccc"); //=> {status: true, value: ['a', ['c', 'c', 'c', 'c', 'c']]} ``` -------------------------------- ### Parsimmon.alt(p1, p2, ...pn) Source: https://github.com/jneen/parsimmon/blob/master/API.md Accepts any number of parsers and yields the value of the first one that succeeds, with backtracking in between. The order of parsers matters; if two parsers match the same prefix, the longer one must come first. ```APIDOC ## Parsimmon.alt(p1, p2, ...pn) ### Description Accepts any number of parsers, yielding the value of the first one that succeeds, backtracking in between. This means that the order of parsers matters. If two parsers match the same prefix, the **longer** of the two must come first. ### Example ```js Parsimmon.alt(Parsimmon.string("ab"), Parsimmon.string("a")).parse("ab"); // => {status: true, value: 'ab'} Parsimmon.alt(Parsimmon.string("a"), Parsimmon.string("ab")).parse("ab"); // => {status: false, ...} ``` ### Note on Second Case In the second case, `Parsimmon.alt` matches on the first parser, then there are extra characters left over (`'b'`), so Parsimmon returns a failure. ``` -------------------------------- ### Using parser.node() to add metadata Source: https://github.com/jneen/parsimmon/blob/master/API.md The `node` combinator wraps a parser's result in an object containing the name, value, and position (start and end) of the parsed text. This is useful for adding semantic meaning or location information to parsed tokens. ```javascript var Identifier = Parsimmon.regexp(/[a-z]+/).node("Identifier"); Identifier.tryParse("hey"); // => { name: 'Identifier', // value: 'hey', // start: { offset: 0, line: 1, column: 1 }, // end: { offset: 3, line: 1, column: 4 } } ``` -------------------------------- ### parser.or(otherParser) Source: https://github.com/jneen/parsimmon/blob/master/API.md Creates a new parser that first attempts to parse with the original parser. If it fails, it then attempts to parse with `otherParser`. This is useful for providing alternative parsing rules. ```APIDOC ## parser.or(otherParser) ### Description Returns a new parser which tries `parser`, and if it fails uses `otherParser`. ### Method Not applicable (JavaScript method) ### Parameters - **otherParser** (Parser) - Required - The alternative parser to try if the primary parser fails. ### Request Example ```js var numberPrefix = Parsimmon.string("+") .or(Parsimmon.string("-")) .fallback(""); numberPrefix.parse("+"); ``` ### Response On success: - **value** (any) - The parsed value from either the primary or the alternative parser. ### Response Example (Success) ```js {status: true, value: '+'} {status: true, value: '-'} {status: true, value: ''} ``` ``` -------------------------------- ### Creating shortcuts for commonly used Parsimmon values Source: https://github.com/jneen/parsimmon/blob/master/API.md When using Babel, you can import specific Parsimmon values like `digits` and `whitespace` to create shortcuts, reducing verbosity in your parser definitions. ```javascript import { digits, whitespace } from "parsimmon"; var parser = digits.sepBy(whitespace); ``` -------------------------------- ### Parsing with Alternative Choices Source: https://github.com/jneen/parsimmon/blob/master/API.md Applies a parser to input, returning success or failure details. Use `Parsimmon.alt` to try multiple parsers in order. Use `.desc()` for clearer error messages. ```javascript var parser = Parsimmon.alt( // Use `parser.desc(string)` in order to have meaningful failure messages Parsimmon.string("a").desc("'a' character"), Parsimmon.string("b").desc("'b' character") ); parser.parse("a"); // => {status: true, value: 'a'} parser.parse("ccc"); // => {status: false, // index: {...}, // expected: ["'a' character", "'b' character"]} ``` -------------------------------- ### Create Language Parser Source: https://github.com/jneen/parsimmon/blob/master/API.md Use `Parsimmon.createLanguage` to define and organize parsers for a language. It allows parsers to refer to each other using a provided namespace object. ```javascript var Lang = Parsimmon.createLanguage({ Value: function(r) { return Parsimmon.alt(r.Number, r.Symbol, r.List); }, Number: function() { return Parsimmon.regexp(/[0-9]+/).map(Number); }, Symbol: function() { return Parsimmon.regexp(/[a-z]+/); }, List: function(r) { return Parsimmon.string("(") .then(r.Value.sepBy(r._)) .skip(Parsimmon.string(")")); }, _: function() { return Parsimmon.optWhitespace; } }); Lang.Value.tryParse("(list 1 2 foo (list nice 3 56 989 asdasdas))"); ``` -------------------------------- ### Binary Constructors Source: https://github.com/jneen/parsimmon/blob/master/API.md Parsimmon supports binary parsing with constructors for bytes and bit sequences. ```APIDOC ## Binary Constructors Parsimmon provides constructors for binary data parsing: - **Parsimmon.byte(int)**: Creates a parser that matches a specific byte value. - **Parsimmon.bitSeq(alignments)**: Creates a parser for a sequence of bits with specified alignments. - **Parsimmon.bitSeqObj(namedAlignments)**: Creates a parser for a named sequence of bits. ``` -------------------------------- ### Defining an Audio Codec Parser Source: https://github.com/jneen/parsimmon/blob/master/GUIDE.md This snippet defines a parser for various audio codec strings using Parsimmon.alt. It serves as a base for demonstrating negative parsing. ```javascript const audioCodec = Parsimmon.alt( Parsimmon.string("aac"), Parsimmon.string("mp3"), Parsimmon.string("ogg"), Parsimmon.string("flac"), Parsimmon.string("wav") ); ``` -------------------------------- ### FantasyLand Support Source: https://github.com/jneen/parsimmon/blob/master/API.md Parsimmon includes support for FantasyLand specifications, enabling integration with functional programming patterns. ```APIDOC ## FantasyLand Support Parsimmon supports several FantasyLand interfaces: - **Parsimmon.empty()**: Returns an empty parser (for `Alternative`). - **parser.empty()**: Returns an empty parser (for `Alternative`). - **parser.concat(otherParser)**: Concatenates two parsers (for `Semigroup`). - **parser.ap(otherParser)**: Applies a parser containing a function to a parser containing a value (for `Apply`). - **parser.sepBy(separator)**: Separates occurrences of this parser with `separator` (for `Alternative`). - **parser.sepBy1(separator)**: Separates one or more occurrences of this parser with `separator` (for `Alternative`). - **parser.chain(newParserFunc)**: Chains parsers (for `Chain`). - **parser.of(result)**: Creates a parser that always succeeds with the given result (for `Applicative`). ``` -------------------------------- ### Equivalent to wrap using seqMap Source: https://github.com/jneen/parsimmon/blob/master/API.md Explains how `wrap` can be replicated using `seqMap` to combine three parsers and extract the middle value, representing the content within delimiters. ```javascript Parsimmon.seqMap(before, parser, after, function(before, middle) { return middle; }); ``` -------------------------------- ### Parsimmon.seqMap(p1, p2, ...pn, function(r1, r2, ...rn)) Source: https://github.com/jneen/parsimmon/blob/master/API.md Matches all provided parsers sequentially. The results of these parsers are passed as arguments to a callback function. The return value of this function is yielded by the resulting parser. This is similar to using `Parsimmon.seq` followed by `.map`, but avoids creating an intermediate array. ```APIDOC ## Parsimmon.seqMap(p1, p2, ...pn, function(r1, r2, ...rn)) ### Description Matches all parsers sequentially, and passes their results as the arguments to a function, yielding the return value of that function. Similar to calling `Parsimmon.seq` and then `.map`, but the values are not put in an array. ### Method Not applicable (function call) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```js Parsimmon.seqMap( Parsimmon.oneOf("abc"), Parsimmon.oneOf("+-*"), Parsimmon.oneOf("xyz"), function(first, operator, second) { console.log(first); // => 'a' console.log(operator); // => '+' console.log(second); // => 'x' return [operator, first, second]; } ).parse("a+x"); ``` ### Response #### Success Response - `any` - The return value of the provided function. #### Response Example None ``` -------------------------------- ### Parsimmon.all Parser Source: https://github.com/jneen/parsimmon/blob/master/API.md Consumes and returns the entire remaining input. Ideal for capturing all remaining text. ```javascript Parsimmon.all ``` -------------------------------- ### Create Named Object Parser with Parsimmon.seqObj Source: https://github.com/jneen/parsimmon/blob/master/API.md Use Parsimmon.seqObj to create a parser that returns an object with results named according to the provided arguments. Requires at least one named parser and unique keys. ```javascript var _ = Parsimmon.optWhitespace; var identifier = Parsimmon.regexp(/[a-z_][a-z0-9_]*/i); var lparen = Parsimmon.string("("); var rparen = Parsimmon.string(")"); var comma = Parsimmon.string(","); var functionCall = Parsimmon.seqObj( ["function", identifier], lparen, ["arguments", identifier.trim(_).sepBy(comma)], rparen ); functionCall.tryParse("foo(bar, baz, quux)"); // => { function: 'foo', // arguments: [ 'bar', 'baz', 'quux' ] } ``` -------------------------------- ### Parsimmon.seqObj(...args) Source: https://github.com/jneen/parsimmon/blob/master/API.md Creates a parser that yields an object of results named based on the provided arguments. It accepts one or more arguments, which can be parsers or named parser pairs ([stringKey, parser]). Requires at least one named parser, and all named parser keys must be unique. ```APIDOC ## Parsimmon.seqObj(...args) ### Description Similar to `Parsimmon.seq(...parsers)`, but yields an object of results named based on arguments. Takes one or more arguments, where each argument is either a parser or a named parser pair (`[stringKey, parser]`). Requires at least one named parser. All named parser keys must be unique. ### Example ```js var _ = Parsimmon.optWhitespace; var identifier = Parsimmon.regexp(/[a-z_][a-z0-9_]*/i); var lparen = Parsimmon.string("("); var rparen = Parsimmon.string(")"); var comma = Parsimmon.string(","); var functionCall = Parsimmon.seqObj( ["function", identifier], lparen, ["arguments", identifier.trim(_).sepBy(comma)], rparen ); functionCall.tryParse("foo(bar, baz, quux)"); // => { function: 'foo', // arguments: [ 'bar', 'baz', 'quux' ] } ``` ### Tip Combines well with `.node(name)` for a full-featured AST node. ``` -------------------------------- ### Using fallback for default values Source: https://github.com/jneen/parsimmon/blob/master/API.md The `fallback` method returns a new parser that yields a specified value if the original parser fails without consuming input. Useful for providing default values. ```javascript var digitOrZero = Parsimmon.digit.fallback("0"); digitOrZero.parse("4"); // => {status: true, value: '4'} digitOrZero.parse(""); // => {status: true, value: '0'} ``` -------------------------------- ### Parsimmon.lazy(description, fn) Source: https://github.com/jneen/parsimmon/blob/master/API.md An enhanced version of `Parsimmon.lazy(fn)` that also allows setting a description for the parser. This is equivalent to calling `.desc(description)` on the parser returned by `Parsimmon.lazy(fn)`. ```APIDOC ## Parsimmon.lazy(description, fn) ### Description Equivalent to `Parsimmon.lazy(f).desc(description)`. ### Method N/A (Function definition) ### Parameters #### Function Parameters - **description** (string) - Required - A description for the parser. - **fn** (function) - Required - A function that returns a parser. ### Response N/A (Returns a parser object) ``` -------------------------------- ### Parsimmon.range equivalent using Parsimmon.test Source: https://github.com/jneen/parsimmon/blob/master/API.md Shows an alternative implementation of Parsimmon.range using a custom test function. ```javascript Parsimmon.test(function(c) { return begin <= c && c <= end; }); ``` -------------------------------- ### parser.atLeast(n) Source: https://github.com/jneen/parsimmon/blob/master/API.md Expects the parser to match at least n times, yielding an array of the results. ```APIDOC ## parser.atLeast(n) ### Description Expects `parser` at least `n` times. Yields an array of the results. ### Method N/A (Method chaining on a parser object) ### Endpoint N/A ``` -------------------------------- ### Parsimmon.seq(p1, p2, ...pn) Source: https://github.com/jneen/parsimmon/blob/master/API.md Accepts any number of parsers and returns a new parser that expects them to match in sequence. It yields an array containing the results of all the parsers. ```APIDOC ## Parsimmon.seq(p1, p2, ...pn) ### Description Accepts any number of parsers and returns a new parser that expects them to match in order, yielding an array of all their results. ### Method Not applicable (function call) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response - `array` (Array) - An array of results from the sequential parsers. #### Response Example None ``` -------------------------------- ### Parsimmon.string(string) Source: https://github.com/jneen/parsimmon/blob/master/API.md Creates a parser that matches a specific literal string. The parser yields the matched string if successful. ```APIDOC ## Parsimmon.string(string) ### Description Returns a parser that looks for `string` and yields that exact value. ### Method N/A (Static method) ### Parameters * **string** (string) - Required - The literal string to match. ### Response * **Parser** - A Parsimmon parser that matches the specified string. ``` -------------------------------- ### Parsimmon.bitSeqObj(namedAlignments) Source: https://github.com/jneen/parsimmon/blob/master/API.md Parses a sequence of bits, similar to `Parsimmon.bitSeq`, but allows for naming specific bit segments to be collected into an object. Unnamed bit segments are parsed but discarded. ```APIDOC ## Parsimmon.bitSeqObj(namedAlignments) ### Description Works like `Parsimmon.bitSeq` except each item in the array is either a number of bits or pair (array with length = 2) of name and bits. The bits are parsed in order and put into an object based on the name supplied. If there's no name for the bits, it will be parsed but discarded from the returned value. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```js var parser = Parsimmon.Binary.bitSeqObj([["a", 3], 5, ["b", 5], ["c", 3]]); parser.parse(Buffer.from([0x04, 0xff])); //=> { status: true, value: { a: 0, b: 31, c: 7 } } ``` ### Response #### Success Response (200) - **status** (boolean) - Indicates if the parsing was successful. - **value** (object) - The parsed result, containing named bit sequences as properties. #### Response Example ```json { "status": true, "value": { "a": 0, "b": 31, "c": 7 } } ``` ``` -------------------------------- ### parser.wrap(before, after) Source: https://github.com/jneen/parsimmon/blob/master/API.md Constructs a new parser that requires a `before` parser to succeed first, then the original parser, and finally an `after` parser. It returns only the result of the original parser. Useful for parsing content enclosed in delimiters. ```APIDOC ## parser.wrap(before, after) ### Description Expects the parser `before` before `parser` and `after` after `parser`. This is useful for parsing content enclosed in specific delimiters. ### Method This is a method on a parser object. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```js Parsimmon.letters .trim(Parsimmon.optWhitespace) .wrap(Parsimmon.string("("), Parsimmon.string(")")) .tryParse("( nice )"); // => 'nice' ``` ### Response #### Success Response - **value** (any) - The value parsed by the original `parser`. ``` -------------------------------- ### Hypothetical Negative Parser Construction Source: https://github.com/jneen/parsimmon/blob/master/GUIDE.md Demonstrates a hypothetical Parsimmon.not parser. Note that Parsimmon generally avoids such negative constructions due to potential debugging and consumption issues. ```javascript const notAudioCodec = Parsimmon.not(audioCodec); ``` -------------------------------- ### Using wrap to parse content within delimiters Source: https://github.com/jneen/parsimmon/blob/master/API.md The `wrap` method applies a parser before and after the main parser, similar to `trim`, but allows specifying distinct parsers for the opening and closing delimiters. It yields the result of the main parser. ```javascript Parsimmon.letters .trim(Parsimmon.optWhitespace) .wrap(Parsimmon.string("("), Parsimmon.string(")")) .tryParse("( nice )"); // => 'nice' ``` -------------------------------- ### parser.skip(otherParser) Source: https://github.com/jneen/parsimmon/blob/master/API.md Creates a new parser that first runs the original parser, then runs `otherParser`, but only returns the result of the original parser. This is useful for consuming unwanted input after a desired value has been parsed. ```APIDOC ## parser.skip(otherParser) ### Description Expects `otherParser` after `parser`, but yields the value of `parser`. This is useful for parsing sequences where you only care about the first part. ### Method This is a method on a parser object. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```js var p1 = Parsimmon.string("hello"); var p2 = Parsimmon.string(" world"); var parserA = p1.skip(p2); parserA.parse("hello world"); // => {status: true, value: 'hello'} ``` ### Response #### Success Response - **value** (any) - The value parsed by the original `parser`. ``` -------------------------------- ### parser.chain(newParserFunc) Source: https://github.com/jneen/parsimmon/blob/master/API.md Returns a new parser that, upon successful parsing by the original parser, calls a provided function with the result. This function must return another parser, which is then applied. This enables dynamic parsing logic based on intermediate results. ```APIDOC ## parser.chain(newParserFunc) ### Description Returns a new parser which tries `parser`, and on success calls the function `newParserFunc` with the result of the parse, which is expected to return another parser, which will be tried next. This allows you to dynamically decide how to continue the parse, which is impossible with the other combinators. ### Method Not applicable (JavaScript method) ### Parameters - **newParserFunc** (function) - Required - A function that receives the result of the current parse and returns a new Parsimmon parser. ### Request Example ```js var CustomString = Parsimmon.string("%") .then(Parsimmon.any) .chain(function(start) { var end = { "[": "]", "(": ")", "{": "}", "<": ">" }[start] || start; return Parsimmon.takeWhile(function(c) { return c !== end; }).skip(Parsimmon.string(end)); }); CustomString.parse("%:a string:"); ``` ### Response On success: - **value** (any) - The final parsed value after applying the chained parsers. ### Response Example (Success) ```js {status: true, value: 'a string'} ``` ``` -------------------------------- ### Parsimmon.string Source: https://github.com/jneen/parsimmon/blob/master/API.md Creates a parser that matches a specific string. ```javascript var parseHello = Parsimmon.string("hello"); parseHello.parse("hello"); // => "hello" ``` -------------------------------- ### Parsimmon.custom(fn) Source: https://github.com/jneen/parsimmon/blob/master/API.md Allows users to add primitive parsers by providing a custom function. This function should return a parser function that takes success and failure callbacks. ```APIDOC ## Parsimmon.custom(fn) ### Description Allows users to add primitive parsers by providing a custom function. This function should return a parser function that takes success and failure callbacks. ### Parameters #### Function Argument `fn` - `fn` (function) - A function that returns a parser function. ### Example Usage ```js function notChar(char) { return Parsimmon.custom(function(success, failure) { return function(input, i) { if (input.charAt(i) !== char) { return success(i + 1, input.charAt(i)); } return failure(i, 'anything different than "' + char + '"'); }; }); } var parser = Parsimmon.seq(Parsimmon.string("a"), notChar("b").times(5)); parser.parse("accccc"); // => { status: true, value: ['a', ['c', 'c', 'c', 'c', 'c']] } ``` **Note:** This method is deprecated. Please use `Parsimmon(fn)` instead. ``` -------------------------------- ### Chaining Parsers with then Source: https://github.com/jneen/parsimmon/blob/master/API.md Use `then` to expect one parser to follow another. It yields the result of the second parser. ```javascript var parserA = p1.then(p2); // is equivalent to... var parserB = Parsimmon.seqMap(p1, p2, function(x1, x2) { return x2; }); ``` -------------------------------- ### parser.lookahead(regexp) Source: https://github.com/jneen/parsimmon/blob/master/API.md Creates a parser that checks if the input matches a given `regexp` without consuming it. It yields the same result as the original parser. ```APIDOC ## parser.lookahead(regexp) ### Description Returns a parser that wants the input to match `regexp`. Yields the same result as `parser`. Equivalent to `parser.skip(Parsimmon.lookahead(regexp))`. ``` -------------------------------- ### parser.times(min, max) Source: https://github.com/jneen/parsimmon/blob/master/API.md Expects the parser to match between min and max times (inclusive), yielding an array of the results. ```APIDOC ## parser.times(min, max) ### Description Expects `parser` between `min` and `max` times, and yields an array of the results. ### Method N/A (Method chaining on a parser object) ### Endpoint N/A ``` -------------------------------- ### Using trim to handle surrounding whitespace Source: https://github.com/jneen/parsimmon/blob/master/API.md The `trim` method applies a parser before and after the main parser, yielding only the result of the main parser. It's ideal for ignoring whitespace or comments around parsed content. ```javascript Parsimmon.digits .map(Number) .trim(Parsimmon.optWhitespace) .sepBy(Parsimmon.string(",")) .tryParse(" 1, 2,3 , 4 "); // => [1, 2, 3, 4] ``` -------------------------------- ### parser.atMost(n) Source: https://github.com/jneen/parsimmon/blob/master/API.md Expects the parser to match at most n times, yielding an array of the results. ```APIDOC ## parser.atMost(n) ### Description Expects `parser` at most `n` times. Yields an array of the results. ### Method N/A (Method chaining on a parser object) ### Endpoint N/A ``` -------------------------------- ### Create a Custom Parser with Parsimmon(fn) Source: https://github.com/jneen/parsimmon/blob/master/API.md Use Parsimmon(fn) to define a custom parser. The function should accept the input string and current index, returning a success or failure object. ```javascript function notChar(char) { return Parsimmon(function(input, i) { if (input.charAt(i) !== char) { return Parsimmon.makeSuccess(i + 1, input.charAt(i)); } return Parsimmon.makeFailure(i, 'anything different than "' + char + '"'); }); } ``` -------------------------------- ### Parsimmon.optWhitespace Source: https://github.com/jneen/parsimmon/blob/master/API.md A pre-defined parser that matches zero or more whitespace characters. It is equivalent to using `Parsimmon.regexp(/\s*/)`. This parser is optional. ```APIDOC ## Parsimmon.optWhitespace ### Description Equivalent to [`Parsimmon.regexp(/\s*/)`](#parsimmonregexpregexp). ### Method N/A (Parser constant) ### Response N/A (Returns a parser object) ``` -------------------------------- ### Parsimmon.empty() Source: https://github.com/jneen/parsimmon/blob/master/API.md Returns a parser that always fails, with a specific error message indicating it's for the fantasy-land/empty operation. ```APIDOC ## Parsimmon.empty() ### Description Returns a parser that always fails, with a specific error message indicating it's for the fantasy-land/empty operation. ### Method Static method ### Endpoint N/A (Static method) ### Parameters None ### Response #### Success Response - Returns a parser object that fails. #### Response Example ```json { "status": false, "error": "fantasy-land/empty" } ``` ``` -------------------------------- ### Parsimmon.range(begin, end) Source: https://github.com/jneen/parsimmon/blob/master/API.md Creates a parser that matches a single character within a specified range (inclusive). ```APIDOC ## Parsimmon.range(begin, end) ### Description Parses a single character from `begin` to `end`, inclusive. ### Method N/A (Static method) ### Parameters * **begin** (string) - Required - The starting character of the range. * **end** (string) - Required - The ending character of the range. ### Response * **Parser** - A Parsimmon parser that matches a character within the specified range. ``` -------------------------------- ### Parsimmon.buffer(length) Source: https://github.com/jneen/parsimmon/blob/master/API.md Returns a parser that consumes a specified number of bytes from a buffer and returns it as a raw buffer. The buffer is cloned to prevent modification of the original input. ```APIDOC ## Parsimmon.buffer(length) ### Description Returns a parser that will consume some of a buffer and present it as a raw buffer for further transformation. This buffer is cloned, so in case you use a destructive method, it will not corrupt the original input buffer. ### Method Not applicable (JavaScript function) ### Endpoint Not applicable (JavaScript function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript var parser = Parsimmon.Binary.buffer(2).skip(Parsimmon.any); parser.parse(Buffer.from([1, 2, 3])); // => { status: true, value: } ``` ### Response #### Success Response - **value** (Buffer) - The consumed portion of the input buffer. #### Response Example ```json { "status": true, "value": "" } ``` ``` -------------------------------- ### Applying a function parser to another parser's result Source: https://github.com/jneen/parsimmon/blob/master/API.md Use the `ap` method when one parser returns a function and you want to apply it to the result of another parser. This is useful for combining parsed values in specific ways. ```javascript Parsimmon.digit .ap(Parsimmon.digit.map(s => t => Number(s) + Number(t))) .parse("23"); // => {status: true, value: 5} ``` -------------------------------- ### Sequential Parsing with Mapping Source: https://github.com/jneen/parsimmon/blob/master/API.md Use seqMap to parse multiple parsers sequentially and transform their results using a mapping function. The results are passed as arguments to the function, and its return value is yielded. ```javascript Parsimmon.seqMap( Parsimmon.oneOf("abc"), Parsimmon.oneOf("+-*"), Parsimmon.oneOf("xyz"), function(first, operator, second) { console.log(first); // => 'a' console.log(operator); // => '+' console.log(second); // => 'x' return [operator, first, second]; } ).parse("a+x"); ``` -------------------------------- ### Fast Whitespace Matching with RegExp Source: https://github.com/jneen/parsimmon/blob/master/GUIDE.md Use Parsimmon.regexp for efficient matching of large character sets like whitespace. This is faster than character-by-character parsing. ```javascript const fastWhitespace = Parsimmon.regexp(/[ \t\r\n]*/); ``` -------------------------------- ### parser.lookahead(anotherParser) Source: https://github.com/jneen/parsimmon/blob/master/API.md Creates a parser that checks if `anotherParser` matches at the current position without consuming input. It yields the same result as the original parser. ```APIDOC ## parser.lookahead(anotherParser) ### Description Returns a parser that looks for whatever `anotherParser` wants to parse, but does not consume it. Yields the same result as `parser`. Equivalent to `parser.skip(Parsimmon.lookahead(anotherParser))`. ``` -------------------------------- ### Transforming Input and Output with promap Source: https://github.com/jneen/parsimmon/blob/master/API.md Use `promap` to transform both the input and output of a parser. Similar to `contramap`, it affects subsequent parsing and requires careful consideration. ```javascript var pNum = Parsimmon.string("A").promap( function(x) { return x.toUpperCase(); }, function(x) { return x.charCodeAt(0); } ); pNum.parse("a"); // => {status: true, value: 65} pNum.parse("A"); // => {status: true, value: 65} ``` -------------------------------- ### Parsimmon.regexp(regexp, [group]) Source: https://github.com/jneen/parsimmon/blob/master/API.md Creates a parser that matches a regular expression. Optionally, it can yield a specific capture group from the match. ```APIDOC ## Parsimmon.regexp(regexp, [group]) ### Description Returns a parser that looks for a match to the regexp and yields the entire text matched. The regexp will always match starting at the current parse location. The regexp may only use the following flags: `imus`. Any other flag will result in an error being thrown. Like [`Parsimmon.regexp(regexp)`](#parsimmonregexpregexp), but yields only the text in the specific regexp match `group`, rather than the match of the entire regexp. ### Method N/A (Static method) ### Parameters * **regexp** (RegExp) - Required - The regular expression to match. * **group** (number) - Optional - The capture group index to yield. If omitted, the entire match is yielded. ### Response * **Parser** - A Parsimmon parser that matches the regular expression or a specific capture group. ``` -------------------------------- ### Parsimmon.Binary.uintLE(length) Source: https://github.com/jneen/parsimmon/blob/master/API.md Parses an unsigned integer in little-endian format. The length parameter specifies the number of bytes to parse, with a maximum of 6 bytes. ```APIDOC ## Parsimmon.Binary.uintLE(length) ### Description Parse an unsigned integer (little-endian) of length bytes. Length cannot exceed 6. ### Parameters #### Path Parameters - **length** (number) - Required - The number of bytes to parse (max 6). ### Request Example ```javascript var parser = Parsimmon.Binary.uintLE(4); parser.parse(Buffer.from([1, 2, 3, 4])); ``` ### Response #### Success Response - **status** (boolean) - Indicates if parsing was successful. - **value** (number) - The parsed unsigned integer. #### Response Example ```json { "status": true, "value": 67305985 } ``` ``` -------------------------------- ### parser.many() Source: https://github.com/jneen/parsimmon/blob/master/API.md Expects the parser to match zero or more times, yielding an array of results. Throws an error if the parser can match an empty string to prevent infinite loops. ```APIDOC ## parser.many() ### Description Expects `parser` zero or more times, and yields an array of the results. **NOTE:** If `parser` is capable of parsing an empty string (i.e. `parser.parse("")` succeeds) then [`parser.many()`](#parsermany) will throw an error. Otherwise [`parser.many()`](#parsermany) would get stuck in an infinite loop. ### Method N/A (Method chaining on a parser object) ### Endpoint N/A ``` -------------------------------- ### Parsimmon.lookahead(parser) Source: https://github.com/jneen/parsimmon/blob/master/API.md Parses using the provided `parser` without consuming input. It yields an empty string upon successful parsing. ```APIDOC ## Parsimmon.lookahead(parser) ### Description Parses using `parser`, but does not consume what it parses. Yields an empty string. ### Method Not applicable (function call) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response - `""` (string) - Yielded upon successful parsing. #### Response Example None ```