Esempio n. 1
0
 public void Visit(BinaryOperation binop)
 {
     binop.leftnode.Accept(this);
     Console.Write($" {binop.op.lexeme} ");
     binop.rightnode.Accept(this);
     Console.WriteLine();
 }
Esempio n. 2
0
        public object VisitBinaryOperation(BinaryOperation node)
        {
            double left  = (double)Visit(node.Left);
            double right = (double)Visit(node.Right);

            switch (node.Operation.Type)
            {
            // TODO: aside from IntDiv, every operation can return a double with decimal places
            case TokenKind.Plus:
                return(left + right);

            case TokenKind.Minus:
                return(left - right);

            case TokenKind.Mul:
                return(left * right);

            case TokenKind.IntDiv:
                return(Math.Truncate(left / right));

            case TokenKind.FloatDiv:
                return(left / right);
            }

            throw new ArgumentException($"TokenKind.{node.Operation.Type} is not supported.");
        }
Esempio n. 3
0
        public RealNumber Apply(BinaryOperation operation, RealNumber value)
        {
            value.Radix = Radix;

            switch (operation)
            {
            case BinaryOperation.Multiply:
                return(Multiply(value));

            case BinaryOperation.Divide:
                return(Divide(value));

            case BinaryOperation.Module:
                return(Module(value));

            case BinaryOperation.Add:
                return(Add(value));

            case BinaryOperation.Substract:
                return(Substract(value));

            default:
                throw new ArgumentException(string.Format("Invalid operation {0}", operation));
            }
        }
        public override IList<AddressIndependentThing> Encode(BinaryOperation<Amd64Operation> op)
        {
            delayAdd = null;
            var ret = new List<AddressIndependentThing>();

            if (RequiresRex(op))
                ret.Add(AIF.Instance.Byte(GenerateRex(op)));

            ret.AddRange(OpCode.Convert());

            byte modrm = 0, sib = 0;
            foreach (var field in Fields)
                PutValue(ref modrm, ref sib, field.Position, field.Value);

            ProcessOp(ref modrm, ref sib, Left, op.Left);
            ProcessOp(ref modrm, ref sib, Right, op.Right);

            if (Right.Type == OperandType.Register)
                PutValue(ref modrm, ref sib, Right.EncodingPosition, RegisterIndex(op.Right));

            ret.Add(AIF.Instance.Byte(modrm));
            if ((modrm & 0xC0) != 0xC0 && (modrm & 7) == 4)
                ret.Add(AIF.Instance.Byte(sib));

            if (delayAdd != null)
                ret.AddRange(delayAdd);

            if(Right.Type == OperandType.Immediate)
            {
                ret.AddRange(EncodeImmediate(op.Right));
            }

            return ret;
        }
Esempio n. 5
0
            private IExpression ParseTerm()
            {
                IExpression left = ParseFactor();

                while (true)
                {
                    if (pos >= text.Length)
                    {
                        return(left);
                    }

                    var c = text[pos];

                    if (c == '*' || c == '/')
                    {
                        ++pos;
                        IExpression right = ParseFactor();
                        left = new BinaryOperation(c, left, right);
                    }
                    else
                    {
                        return(left);
                    }
                }
            }
Esempio n. 6
0
 public static UnaryOperation Apply(BinaryOperation binOp, object arg)
 {
     return(delegate(object e)
     {
         return binOp(arg, e);
     });
 }
Esempio n. 7
0
		public BinaryExpression (SourceLocation location, BinaryOperation op, AstNode left, AstNode right)
			: base (location)
		{
			Operation = op;
			Add (left);
			Add (right);
		}
Esempio n. 8
0
 public override AstNode Visit(BinaryOperation node)
 {
     // Visit recursively.
     node.GetLeftExpression().Accept(this);
     node.GetRightExpression().Accept(this);
     return(node);
 }
 protected override void VisitBinaryOperation(BinaryOperation operation)
 {
     if (operation.Operator == BinaryOperator.LeftShift)
     {
         this.CommandText.Append("(");
         this.VisitField(operation.Left);
         this.CommandText.Append(" << ");
         this.VisitField(operation.Right);
         this.CommandText.Append(")");
     }
     else if (operation.Operator == BinaryOperator.RightShift)
     {
         this.CommandText.Append("(");
         this.VisitField(operation.Left);
         this.CommandText.Append(" >> ");
         this.VisitField(operation.Right);
         this.CommandText.Append(")");
     }
     else
     {
         this.CommandText.Append("(");
         this.VisitField(operation.Left);
         this.CommandText.Append(" ");
         this.CommandText.Append(GetOperatorName(operation.Operator));
         this.CommandText.Append(" ");
         this.VisitField(operation.Right);
         this.CommandText.Append(")");
     }
 }
Esempio n. 10
0
        public WhileAST binaryFactorNumericExpression(WhileAST left, Token <WhileToken> operatorToken, WhileAST right)
        {
            BinaryOperator oper = BinaryOperator.MULTIPLY;

            switch (operatorToken.TokenID)
            {
            case WhileToken.TIMES:
            {
                oper = BinaryOperator.MULTIPLY;
                break;
            }

            case WhileToken.DIVIDE:
            {
                oper = BinaryOperator.DIVIDE;
                break;
            }

            default:
            {
                break;
            }
            }
            BinaryOperation operation = new BinaryOperation(left as Expression, oper, right as Expression);

            return(operation);
        }
