Make thunk used for recursive braces more understandable

This commit is contained in:
Tangent Wantwight 2023-07-29 14:50:49 -04:00
parent 9b87906c09
commit e61485012e
2 changed files with 23 additions and 11 deletions

View file

@ -6,7 +6,7 @@
*/
var Notcl = (() => {
const { AtLeast, Choose, End, Map, Regex, Sequence } = Peg;
const { AtLeast, Choose, End, Map, Regex, Sequence, Use } = Peg;
const InterCommandWhitespace = Regex(/\s+/y);
@ -23,13 +23,17 @@ var Notcl = (() => {
// WIP, need to be able to escape braces correctly
// WIP, error if anything after closing brace
const BracePattern = Map(
/** @type {Peg.Pattern<string>} */
const Brace = Map(
Sequence(
Regex(/\{/y),
AtLeast(
0,
Choose(
Map(Brace, (text) => `{${text}}`),
Map(
Use(() => Brace),
(text) => `{${text}}`
),
Map(Regex(/[^{}]+/y), ([text]) => text)
)
),
@ -37,19 +41,12 @@ var Notcl = (() => {
),
([_left, fragments, _right]) => fragments.join("")
);
/**
* @type {Peg.Pattern<string>}
*/
function Brace(source, index) {
// Thunk to allow Brace to recurse
return BracePattern(source, index);
}
const Word = Map(
Sequence(
PreWordWhitespace,
Choose(
Map(BracePattern, (text) => ({
Map(Brace, (text) => ({
text,
})),
BasicWord

15
peg.js
View file

@ -21,6 +21,21 @@ Peg.WrapPattern = function (pattern) {
return /** @type {Peg.Pattern<T>} */ (pattern);
};
/**
* Proxies to a pattern retrieved from an accessor function.
*
* Allows using a pattern recursively in its own definition, by returning the value of the const assigned to.
*
* @template T
* @param {() => Peg.Pattern<T>} getPattern
* @returns {Peg.Pattern<T>}
*/
Peg.Use = function (getPattern) {
return Peg.WrapPattern(function (source, index) {
return getPattern()(source, index);
});
};
/**
* Creates a pattern that wraps another pattern, transforming the returned value on a match
* @template T, U