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

67 lines
1.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 <stdio.h>
#include <stdlib.h>
#include <string.h>
extern char *yytext;
void yyerror(const char *s);
extern int yylex();
extern FILE *yyin;
%}
%union {
char *str;
}
%token <str> IDENTIFIER NUMBER RET PRINT
%token LBRACE RBRACE SEMICOLON ASSIGN PLUS MINUS MULT DIV
%type <str> expr program statement block
%%
// Program - последовательность утверждений
program:
| program statement
;
// Утверждение - либо блок {...}, либо выражение с ; в конце
statement:
expr SEMICOLON
| block
;
// Блок - { program }, т.е. это последовательность утверждений и она находится в скобках { }
block:
LBRACE program RBRACE
;
// Возможные выражения
expr:
RET expr // выражение вида return expr
| PRINT expr // выражение вида print expr
| IDENTIFIER ASSIGN expr // выражения вида a=expr
| expr PLUS expr // выражения вида expr+expr
| expr MINUS expr // выражения вида expr-expr
| expr MULT expr // выражения вида expr*expr
| expr DIV expr // выражения вида expr/expr
| IDENTIFIER { printf("IDENTIFIER = %s\n", $1); free($1); }
| NUMBER { printf("NUMBER = %s\n", $1); free($1); }
;
%%
int main(int argc, char **argv) {
if (argc > 1) {
FILE *f = fopen(argv[1], "r");
if (!f) {
perror("\033[91mFail open file\033[0m");
return 1;
}
yyin = f;
}
yyparse();
printf("\033[92mSuccess parsed!\033[0m");
return 0;
}