From e61485012ecfaf8145668790ec3fb17ff2307862 Mon Sep 17 00:00:00 2001 From: Tangent Wantwight Date: Sat, 29 Jul 2023 14:50:49 -0400 Subject: [PATCH] Make thunk used for recursive braces more understandable --- notcl.js | 19 ++++++++----------- peg.js | 15 +++++++++++++++ 2 files changed, 23 insertions(+), 11 deletions(-) diff --git a/notcl.js b/notcl.js index 05478f3..be89430 100644 --- a/notcl.js +++ b/notcl.js @@ -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} */ + 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} - */ - 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 diff --git a/peg.js b/peg.js index 5f2c76b..2c81c0e 100644 --- a/peg.js +++ b/peg.js @@ -21,6 +21,21 @@ Peg.WrapPattern = function (pattern) { return /** @type {Peg.Pattern} */ (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} getPattern + * @returns {Peg.Pattern} + */ +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