From 8a57bedc04fff7a92ef6d2762cfe5fc17050f021 Mon Sep 17 00:00:00 2001 From: Akshay Date: Fri, 30 Apr 2021 22:22:13 +0530 Subject: add yacc programs --- 7/main.l | 22 ++++++++++++++++++++++ 7/main.y | 34 ++++++++++++++++++++++++++++++++++ 2 files changed, 56 insertions(+) create mode 100644 7/main.l create mode 100644 7/main.y (limited to '7') diff --git a/7/main.l b/7/main.l new file mode 100644 index 0000000..7e1332f --- /dev/null +++ b/7/main.l @@ -0,0 +1,22 @@ +%{ +#include "y.tab.h" +extern int yylval; +%} + +%% +[0-9]+ { + yylval = atoi(yytext); + return NUM; +} +"+" return ADD;; +"-" return SUB; +"*" return MUL; +"/" return DIV; +"(" return LPAR; +")" return RPAR; +\n return 0; +%% + +int yywrap() { + return 1; +} diff --git a/7/main.y b/7/main.y new file mode 100644 index 0000000..26a2007 --- /dev/null +++ b/7/main.y @@ -0,0 +1,34 @@ +%{ +#include +#include +int yylex(); +int yyerror(char *); +%} + +%token NUM ADD SUB MUL DIV LPAR RPAR +%left ADD SUB MUL DIV +%right NEG + +%% + +S: + E { printf("\n"); }; +E: + E ADD E { printf("+ "); } + | E MUL E { printf("* "); } + | E SUB E { printf("- "); } + | E DIV E { printf("/ "); } + | LPAR E RPAR + | SUB E %prec NEG { printf("- "); } + | NUM { printf("%d ", yylval); } + ; +%% + +int main() { + yyparse(); +} + +int yyerror(char *s) { + printf("error: %s", s); + exit(0); +} -- cgit v1.2.3