/* Kleines Beispiel fuer Mini-Compiler mit PCYACC geschrieben */ %{ #include #include %} %union { long in; char *ch; } %start programm %left '+' '-' %left '*' '/' %left UNARYMINUS %token IDENTIFIER %token NUMBER %type constausdruck %% programm: anweisungen ; anweisungen: zuweisung ';' | anweisungen zuweisung ';' ; zuweisung: IDENTIFIER '=' constausdruck { printf("mov %d,r16\n", $3); printf("st.l r16,%s\n", $1); } ; constausdruck: NUMBER { $$ = $1; } | constausdruck '+' constausdruck { $$ = $1 + $3; } | constausdruck '-' constausdruck { $$ = $1 - $3; } | constausdruck '*' constausdruck { $$ = $1 * $3; } | constausdruck '/' constausdruck { $$ = $1 / $3; } | '-'constausdruck %prec UNARYMINUS { $$ = -$2; } | '(' constausdruck ')' { $$ = $2; } ; %% int nextch; /* global verwendet */ int chcnt = 0; int chpos = 0; char linebuff[160]; int getit() { if (chcnt == 0) { printf("\nEingabe:"); gets(linebuff); chcnt = strlen(linebuff); if (chcnt != 0) /* nur wenn keine leere Eingabe */ { linebuff[chcnt] = ' '; /* zeilenende als blank uebertragen */ chcnt++; /* incl blank */ } /* sonst wird EOF uebertragen */ chpos = 0; } if (chcnt == 0) return(EOF); chcnt--; return(linebuff[chpos++]); } char buffer[160]; yylex() { int i,val; while (nextch == ' ') nextch = getit(); if (nextch == EOF) return(EOF); if (isdigit(nextch)) { yylval.in = 0; while (isdigit(nextch)) { yylval.in = yylval.in * 10l + (nextch - '0'); nextch = getit(); } return(NUMBER); } else if (isalpha(nextch)) { i = 0; while (isalnum(nextch)) { buffer[i++] = nextch; nextch = getit(); } buffer[i] = 0; yylval.ch = malloc(strlen(buffer)+1); strcpy(yylval.ch, buffer); return(IDENTIFIER); } else { val = nextch; nextch = getit(); return(val); } } main() { chcnt = 0; nextch = getit(); if (yyparse()) { printf("Fehler im Programm\n"); } } yyerror(s) /* Fehlerbehandlung */ char *s; { fprintf(stderr, "%s\n", s); } /* end */