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:
- The first step is to define the
enumtoken for the unary operator in thetoy.cppfile:enum Token_Type { … … BINARY_TOKEN, UNARY_TOKEN } - 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 =...