I want to get param from a input. For example: Input:12+10
.
After running my calculator.
I want to get 12 and 10. I know, I have to use the fourth param in Parse(pParser, hTokenID, sTokenData, pArg);
, but how?
parser.y:
%syntax_error{fprintf(stderr, "Syntax error\n");}
%left PLUS MINUS.
%left TIMES DIVIDE.
program ::= expr(A).{printf("Result = %d\n", A);}
expr(A) ::= expr(B) PLUS expr(C).{A = B + C; }
expr(A) ::= expr(B) MINUS expr(C). {A = B - C; }
expr(A) ::= expr(B) TIMES expr(C). {A = B * C; }
expr(A) ::= expr(B) DIVIDE expr(C). {if (C != 0)A = B / C;else fprintf(stderr,"divide by 0");}
expr(A) ::= LPAR expr(B) RPAR. {A = (B);}
expr(A) ::= INTEGER(B).{A = B;}
calc.c:
int main(int argc, char ** argv){
pParser = (void *)ParseAlloc(malloc);
for (c = argv[1]; *c; c++){
switch (*c){
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
for (value = 0; *c && *c >= '0' && *c <= '9'; c++)
value = value * 10 + (*c - '0');
c--;
Parse(pParser, INTEGER, value);
break;
case '+':
Parse(pParser, PLUS, 0);
break;
case '-':
Parse(pParser, MINUS, 0);
break;
case '*':
Parse(pParser, TIMES, 0);
break;
...(the rest case I dont write anymore,the same as before)
}
}
Parse(pParser, 0, 0);
ParseFree(pParser, free);
}
If you want to pass some data into
lemon
's blocks through 4-th parameter, you have to add into your.y
file the following line:See lemon's documentation (http://www.hwaci.com/sw/lemon/lemon.html):
But notice that "that is the value of the 4th parameter in the most recent call to
Parse()
"So, I believe that you want to pass exactly token value. In this case you have to wrap token value into structure:
Your program modified in this way:
parse.y:
main.c:
types.h:
Sample output:
And just in case, CMake script to compile this sample:
CMakeLists.txt: