From b287b1d9b61474f5d914cbc3b813f1d95e93d8d3 Mon Sep 17 00:00:00 2001 From: Tangent Wantwight Date: Fri, 4 Aug 2023 17:43:11 -0400 Subject: [PATCH] WIP hack combinator to try and improve error messages. --- peg.js | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/peg.js b/peg.js index 95a8231..d3c1171 100644 --- a/peg.js +++ b/peg.js @@ -183,3 +183,26 @@ Peg.End = () => { }).expects(""); return end; }; + +/** + * Creates a pattern that never succeeds, but reports how far its wrapped pattern could match before failing. + * + * This is a hack, meant to improve error messages after an AtLeast(). Maybe this can be removed by patterns returning both success and failure + * + * Never consumes input, and fails with zero length if the pattern succeeds. + * @param {Peg.Pattern} pattern + * @return {Peg.Pattern} + */ +Peg.Hint = function (pattern) { + return /** @type {Peg.Pattern} */ ( + Peg.WrapPattern(function (source, index) { + const match = pattern(source, index); + if (match[0]) { + console.log("oops match", match); + return [false, index, pattern.expectLabel]; + } else { + return match; + } + }) + ).expects(pattern.expectLabel); +};