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

37 lines
1.3 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>
void yyerror(const char *s);
int yylex();
%}
// В Bison приоритет операторов определяется обратным порядком объявления
// left означает левоассоциативность, т.е. вычисление 8/2/2/2 например производится слева направо
%token NUMBER
%left '+' '-' // т.е. операторы в этой строке имеют более низкий приотритет
%left '*' '/' // нежели операторы в этой строке
%%
// Это правило отвечает за обработку потока выражений и вывод результатов.
input:
| input expr { printf("= %d\n", $2); }
;
// $1 - значение первого операнда, $2 - оператор, а $3 - значение второго операнда
expr: NUMBER { $$ = $1; }
| expr '+' expr { $$ = $1 + $3; }
| expr '-' expr { $$ = $1 - $3; }
| expr '*' expr { $$ = $1 * $3; }
| expr '/' expr { $$ = $1 / $3; }
| '(' expr ')' { $$ = $2; }
;
%%
void yyerror(const char *s) {
fprintf(stderr, "ERROR: %s\n", s);
}
int main() {
yyparse();
return 0;
}