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

Handling user-defined operators – unary operators


We saw in the previous recipe how binary operators can be handled. A language may also have some unary operator, operating on 1 operand. In this recipe, we will see how to handle unary operators.

Getting ready

The first step is to define a unary operator in the TOY language. A simple unary NOT operator (!) can serve as a good example; let's see one definition:

def unary!(v)
  if v then
    0
  else
    1;

If the value v is equal to 1, then 0 is returned. If the value is 0, 1 is returned as the output.

How to do it...

Do the following steps:

  1. The first step is to define the enum token for the unary operator in the toy.cpp file:

    enum Token_Type {
    …
    …
    BINARY_TOKEN,
    UNARY_TOKEN
    }
  2. Then we identify the unary string and return a unary token:

    static int get_token() {
    …
    …
    if (Identifier_string == "in") return IN_TOKEN;
    if (Identifier_string == "binary") return BINARY_TOKEN;
    if (Identifier_string == "unary") return UNARY_TOKEN;
    
    …
    …
    }
  3. Next, we define an AST for...