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 ...

Get LLVM Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.