-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBA_Stack_machine.y
70 lines (66 loc) · 1.69 KB
/
BA_Stack_machine.y
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
65
66
67
68
69
70
%{
#include <stdio.h>
#include <string.h>
#include <math.h>
void yyerror(const char *message);
int stack[1000];
int stack_ptr;
%}
%union{
int value;
}
%token <value> INT
%token LOAD
%token ADD
%token SUB
%token MUL
%token MOD
%token INC
%token DEC
%type <value> exp stmt stmts program
%%
program : stmts {if(stack_ptr == 0){printf("%d\n", stack[0]);}else{printf("Invalid format\n");return(0);}}
;
stmts : stmt stmts {}
| stmt {}
;
stmt : exp {}
;
exp : LOAD INT {stack_ptr++; stack[stack_ptr] = $2;}
| ADD {
if(stack_ptr < 1){printf("Invalid format\n");return(0);}
stack[stack_ptr-1] = stack[stack_ptr] + stack[stack_ptr-1];
stack_ptr--;
}
| SUB {
if(stack_ptr < 1){printf("Invalid format\n");return(0);}
stack[stack_ptr-1] = stack[stack_ptr] - stack[stack_ptr-1];
stack_ptr--;
}
| MUL {
if(stack_ptr < 1){printf("Invalid format\n");return(0);}
stack[stack_ptr-1] = stack[stack_ptr] * stack[stack_ptr-1];
stack_ptr--;
}
| MOD {
if(stack_ptr < 1){printf("Invalid format\n");return(0);}
stack[stack_ptr-1] = stack[stack_ptr] % stack[stack_ptr-1];
stack_ptr--;
}
| INC {
if(stack_ptr < 0){printf("Invalid format\n");return(0);}
stack[stack_ptr] = stack[stack_ptr] + 1;
}
| DEC {
if(stack_ptr < 0){printf("Invalid format\n");return(0);}
stack[stack_ptr] = stack[stack_ptr] - 1;
}
%%
void yyerror(const char* message){
printf("%s\n", message);
}
int main(int argc, char* argv[]){
stack_ptr = -1;
yyparse();
return(0);
}