LEX & YACC - spaces in expressions

I read in a file and for some reason I get a syntax error when I try to express an expression like 5+5 however, if I do this 5 + 5 it works well. I am confused why he did it?

Here is my lex file (I will leave main, which reads in the file):

 %{ #include "y.tab.h" #include "stdio.h" #include <stdlib.h> %} %% (\/\*([^*]|(\*+([^*/]|[\r\n])))*\*+\/)+ {} \/\/[^\n]*\n {} fd { return FD; } [\r\t\n]+ {} [ ]* {} bk { return BK;} setc {return SETC;} [-+]?[0-9]+ { yylval = atoi(yytext); return NUMBER;} fd[0-9]+ { } rt {return RT;} pink {return COLOR_TYPE;} magenta {return COLOR_TYPE; } if {return IF; } ifelse {return IFELSE; } \[ {return LBRACKET; } \] {return RBRACKET; } \< {return LESS_THAN; } \> {return GREATER_THAN; } \+ {return PLUS; } \- {return MINUS; } \/ {return DIVIDE; } \* {return MULT; } \( {return LPAREN;} \) {return RPAREN;} \= {return EQ;} %% 

Here is the part of my yacc file that deals with the expression:

 expr : NUMBER { printf("EXPR-->NUMBER: %d\n", $1);} |expr PLUS expr {$$ = $1 + $3; printf("EXPR-->expression PLUS expression: %d\n", $$);} |expr DIVIDE expr {$$ = $1 / $3; printf("EXPR-->expression DIVIDE expression %d\n", $$);} |expr MULT expr {$$ = $1 * $3; printf("EXPR-->expression MULTIPLY expression %d\n", $$);} |expr MINUS expr {$$ = $1 - $3; printf("EXPR-->expression MINUS expression %d\n", $$);} |COLOR_TYPE {printf("EXPR-->COLOR\n");} ; 

was there a problem in the lex file?

+4
source share
1 answer

The notation (lexer) returns these two to the parser: 5 and +5 . Which in your grammar (and logically) is invalid.

I think it’s better for you to change your lexer and move the rules for operators. (This means at least above the rule returning NUMBER ).

EDIT: After some thought ( EDIT No. 2: and a more useful comment by Jerry Coffin), I suggest changing the lexical rule for NUMBER to [0-9]+ . In order for the parser to still accept input like "+123" or "-123", you must add this to your grammar:

 %left PLUS MINUS ... %right UNARY %% expr : number | expr PLUS expr ... ; number : PLUS NUMBER %prec UNARY {$$ = $2} | MINUS NUMBER %prec UNARY {$$ = -$2} | NUMBER ; 

This will allow you to use unary + or - up to any number, while at the same time giving operators + and - a higher priority.

+6
source

Source: https://habr.com/ru/post/1396905/


All Articles