/* Infix symbol calculator */
% {
# Define yystype double/* define the c Data Type of the semantic value */
# Include <math. h>
# Include <stdio. h>
# Include <ctype. h>
Int yylex (void );
Void yyerror (char const *);
%}
% Token num/* mark type, only one num */
% Left '-''+'/* Definition +,-OPERATOR: left combination */
/* The so-called left combination refers to the expression 1 + 2 + 3.
It is calculated as follows: (1 + 2) + 3
The most obvious right combination x = y = z is calculated as follows: x = (y = z)
*/
% Left '*'/* The higher the backend priority */
% Left Neg/* because the negative sign is the same as the minus sign, it is marked with another symbol, which is described later */
% Right '^'/* power calculation is right combination */
%
Input:/* The input can be an empty string, so that when the program receives the EOF from the beginning, it will not cause an error */
| Input line/* can also be a row */
;
Line: '/N'/* You can simply press ENTER for a line, and ignore the processing */
| Exp '/N' {printf ("/T %. 10g/N", $1 );}
/* If it is an expression, print the Semantic Value of exp, and the semantic value of this sentence will be discarded */
;
Exp: num {$ = $1 ;}
/* The expression can only be a number. In this case, the Semantic Value of the sentence is assigned to this number */
| Exp '+ 'exp {$ = $1 + $3 ;}
/* The expression can be added with another expression, and the corresponding semantic values are also added, the same below */
| Exp '-'exp {$ = =$ 1-$3 ;}
| Exp '*' exp {$ = =$ 1*$3 ;}
| Exp '/'exp {$ $ = $1/$3 ;}
| '-' Exp % prec neg {$ =- $2 ;}
/* The priority of this syntax structure is the same as that of neg */
| Exp '^' exp {$ $ = POW ($1, $3 );}
| '('Exp') '{$ = $2 ;}
;
%
/* The main function directly calls yyparse for analysis */
Int main (void)
{
Return yyparse ();
}
/* Lexical analysis functions
This was what Lex was supposed to do.
This function simply picks out the numbers in the stream, and returns other characters.
If the return value is less than or equal to 0, yyparse considers the input to be over.
*/
Int yylex (void)
{
Int C;
While (C = getchar () = ''| C = '/t ');
If (C = '.' | isdigit (c )){
Ungetc (C, stdin );
Scanf ("% lf", & yylval );
Return num;
}
If (C = EOF) return 0;
Return C;
}
/* Handle the error and print it out */
Void yyerror (char const * s)
{
Fprintf (stderr, "% s/n", S );
}
======================================
Compile: $ YACC Calc. Y
$ Gcc-O calc Y. Tab. c