import { escapeHtml } from "./helpers"; import { AtLeast, Choose, End, Pattern, Regex, Sequence, Use } from "./peg"; export type Word = { text: string; }; export type Command = Word[]; export type Script = Command[]; const InterCommandWhitespace = Regex(/\s+/y).expects("whitespace"); const Comment = Regex(/#[^\n]*/y) .expects("#") .map(() => []); const PreCommand = AtLeast(0, InterCommandWhitespace); const PreWordWhitespace = Regex(/[^\S\n;]+/y).expects("whitespace"); const BasicWord = Regex(/(?!\{)[^\s;]+/y) .map(([word]) => ({ text: word })) .expects("BASIC_WORD"); // WIP, need to be able to escape braces correctly const Brace: Pattern = Sequence( Regex(/\{/y).expects("{"), AtLeast( 0, Choose( Use(() => Brace) .expects("{") .map((text) => `{${text}}`), Regex(/[^{}]+/y) .expects("text") .map(([text]) => text) ) ), Regex(/\}/y).expects("}") ).map(([_left, fragments, _right]) => fragments.join("")); const Word = Choose( BasicWord, Brace.map((text) => ({ text })) ); const CommandTerminator = Regex(/[\n;]/y) .expects("NEWLINE | ;") .map(() => true); const Command = Sequence( Word, AtLeast( 0, Sequence(PreWordWhitespace, Word).map(([, word]) => word) ), AtLeast(0, PreWordWhitespace) ).map(([word, moreWords]) => [word].concat(moreWords)); const Script = Sequence( AtLeast( 0, Choose( PreWordWhitespace.map(() => []), CommandTerminator.map(() => []), Sequence(Comment, Choose(CommandTerminator, End())).map(() => []), Sequence(Command, Choose(CommandTerminator, End())).map( ([words]) => words ) ) ), End() ).map(([commands]) => commands.filter((command) => command.length > 0)); const ERROR_CONTEXT = /(?<=([^\n]{0,50}))([^\n]{0,50})/y; /** * Parse out a Notcl script into an easier-to-interpret representation. * No script is actually executed yet. * * @param - code to parse * @returns - parsed list of commands, or error message on failure */ export function parse(code: string): [true, Script] | [false, string] { /* Preprocess */ // fold line endings code = code.replace(/(?Error at position ${errorPos} ${escapeHtml(before + "" + after)} ${"-".repeat(before.length)}^ Expected: ${escapeHtml(expected)}`, ]; } }