So I have generated a parser using JISON
:
%lex
%x TEXT
%%
("Project"|"project") {return 'PROJECTCOMMAND';}
"-au" {return 'ADDUSER';}
"-n" {this.begin('TEXT'); return 'NAMEOPTION';}
"-k" {return 'KEYOPTION';}
"-desc" {return 'DESCRIPTION';}
("--add"|"-a") {return 'ADDOPTION';}
<TEXT>[-a-zA-Z0-9@\.]+ {this.popState(); return 'TEXT';}
<INITIAL,TEXT>\s+ // Ignore white space...
/lex
%%
line :
PROJECTCOMMAND ADDUSER
{
//Project Command of add user
var res = new Object();
res.value = "addUser Project";
return res;
}
| PROJECTCOMMAND ADDOPTION
{
//Project Command with no arguments
var res = new Object();
res.value = "addProject";
return res;
}
| PROJECTCOMMAND ADDOPTION NAMEOPTION TEXT
{
//Project command with project name as argument
var res = new Object();
res.value = "addProject name";
res.name = $4;
return res;
}
Is there any way I can do validations on command, i.e. If command does not satisfy any of above rules then throw a error, .i.e. having a default option.
Something like this at end of parser:
| return "command is invalid";
Thanks in Advance
This question has not had an answer, because it is bigger than it seems. You are asking about the general problem of giving meaningful error message from parsers built from a parser generator tool. This has been an issue for compiler writers and tool writers for some many years.
Parsers do not normally work like procedural programs, in that you cannot have a "default" or "else" clause like you might have in a switch or if statement when programming, and although it seems like an easy extension it is not. It is for this reason some people still hand write their own custom parser because it gives them the flexibility to handle such error situations. An error situation is when the rules fail to match the text. Many academic papers have been written on this subject, but a small example discussion can be found here: http://research.swtch.com/yyerror.
You asked about JISON, which is based on yacc/bison. In yacc/bison the error situation is handled by a built in feature known as yyerror. This enables the failure error message to be customised to something like "command is invalid". As far as I can tell, this feature is not yet implemented in JISON.
In this situation you have to amend your grammar rules to give an action for all the possible alternatives that will be the error message. For example:
and as you can see that is both horrible and less than satisfactory.