prototype-3x5/notcl.js

105 lines
2.7 KiB
JavaScript

/**
* @typedef {Notcl.Command[]} Notcl.Script
* @typedef {Notcl.Word[]} Notcl.Command
* @typedef {object} Notcl.Word
* @property {string} text
*/
var Notcl = (() => {
const { AtLeast, Choose, End, Regex, Sequence, Use, Hint } = Peg;
const InterCommandWhitespace = Regex(/\s+/y).expects("whitespace");
const Comment = Regex(/#[^\n]*/y).expects("#");
const PreCommand = AtLeast(0, Choose(InterCommandWhitespace, Comment));
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
/** @type {Peg.Pattern<string>} */
const Brace = Sequence(
Regex(/\{/y).expects("{"),
AtLeast(
0,
Choose(
Use(() => Brace).map((text) => `{${text}}`),
Regex(/[^{}]+/y).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 | ;");
/** @type {Peg.Pattern<Notcl.Command>} */
const Command = Sequence(
Word,
AtLeast(
0,
Sequence(PreWordWhitespace, Word).map(([, word]) => word)
),
AtLeast(0, PreWordWhitespace)
).map(([word, moreWords]) => [word].concat(moreWords));
/** @type {Peg.Pattern<Notcl.Script>} */
const Script = Sequence(
PreCommand,
AtLeast(0, Command),
AtLeast(
0,
Sequence(CommandTerminator, PreCommand, Command).map(
([, , command]) => command
)
),
AtLeast(0, PreCommand),
End()
).map(([, command, moreCommands]) => command.concat(moreCommands));
const ERROR_CONTEXT = /(?<=([^\n]{0,50}))([^\n]{0,50})/y;
return {
/**
* Parse out a Notcl script into an easier-to-interpret representation.
* No script is actually executed yet.
*
* @param {string} code to parse
* @returns {[true, Notcl.Script] | [false, string]} parsed list of commands, or error message on failure
*/
parse(code) {
/* Preprocess */
// fold line endings
code = code.replace(/(?<!\\)((\\\\)*)\\\n/g, "$1");
/* Parse */
const [commands, errorPos, expected] = Script(code, 0);
if (commands) {
return [true, commands[0]];
} else {
ERROR_CONTEXT.lastIndex = errorPos;
const [, before, after] = /** @type {RegExpExecArray} */ (
ERROR_CONTEXT.exec(code)
);
return [
false,
`<pre>Error at position ${errorPos}
${escapeHtml(before + "" + after)}
${"-".repeat(before.length)}^
Expected: ${escapeHtml(expected)}</pre>`,
];
}
},
};
})();