Esempio n. 11
0
        public WhileAST binaryComparisonExpression(WhileAST left, Token <WhileToken> operatorToken, WhileAST right)
        {
            var oper = BinaryOperator.ADD;

            switch (operatorToken.TokenID)
            {
            case WhileToken.LESSER:
            {
                oper = BinaryOperator.LESSER;
                break;
            }

            case WhileToken.GREATER:
            {
                oper = BinaryOperator.GREATER;
                break;
            }

            case WhileToken.EQUALS:
            {
                oper = BinaryOperator.EQUALS;
                break;
            }

            case WhileToken.DIFFERENT:
            {
                oper = BinaryOperator.DIFFERENT;
                break;
            }
            }

            var operation = new BinaryOperation(left as Expression, oper, right as Expression);

            return(operation);
        }
Esempio n. 12
0
        /// <summary>
        /// Абсолютно та же логика, что и ReadOperation, только с * и :
        /// </summary>
        /// <returns></returns>
        private Operation ReadPriority2()
        {
            // читаем левую часть - она должна быть выше приоритетом, чем * или :
            Operation left, right;

            left = ReadPriority3();
            while (true)
            {
                if (Is(ChunkTypes.Multiply))
                {
                    // переходим к следующему куску и читаем вес_3
                    MoveNext();
                    right = ReadPriority3();
                    // готовое выражение - теперь новая левая часть
                    left = new BinaryOperation(left, right, MathOperations.Multiply);
                }
                else if (Is(ChunkTypes.Divide))
                {
                    MoveNext();
                    right = ReadPriority3();
                    left  = new BinaryOperation(left, right, MathOperations.Divide);
                }
                else
                {
                    // если * и : кончились, выходим
                    break;
                }
            }

            return(left);
        }
Esempio n. 13
0
        private static bool EvaluateConstantComparison(BinaryOperation operation, long left, long right)
        {
            switch (operation)
            {
            case BinaryOperation.LessThan:
                return(left < right);

            case BinaryOperation.LessThanOrEqual:
                return(left <= right);

            case BinaryOperation.GreaterThan:
                return(left > right);

            case BinaryOperation.GreaterThanOrEqual:
                return(left >= right);

            case BinaryOperation.Equal:
                return(left == right);

            case BinaryOperation.NotEqual:
                return(left != right);

            default:
                throw new NotImplementedException("Unimplemented comparison expression");
            }
        }
Esempio n. 14
0
 public PatternExpression(SourceLocation location, BinaryOperation op, AstNode left, AstNode right)
     : base(location)
 {
     Operation = op;
     Left      = left;
     Right     = right;
 }
Esempio n. 15
0
        /// <summary>
        /// Квадратные скобки означают, что эта часть может существовать, а может и нет.
        /// Квадратные скобки со звездочкой - что часть может повторяться 0 или более раз.
        ///
        /// Операция := ВыражениеПриоритета_2 [ ЗнакПриоритета_1 ВыражениеПриоритета_2 ]*;
        /// ВыражениеПриоритета_2 := ВыражениеПриоритета_3 [ ЗнакПриоритета_2 ВыражениеПриоритета_3]*;
        /// ВыражениеПриоритета_3 := ['-'] Число ИЛИ ОперацияСоСкобками
        ///
        /// ОперацияСоСкобками := '(' Операция ')'
        ///
        /// ЗнакПриоритета1 := '+' ИЛИ '-'
        /// ЗнакПриоритета2 := '*' ИЛИ ':'
        /// </summary>
        /// <returns></returns>
        private Operation ReadOperation()
        {
            // читаем левую часть - она должна быть выше приоритетом, чем + или -
            Operation left, right;

            left = ReadPriority2();
            while (true)
            {
                if (Is(ChunkTypes.Minus))
                {
                    // переходим к следующему куску и читаем вес_2
                    MoveNext();
                    right = ReadPriority2();
                    // готовое выражение - теперь новая левая часть
                    left = new BinaryOperation(left, right, MathOperations.Subtract);
                }
                else if (Is(ChunkTypes.Plus))
                {
                    MoveNext();
                    right = ReadPriority2();
                    left  = new BinaryOperation(left, right, MathOperations.Add);
                }
                else
                {
                    // если плюсы и минусы кончились, выходим
                    break;
                }
            }

            return(left);
        }
        public override Dictionary <string, string> CommandTransferFunction(Dictionary <string, string> input, BasicBlock block, int commandNumber)
        {
            ThreeAddressCommand command = block.Commands[commandNumber];

            if (command.GetType() == typeof(Assignment))
            {
                string     newValue = NAC;
                Expression expr     = (command as Assignment).Value;
                if (expr.GetType() == typeof(Int32Const) || expr.GetType() == typeof(Identifier))
                {
                    newValue = getConstantFromSimpleExpression(input, (expr as SimpleExpression));
                }
                else if (expr.GetType() == typeof(UnaryOperation))
                {
                    UnaryOperation operation = (expr as UnaryOperation);
                    newValue = calculateVal(getConstantFromSimpleExpression(input, operation.Operand), operation.Operation);
                }
                else if (expr.GetType() == typeof(BinaryOperation))
                {
                    BinaryOperation operation = (expr as BinaryOperation);
                    newValue = calculateVal(getConstantFromSimpleExpression(input, operation.Left), getConstantFromSimpleExpression(input, operation.Right), operation.Operation);
                }
                string leftOperand = (command as Assignment).Target.Name;
                input[leftOperand] = newValue;
            }
            return(input);
        }
