summaryrefslogtreecommitdiff
path: root/examples/hello_calc2/parser.y
blob: 67bef504c398061f29c64b8259077a9f6976ed3b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
%{
#include <stdio.h>
#include <math.h>
%}

%union {
	double value;
	char* name;
}

%token <value> NUMBER

%type  <value>  expr

%left '+' '-'
%right SQRT
%left '*' '/'
%right '^'
%right UMINUS

%%
lines:	lines expr '\n'		{ printf("%.10g\n", $2); }
	|	lines '\n'
	|	error '\n' 		{ printf("Please re-enter last line: ");
	                	  yyerrok; }
	|
	;

expr:	expr '+' expr	{ $$ = $1 + $3; }
	|	expr '-' expr	{ $$ = $1 - $3; }
	|	expr '*' expr	{ $$ = $1 * $3; }
	|	expr '/' expr	{ $$ = $1 / $3; }
	|	expr '^' expr	{ $$ = pow($1, $3); }
	|	'(' expr ')'	{ $$ = $2; }
	|	'-' expr  %prec UMINUS { $$ = -$2; }
	|	NUMBER
	;

%%
#include <ctype.h>
#include <stdio.h>

int main (int argc, char **argv)
{
	return yyparse ();
}

int yyerror (char* errstr)
{
	printf ("Error: %s\n", errstr);
	return 1;
}