Parse Commands with Peg
This commit is contained in:
parent
a3cdc53330
commit
88497965b3
1 changed files with 17 additions and 36 deletions
53
notcl.js
53
notcl.js
|
@ -26,6 +26,19 @@ var Notcl = (() => {
|
|||
([_, word]) => word
|
||||
);
|
||||
|
||||
const CommandTerminator = Peg.Sequence(
|
||||
PreWordWhitespace,
|
||||
Peg.Choose(
|
||||
/** @type {Peg.Pattern<unknown>} */ (Peg.Regex(/[\n;]/y)),
|
||||
Peg.End
|
||||
)
|
||||
);
|
||||
|
||||
const Command = Peg.Map(
|
||||
Peg.Sequence(PreCommand, Peg.AtLeast(0, Word), CommandTerminator),
|
||||
([_padding, words, _end]) => words
|
||||
);
|
||||
|
||||
return {
|
||||
/**
|
||||
* Parse out a Notcl script into an easier-to-interpret representation.
|
||||
|
@ -39,42 +52,10 @@ var Notcl = (() => {
|
|||
// fold line endings
|
||||
code = code.replace(/(?<!\\)((\\\\)*)\\\n/g, "$1");
|
||||
|
||||
/* Parse */
|
||||
function nextWord(/* TODO: null/]/" terminator */) {
|
||||
// TODO: handle all kinds of brace/substitution stuff
|
||||
const [word, nextIndex] = Word(code, 0) ?? [null, 0];
|
||||
if (word) {
|
||||
code = code.substring(nextIndex);
|
||||
return word;
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function nextCommand(/* TODO: null/]/" terminator */) {
|
||||
const command = /** @type {Notcl.Word[]} */ ([]);
|
||||
while (true) {
|
||||
// Strip whitespace and comments
|
||||
const [preCmd, startIndex] = PreCommand(code, 0) ?? [null, 0];
|
||||
code = code.substring(startIndex);
|
||||
// Strip semicolons
|
||||
if (code[0] == ";") {
|
||||
code = code.substring(1);
|
||||
continue;
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
while (true) {
|
||||
const word = nextWord();
|
||||
if (word) {
|
||||
command.push(word);
|
||||
continue;
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
return command;
|
||||
function nextCommand() {
|
||||
const [words, nextIndex] = Command(code, 0) ?? [[], 0];
|
||||
code = code.substring(nextIndex);
|
||||
return words;
|
||||
}
|
||||
|
||||
/* Loop through commands, with safety check */
|
||||
|
|
Loading…
Reference in a new issue