From 8a57bedc04fff7a92ef6d2762cfe5fc17050f021 Mon Sep 17 00:00:00 2001 From: Akshay Date: Fri, 30 Apr 2021 22:22:13 +0530 Subject: add yacc programs --- 11/input | 1 + 11/main.l | 33 +++++++++++++++++++++++++++ 11/main.y | 76 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 110 insertions(+) create mode 100644 11/input create mode 100644 11/main.l create mode 100644 11/main.y (limited to '11') 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 @@ +%{ +#include "y.tab.h" +extern int yylval; +%} + +%% +"++" return INC; +"--" return DEC; +"+" return ADD; +"-" return SUB; +"*" return MUL; +"/" return DIV; +"=" return ASSIGN; +"==" return EQ; +"!=" return NEQ; +"<" return LT; +">" return GT; +"<=" return LTE; +">=" return GTE; +";" return ENDL; +"for" return FOR; +[0-9]+ { + yylval = atoi(yytext); + return NUM; +}; +[a-zA-Z_][a-zA-Z_0-9]* return ID; +. return yytext[0]; +\n return 0; +%% + +int yywrap() { + return 1; +} 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 @@ +%{ +#include +#include +#include "lex.yy.cc" +int yylex(); +int yyerror(char *); +int loop_count = 0; +%} + +%token ADD SUB MUL DIV INC DEC +%token LT GT LTE GTE EQ NEQ ASSIGN +%token FOR +%token ENDL +%token NUM ID + +%start statement + +%% +primary_expr: NUM + | ID + ; + +postfix_expr: postfix_expr INC + | postfix_expr DEC + | primary_expr + ; + +unary_expr: INC unary_expr + | DEC unary_expr + | postfix_expr + ; + +boolean_expr: unary_expr LT unary_expr + | unary_expr GT unary_expr + | unary_expr LTE unary_expr + | unary_expr GTE unary_expr + | unary_expr EQ unary_expr + | unary_expr NEQ unary_expr + ; + +assignment_expr: unary_expr ASSIGN unary_expr + | unary_expr ASSIGN boolean_expr + ; + +expression: unary_expr + | boolean_expr + | assignment_expr + ; + +block: '{' statement block_cont + ; +block_cont: statement block_cont + | '}' + ; + +statement: expression ENDL + | block + | for_expr {loop_count++;} + | ENDL + ; + +for_expr: FOR '(' statement statement expression ')' statement + | FOR '(' statement statement ')' statement + ; + +%% + +int main() { + yyparse(); + printf("valid expression, nested %d", loop_count); +} + +int yyerror(char *s) { + printf("error: %s", s); + exit(0); +} -- cgit v1.2.3