Esempio n. 17
0
 public override IExpression Visit(BinaryOperation binaryOperation)
 {
     binaryOperation.RightOperand = this.Visit(binaryOperation.RightOperand);
     binaryOperation.LeftOperand  = this.Visit(binaryOperation.LeftOperand);
     binaryOperation.Type         = this.Visit(binaryOperation.Type);
     return(binaryOperation);
 }
Esempio n. 18
0
            private IExpression ParseExpression()
            {
                var left = ParseTerm();

                while (true)
                {
                    if (pos >= text.Length)
                    {
                        return(left);
                    }

                    var c = text[pos];

                    if (c == '+' || c == '-')
                    {
                        ++pos;
                        var right = ParseTerm();
                        left = new BinaryOperation(c, left, right);
                    }
                    else
                    {
                        return(left);
                    }
                }
            }
Esempio n. 19
0
 public BinaryExpression(Location location, Expression left, Expression right, BinaryOperation operation)
     : base(location)
 {
     this.left = left;
     this.right = right;
     this.operation = operation;
 }
 public BinaryOperationNode(SourceLocation location, BinaryOperation operation, AstNode left, AstNode right)
 {
     this.SourceLocation = location;
     BinaryOperation = operation;
     Children.Add(left);
     Children.Add(right);
 }
Esempio n. 21
0
        private static bool IsIntegerBinary(BinaryOperation operation)
        {
            switch (operation)
            {
            case BinaryOperation.Plus:
            case BinaryOperation.Minus:
            case BinaryOperation.Times:
            case BinaryOperation.Divide:
            case BinaryOperation.Modulo:
            case BinaryOperation.ShiftLeft:
            case BinaryOperation.ShiftRight:
            case BinaryOperation.And:
            case BinaryOperation.Or:
            case BinaryOperation.Xor:
            case BinaryOperation.LessThan:
            case BinaryOperation.LessThanOrEqual:
            case BinaryOperation.GreaterThan:
            case BinaryOperation.GreaterThanOrEqual:
            case BinaryOperation.Equal:
            case BinaryOperation.NotEqual:
                return(true);

            default:
                return(false);
            }
        }
Esempio n. 22
0
        private static void SwapOps(BinaryOperation first, BinaryOperation second)
        {
            switch (first)
            {
            case ArithmeticOperation firstArithmeticOperation:
                var arithmeticType            = firstArithmeticOperation.OperationType;
                var secondArithmeticOperation = (ArithmeticOperation)second;
                firstArithmeticOperation.OperationType  = secondArithmeticOperation.OperationType;
                secondArithmeticOperation.OperationType = arithmeticType;
                break;

            case Comparison firstComparision:
                var comparisonType    = firstComparision.OperationType;
                var secondComparision = (Comparison)second;
                firstComparision.OperationType  = secondComparision.OperationType;
                secondComparision.OperationType = comparisonType;
                break;

            case LogicalBinaryOperation firstLogicOperation:
                var logicType            = firstLogicOperation.BinaryOperationType;
                var secondLogicOperation = (LogicalBinaryOperation)second;
                firstLogicOperation.BinaryOperationType  = secondLogicOperation.BinaryOperationType;
                secondLogicOperation.BinaryOperationType = logicType;
                break;
            }
        }
Esempio n. 23
0
        public WhileAST binaryTermNumericExpression(WhileAST left, Token <WhileToken> operatorToken, WhileAST right)
        {
            BinaryOperator oper = BinaryOperator.ADD;

            switch (operatorToken.TokenID)
            {
            case WhileToken.PLUS:
            {
                oper = BinaryOperator.ADD;
                break;
            }

            case WhileToken.MINUS:
            {
                oper = BinaryOperator.SUB;
                break;
            }

            default:
            {
                break;
            }
            }
            BinaryOperation operation = new BinaryOperation(left as Expression, oper, right as Expression);

            return(operation);
        }
Esempio n. 24
0
        /// <summary>
        /// Construct a MACD, recommand (12, 26, 9)
        /// </summary>
        /// <param name="source">Source</param>
        /// <param name="fastPeriod">Fast EMA Period</param>
        /// <param name="slowPeriod">Slow EMA Period</param>
        /// <param name="diffPeriod">Diff EMA Period</param>
        public MACD(IIndicator <double> source, int fastPeriod, int slowPeriod, int diffPeriod)
        {
            Source     = source;
            FastPeriod = fastPeriod;
            SlowPeriod = slowPeriod;
            DiffPeriod = diffPeriod;
            var Title = $"{Source}.MACD({FastPeriod}, {SlowPeriod}, {DiffPeriod})";

            Fast = new EMA(Source, FastPeriod)
            {
                Title = Title + ".Fast"
            };
            Slow = new EMA(Source, SlowPeriod)
            {
                Title = Title + ".Slow"
            };
            Diff = new BinaryOperation <double, double, double>(Fast, Slow, (f, s) => f - s)
            {
                Title = Title + ".DIFF"
            };
            Dea = new EMA(Diff, DiffPeriod)
            {
                Title = Title + ".DEA"
            };
            Macd = new BinaryOperation <double, double, double>(Diff, Dea, (f, s) => 2 * (f - s))
            {
                Title = Title + ".MACD"
            };
            Diff.Update += Main;
            Dea.Update  += Main;
            Macd.Update += Main;
        }
Esempio n. 25
0
        public WhileAST binaryStringExpression(WhileAST left, Token <WhileToken> operatorToken, WhileAST right)
        {
            var oper      = BinaryOperator.CONCAT;
            var operation = new BinaryOperation(left as Expression, oper, right as Expression);

            return(operation);
        }
Esempio n. 26
0
        public void TestAssignAdd()
        {
            var buildResult = buildParser();

            Assert.False(buildResult.IsError);
            var parser = buildResult.Result;
            ParseResult <WhileToken, WhileAST> result = parser.Parse("(a:=1+1)");

            Assert.False(result.IsError);
            Assert.NotNull(result.Result);

            Assert.IsType <SequenceStatement>(result.Result);
            SequenceStatement seq = result.Result as SequenceStatement;

            Assert.IsType <AssignStatement>(seq.Get(0));
            AssignStatement assign = seq.Get(0) as AssignStatement;

            Assert.Equal("a", assign.VariableName);
            Expression val = assign.Value;

            Assert.IsType <BinaryOperation>(val);
            BinaryOperation bin = val as BinaryOperation;

            Assert.Equal(BinaryOperator.ADD, bin.Operator);
            Assert.Equal(1, (bin.Left as IntegerConstant)?.Value);
            Assert.Equal(1, (bin.Right as IntegerConstant)?.Value);
        }
Esempio n. 27
0
        private Tuple <bool, ISymbol> TransformBinary(BinaryOperation op)
        {
            BinaryOperation output       = op;
            var             transformOp1 = TransformGeneric(output.Operand1);

            if (transformOp1.Item1)
            {
                output = op.ReplaceOperand1(transformOp1.Item2) as BinaryOperation;
            }

            var transformOp2 = TransformGeneric(output.Operand2);

            if (transformOp2.Item1)
            {
                output = op.ReplaceOperand2(transformOp2.Item2) as BinaryOperation;
            }

            var transformOccurred = transformOp1.Item1 || transformOp2.Item1;

            if (!output.Matches(_constraint))
            {
                return(new Tuple <bool, ISymbol>(transformOccurred, output));
            }

            var transformed = RunTransformOn(output);

            return(new Tuple <bool, ISymbol>(true, transformed));
        }
Esempio n. 28
0
        public void TestPrintBoolExpression()
        {
            var buildResult = buildParser();

            Assert.False(buildResult.IsError);
            var parser = buildResult.Result;
            ParseResult <WhileToken, WhileAST> result = parser.Parse("print true and false");

            Assert.False(result.IsError);
            Assert.NotNull(result.Result);

            Assert.IsType <SequenceStatement>(result.Result);
            SequenceStatement seq = result.Result as SequenceStatement;

            Assert.IsType <PrintStatement>(seq.Get(0));
            PrintStatement print = seq.Get(0) as PrintStatement;
            Expression     expr  = print.Value;

            Assert.IsType <BinaryOperation>(expr);
            BinaryOperation bin = expr as BinaryOperation;

            Assert.Equal(BinaryOperator.AND, bin.Operator);
            Assert.True((bin.Left as BoolConstant)?.Value);
            Assert.False((bin.Right as BoolConstant)?.Value);
        }
Esempio n. 29
0
    private static IExpression InvertBinaryOperation(IBinaryOperation binOp) {
      Contract.Requires(binOp != null);
      Contract.Ensures(Contract.Result<IExpression>() != null);

      BinaryOperation/*?*/ result = null;
      if (binOp is IEquality && binOp.LeftOperand.Type.TypeCode != PrimitiveTypeCode.Float32 && binOp.LeftOperand.Type.TypeCode != PrimitiveTypeCode.Float64)
        result = new NotEquality();
      else if (binOp is INotEquality && binOp.LeftOperand.Type.TypeCode != PrimitiveTypeCode.Float32 && binOp.LeftOperand.Type.TypeCode != PrimitiveTypeCode.Float64)
        result = new Equality();
      else if (binOp is ILessThan)
        result = new GreaterThanOrEqual() { IsUnsignedOrUnordered = KeepUnsignedButInvertUnordered(((ILessThan)binOp).IsUnsignedOrUnordered, binOp) };
      else if (binOp is ILessThanOrEqual)
        result = new GreaterThan() { IsUnsignedOrUnordered = KeepUnsignedButInvertUnordered(((ILessThanOrEqual)binOp).IsUnsignedOrUnordered, binOp) };
      else if (binOp is IGreaterThan)
        result = new LessThanOrEqual() { IsUnsignedOrUnordered = KeepUnsignedButInvertUnordered(((IGreaterThan)binOp).IsUnsignedOrUnordered, binOp) };
      else if (binOp is IGreaterThanOrEqual)
        result = new LessThan() { IsUnsignedOrUnordered = KeepUnsignedButInvertUnordered(((IGreaterThanOrEqual)binOp).IsUnsignedOrUnordered, binOp) };
      if (result != null) {
        result.LeftOperand = binOp.LeftOperand;
        result.RightOperand = binOp.RightOperand;
        result.Type = binOp.Type;
        result.Locations.AddRange(binOp.Locations);
        return result;
      }
      LogicalNot logicalNot = new LogicalNot();
      logicalNot.Operand = binOp;
      logicalNot.Type = binOp.Type;
      logicalNot.Locations.AddRange(binOp.Locations);
      return logicalNot;
    }
Esempio n. 30
0
 public BinaryInstruction(uint label, IVariable result, IVariable left, BinaryOperation operation, IVariable right)
     : base(label, result)
 {
     this.Operation    = operation;
     this.LeftOperand  = left;
     this.RightOperand = right;
 }
Esempio n. 31
0
 public BinaryExpression(Expression left, Expression right, BinaryOperation operation, MjoType type)
 {
     Left      = left;
     Right     = right;
     Operation = operation;
     Type      = type;
 }
Esempio n. 32
0
 public BinaryExpression(SourceLocation location, BinaryOperation op, AstNode left, AstNode right)
     : base(location)
 {
     Operation = op;
     Add(left);
     Add(right);
 }
Esempio n. 33
0
        public void Binary_operation_is_left_associative(string source, BinaryOperation operation)
        {
            var parser = GetParserInstance(source, out var diagnostics);

            var returnValue = parser.TryParseExpression(out var expression);

            Assert.That(diagnostics.Diagnostics, Is.Empty);
            Assert.That(returnValue, Is.True);
            Assert.That(expression, Is.Not.Null);

            var binary = (BinaryExpressionSyntax)expression !;

            Assert.That(binary.Operation, Is.EqualTo(operation));

            var left = (BinaryExpressionSyntax)binary.Left;

            Assert.That(left.Operation, Is.EqualTo(operation));
            Assert.That(left.Left, Is.InstanceOf <IntegerLiteralSyntax>());
            Assert.That(((IntegerLiteralSyntax)left.Left).Value, Is.EqualTo(1));
            Assert.That(left.Right, Is.InstanceOf <IntegerLiteralSyntax>());
            Assert.That(((IntegerLiteralSyntax)left.Right).Value, Is.EqualTo(2));

            Assert.That(binary.Right, Is.InstanceOf <IntegerLiteralSyntax>());
            Assert.That(((IntegerLiteralSyntax)binary.Right).Value, Is.EqualTo(3));
        }
Esempio n. 34
0
        // after reading syntaxes creates syntax tree
        // - removes extra brackets
        // - finds operator with minimum prio
        private ISyntaxNode BuildSyntaxTree(List <ISyntaxNode> listNode)
        {
            DeleteExcessiveBrackets(listNode);
            if (listNode.Count == 1)
            {
                return(listNode[0]);
            }

            int         position;
            ISyntaxNode min = FindMinPrioritiOperation(listNode, out position);

            if (listBinaryOperations.IndexOf(min.ToStringValue()) != -1)
            {
                BinaryOperation operation = min as BinaryOperation;
                operation.SetA(BuildSyntaxTree(listNode.GetRange(0, position)));
                operation.SetB(BuildSyntaxTree(listNode.GetRange(position + 1, listNode.Count - (position + 1))));
            }
            if (listUnaryOperations.IndexOf(min.ToStringValue()) != -1)
            {
                UnaryOperation operation = min as UnaryOperation;
                operation.SetA(BuildSyntaxTree(listNode.GetRange(position + 1, listNode.Count - (position + 1))));
            }
            if (listFunctions.IndexOf(min.ToStringValue()) != -1)
            {
                Function function = min as Function;
                function.SetX(BuildSyntaxTree(listNode.GetRange(position + 1, listNode.Count - (position + 1))));
            }
            return(min);
        }
Esempio n. 35
0
 public BinOpNode(BinaryOperation type, BinaryOperation assign, AstNode left, AstNode right)
 {
     BinOp = type;
     AssignOperation = assign;
     IsAssign = true;
     Children.Add(left);
     Children.Add(right);
 }
