719
Le
lextide / files
lextide / src / core / grammar.ts
2.0 KB
1import type { GrammarDefinition, GrammarRule } from "../types"; 2 3export const INTERNAL_STATES = Symbol("lextide.internalStates"); 4 5export interface EmptyChild { 6 position: number; 7 scopes: string[]; 8} 9 10type MatchResultObject = { 11 length: number; 12 scope?: string | undefined; 13 push?: string | undefined; 14 pop?: boolean | undefined; 15 children?: InternalRule[] | undefined; 16 emptyChildren?: EmptyChild[] | undefined; 17 relevance?: number | undefined; 18 pushScope?: string | null | undefined; 19}; 20 21export type MatchResult = number | MatchResultObject | null; 22 23export type InternalMatcher = (input: string, pos: number) => MatchResult; 24 25export interface InternalRule extends Omit<GrammarRule, "match" | "children"> { 26 match: RegExp | InternalMatcher; 27 children?: InternalRule[]; 28 pushScope?: string | null | undefined; 29} 30 31export interface InternalState { 32 defaultScope?: string | undefined; 33 rules: InternalRule[]; 34} 35 36export interface InternalGrammarDefinition extends GrammarDefinition { 37 [INTERNAL_STATES]?: Record<string, InternalState>; 38} 39 40export function defineGrammar(config: { 41 name: string; 42 aliases?: string[]; 43 relevance?: number; 44 startState: string; 45 states: Record<string, InternalState>; 46}): GrammarDefinition { 47 const grammar: InternalGrammarDefinition = { 48 name: config.name, 49 aliases: config.aliases, 50 relevance: config.relevance, 51 startState: config.startState, 52 states: Object.fromEntries( 53 Object.entries(config.states).map(([name, state]) => [ 54 name, 55 state.rules as unknown as GrammarRule[], 56 ]), 57 ), 58 }; 59 60 grammar[INTERNAL_STATES] = config.states; 61 62 return grammar; 63} 64 65export function getInternalStates( 66 grammar: GrammarDefinition, 67): Record<string, InternalState> { 68 const internalGrammar = grammar as InternalGrammarDefinition; 69 70 if (internalGrammar[INTERNAL_STATES]) { 71 return internalGrammar[INTERNAL_STATES]; 72 } 73 74 return Object.fromEntries( 75 Object.entries(grammar.states).map(([name, rules]) => [ 76 name, 77 { rules: rules as InternalRule[] }, 78 ]), 79 ); 80}