From 797d3cc6b2e4a383049ff0e751cf2631bd7530a3 Mon Sep 17 00:00:00 2001 From: Tangent Wantwight Date: Fri, 4 Aug 2023 19:25:47 -0400 Subject: [PATCH] Try to improve error location identification --- notcl.js | 2 +- peg.js | 25 +++++++++++++------------ 2 files changed, 14 insertions(+), 13 deletions(-) diff --git a/notcl.js b/notcl.js index 195d3a7..512d3ed 100644 --- a/notcl.js +++ b/notcl.js @@ -63,7 +63,7 @@ var Notcl = (() => { ) ), AtLeast(0, PreCommand), - Choose(End(), Hint(Command)) + End() ).map(([, command, moreCommands]) => command.concat(moreCommands)); const ERROR_CONTEXT = /(?<=([^\n]{0,50}))([^\n]{0,50})/y; diff --git a/peg.js b/peg.js index 13979aa..30cda91 100644 --- a/peg.js +++ b/peg.js @@ -5,8 +5,8 @@ * * On success or failure, it returns the furthest point the pattern could make sense of, and a description of what was expected next at that point. * - * For simple patterns, the "furthest point" may just be index; however, some more complex patterns might succeed, - * but consume much less input than they would have been able to if some other expected symbol was found. Reporting + * For simple patterns, the "furthest point" may just be the following index; however, some more complex patterns might succeed, + * but consume less input than they would have been able to if some other expected symbol was found. Reporting * the furthest a pattern could hypothetically have gotten can help generate better error messages if no valid parse tree is found. * * @template T @@ -78,11 +78,9 @@ Peg.Regex = function (regex) { const pattern = Peg.WrapPattern(function (source, index) { regex.lastIndex = index; const matches = regex.exec(source); - return [ - matches ? [matches, regex.lastIndex] : null, - index, - pattern.expectLabel, - ]; + return matches + ? [[matches, regex.lastIndex], regex.lastIndex, pattern.expectLabel] + : [null, index, pattern.expectLabel]; }).expects(regex.source); return pattern; }; @@ -130,13 +128,15 @@ Peg.Sequence = function (...patterns) { let furthestExpected = genericExpected; for (const pattern of patterns) { const [value, furthest, expected] = pattern(source, index); + if (furthest >= furthestFound) { + furthestFound = furthest; + furthestExpected = expected; + } if (value == null) { - return [value, furthest, expected]; + return [null, furthestFound, furthestExpected]; } values.push(value[0]); index = value[1]; - furthestFound = furthest; - furthestExpected = expected; } return [[values, index], furthestFound, furthestExpected]; }).expects(genericExpected); @@ -162,14 +162,15 @@ Peg.AtLeast = function (min, pattern) { let furthestExpected = pattern.expectLabel; do { const [value, furthest, expected] = pattern(source, index); - if (value == null) { + if (furthest > furthestFound) { furthestFound = furthest; furthestExpected = expected; + } + if (value == null) { break; } values.push(value[0]); if (index == value[1]) { - furthestFound = value[1]; break; } index = value[1];