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); +};