9 ## ---------------------------------------------------- ##
10 ## Compile the grammar described in the documentation. ##
11 ## ---------------------------------------------------- ##
13 # We use integers to avoid dependencies upon the precision of doubles.
14 AT_SETUP(Compiling a grammar)
17 [[/* Infix notation calculator--calc */
25 static int power (int base, int exponent);
26 static int read_signed_integer (FILE *stream);
27 static void yyerror (const char *s);
28 extern void perror (const char *s);
31 /* BISON Declarations */
35 %left NEG /* negation--unary minus */
36 %right '^' /* exponentiation */
40 input: /* empty string */
45 | exp '\n' { printf ("%d", $1); }
49 | exp '+' exp { $$ = $1 + $3; }
50 | exp '-' exp { $$ = $1 - $3; }
51 | exp '*' exp { $$ = $1 * $3; }
52 | exp '/' exp { $$ = $1 / $3; }
53 | '-' exp %prec NEG { $$ = -$2; }
54 | exp '^' exp { $$ = power ($1, $3); }
55 | '(' exp ')' { $$ = $2; }
62 yyerror (const char *s)
64 fprintf (stderr, "%s\n", s);
68 read_signed_integer (FILE *stream)
70 int c = getc (stream);
82 n = 10 * n + (c - '0');
91 /*---------------------------------------------------------------.
92 | Lexical analyzer returns an integer on the stack and the token |
93 | NUM, or the ASCII character read if not a number. Skips all |
94 | blanks and tabs, returns 0 for EOF. |
95 `---------------------------------------------------------------*/
102 /* Skip white space. */
103 while ((c = getc (yyin)) == ' ' || c == '\t')
105 /* process numbers */
106 if (c == '.' || isdigit (c))
109 yylval = read_signed_integer (yyin);
112 /* Return end-of-file. */
115 /* Return single chars. */
120 power (int base, int exponent)
125 for (/* Niente */; exponent; --exponent)
131 main (int argn, const char **argv)
134 yyin = fopen (argv[1], "r");
148 # Specify the output files to avoid problems on different file systems.
149 AT_CHECK([bison calc.y -o calc.c], 0, [], [])
150 AT_CHECK([$CC $CFLAGS calc.c -o calc], 0, [], [])
152 # AT_CHECK_CALC(INPUT, OUTPUT)
153 # ----------------------------
154 # Run `calc' on INPUT, and expect OUTPUT.
155 AT_DEFINE([AT_CHECK_CALC],
156 [AT_CHECK([echo "$1" | calc], 0, [$2], [])])
158 # Test the priorities.
159 AT_CHECK_CALC([1 + 2 * 3], [7])
160 AT_CHECK_CALC([1 + 2 * -3], [-5])
162 AT_CHECK_CALC([-1^2], [-1])
163 AT_CHECK_CALC([(-1)^2], [1])
165 AT_CHECK_CALC([---1], [-1])
167 AT_CHECK_CALC([1 - 2 - 3], [-4])
168 AT_CHECK_CALC([1 - (2 - 3)], [2])
170 AT_CHECK_CALC([2^2^3], [256])
171 AT_CHECK_CALC([(2^2)^3], [64])
173 AT_CLEANUP(calc calc.c)