**Question:** Ok so I am creating a programming language named: TEPL, and I need help adding support for unary operations.

**Repl link:** https://replit.com/@VALUEX/TEPL-V-0325

**Question:** Ok so I am creating a programming language named: TEPL, and I need help adding support for unary operations.

**Repl link:** https://replit.com/@VALUEX/TEPL-V-0325

1 Like

You will need to modify some parsing rules in your code, for example, in your precedence rules you need to support the unary minus

```
precedence = (
('right', 'UMINUS'), # Add this for unary minus
('left', 'PLUS', 'MINUS'),
('left', 'MULTIPLY', 'DIVIDE'),
)
```

And add a new rule to handle unary minus:

```
def p_expression_uminus(p):
'expression : MINUS expression %prec UMINUS'
p[0] = -p[2]
```

This rule matches an expression that is a minus sign followed by another expression, and it has a higher precedence than multiplication/division due to the `%prec UMINUS`

directive.

It looks like you are handling the operations directly in your node class, so I think in the binop method you can handle the unary minus (or not since unary minus is a separate rule) keep trying to see what you accomplish.

Ps.: I’d recommend consider updating your lexer to differentiate between unary and binary operators (might be useful in the future).

3 Likes

Thank you so much!

For some strange reason, my code doesn’t work with the additions I added(unary operations). Could you check to see what the problem could be? @WindLother

I was talking about the AST here… you need to integrate unary operations into your AST structure. Your `Node`

class does not have a method to handle unary operations. That’s why I said to test the binop method.

But you can change this by using a method like unaryop

and modify the `p_expression_uminus`

function to create a unary operation node:

```
class Node:
def unaryop(self):
operand = self.children[0]
if self.type == "uminus":
return -operand
else:
return f"Unknown unary operator, {self.type}"
def p_expression_uminus(p):
'expression : MINUS expression %prec UMINUS'
p[0] = Node("uminus", [p[2]])
def p_expression_binop(p):
'''expression : expression PLUS expression
| expression MINUS expression
| expression MULTIPLY expression
| expression DIVIDE expression'''
equation = Node("binop", [p[1], p[3]], p[2])
result = equation.binop()
p[0] = result
print(p[0])
```

2 Likes

Ok, I will test this, thank you again.