diff options
author | Yuqian Yang <crupest@crupest.life> | 2025-02-12 15:55:21 +0800 |
---|---|---|
committer | Yuqian Yang <crupest@crupest.life> | 2025-02-12 15:55:21 +0800 |
commit | 1ecfd0ab7f1f511268fd6404dbc110c3c277b48c (patch) | |
tree | 49449a4076ded9bd937a51679318edbe2a532cae /works/life/compile-principle-experiment/1/hoc.y | |
parent | 55d8b025e8d6ea971e8ee5762c892405fedc316b (diff) | |
parent | f8c10dd1fc55e60f35286475356e48c4f642eb63 (diff) | |
download | crupest-1ecfd0ab7f1f511268fd6404dbc110c3c277b48c.tar.gz crupest-1ecfd0ab7f1f511268fd6404dbc110c3c277b48c.tar.bz2 crupest-1ecfd0ab7f1f511268fd6404dbc110c3c277b48c.zip |
import(life): IMPORT crupest/life COMPLETE.
Diffstat (limited to 'works/life/compile-principle-experiment/1/hoc.y')
-rw-r--r-- | works/life/compile-principle-experiment/1/hoc.y | 65 |
1 files changed, 65 insertions, 0 deletions
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 <stdio.h> +#include <ctype.h> +#include <math.h> + +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; +} |