%{
#include "Parser.h"
%}
%%
"+" {
return PLUS;
}
"-" {
return minus;
}
"/" {
return DIV;
}
"*" {
return MULT;
}
"(" {
return l_par;
}
")" {
return r_par;
}
[0-9]+ {
Yylval = Atoi (Yytext);
return INTEGER;
}
"/n" {
return NL;
}
. ;
%%
----------------------------------------------------------------------------------------------------------- ----------------------------------------
%{
int tempCount1 =-1;
int tempCount2 =-1;
int tempCount3 =-1;
int tempCount4 =-1;
int tempCount5 =-1;
int tempCount6 =-1;
int tempCount7 =-1;
%}
%token PLUS
%token minus
%token DIV
%token MULT
%token L_par
%token R_par
%token INTEGER
%token NL
%%
Calc
: Calc expression NL {printf ("%d/n", $ $);}
| Expression NL {printf ("%d/n", $ $);}
;
Expression
: term {$$ = $;}
| Expression PLUS Term {tempCount6 = $ + $; $$ = $ + $; }
| Expression minus term {tempCount7 = $-$ $; $$ = $-$;}
;
Term
: Factor {$$ = $;}
| Term MULT Factor {tempCount4 = $ * $ $; $$ = $ * $ $; }
| Term DIV Factor {TEMPCOUNT5 =$1/$ $; $$ = $/$;}
;
Factor
: L_par expression R_par {tempCount1 = $; $$ = $;}
| INTEGER {tempCount2 = $; $$ = $;}
| Minus factor {tempCount3 =-$2; $$ =-$2;}
%%
int Yyerror (char *str) {
printf ("%s/n", str);
}
Input (4-1)
TempCount2 = 2
TempCount2 = 4
TempCount2 = 1
TEMPCOUNT7 = 3
TempCount1 = 3
TEMPCOUNT4 = 6
Read into 2→ multiplication sign →integer (factor) match
Factor (term) → Read into the left width → read into the 4→ read and subtract
INTEGER (factor) match →factor (term) →term (expression)
Read into the 1→ read into the right width →integer (factor) match →factor (term)
L_par expression r_par match →term MULT factor match →term (expression)
----------------------------------
You can define terminator and non-terminator types,
%token PLUS
%token minus
%token DIV
%token MULT
%token L_par
%token R_par
%token <value> integers
%token NL
%type <node> Calc
%type <node> Expression
%type <node> Term
%type <node> Factor
%union{
int value;
CNode *node;
};