diff --git a/src/notcl.ts b/src/notcl.ts index 3bcf8e2..817094c 100644 --- a/src/notcl.ts +++ b/src/notcl.ts @@ -1,5 +1,14 @@ import { escapeHtml } from "./helpers"; -import { AtLeast, Choose, End, Pattern, Regex, Sequence, Use } from "./peg"; +import { + AtLeast, + Choose, + End, + Pattern, + Peek, + Regex, + Sequence, + Use, +} from "./peg"; import { Script, Word as WordType, @@ -105,10 +114,12 @@ function scriptTmpl(bareWordCharRegex: RegExp, endPattern: Pattern) { Choose( PreWordWhitespace.map(() => []), CommandTerminator.map(() => []), - Sequence(Comment, Choose(CommandTerminator, endPattern)).map(() => []), + Sequence(Comment, Choose(CommandTerminator, Peek(endPattern))).map( + () => [] + ), Sequence( commandTmpl(bareWordCharRegex), - Choose(CommandTerminator, endPattern) + Choose(CommandTerminator, Peek(endPattern)) ).map(([words]) => words) ) ), diff --git a/src/peg.ts b/src/peg.ts index 3705b7d..e93faba 100644 --- a/src/peg.ts +++ b/src/peg.ts @@ -182,6 +182,16 @@ export function AtLeast(min: number, pattern: Pattern): Pattern { }).expects(pattern.expectLabel); } +/** + * Creates a pattern that matches the given pattern, but consumes no input. + */ +export function Peek(pattern: Pattern): Pattern { + return WrapPattern(function (source, index) { + const [value, furthest, expected] = pattern(source, index); + return [value ? [value[0], index] : null, furthest, expected]; + }).expects(pattern.expectLabel); +} + /** * Creates a pattern that matches the end of input */