From 226bfe84c5f690462adbf386dc66316cc21fdb28 Mon Sep 17 00:00:00 2001 From: crupest Date: Mon, 22 Nov 2021 20:53:01 +0800 Subject: import(life): Add compile principle codes. --- works/life/compile-principle-experiment/1/hoc.y | 65 ++++++++++++++++++++++ works/life/compile-principle-experiment/1/makefile | 5 ++ 2 files changed, 70 insertions(+) create mode 100644 works/life/compile-principle-experiment/1/hoc.y create mode 100644 works/life/compile-principle-experiment/1/makefile (limited to 'works/life/compile-principle-experiment/1') diff --git a/works/life/compile-principle-experiment/1/hoc.y b/works/life/compile-principle-experiment/1/hoc.y new file mode 100644 index 0000000..c4452ad --- /dev/null +++ b/works/life/compile-principle-experiment/1/hoc.y @@ -0,0 +1,65 @@ +%{ +#define YYSTYPE double /* data type of yacc stack */ +#include +#include +#include + +int yylex(); +int yyerror(const char * s); +%} +%token NUMBER +%left '+' '-' /* left associative, same precedence */ +%left '*' '/' '%' /* left assoc., higher precedence */ +%left UNARYMINUS +%% +list: /* nothing */ + | list '\n' + | list expr '\n' { printf("%lf\n", $2); } + ; +expr: NUMBER { $$ = $1; } + | expr '+' expr { $$ = $1 + $3; } + | expr '-' expr { $$ = $1 - $3; } + | expr '*' expr { $$ = $1 * $3; } + | expr '/' expr { $$ = $1 / $3; } + | expr '%' expr { $$ = fmod($1, $3); } + | '-' expr %prec UNARYMINUS { $$ = -$2; } + | '(' expr ')' { $$ = $2; } + ; +%% + +int lineno = 1; + +int main(int argc, char** argv) +{ + yyparse(); + return 0; +} + +int yylex() +{ + int c; + + do { + c = getchar(); + } while (c == ' ' || c == '\t'); + + if (c == EOF) + return 0; + + if (c == '.' || isdigit(c)) { + ungetc(c, stdin); + scanf("%lf", &yylval); + return NUMBER; + } + + if (c == '\n') + lineno++; + + return c; +} + +int yyerror(const char* s) +{ + fprintf(stderr, "Error occured near line %d\n", lineno); + return 0; +} diff --git a/works/life/compile-principle-experiment/1/makefile b/works/life/compile-principle-experiment/1/makefile new file mode 100644 index 0000000..65bcca2 --- /dev/null +++ b/works/life/compile-principle-experiment/1/makefile @@ -0,0 +1,5 @@ +hoc: hoc.c + cc hoc.c -o hoc + +hoc.c: hoc.y + bison hoc.y -o hoc.c -- cgit v1.2.3