pegjs: "unexpected" rule
- Feature Request:
Add “unexpected” rule to override standard error message.
unexpected =
keywords { return "Unexpected keyword "+text()+"."; }
/ expression { return "Unexpected expression «"+text()+"»."; }
/ lamdba_function { return "Unexpected lambda function."; } ;
To implement it just change peg$buildError by:
function peg$buildError() {
var expected = peg$expected[0];
var failPos = expected.pos;
// if "unexpected" rule exist this might throw the appropriate error.
if (typeof peg$parseunexpected !== 'undefined') {
// make peg$expect temporary unavailable, set the cursor position to the fail position
// next get the output of the rule, if it's a string, return it.
const tmp = peg$expect;
peg$expect = new Function();
peg$currPos = failPos;
const unexpected = peg$parseunexpected();
peg$expect = tmp;
if (typeof unexpected === 'string') {
const length = peg$currPos - failPos;
const location = failPos < input.length
? peg$computeLocation(failPos, failPos + length)
: peg$computeLocation(failPos, failPos);
return new peg$SyntaxError(unexpected, expected.variants, unexpected, location);
}
}
// else return standard error.
const unexpected = input.charAt(failPos);
const location = failPos < input.length
? peg$computeLocation(failPos, failPos + 1)
: peg$computeLocation(failPos, failPos);
return new peg$SyntaxError(
peg$SyntaxError.buildMessage(expected.variants, unexpected), expected.variants, unexpected, location);
}
Expected behavior: Improve error handling.
If it’s not ethical, is there anyone who can tell me how to create a plugin that would make the change? Thanks a lot
About this issue
- Original URL
- State: open
- Created 5 years ago
- Comments: 25 (4 by maintainers)
Just some bikeshedding, but when such feature is implemented, it should be let to the user the choice of the rule to be defined as the “unexpected” rule, e.g. with
Use a tokenizer has a cost. such feature is simple to implement and cost nothing to nobody