aboutsummaryrefslogtreecommitdiff
path: root/11
diff options
context:
space:
mode:
authorAkshay <[email protected]>2021-04-30 17:52:13 +0100
committerAkshay <[email protected]>2021-04-30 17:52:13 +0100
commit8a57bedc04fff7a92ef6d2762cfe5fc17050f021 (patch)
tree192ea2a1bd2eec0c0f84a9cb7adc9b10d005e1db /11
parent30047205e440e9ad8984e1830b8b819b5fe1f9f7 (diff)
add yacc programs
Diffstat (limited to '11')
-rw-r--r--11/input1
-rw-r--r--11/main.l33
-rw-r--r--11/main.y76
3 files changed, 110 insertions, 0 deletions
diff --git a/11/input b/11/input
new file mode 100644
index 0000000..7e9718c
--- /dev/null
+++ b/11/input
@@ -0,0 +1 @@
for(i=0;i!=20;i--){for(;;){for(;;)i=1;}}
diff --git a/11/main.l b/11/main.l
new file mode 100644
index 0000000..5cc2a4e
--- /dev/null
+++ b/11/main.l
@@ -0,0 +1,33 @@
1%{
2#include "y.tab.h"
3extern int yylval;
4%}
5
6%%
7"++" return INC;
8"--" return DEC;
9"+" return ADD;
10"-" return SUB;
11"*" return MUL;
12"/" return DIV;
13"=" return ASSIGN;
14"==" return EQ;
15"!=" return NEQ;
16"<" return LT;
17">" return GT;
18"<=" return LTE;
19">=" return GTE;
20";" return ENDL;
21"for" return FOR;
22[0-9]+ {
23 yylval = atoi(yytext);
24 return NUM;
25};
26[a-zA-Z_][a-zA-Z_0-9]* return ID;
27. return yytext[0];
28\n return 0;
29%%
30
31int yywrap() {
32 return 1;
33}
diff --git a/11/main.y b/11/main.y
new file mode 100644
index 0000000..9ed51a0
--- /dev/null
+++ b/11/main.y
@@ -0,0 +1,76 @@
1%{
2#include <stdio.h>
3#include <stdlib.h>
4#include "lex.yy.cc"
5int yylex();
6int yyerror(char *);
7int loop_count = 0;
8%}
9
10%token ADD SUB MUL DIV INC DEC
11%token LT GT LTE GTE EQ NEQ ASSIGN
12%token FOR
13%token ENDL
14%token NUM ID
15
16%start statement
17
18%%
19primary_expr: NUM
20 | ID
21 ;
22
23postfix_expr: postfix_expr INC
24 | postfix_expr DEC
25 | primary_expr
26 ;
27
28unary_expr: INC unary_expr
29 | DEC unary_expr
30 | postfix_expr
31 ;
32
33boolean_expr: unary_expr LT unary_expr
34 | unary_expr GT unary_expr
35 | unary_expr LTE unary_expr
36 | unary_expr GTE unary_expr
37 | unary_expr EQ unary_expr
38 | unary_expr NEQ unary_expr
39 ;
40
41assignment_expr: unary_expr ASSIGN unary_expr
42 | unary_expr ASSIGN boolean_expr
43 ;
44
45expression: unary_expr
46 | boolean_expr
47 | assignment_expr
48 ;
49
50block: '{' statement block_cont
51 ;
52block_cont: statement block_cont
53 | '}'
54 ;
55
56statement: expression ENDL
57 | block
58 | for_expr {loop_count++;}
59 | ENDL
60 ;
61
62for_expr: FOR '(' statement statement expression ')' statement
63 | FOR '(' statement statement ')' statement
64 ;
65
66%%
67
68int main() {
69 yyparse();
70 printf("valid expression, nested %d", loop_count);
71}
72
73int yyerror(char *s) {
74 printf("error: %s", s);
75 exit(0);
76}