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 extern void perror (const char *s);
30 /* BISON Declarations */
34 %left NEG /* negation--unary minus */
35 %right '^' /* exponentiation */
39 input: /* empty string */
44 | exp '\n' { printf ("%d", $1); }
48 | exp '+' exp { $$ = $1 + $3; }
49 | exp '-' exp { $$ = $1 - $3; }
50 | exp '*' exp { $$ = $1 * $3; }
51 | exp '/' exp { $$ = $1 / $3; }
52 | '-' exp %prec NEG { $$ = -$2; }
53 | exp '^' exp { $$ = power ($1, $3); }
54 | '(' exp ')' { $$ = $2; }
60 main (int argn, const char **argv)
63 yyin = fopen (argv[1], "r");
74 yyerror (const char *s)
76 fprintf (stderr, "%s\n", s);
80 read_signed_integer (FILE *stream)
82 int c = getc (stream);
94 n = 10 * n + (c - '0');
103 /*---------------------------------------------------------------.
104 | Lexical analyzer returns an integer on the stack and the token |
105 | NUM, or the ASCII character read if not a number. Skips all |
106 | blanks and tabs, returns 0 for EOF. |
107 `---------------------------------------------------------------*/
114 /* Skip white space. */
115 while ((c = getc (yyin)) == ' ' || c == '\t')
117 /* process numbers */
118 if (c == '.' || isdigit (c))
121 yylval = read_signed_integer (yyin);
124 /* Return end-of-file. */
127 /* Return single chars. */
132 power (int base, int exponent)
137 for (/* Niente */; exponent; --exponent)
143 # Specify the output files to avoid problems on different file systems.
144 AT_CHECK([bison calc.y -o calc.c], 0, [], [])
145 AT_CHECK([$CC $CFLAGS calc.c -o calc], 0, [], [])
147 # AT_CHECK_CALC(INPUT, OUTPUT)
148 # ----------------------------
149 # Run `calc' on INPUT, and expect OUTPUT.
150 AT_DEFINE([AT_CHECK_CALC],
151 [AT_CHECK([echo "$1" | calc], 0, [$2], [])])
153 # Test the priorities.
154 AT_CHECK_CALC([1 + 2 * 3], [7])
155 AT_CHECK_CALC([1 + 2 * -3], [-5])
157 AT_CHECK_CALC([-1^2], [-1])
158 AT_CHECK_CALC([(-1)^2], [1])
160 AT_CHECK_CALC([---1], [-1])
162 AT_CHECK_CALC([1 - 2 - 3], [-4])
163 AT_CHECK_CALC([1 - (2 - 3)], [2])
165 AT_CHECK_CALC([2^2^3], [256])
166 AT_CHECK_CALC([(2^2)^3], [64])
168 AT_CLEANUP(calc calc.c)