-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprog.y
More file actions
64 lines (50 loc) · 919 Bytes
/
prog.y
File metadata and controls
64 lines (50 loc) · 919 Bytes
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
54
55
56
57
58
59
60
61
62
63
64
%{
#include <stdio.h>
#include <stdlib.h>
#include <string>
extern int yylex();
extern int yyparse();
extern FILE* yyin;
char *name;
void yyerror(const char* s);
%}
%start prog
%union{
char *name;
int ival;
}
%token PROGRAM
%token PRINT
%token<ival> NUM
%token<name> NAME
%left '-' '+'
%type<ival> EXPRESSION
%type<name> PROG_NAME
%%
prog: PROGRAM PROG_NAME '\n' STATEMENTS
;
PROG_NAME: NAME { name = $1; }
;
STATEMENTS: STATEMENT '\n' STATEMENTS
|
;
STATEMENT: EXPRESSION {;}
| PRINT EXPRESSION { printf("> %d\n", $2);}
| PRINT PROGRAM { printf("> %s\n", name);}
;
EXPRESSION: EXPRESSION '+' EXPRESSION { $$= $1+$3;}
| EXPRESSION '-' EXPRESSION { $$= $1-$3;}
| NUM { $$=$1;}
| '(' EXPRESSION ')' { $$=$2; }
;
%%
int main() {
yyin = stdin;
do {
yyparse();
} while(!feof(yyin));
}
void yyerror(const char* s) {
fprintf(stderr, "Parse error: %s\n", s);
exit(1);
}