Next: , Up: Multi-Function Calculator: mfcalc   [Contents][Index]


2.5.1 Declarations for mfcalc

Here are the C and Bison declarations for the multi-function calculator.

%{
  #include <stdio.h>  /* For printf, etc. */
  #include <math.h>   /* For pow, used in the grammar. */
  #include "calc.h"   /* Contains definition of 'symrec'. */
  int yylex (void);
  void yyerror (char const *);
%}

%define api.value.type union /* Generate YYSTYPE from these types: */
%token <double>  NUM     /* Double precision number. */
%token <symrec*> VAR FUN /* Symbol table pointer: variable/function. */
%nterm <double>  exp

%precedence '='
%left '-' '+'
%left '*' '/'
%precedence NEG /* negation--unary minus */
%right '^'      /* exponentiation */

The above grammar introduces only two new features of the Bison language. These features allow semantic values to have various data types (see More Than One Value Type).

The special union value assigned to the %define variable api.value.type specifies that the symbols are defined with their data types. Bison will generate an appropriate definition of YYSTYPE to store these values.

Since values can now have various types, it is necessary to associate a type with each grammar symbol whose semantic value is used. These symbols are NUM, VAR, FUN, and exp. Their declarations are augmented with their data type (placed between angle brackets). For instance, values of NUM are stored in double.

The Bison construct %nterm is used for declaring nonterminal symbols, just as %token is used for declaring token kinds. Previously we did not use %nterm before because nonterminal symbols are normally declared implicitly by the rules that define them. But exp must be declared explicitly so we can specify its value type. See Nonterminal Symbols.