From 0a7e051ab577ac9242b32e7873c2fe96fc7375cb Mon Sep 17 00:00:00 2001
From: Tangent Wantwight <tangent128@gmail.com>
Date: Thu, 3 Aug 2023 23:15:14 -0400
Subject: [PATCH] Match entire script from a top level grammar symbol

---
 notcl.js | 21 +++++++++------------
 1 file changed, 9 insertions(+), 12 deletions(-)

diff --git a/notcl.js b/notcl.js
index 726b71c..c1f2308 100644
--- a/notcl.js
+++ b/notcl.js
@@ -47,10 +47,16 @@ var Notcl = (() => {
     Choose(/** @type {Peg.Pattern<unknown>} */ (Regex(/[\n;]/y)), End)
   );
 
+  /** @type {Peg.Pattern<Notcl.Command>} */
   const Command = Sequence(PreCommand, AtLeast(0, Word), CommandTerminator).map(
     ([_padding, words, _end]) => words
   );
 
+  /** @type {Peg.Pattern<Notcl.Script>} */
+  const Script = Sequence(AtLeast(0, Command), End).map(
+    ([commands, _eof]) => commands
+  );
+
   return {
     /**
      * Parse out a Notcl script into an easier-to-interpret representation.
@@ -64,19 +70,10 @@ var Notcl = (() => {
       // fold line endings
       code = code.replace(/(?<!\\)((\\\\)*)\\\n/g, "$1");
 
-      function nextCommand() {
-        const [words, nextIndex] = Command(code, 0) ?? [[], 0];
-        code = code.substring(nextIndex);
-        return words;
-      }
+      /* Parse */
+      const commands = Script(code, 0);
 
-      /* Loop through commands, with safety check */
-      const script = /** @type {Notcl.Command[]} */ ([]);
-      for (let i = 0; i < 1000 && code != ""; i++) {
-        script.push(nextCommand());
-      }
-
-      return script;
+      return commands?.[0] ?? [];
     },
   };
 })();