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

126 lines
2.7 KiB
Plaintext
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

%{
#include "C:\Users\user\Desktop\УЧЕБА\6_СЕМ\КОМПИЛЯТОРЫ\flex_bison_test\analyzers\polynomials\stack\stack.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
Element tokens[100];
int token_count = 0;
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 {
tokens[token_count].str_ptr = "+";
tokens[token_count].type = 'o';
token_count++;
//printf("Found operator: +\n");
}
| expr MINUS term {
tokens[token_count].str_ptr = "-";
tokens[token_count].type = 'o';
token_count++;
//printf("Found operator: -\n");
}
;
term:
factor
| term MULTIPLY factor {
tokens[token_count].str_ptr = "*";
tokens[token_count].type = 'o';
token_count++;
//printf("Found operator: *\n");
}
;
factor:
NUMBER {
char* num_str = malloc(20);
sprintf(num_str, "%d", $1);
tokens[token_count].str_ptr = num_str;
tokens[token_count].type = 'n';
token_count++;
//printf("Found number: %d\n", $1);
}
| VARIABLE {
char* var_str = malloc(2);
var_str[0] = $1;
var_str[1] = '\0';
tokens[token_count].str_ptr = var_str;
tokens[token_count].type = 'v';
token_count++;
//printf("Found variable: %c\n", $1);
}
| LPAREN expr RPAREN
;
%%
void yyerror(const char *s) {
fprintf(stderr, "\033[91mError: %s\033[0m\n", s);
}
void print_tokens() {
printf("\nToken sequence:\n");
printf("Index | Token | Type\n");
printf("------|-------|-----\n");
for (int i = 0; i < token_count; i++) {
printf("%5d | %5s | %c\n", i, tokens[i].str_ptr, tokens[i].type);
}
}
void free_tokens() {
for (int i = 0; i < token_count; i++) {
if (tokens[i].type == 'n' || tokens[i].type == 'v') {
free(tokens[i].str_ptr);
}
}
}
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();
print_tokens();
char* res = calulate(tokens, token_count);
printf("Result: %s\n", res);
free(res);
free_tokens();
fclose(input_file);
printf("\033[92mParsing complete\033[0m\n");
return 0;
}