/** * A Pattern is a function that matches against a string starting at a given index. * * If it matches successfully, it returns some captured value, and the index following the match. * * @template T * @typedef {(source: string, index: number) => ([T, number] | null)} Peg.Pattern */ var Peg = { /** * Creates a pattern that wraps another pattern, transforming the returned value on a match * @template T, U * @param {Peg.Pattern} pattern * @param {(value: T)=> U} map * @return {Peg.Pattern} */ Map(pattern, map) { return function (source, index) { const match = pattern(source, index); return match ? [map(match[0]), match[1]] : null; }; }, /** * Creates a pattern matching a regex & returning any captures. The regex needs to be sticky (using the //y modifier) * @param {RegExp} regex * @return {Peg.Pattern} */ Regex(regex) { return function (source, index) { regex.lastIndex = index; const matches = regex.exec(source); return matches ? [matches, regex.lastIndex] : null; }; }, /** * @template T * @param {...Peg.Pattern} patterns * @return {Peg.Pattern} */ Choose(...patterns) { return function (source, index) { for (const pattern of patterns) { const match = pattern(source, index); if (match) { return match; } } return null; }; }, /** * @template {unknown[]} T * @param {{[K in keyof T]: Peg.Pattern}} patterns * @return {Peg.Pattern} */ Sequence(...patterns) { return function (source, index) { const values = /** @type {T} */ (/** @type {unknown} */ ([])); for (const pattern of patterns) { const match = pattern(source, index); if (match == null) { return null; } values.push(match[0]); index = match[1]; } return [values, index]; }; }, };