The YACC Parser Generator/Example: Calculator with Variables

From Wiki**3

< The YACC Parser Generator
Revision as of 16:45, 18 April 2008 by Root (talk | contribs)

This example implements a simple calculator. The calculator has an unspecified number of integer variables and the common binary integer operators (namely, addition, subtraction, multiplication, division, and modulus), and unary integer operators (+ and -).

The Lexical Analyzer (Flex) Specification

The lexical analyzer is very simple and limited to recognizing variable names, integers numbers, and the operators themselves. <text> </text>

The Syntactic Analyzer (YACC) Specification

The syntactic analyzer will be built to immediately compute the expressions in a syntax-directed fashion as they occur. It is, thus, important to use trees that build nodes as the expressions occur (left-recursive grammars). If the grammar were right-recursive, the last node would be the first to be built and the (syntax-directed) evaluation would be from the last expression to the first.

The first task is to define the grammar itself (without worrying with semantics). <text> </text>