0

I am currently writing a PEG.js grammar and I want it to output custom errors. For instance I currently have this structure for creating a function.

//Function Declaration
FUNCTION_DECLARATION = 
FUNCTION __ t:(TYPE/VOID) __ n:KEY a:ARGUMENT_DECLARATION
_ b:FUNCTION_BLOCK
(END)
{return {context : "FUNCTION_DECLARATION",location:location(), type:t,name:n, 
args:a, block:b};
}

I want to be able to detect specific errors, like a missing END tag at the end of the function declaration. To do this, I need to be able to run a {action] when the expression DOES NOT MATCH.

Does anyone know how to do this? I only know how to run {action] when the expression actually matches as you can see with my return statement.

Additionally, it would be great if it was possible for the error location to point to the part of the expression that was already parsed before the missing END.

Best regards, Ricardo

1 Answers1

3

PEG.js already contains some custom error handling. When you run the parse() method, you can catch the error and check the location attribute to pinpoint where it came from. Here's an example:

 try {
    var entry = Parser.parse(text);
 } catch (err) {
    if (!err.hasOwnProperty('location')) throw(err);
    // Slice `text` with a little context before and after the error offset
    alert('Error: ' + text.slice(err.location.start.offset-10,
       err.location.end.offset+10).replace(/\r/g, '\\r'));
 }

EDIT

Try looking here. The error method might be helpful to look into. Here's an example pulled from github issues.

start = sign:[+-]? digits:[0-9]+ {
  var result = parseInt((sign || "") + digits.join(""), 10);

  if (result % 2 == 0) {
    error("The number must be an odd integer.");
  }

  return result;
}
Josh Voigts
  • 4,114
  • 1
  • 18
  • 43
  • This is not very helpful when you have a giant grammar for an entire programming language. You will get something like : found "CHARACTER" and expected ... (insert giant list of identifiers) ... What I need is to be able to detect specific errors in order to hand out custom error messages to better inform the user about what went wrong. – Ricardo Ferreira da Silva Jul 04 '18 at 08:19