Boost C++ Libraries Home Libraries People FAQ More

PrevUpHomeNext

7.2. Adding support for precedence of operators

[Note] Note

Note that you can find everything that has been included and defined so far here.

Let's make it possible for different operators to have different precedence. To do this, we define a new parser for parsing expressions containing only * operators (that is the operator with the lowest precedence):

> using mult_exp1 = foldl_start_with_parser<sequence<times_token, int_token>, int_token, boost::mpl::quote2<binary_op>>;

mult_exp1 can parse expressions containing only * operator. For example 3 * 2 or 6 * 7 * 8. Now we can create a parser supporting only the + and - operators but instead of separating numbers with these operators we will separate expressions containing only * operators. This means that the expression 1 * 2 + 3 * 4 is interpreted as the expressions 1 * 2 and 3 * 4 separated by a + operator. A number (eg. 13) is the special case of an expression containing only * operators.

Here is the parser implementing this:

> using exp_parser15 = \
...> build_parser< \
...>   foldl_start_with_parser< \
...>     sequence<one_of<plus_token, minus_token>, mult_exp1>, \
...>     mult_exp1, \
...>     boost::mpl::quote2<binary_op> \
...>   > \
...> >;

copy-paste friendly version

Note that this is almost the same as exp_parser13. The only difference is that it uses mult_exp1 everywhere, where exp_parser13 was using int_token. Let's try it out:

> exp_parser15::apply<BOOST_METAPARSE_STRING("1 + 2 * 3")>::type
mpl_::integral_c<int, 7>

This takes the precedence rules into account. The following diagram shows how it works:

Subexpressions using * operators only are evaluated (by mult_exp1) and treated as single units while interpreting expressions using + and - operators. Numbers not surrounded by * operators are treated also as operators using * only (containing no operations but a number).

If you need more layers (eg. introducing the ^ operator) you can extend this solution with further layers. The order of the layers determine the precedence of the operators.


PrevUpHomeNext