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

Implementing a parser


Parser analyzes a code syntactically according to the rules of the language's grammar. The parsing phase determines if the input code can be used to form a string of tokens according to the defined grammar. A parse tree is constructed in this phase. Parser defines functions to organize language into a data structure called AST. The parser defined in this recipe uses a recursive decent parser technique which is a top-down parser, and uses mutually recursive functions to build the AST.

Getting ready

We must have the custom-defined language, that is the TOY language in this case, and also a stream of tokens generated by the lexer.

How to do it…

Define some basic value holders in our TOY parser as shown in the following:

  1. Open the toy.cpp file as follows:

    $ vi toy.cpp
  2. Define a global static variable to hold the current token from the lexer as follows:

    static int Current_token;
  3. Define a function to get the next token from the input stream from the lexer as follows:

    static void next_token...