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 simple expressions


In this recipe, you will learn how to parse a simple expression. A simple expression may consist of numeric values, identifiers, function calls, a function declaration, and function definitions. For each type of expression, individual parser logic needs to be defined.

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. We already defined ASTs above. Further, we are going to parse the expression and invoke AST constructors for every type of expression.

How to do it…

To parse simple expressions, proceed with the following code flow:

  1. Open the toy.cpp file as follows:

    $ vi toy.cpp

    We already have lexer logic present in the toy.cpp file. Whatever code follows needs to be appended after the lexer code in the toy.cpp file.

  2. Define the parser function for numeric expression as follows:

    static BaseAST *numeric_parser() {
      BaseAST *Result = new NumericAST(Numeric_Val);
      next_token();
      return...