Hi I am a newbie to JISON and stuck in following code:
For parsing a command:
project -a -n <projectname>
My code is as follows:
"project" {return 'PROJECTCOMMAND';}
"-n" {return 'NAMEOPTION';}
("--add"|"-a") {return 'ADDOPTION';}
[-a-zA-Z0-9@\.]+ {return 'TEXT';}
line :
PROJECTCOMMAND ADDOPTION NAMEOPTION TEXT
{
//Prject command with project name as argument
var res = new Object();
res.value = "addProject name";
res.name = $4;
return res;
}
This works fine if command is as follows:
project -a -n samplePro
But gives error if command is:
project -a -n project
Error : Expecting TEXT and got PROJECTCOMMAND.
Same happens if project name in command is project1, project2, myproject, etc..
Is there any way I can fix this?
Thanks in advance
One way to solve this is to use state. The formal name for what I call "state" here is "start condition" but I find that "state" is a clearer term to me than "start condition".
I've declared a new lexer state with
%x TEXT. There is anINITIALstate that exists implicitly. This is the state in which the lexer starts. Any pattern that does not get a state specified exists only in theINITIALstate.I've put
<TEXT>in front of the pattern that results in theTEXTtoken so that this token is generated only when we are in theTEXTstate.I've set the pattern for white space to apply to the states
INITIALandTEXT.I've made it so that
-ncauses the lexer to enter theTEXTstate and when aTEXTtoken is encountered, the state is popped.With this in place, when Jison encounters
-ninproject -a -n projectit gets into theTEXTstate where the only things expected are spaces, which are ignored, orTEXTtokens. Jison then processes the white space, which it ignores. Then it processes the text that follows which is understood as aTEXTtoken and pops the state.Complete code: