Exemple #1
0
        // A hot mess but gets the return value based on types given left and right
        public dynamic visit(BinOp binOp)
        {
            int  left      = 0;
            int  right     = 0;
            Type leftType  = binOp.getLeft().GetType();
            Type rightType = binOp.getRight().GetType();

            if (leftType == typeof(Num))
            {
                left = this.visit((Num)binOp.getLeft());
            }
            else if (leftType == typeof(BinOp))
            {
                left = this.visit((BinOp)binOp.getLeft());
            }
            else if (leftType == typeof(Var))
            {
                left = this.visit((Var)binOp.getLeft());
            }

            if (rightType == typeof(Num))
            {
                right = this.visit((Num)binOp.getRight());
            }
            else if (rightType == typeof(BinOp))
            {
                right = this.visit((BinOp)binOp.getRight());
            }
            else if (rightType == typeof(Var))
            {
                right = this.visit((Var)binOp.getRight());
            }

            if (leftType == typeof(Str))
            {
                if (rightType == typeof(Str))
                {
                    if (binOp.getOp().GetTokenValueType() == TokenValues.PLUS)
                    {
                        return(this.visit((Str)binOp.getLeft()) + this.visit((Str)binOp.getRight()));
                    }
                }
                else
                {
                    throw new InterpreterException(String.Format("Incompatible types for operation {0}: {1} {2}", binOp.getOp().GetTokenValueType(), leftType, rightType));
                }
            }

            switch (binOp.getOp().GetTokenValueType())
            {
            case TokenValues.PLUS:
                return(left + right);

            case TokenValues.MINUS:
                return(left - right);

            case TokenValues.MULTIPLY:
                return(left * right);

            case TokenValues.DIVISION:
                return(left / right);

            case TokenValues.EQUAL:
                return(left == right);

            case TokenValues.LESSTHAN:
                return(left < right);

            default:
                throw(new InterpreterException("Invalid syntax"));
            }
        }