flex-bison-in-action/analyzers/polynomials/polynomials.y

64 lines
1.2 KiB
Plaintext

%{
#include <stdio.h>
#include <stdlib.h>
void yyerror(const char *s);
int yylex(void);
extern FILE* yyin;
%}
%union { int num; char var; }
%token <num> NUMBER
%token <var> VARIABLE
%token LPAREN RPAREN PLUS MINUS MULTIPLY
%%
input:
| expr
;
expr:
term
| expr PLUS term { printf("Found operator: +\n"); }
| expr MINUS term { printf("Found operator: -\n"); }
;
term:
factor
| term MULTIPLY factor { printf("Found operator: *\n"); }
;
factor:
NUMBER { printf("Found number: %d\n", $1); }
| VARIABLE { printf("Found variable: %c\n", $1); }
| LPAREN expr RPAREN
;
%%
void yyerror(const char *s) {
fprintf(stderr, "033[91mError: %s\033[0m\n", s);
}
int main(int argc, char** argv) {
if (argc != 2) {
fprintf(stderr, "\033[91mUsage: %s <input_file>\033[0m\n", argv[0]);
return 1;
}
FILE* input_file = fopen(argv[1], "r");
if (!input_file) {
perror("033[91mFailed to open input file\033[0m\n");
return 1;
}
yyin = input_file;
printf("\033[34mParsing expression from file: %s\033[0m\n", argv[1]);
yyparse();
fclose(input_file);
printf("\033[92mParsing complete\033[0m\n");
return 0;
}