/** * Function VisitUnaryExpr * Param : unary expression to evaluate * Return : the negated value of the right operand or error */ public Value VisitUnaryExpr(Expr.Unary expr) { Value right = Evaluate(expr.Right); /* If the operator is NOT and the right operand is BOOL */ if (expr.OperatorToken.Kind == TokenKind.Not) { if (right.Type.Equals(VALTYPE.BOOL)) { return(new Value(VALTYPE.BOOL, !((bool)right.Val))); } /* If the right operand is not BOOL throw an error */ else { throw new RuntimeError(expr.OperatorToken, "Trying to negate a non bool value"); } } return(null); }
/** * Function VisitUnaryExpr : checks that the operator is NOT and * that the right expression is BOOL. Otherwise throws an error * Param : unary expression to ckeck * Return : the type of the unary expression */ public VALTYPE VisitUnaryExpr(Expr.Unary expr) { VALTYPE right = GetType(expr.Right); /* If the operator is NOT and the right expr is BOOL */ if (expr.OperatorToken.Kind == TokenKind.Not) { if (right.Equals(VALTYPE.BOOL)) { return(right); } /* Error if right expr is not BOOL */ else { throw new TypeError(expr.OperatorToken, "'" + expr.OperatorToken.Text + "' expects a BOOL expression, got " + right.ToString() + " instead."); } } /* Single operand */ else { return(right); } }
/** * Function VisitUnaryExpr * Param : unary expression to visit * Return : parenthesized string of the value */ public String VisitUnaryExpr(Expr.Unary expr) { return(Parenthesize(expr.OperatorToken.Text, expr.Right)); }