Book Image

LLVM Cookbook

Book Image

LLVM Cookbook

Overview of this book

Table of Contents (16 chapters)
LLVM Cookbook
Credits
About the Authors
About the Reviewers
www.PacktPub.com
Preface
Index

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:

  1. Open the toy.cpp file as follows:

    $ vi toy.cpp
  2. Declare a map for operator precedence to store the precedence at global scope in the toy.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 -< + < / < *.

  3. A function to initialize precedence—that is, to store precedence value in map—can be defined in global scope in the toy.cpp file as follows:

    static void init_precedence() {
      Operator_Precedence['-'...