Esempio n. 36
0
        public static string GetBinaryOperator(BinaryOperation binaryOperation)
        {
            if (!BinaryOperators.Keys.Contains(binaryOperation))
            {
                throw new InvalidOperationException("Required operation was not recognized.");
            }

            return BinaryOperators[binaryOperation];
        }
        public void AllowStringEqualityAndInequalityComparison(string op)
        {
            var left = new StringLiteral ("foobar");
            var right = new StringLiteral ("baz");
            var compared = new BinaryOperation (op, left, right);

            var type = compared.Walk (new TypeChecker ());

            Assert.AreEqual (SpecType.Boolean, type.Type);
        }
        public void AllowBooleanEqualityComparison(string op)
        {
            var left = new BooleanLiteral (true);
            var right = new BooleanLiteral (false);
            var compared = new BinaryOperation (op, left, right);

            var type = compared.Walk (new TypeChecker ());

            Assert.AreEqual (SpecType.Boolean, type.Type);
        }
Esempio n. 39
0
 public static Func<Number, Number, Number> GetBinaryOperationEvaluator(BinaryOperation operation)
 {
     switch(operation) {
         case BinaryOperation.Add:
             return (x1, x2) => x1 + x2;
         case BinaryOperation.Multiply:
             return (x1, x2) => x1 * x2;
         default:
             throw new NotImplementedException();
     }
 }
Esempio n. 40
0
 static BinaryOperationEx GetBinaryOperationEx(BinaryOperation operation)
 {
     switch(operation) {
         case BinaryOperation.Add:
             return BinaryOperationEx.Add;
         case BinaryOperation.Multiply:
             return BinaryOperationEx.Multiply;
         default:
             throw new NotImplementedException();
     }
 }
        /// <summary>
        /// Initializes a new instance of the <see cref="BinaryOperationProcessor"/> class.
        /// </summary>
        /// <param name="operation">The operation to execute.</param>
        /// <exception cref="System.ArgumentOutOfRangeException">operation</exception>
        public BinaryOperationProcessor(BinaryOperation operation)
        {
            _operation = operation;
            _operationMethodNames = new[] { "op_" + operation };

            switch (operation)
            {
                case BinaryOperation.Addition:
                    _operationMethod = _additionMethod;
                    _operationMethodNames = new[] { "op_" + operation, "Offset" };
                    break;

                case BinaryOperation.Subtraction:
                    _operationMethod = _subtractionMethod;
                    break;

                case BinaryOperation.Multiply:
                    _operationMethod = _multiplyMethod;
                    _operationMethodNames = new[] { "op_" + operation, "Transform" };
                    break;

                case BinaryOperation.Division:
                    _operationMethod = _divisionMethod;
                    break;

                case BinaryOperation.Equality:
                    _operationMethod = _equalityMethod;
                    break;

                case BinaryOperation.Inequality:
                    _operationMethod = _inequalityMethod;
                    break;

                case BinaryOperation.GreaterThan:
                    _operationMethod = _greaterThanMethod;
                    break;

                case BinaryOperation.LessThan:
                    _operationMethod = _lessThanMethod;
                    break;

                case BinaryOperation.GreaterThanOrEqual:
                    _operationMethod = _greaterThanOrEqualMethod;
                    break;

                case BinaryOperation.LessThanOrEqual:
                    _operationMethod = _lessThanOrEqualMethod;
                    break;

                default:
                    throw new ArgumentOutOfRangeException("operation", operation, null);
            }

        }
Esempio n. 42
0
        public void SerializeBinaryOperation(string op)
        {
            var binaryNode = new BinaryOperation (op,
                new NumberLiteral (1),
                new NumberLiteral (2)
            );

            var binarySql = binaryNode.Walk (new Sqlizer (foobarTable()));

            var expected = String.Format ("(1 {0} 2)", op);
            Assert.AreEqual (expected, binarySql);
        }
        public void AllowNullEqualityComparison(string op)
        {
            var nullVal = new NullLiteral ();
            var numberVal = new NumberLiteral (42);

            var left = new BinaryOperation (op, nullVal, numberVal);
            var right = new BinaryOperation (op, numberVal, nullVal);

            var leftType = left.Walk (new TypeChecker ());
            var rightType = right.Walk (new TypeChecker ());

            Assert.AreEqual (SpecType.Boolean, leftType.Type);
            Assert.AreEqual (SpecType.Boolean, rightType.Type);
        }
Esempio n. 44
0
        /// <summary>
        /// Used to create: {Value[0]}{BinaryOperator}{Value[1]}...{Value[n]}
        /// </summary>
        public Expression(BinaryOperation binaryOperation, params IValueType[] value)
        {
            this.BinaryOperator = Operation.GetBinaryOperator(binaryOperation);

            StringBuilder sb = new StringBuilder(512);

            for (int i = 0; i < value.Length; i++)
            {
                sb.Append(value[i].ToString());

                if ((i + 1) < value.Length)
                {
                    sb.Append(this.BinaryOperator);
                }
            }

            this.Value = sb.ToString();
        }
Esempio n. 45
0
        public void ExpectJoinTableToExist()
        {
            var justAnId = new List<FieldConfig>
            {
                new FieldConfig("Id", null)
            };
            var tables = new List<OracularTable>
            {
                new OracularTable("Foobar", null, null, justAnId)
            };
            var specs = new List<OracularSpec>();
            var config = new OracularConfig (tables, specs);
            var checker = new RefChecker (config);

            var fingerlingPotatoes = new BinaryOperation("=",
                new Reference(new [] { "Potato", "Type" }),
                new StringLiteral("Fingerling")
            );

            var call = new MacroExpansion(
                new Reference(new [] { "ANY" }),
                new [] { fingerlingPotatoes }
            );

            var initial = new []{ "Foobar" };

            var ex = Assert.Throws<RefCheckException> (() => call.Walk (checker, initial));

            Assert.That (REFERENCE_RE.IsMatch (ex.Message));
        }
Esempio n. 46
0
        public void CheckOperatorDoesNothing()
        {
            var str = new StringLiteral ("baz");
            var nullNode = new NullLiteral ();
            var operation = new BinaryOperation ("=", str, nullNode);

            var result = operation.Walk (new RefChecker (), new [] { "Foobar" });

            Assert.AreEqual (1, result.Length);
            Assert.Contains ("Foobar", result);
        }
Esempio n. 47
0
			private IExpression ParseTerm() {
				IExpression left = ParseFactor();

				while (true) {
					if (pos >= text.Length) return left;

					var c = text[pos];

					if (c == '*' || c == '/') {
						++pos;
						IExpression right = ParseFactor();
						left = new BinaryOperation(c, left, right);
					} else {
						return left;
					}
				}
			}
 public TotemBinaryOperationBinder Register(Type type1, Type type2, BinaryOperation binder)
 {
     binops.Add(new TypePair(type1, type2), binder);
     return this;
 }
Esempio n. 49
0
 public BinaryOpNode(BinaryOperation op, AstNode left, AstNode right)
 {
     BinaryOp = op;
     Children.Add(left);
     Children.Add(right);
 }
 private bool RequiresRex(BinaryOperation<Amd64Operation> op)
 {
     return
         IsLargeOperand(op.Left) || IsLargeOperand(op.Right) ||
         IsExtendedRegister(op.Left) || IsExtendedRegister(op.Right);
 }
Esempio n. 51
0
 public BinOp(BinaryOperation operation)
 {
     this.operation = operation;
 }
Esempio n. 52
0
 public BinaryOperationExpression(BinaryOperation op, Expression left, Expression right)
 {
     mOp = op;
     mLeft = left;
     mRight = right;
 }
Esempio n. 53
0
        public void CheckJoinTables()
        {
            var justAnId = new List<FieldConfig>
            {
                new FieldConfig("Id", null)
            };
            var potatoFields = new List<FieldConfig>
            {
                new FieldConfig("Id", null),
                new FieldConfig("FoobarId", null),
                new FieldConfig("Type", null)
            };
            var foobarRelationship = new ParentConfig ("Foobar", null, null);
            var tables = new List<OracularTable>
            {
                new OracularTable("Foobar", null, null, justAnId),
                new OracularTable("Potato", null, new List<ParentConfig>{foobarRelationship}, potatoFields)
            };
            var specs = new List<OracularSpec>();
            var config = new OracularConfig (tables, specs);
            var checker = new RefChecker (config);

            var fingerlingPotatoes = new BinaryOperation("=",
                new Reference(new [] { "Potato", "Type" }),
                new StringLiteral("Fingerling")
            );

            var call = new MacroExpansion(
                new Reference(new [] { "ANY" }),
                new AstNode[] {
                    new Reference(new [] { "Potato" }),
                    fingerlingPotatoes
                }
            );

            var initial = new []{ "Foobar" };

            var result = call.Walk (checker, initial);

            Assert.AreEqual (2, result.Length);
            Assert.Contains ("Foobar", result);
            Assert.Contains ("Potato", result);
        }
Esempio n. 54
0
 public BinaryExpression(Expression Left, Expression Right, BinaryOperation Operation)
 {
     this.Left = Left;
     this.Right = Right;
     this.Operation = Operation;
 }
Esempio n. 55
0
            IExpression ParseExpression()
            {
                IExpression left = ParseTerm();

                while (true)
                {
                    if (pos >= text.Length)
                    {
                        return left;
                    }

                    var c = text[pos];

                    if (c == '+' || c == '-')
                    {
                        ++pos;
                        IExpression right = ParseTerm();
                        left = new BinaryOperation(c, left, right);
                    }
                    else
                    {
                        return left;
                    }
                }
            }
Esempio n. 56
0
 public Operator(string Name, int Precedence, BinaryOperation Operation)
 {
     this.Name = Name;
     this.Precedence = Precedence;
     this.Operation = Operation;
 }
Esempio n. 57
0
        public IodineObject PerformBinaryOperation(VirtualMachine vm,
			BinaryOperation binop,
			IodineObject rvalue)
        {
            switch (binop) {
            case BinaryOperation.Add:
                return Add (vm, rvalue);
            case BinaryOperation.Sub:
                return Sub (vm, rvalue);
            case BinaryOperation.Mul:
                return Mul (vm, rvalue);
            case BinaryOperation.Div:
                return Div (vm, rvalue);
            case BinaryOperation.And:
                return And (vm, rvalue);
            case BinaryOperation.Xor:
                return Xor (vm, rvalue);
            case BinaryOperation.Or:
                return Or (vm, rvalue);
            case BinaryOperation.Mod:
                return Mod (vm, rvalue);
            case BinaryOperation.Equals:
                return Equals (vm, rvalue);
            case BinaryOperation.NotEquals:
                return NotEquals (vm, rvalue);
            case BinaryOperation.RightShift:
                return RightShift (vm, rvalue);
            case BinaryOperation.LeftShift:
                return LeftShift (vm, rvalue);
            case BinaryOperation.LessThan:
                return LessThan (vm, rvalue);
            case BinaryOperation.GreaterThan:
                return GreaterThan (vm, rvalue);
            case BinaryOperation.LessThanOrEqu:
                return LessThanOrEqual (vm, rvalue);
            case BinaryOperation.GreaterThanOrEqu:
                return GreaterThanOrEqual (vm, rvalue);
            case BinaryOperation.BoolAnd:
                return LogicalAnd (vm, rvalue);
            case BinaryOperation.BoolOr:
                return LogicalOr (vm, rvalue);
            case BinaryOperation.HalfRange:
                return HalfRange (vm, rvalue);
            case BinaryOperation.ClosedRange:
                return ClosedRange (vm, rvalue);
            }
            vm.RaiseException (new IodineNotSupportedException (
                "The requested binary operator has not been implemented"));
            return null;
        }
Esempio n. 58
0
        // precedence-climbing method
        // https://en.wikipedia.org/wiki/Operator-precedence_parser#Precedence_climbing_method
        private Node parseExpression(Node lhs, int minPrecedence)
        {
            spyScannerToken();
            // the spied token is an operator and has precedence >= the minimumum precedence
            while (isOperator(spiedScannerToken.GetValueOrDefault()) && OPERATOR_PRECEDENCE[spiedScannerToken.GetValueOrDefault()].precedence >= minPrecedence)
            {
                GingerToken op = spiedScannerToken.GetValueOrDefault();
                // move to spied position
                nextScannerToken();

                nextScannerToken();
                Node rhs = parseTerminalExpression();

                spyScannerToken();
                // the spied token is an operator, and its precedence is greater than the previous op's precedence OR it is a right associated operator with precedence equal to op's precedence
                while (isOperator(spiedScannerToken.GetValueOrDefault()) && (OPERATOR_PRECEDENCE[spiedScannerToken.GetValueOrDefault()].precedence > OPERATOR_PRECEDENCE[op].precedence || (OPERATOR_PRECEDENCE[spiedScannerToken.GetValueOrDefault()].rightAssociated && OPERATOR_PRECEDENCE[spiedScannerToken.GetValueOrDefault()].precedence == OPERATOR_PRECEDENCE[op].precedence)))
                {
                    rhs = parseExpression(rhs, OPERATOR_PRECEDENCE[spiedScannerToken.GetValueOrDefault()].precedence);
                    spyScannerToken();
                }

                if (Grammar.isBinaryOperator(op))
                {
                    lhs = new BinaryOperation(op, lhs, rhs);
                }
                else if (Grammar.isConditionOperator(op))
                {
                    lhs = new InequalityOperation(op, lhs, rhs);
                }
                else
                {
                    throw new ParseException(scanner.row, scanner.col, $"Expected '{GingerToken.Addition.ToString()}', or '{GingerToken.LessThan.ToString()}',  found '{currentScannerToken.ToString()}'", ExceptionLevel.ERROR);
                }
            }

            return lhs;
        }
        private byte GenerateRex(BinaryOperation<Amd64Operation> op)
        {
            byte toAdd = 0x40;

            if (IsLargeOperand(op.Left) || IsLargeOperand(op.Right))
                toAdd |= 0x08;

            // modrm.reg extension
            if( (Left.EncodingPosition == EncodingPosition.Reg && IsExtendedRegister(op.Left)) ||
                (Right.EncodingPosition == EncodingPosition.Reg && IsExtendedRegister(op.Right)))
            {
                toAdd |= 0x04;
            }

            // sib index extension
            if ((Left.EncodingPosition == EncodingPosition.Index && IsExtendedRegister(op.Left)) ||
                (Right.EncodingPosition == EncodingPosition.Index && IsExtendedRegister(op.Right)))
            {
                toAdd |= 0x02;
            }

            // modrm.rm / sib.base extension
            if (((Left.EncodingPosition == EncodingPosition.RM || Left.EncodingPosition == EncodingPosition.Base) && IsExtendedRegister(op.Left)) ||
                ((Right.EncodingPosition == EncodingPosition.RM || Right.EncodingPosition == EncodingPosition.Base) && IsExtendedRegister(op.Right)))
            {
                toAdd |= 0x01;
            }

            return toAdd;
        }
Esempio n. 60
0
 /// <summary>
 /// Initializes a new instance of the <see cref="TIBASIC.Parser.BinaryOpNode"/> class.
 /// </summary>
 /// <param name="binaryOperation">Binary operation.</param>
 /// <param name="left">Left.</param>
 /// <param name="right">Right.</param>
 public BinaryOpNode(BinaryOperation binaryOperation, AstNode left, AstNode right)
 {
     BinaryOperation = binaryOperation;
     Children.Add(left);
     Children.Add(right);
 }