UNPKG

functionalscript

Version:

FunctionalScript is a purely functional subset of JavaScript

78 lines (77 loc) 2.46 kB
/** * Rules for serializing and deserializing the BNF grammar. * * @module * * @example * * ```ts * // Define a simple grammar * const grammar: Rule = () => [ * [range('AZ')], // 'A-Z' * [range('az'), grammar], // 'a-z' followed by more grammar * ] * * const parse = parser(toRuleMap(grammar)) * * // Parse an input * const input = toArray(stringToCodePointList('abcdefgA')) * const result = parse(grammar.name, input) * if (result === null) { throw result } * const [, b] = result * if (b?.length !== 0) { throw b } * ``` */ import type { CodePoint } from '../../text/utf16/module.f.ts'; import type { TerminalRange, Rule as FRule } from '../func/module.f.ts'; /** * Represents a sequence of grammar rules, including terminal ranges or rule identifiers. * @template Id - The type for rule identifiers. */ export type Sequence<Id> = readonly (TerminalRange | Id)[]; /** * Represents a grammar rule as a collection of sequences. * @template Id - The type for rule identifiers. */ export type Rule<Id> = readonly Sequence<Id>[]; /** * Represents a map of grammar rules, where each rule is identified by a unique string identifier. * @template Id - The type for rule identifiers. */ export type RuleMap<Id extends string> = { readonly [k in Id]: Rule<Id>; }; /** * Transforming functional rule to a serializable rule map. * * @param src a functional rule. * @returns a serializable rule map. */ export declare const toRuleMap: (src: FRule) => RuleMap<string>; /** * Represents a parsed Abstract Syntax Tree (AST) sequence. */ export type AstSequence = readonly (AstRule | CodePoint)[]; /** * Represents a parsed AST rule, consisting of a rule name and its parsed sequence. */ export type AstRule = readonly [string, AstSequence]; /** * Represents the remaining input after a match attempt, or `null` if no match is possible. */ export type Remainder = readonly CodePoint[] | null; /** * Represents the result of a match operation, including the parsed AST rule and the remainder of the input. */ export type MatchResult = readonly [AstRule, Remainder]; /** * Represents an LL(1) parser function for matching input against grammar rules. */ export type Match = (name: string, s: readonly CodePoint[]) => MatchResult; /** * Creates a simple LL1 parser for the given map. * * @param map a prepared rule map. * @returns a parser. */ export declare const parser: (rm: RuleMap<string>) => Match;