Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- %{
- #include <stdio.h>
- #include <stdlib.h>
- #include "y.tab.h"
- #include "lex.yy.c"
- double symbolTable[4];
- double *arrayTable[4] = {NULL, NULL, NULL, NULL};
- int arraySize[4] = {0};
- void yyerror(char const *);
- %}
- %union{
- int ival;
- double dval;
- }
- %token <ival> ID ID2
- %token <dval> NUM
- %type <dval> Expr
- %token PRT DIM
- %left '+' '-'
- %left '/' '*' '%' QUO
- %start Program
- %%
- Program: Statement
- | Program Statement
- ;
- Statement: Assign ';'
- | Print ';'
- | Decl ';'
- ;
- Assign: ID '=' Expr { symbolTable[$1] = $3; }
- | ID2 '[' Expr ']' '=' Expr {
- if (arraySize[$1] <= 0) {
- yyerror("no initialize.");
- } else if ($3 < 0 || arraySize[$1] <= $3) {
- yyerror("index error.");
- } else {
- arrayTable[$1][(int )$3] = $6;
- }
- }
- ;
- Print: PRT Expr { printf("%f\n", $2); }
- ;
- Decl: DIM ID2 '[' Expr ']' {
- if (arraySize[$2] > 0) {
- yyerror("almost declared.");
- } else if ($4 < 0) {
- yyerror("index error.");
- } else {
- int n = $4;
- arraySize[$2] = n;
- double *p = arrayTable[$2] = calloc(sizeof *p, n);
- for (int i = 0; i < n; ++i) {
- p[i] = 0.;
- }
- }
- }
- ;
- Expr: Expr '+' Expr { $$ = $1 + $3; }
- | Expr '-' Expr { $$ = $1 - $3; }
- | Expr '*' Expr { $$ = $1 * $3; }
- | Expr '/' Expr { $$ = $1 / $3; }
- | Expr '%' Expr { $$ = (int )$1 % (int )$3; }
- | Expr QUO Expr { $$ = (int )$1 / (int )$3;}
- | '(' Expr ')' { $$ = $2; }
- | NUM { $$ = $1; }
- | ID { $$ = symbolTable[$1]; }
- | ID2 '[' Expr ']' {
- if (arraySize[$1] <= 0) {
- yyerror("no initialize.");
- $$ = 0.;
- } else if ($3 < 0 || arraySize[$1] <= $3) {
- yyerror("index error.");
- $$ = 0.;
- } else {
- $$ = arrayTable[$1][(int )$3];
- }
- }
- ;
- %%
- int main(void){
- yyparse();
- }
- void yyerror(char const *msg) {
- fprintf(stderr, "error: %s\n", msg);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement