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.

  1. unop = Ex.Prefix (UnaryOp <$> op)

We add this to the expression parser like above.

  1. expr :: Parser Expr
  2. 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.

  1. unarydef :: Parser Expr
  2. unarydef = do
  3. reserved "def"
  4. reserved "unary"
  5. o <- op
  6. args <- parens $ many identifier
  7. body <- expr
  8. 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-“).

  1. codegenTop (S.UnaryDef name args body) =
  2. 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.

  1. cgen (S.UnaryOp op a) = do
  2. cgen $ S.Call ("unary" ++ op) [a]

That’s it for unary operators, quite easy indeed!