Initial commit based on https://thegeekuday.wordpress.com/2012/11/14/calculator-progr...
authorNick Downing <downing.nick@gmail.com>
Thu, 21 Jun 2018 13:03:22 +0000 (23:03 +1000)
committerNick Downing <downing.nick@gmail.com>
Thu, 21 Jun 2018 13:07:11 +0000 (23:07 +1000)
.gitignore [new file with mode: 0644]
Makefile [new file with mode: 0644]
cal.l [new file with mode: 0644]
cal.y [new file with mode: 0644]
doc/Calculator program using yacc and lex _ thegeekuday.pdf [new file with mode: 0644]

diff --git a/.gitignore b/.gitignore
new file mode 100644 (file)
index 0000000..d719633
--- /dev/null
@@ -0,0 +1,4 @@
+*.o
+cal
+lex.yy.c
+y.tab.c
diff --git a/Makefile b/Makefile
new file mode 100644 (file)
index 0000000..ecd7219
--- /dev/null
+++ b/Makefile
@@ -0,0 +1,13 @@
+cal: y.tab.o
+       ${CC} -o $@ $<
+
+y.tab.o: y.tab.c lex.yy.c
+
+y.tab.c: cal.y
+       yacc $<
+
+lex.yy.c: cal.l
+       lex $<
+
+clean:
+       rm -f *.o cal lex.yy.c y.tab.c
diff --git a/cal.l b/cal.l
new file mode 100644 (file)
index 0000000..95b4a25
--- /dev/null
+++ b/cal.l
@@ -0,0 +1,9 @@
+DIGIT [0-9]+\.?|[0-9]*\.[0-9]+
+
+%option noyywrap
+
+%%
+
+[ ]
+{DIGIT}        { yylval = atof(yytext); return NUM; }
+\n|.   { return yytext[0]; }
diff --git a/cal.y b/cal.y
new file mode 100644 (file)
index 0000000..637cb82
--- /dev/null
+++ b/cal.y
@@ -0,0 +1,41 @@
+%{
+#include <ctype.h>
+#include <stdio.h>
+#define YYSTYPE double
+%}
+%token NUM
+
+%left '+' '-'
+%left '*' '/'
+%right UMINUS
+
+%%
+
+S : S E '\n' { printf("Answer: %g\nEnter:\n", $2); }
+  | S '\n'
+  |
+  | error '\n' { yyerror("Error: Enter once more...\n"); yyerrok; }
+  ;
+E : E '+' E { $$ = $1 + $3; }
+  | E '-' E { $$ = $1 - $3; }
+  | E '*' E { $$ = $1 * $3; }
+  | E '/' E { $$ = $1 / $3; }
+  | '(' E ')' { $$ = $2; }
+  | '-' E %prec UMINUS { $$ = -$2; }
+  | NUM
+  ;
+%%
+
+#include "lex.yy.c"
+
+int main()
+{
+  printf("Enter the expression: ");
+  yyparse();
+}
+
+yyerror(char * s)
+{
+  printf("%s\n", s);
+  exit(1);
+}
diff --git a/doc/Calculator program using yacc and lex _ thegeekuday.pdf b/doc/Calculator program using yacc and lex _ thegeekuday.pdf
new file mode 100644 (file)
index 0000000..dcbc1a5
Binary files /dev/null and b/doc/Calculator program using yacc and lex _ thegeekuday.pdf differ