Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -50,3 +50,8 @@ modules.order
Module.symvers
Mkfile.old
dkms.conf

y.tab.h
y.tab.c
lex.yy.c
bin/*
4 changes: 4 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
comp:
lex src/lex.l
yacc -d src/grammar.y
gcc -o bin/main y.tab.c lex.yy.c
52 changes: 52 additions & 0 deletions src/grammar.y
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
%{
#include <stdio.h>
#include <stdlib.h>

int yylex();
int yyerror(const char *s);
%}

%union {
double double_value;
}

%token <double_value> DOUBLE_LITERAL
%token CR LP RP
%left ADD SUB
%left MUL DIV

%type <double_value> expr

%%
stmt_list:
stmt
| stmt_list stmt
;

stmt:
expr CR {
printf(">>%lf\n", $1);
}

expr:
DOUBLE_LITERAL { $$ = $1; }
| expr ADD expr { $$ = $1 + $3; }
| expr SUB expr { $$ = $1 - $3; }
| expr MUL expr { $$ = $1 * $3; }
| expr DIV expr { $$ = $1 / $3; }
| LP expr RP { $$ = $2; }
;
%%

int yyerror(char const *str) {
extern char *yytext;
fprintf(stderr, "parse error near %s\n", yytext);
return 0;
}

int main(void) {
if (yyparse()) {
exit(1);
}
return 0;
}
32 changes: 32 additions & 0 deletions src/lex.l
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
%{
#include <stdio.h>
#include "y.tab.h"
%}

%%
"+" return ADD;
"-" return SUB;
"*" return MUL;
"/" return DIV;
"(" return LP;
")" return RP;
"\n" return CR;

([1-9][0-9]*)|0|([0-9]+\.[0-9]+) {
double val;
sscanf(yytext, "%lf", &val);
yylval.double_value = val;
return DOUBLE_LITERAL;
}

[ \t] ;

. {
fprintf(stderr, "lexical error\n");
exit(1);
}
%%

int yywrap(void) {
return 1;
}