Parsing binary expressions
In this recipe, you will learn how to parse a binary expression.
Getting ready
We must have the custom-defined language—that is, the toy language in this case—and also stream of tokens generated by lexer. The binary expression parser requires precedence of binary operators for determining LHS and RHS in order. An STL map can be used to define precedence of binary operators.
How to do it…
To parse a binary expression, proceed with the following code flow:
Open the
toy.cpp
file as follows:$ vi toy.cpp
Declare a
map
for operator precedence to store the precedence at global scope in thetoy.cpp
file as follows:static std::map<char, int>Operator_Precedence;
The TOY language for demonstration has 4 operators where precedence of operators is defined as
-
<+
</
<*
.A function to initialize precedence—that is, to store precedence value in
map
—can be defined in global scope in thetoy.cpp
file as follows:static void init_precedence() { Operator_Precedence['-'...