Unlike many parser libraries, ts-parsec does not force you to create Abstract Syntax Trees (ASTs) manually. Instead, the parser naturally produces a data structure that mirrors your grammar.
For example, a grammar defined as A B (C|D) {E F, ...} G can be implemented using combinators like seq, alt, and list_sc. The resulting output type will be a tuple representing the sequence of parsed components: [TA, TB, (TC | TD), [TE, TF][], TG].
To convert these grammar-aligned structures into your own domain-specific data structures (like a custom AST), use the apply combinator. This allows you to perform transformations or calculations during the parsing process itself.
// Example: Converting grammar-aligned tuples to a custom structure
function convertToSomething(value: [TA, TB, (TC | TD), [TE, TF][], TG]): Something {
// ... transformation logic
}
const myParser = apply(
seq(A, B, alt(C, D), list_sc(seq(E, F), str(',')), G),
convertToSomething
);
// To ensure the parser consumes the entire input and returns exactly one result:
const output = expectSingleResult(expectEOF(myParser.parse(myTokenizer.parse(`INPUT`))));