Unary Operators
For unary operators we implement the same strategy as binary operators. We add a parser for unary operators simply as a Prefix operator matching any symbol.
unop = Ex.Prefix (UnaryOp <$> op)
We add this to the expression parser like above.
expr :: Parser Expr
expr = Ex.buildExpressionParser (binops ++ [[unop], [binop]]) factor
The parser extension for the toplevel unary definition is precisely the same as function syntax except prefixed with the “unary” keyword.
unarydef :: Parser Expr
unarydef = do
reserved "def"
reserved "unary"
o <- op
args <- parens $ many identifier
body <- expr
return $ UnaryDef o args body
For toplevel declarations we’ll simply emit a function with the convention that the name is prefixed with the word “unary”. For example (“unary!”, “unary-“).
codegenTop (S.UnaryDef name args body) =
codegenTop $ S.Function ("unary" ++ name) args body
Up until now we have not have had any unary operators so for code generation we will simply always search for an implementation as a function.
cgen (S.UnaryOp op a) = do
cgen $ S.Call ("unary" ++ op) [a]
That’s it for unary operators, quite easy indeed!