public override Expression Visit(AdditionNode node)
        {
            var left  = Visit(node.Left);
            var right = Visit(node.Right);

            return(new Expression(left.Terms, right.Terms));
        }
Example #2
0
        public void FlattenExpression_Assignment_MemoryValue_Both()
        {
            var ast = new ASTNode();

            ast.AddChild(new VariableDeclarationNode("byte", "x"));
            var additionnode = new AdditionNode(new MemoryValueNode(100), new MemoryValueNode(100));
            var assignment   = new VariableAssignmentNode("x", additionnode);

            ast.AddChild(assignment);

            var changes = FlattenExpression(ast, 1);

            Assert.IsTrue(changes > 0);
            var children = ast.GetChildren().ToList();

            Assert.AreEqual(6, children.Count);
            Assert.IsInstanceOfType(additionnode.Left, typeof(VariableValueNode));
            Assert.IsInstanceOfType(additionnode.Right, typeof(VariableValueNode));
            Assert.IsInstanceOfType(children[0], typeof(VariableDeclarationNode));
            Assert.IsInstanceOfType(children[1], typeof(VariableDeclarationNode));
            Assert.IsInstanceOfType(children[2], typeof(VariableAssignmentNode));
            Assert.IsInstanceOfType(children[3], typeof(VariableDeclarationNode));
            Assert.IsInstanceOfType(children[4], typeof(VariableAssignmentNode));
            Assert.IsInstanceOfType(children[5], typeof(VariableAssignmentNode));
            Assert.AreSame(children[5], assignment);
            Assert.AreNotEqual(((VariableAssignmentNode)children[2]).VariableName, ((VariableAssignmentNode)children[4]).VariableName);
        }
        // Make calls to the classes that does the final calculation
        public override double Evaluate()
        {
            switch (this.Operator)
            {
            case '+':
                AdditionNode add = new AdditionNode('+');
                add.Left  = this.Left;
                add.Right = this.Right;
                return(add.Evaluate());

            case '-':
                SubtractionNode sub = new SubtractionNode('-');
                sub.Left  = this.Left;
                sub.Right = this.Right;
                return(sub.Evaluate());

            case '*':
                MultiplicationNode mul = new MultiplicationNode('*');
                mul.Left  = this.Left;
                mul.Right = this.Right;
                return(mul.Evaluate());

            case '/':
                DivisionNode div = new DivisionNode('/');
                div.Left  = this.Left;
                div.Right = this.Right;
                return(div.Evaluate());

            default:
                break;
            }

            return(0.0);
        }
Example #4
0
        public override Node VisitInfixValueExpr(ML4DParser.InfixValueExprContext context)
        {
            InfixExpressionNode node;

            switch (context.op.Type)
            {
            case ML4DLexer.PLUS:
                node = new AdditionNode("+");
                break;

            case ML4DLexer.MINUS:
                node = new SubtractionNode("-");
                break;

            case ML4DLexer.MUL:
                node = new MultiplicationNode("*");
                break;

            case ML4DLexer.DIV:
                node = new DivisionNode("/");
                break;

            case ML4DLexer.POW:
                node = new PowerNode("**");
                break;

            default:
                throw new NotSupportedException(
                          $"The operator {context.op.Text}, is not a valid arithmetic operator.");
            }
            node.Left  = (ExpressionNode)Visit(context.left);
            node.Right = (ExpressionNode)Visit(context.right);
            return(node);
        }
Example #5
0
        public void Setup()
        {
            _left = Mock.Interface<ICalculationNode>();
            _right = Mock.Interface<ICalculationNode>();

            _additionNode = new AdditionNode(_left, _right);
        }
Example #6
0
 /// <summary>
 /// 加算ノードの評価
 /// </summary>
 /// <param name="node">加算ノード</param>
 /// <returns>演算後の数値(Double)、もしくは文字列(String)</returns>
 public override object Visit(AdditionNode node)
 {
     if (Visit(node.Left).GetType() == typeof(string) || Visit(node.Right).GetType() == typeof(string))
     {
         return(Visit(node.Left).ToString() + Visit(node.Right).ToString()); //文字列の結合
     }
     return((double)Visit(node.Left) + (double)Visit(node.Right));
 }
Example #7
0
        public void Addition_Optimize_UnknownVariableRemains()
        {
            var originalnode = new AdditionNode(new ShortValueNode(1), new VariableValueNode("x"));

            var optimizednode = originalnode.Optimize(NoVariables);

            Assert.IsInstanceOfType(optimizednode, typeof(AdditionNode));
        }
Example #8
0
        public void Addition_Optimize_FullyConstantCollapses()
        {
            var originalnode = new AdditionNode(new ShortValueNode(1), new ShortValueNode(1));

            var optimizednode = originalnode.Optimize(NoVariables);

            Assert.IsInstanceOfType(optimizednode, typeof(ConstantNode));
        }
Example #9
0
        public void Addition_Optimize_FullyConstant_Value()
        {
            var originalnode = new AdditionNode(new ShortValueNode(1), new ShortValueNode(1));

            var optimizednode = originalnode.Optimize(NoVariables);

            Assert.AreEqual(2, optimizednode.GetValue());
        }
Example #10
0
        private object AdditionNode(AdditionNode a)
        {
            var l = Evaluate(a.l);
            var r = Evaluate(a.r);

            if (l is decimal && r is decimal)
            {
                return((decimal)l + (decimal)r);
            }
            throw(new Exception($"Can't add {l.GetType()} and {r.GetType()}"));
        }
Example #11
0
 public void Generate(Grid grid)
 {
     for (int i = 0; i < grid.Width; i++) {
         for (int j = 0; j < grid.Height; j++) {
             if (Random.Range(0, 2) == 0) {
                 grid[i, j] = new AdditionNode();
             } else {
                 grid[i, j] = new SubtractionNode();
             }
         }
     }
 }
Example #12
0
        public void Addition_Optimize_RecursiveReduction()
        {
            var originalnode = new AdditionNode(
                new VariableValueNode("a"),
                new VariableValueNode("b")
                );

            var optimizednode = originalnode.Optimize(new Dictionary <string, ushort> {
                { "a", 1 },
                { "b", 1 }
            });

            Assert.IsInstanceOfType(optimizednode, typeof(ConstantNode));
        }
Example #13
0
        public void PropagateConstants_DetectsSubNodeChanges()
        {
            var ast = new ASTNode();

            ast.AddChild(new VariableDeclarationNode("byte", "x"));
            ast.AddChild(new VariableAssignmentNode("x", new ShortValueNode(5)));
            ast.AddChild(new VariableDeclarationNode("byte", "a"));
            var value = new AdditionNode(new VariableValueNode("y"), new VariableValueNode("x"));

            ast.AddChild(new VariableAssignmentNode("a", value));

            var changed = PropagateConstants(ast);

            Assert.IsTrue(changed);
        }
        public void Visit_AdditionNodeWithIncompatibleTypes_LogsCannotUseWithOperatorError()
        {
            // Arrange
            AdditionNode   additionNode = new AdditionNode(DummySrcPos);
            ReferenceNode  left         = PlayerReferenceNode;
            IntegerLiteral right        = new IntegerLiteral("5", DummySrcPos);

            additionNode.Left  = left;
            additionNode.Right = right;

            // Act
            Checker.Visit(additionNode);

            // Assert
            Assert.IsTrue(ErrorLogger.Errors.Count == 1 && ErrorLogger.Errors.First() is CannotUseWithOperatorError);
        }
        public void Visit_AdditionNodeWithCompatibleTypes_LogsNoError()
        {
            // Arrange
            AdditionNode   additionNode = new AdditionNode(DummySrcPos);
            IntegerLiteral left         = new IntegerLiteral("2", DummySrcPos);
            IntegerLiteral right        = new IntegerLiteral("5", DummySrcPos);

            additionNode.Left  = left;
            additionNode.Right = right;

            // Act
            Checker.Visit(additionNode);

            // Assert
            Assert.IsTrue(ErrorLogger.Errors.Count == 0);
        }
Example #16
0
        public void IllegalTensorAddition()
        {
            // tensor a[2][1] = { [2.4], [5.1] }
            // tensor b[2][2] = { [1, 1],
            //                    [1, 1] }
            // tencor c[2][2] = a*b;

            TensorInitNode aInit = new TensorInitNode();

            aInit.FirstRowElements = new List <ExpressionNode>()
            {
                new DoubleNode(2.4)
            };
            aInit.Elements = new List <ExpressionNode>()
            {
                new DoubleNode(5.1)
            };
            TensorDCLNode a = new TensorDCLNode("tensor", "a", 2, 1, aInit);

            TensorInitNode bInit = new TensorInitNode();

            bInit.FirstRowElements = new List <ExpressionNode>()
            {
                new DoubleNode(1), new DoubleNode(1)
            };
            bInit.Elements = new List <ExpressionNode>()
            {
                new DoubleNode(1), new DoubleNode(1),
            };
            TensorDCLNode b = new TensorDCLNode("tensor", "b", 2, 2, bInit);

            AdditionNode addNode = new AdditionNode("+");

            addNode.Left  = new IDNode("a");
            addNode.Right = new IDNode("b");

            SymbolTable symbolTable             = new SymbolTable();
            TypeCheckSymbolTableVisitor visitor = new TypeCheckSymbolTableVisitor(symbolTable);

            visitor.Visit(a);
            visitor.Visit(b);
            Assert.ThrowsException <InvalidOperandsException>(() =>
            {
                visitor.Visit(addNode);
            });
        }
Example #17
0
        public void MixedExpressionDoubleAndIntBecomesDoubleNode()
        {
            //Arrange
            InfixExpressionNode node = new AdditionNode("+");

            node.Left  = new DoubleNode(25.5);
            node.Right = new IntNode(1);

            SymbolTable symbolTable             = new SymbolTable();
            TypeCheckSymbolTableVisitor visitor = new TypeCheckSymbolTableVisitor(symbolTable);

            //Act
            visitor.Visit(node);

            //Assert
            Assert.AreEqual(node.Type, "double");
        }
Example #18
0
        public void Visit_AdditionNode_EmitsCorrectCode()
        {
            // Arrange
            AdditionNode   additionNode = new AdditionNode(DummySrcPos);
            IntegerLiteral left         = new IntegerLiteral("2", DummySrcPos);
            IntegerLiteral right        = new IntegerLiteral("5", DummySrcPos);

            additionNode.Left  = left;
            additionNode.Right = right;

            string expectedResult = "2 + 5";

            // Act
            string actualResult = CodeGenerator.Visit(additionNode);

            // Assert
            Assert.AreEqual(expectedResult, actualResult);
        }
Example #19
0
        public void ValidOperandsToOrOperation()
        {
            OrNode node = new OrNode("Or");

            EqualNode fourplus6equal10 = new EqualNode("=");

            InfixExpressionNode addNode = new AdditionNode("+");

            addNode.Left           = new IntNode(4);
            addNode.Right          = new IntNode(6);
            fourplus6equal10.Left  = addNode;
            fourplus6equal10.Right = new IntNode(10);

            node.Left  = fourplus6equal10;
            node.Right = new BoolNode(false);

            SymbolTable symbolTable             = new SymbolTable();
            TypeCheckSymbolTableVisitor visitor = new TypeCheckSymbolTableVisitor(symbolTable);

            visitor.Visit(node);

            Assert.AreEqual(node.Type, "bool");
        }
Example #20
0
        private ExpressionNode ParseMathExpr()
        {
            var lhs = ParseTerm();

            while (true)
            {
                if (_reader.Peek() is Plus)
                {
                    Match <Plus>();
                    lhs = new AdditionNode(lhs, ParseTerm());
                }
                else if (_reader.Peek() is Dash)
                {
                    Match <Dash>();
                    lhs = new SubtractionNode(lhs, ParseTerm());
                }
                else
                {
                    break;
                }
            }

            return(lhs);
        }
Example #21
0
        protected SyntaxNode buildSyntaxTree(List <ISyntaxUnit> postfixForm)
        {
            Queue <ISyntaxUnit> inputQueue   = new Queue <ISyntaxUnit>(postfixForm);
            Stack <SyntaxNode>  operandStack = new Stack <SyntaxNode>();

            while (inputQueue.Count > 0)
            {
                ISyntaxUnit input = inputQueue.Dequeue();
                if (input is Lexeme)
                {
                    Lexeme            token = input as Lexeme;
                    Lexeme.LexemeType ttype = token.Type;
                    if (properties.IsVariable(token.Value))
                    {
                        VariableIdentifierNode variable = new VariableIdentifierNode(token.Value);
                        operandStack.Push(variable);
                    }
                    else if (properties.IsConstant(token.Value))
                    {
                        double constantValue            = properties.getConstantValue(token.Value);
                        ConstantIdentifierNode constant = new ConstantIdentifierNode(token.Value, constantValue);
                        operandStack.Push(constant);
                    }
                    else if (properties.IsFunctionName(token.Value))
                    {
                        int nArguments = properties.getFunctionArgumentsCount(token.Value);
                        FunctionApplyNode.FunctionBody funcBody = properties.getFunctionDefinition(token.Value);
                        ArgumentListNode argumentList           = new ArgumentListNode();
                        try
                        {
                            for (int i = 0; i < nArguments; i++)
                            {
                                argumentList.addArgument(operandStack.Pop());
                            }
                        }
                        catch (InvalidOperationException ex)
                        {
                            throw new ParseException("Not enough operands on operand stack for function call.");
                        }

                        FunctionApplyNode functionCall = new FunctionApplyNode(argumentList, funcBody, token.Value);
                        operandStack.Push(functionCall);
                    }
                    else if (ttype == Lexeme.LexemeType.REAL_VALUE)
                    {
                        double value;
                        if (!double.TryParse(token.Value, NumberStyles.Any, CultureInfo.InvariantCulture, out value))
                        {
                            throw new ParseException("Couldn't parse literal value: " + token.Value);
                        }
                        LiteralNode literal = new LiteralNode(value);
                        operandStack.Push(literal);
                    }
                    else if (ttype == Lexeme.LexemeType.OP_PLUS)
                    {
                        try
                        {
                            SyntaxNode   right    = operandStack.Pop();
                            SyntaxNode   left     = operandStack.Pop();
                            AdditionNode addition = new AdditionNode(left, right);
                            operandStack.Push(addition);
                        }
                        catch (InvalidOperationException ex)
                        {
                            throw new ParseException("Missing operand(s) for addition.");
                        }
                    }
                    else if (ttype == Lexeme.LexemeType.OP_MINUS)
                    {
                        try
                        {
                            SyntaxNode      right       = operandStack.Pop();
                            SyntaxNode      left        = operandStack.Pop();
                            SubtractionNode subtraction = new SubtractionNode(left, right);
                            operandStack.Push(subtraction);
                        }
                        catch (InvalidOperationException ex)
                        {
                            throw new ParseException("Missing operand(s) for subtraction.");
                        }
                    }
                    else if (ttype == Lexeme.LexemeType.OP_MUL)
                    {
                        try
                        {
                            SyntaxNode         right          = operandStack.Pop();
                            SyntaxNode         left           = operandStack.Pop();
                            MultiplicationNode multiplication = new MultiplicationNode(left, right);
                            operandStack.Push(multiplication);
                        }
                        catch (InvalidOperationException ex)
                        {
                            throw new ParseException("Missing operand(s) for multiplication.");
                        }
                    }
                    else if (ttype == Lexeme.LexemeType.OP_DIV)
                    {
                        try
                        {
                            SyntaxNode   right    = operandStack.Pop();
                            SyntaxNode   left     = operandStack.Pop();
                            DivisionNode division = new DivisionNode(left, right);
                            operandStack.Push(division);
                        }
                        catch (InvalidOperationException ex)
                        {
                            throw new ParseException("Missing operand(s) for division.");
                        }
                    }
                    else if (ttype == Lexeme.LexemeType.OP_POW)
                    {
                        try
                        {
                            SyntaxNode exponent = operandStack.Pop();
                            SyntaxNode baseNode = operandStack.Pop();
                            PowerNode  power    = new PowerNode(baseNode, exponent);
                            operandStack.Push(power);
                        }
                        catch (InvalidOperationException ex)
                        {
                            throw new ParseException("Missing operand(s) for exponentiation.");
                        }
                    }
                    else if (ttype == Lexeme.LexemeType.EQ_SIGN)
                    {
                        try
                        {
                            SyntaxNode right  = operandStack.Pop();
                            SyntaxNode left   = operandStack.Pop();
                            EqualsNode eqNode = new EqualsNode(left, right);
                            operandStack.Push(eqNode);
                        }
                        catch (InvalidOperationException ex)
                        {
                            throw new ParseException("Missing operand(s) for assignment.");
                        }
                    }
                    else if (ttype == Lexeme.LexemeType.OP_PLUS_UNARY)
                    {
                        try
                        {
                            SyntaxNode    child     = operandStack.Pop();
                            UnaryPlusNode unaryPlus = new UnaryPlusNode(child);
                            operandStack.Push(unaryPlus);
                        }
                        catch (InvalidOperationException ex)
                        {
                            throw new ParseException("Missing operand for unary plus.");
                        }
                    }
                    else if (ttype == Lexeme.LexemeType.OP_MINUS_UNARY)
                    {
                        try
                        {
                            SyntaxNode     child      = operandStack.Pop();
                            UnaryMinusNode unaryMinus = new UnaryMinusNode(child);
                            operandStack.Push(unaryMinus);
                        }
                        catch (InvalidOperationException ex)
                        {
                            throw new ParseException("Missing operand for unary minus.");
                        }
                    }
                    else
                    {
                        throw new ParseException("Unexpected token in postfix expression: " + token.simpleRepresentation());
                    }
                }
                else if (input is SyntaxNode)
                {
                    operandStack.Push(input as SyntaxNode);
                }
                else
                {
                    throw new ParseException("Unexpected object type in postfix expression.");
                }
            }

            if (operandStack.Count == 1)
            {
                return(operandStack.Pop());
            }
            else
            {
                throw new ParseException("Too many operands in postfix expression.");
            }
        }
Example #22
0
 public abstract T Visit(AdditionNode node);
        public void CalculateCorrectly()
        {
            var additionNode = new AdditionNode(new NumberNode(42), new NumberNode(54));

            additionNode.Calculate().Should().Be(96);
        }
        public void PrintCorrectly()
        {
            var additionNode = new AdditionNode(new NumberNode(42), new NumberNode(54));

            additionNode.Print().Should().Be("(+ 42 54)");
        }
Example #25
0
        public BinaryExpressionNode ParseBinaryExpresssion(Token operatorToken, AstNode leftOperand, AstNode rightOperand)
        {
            BinaryExpressionNode expression = null;

            switch (operatorToken.Type)
            {
            case TokenType.Plus:
                expression = new AdditionNode(operatorToken.SourceLine);
                break;

            case TokenType.Minus:
                expression = new SubstractionNode(operatorToken.SourceLine);
                break;

            case TokenType.Asterisk:
                expression = new MultiplicationNode(operatorToken.SourceLine);
                break;

            case TokenType.Slash:
                expression = new DivisionNode(operatorToken.SourceLine);
                break;

            case TokenType.Equals:
                expression = new EqualsComparisonNode(operatorToken.SourceLine);
                break;

            case TokenType.NotEquals:
                expression = new NotEqualsComparisonNode(operatorToken.SourceLine);
                break;

            case TokenType.Less:
                expression = new LessComparisonNode(operatorToken.SourceLine);
                break;

            case TokenType.EqualsOrLess:
                expression = new EqualsOrLessComparisonNode(operatorToken.SourceLine);
                break;

            case TokenType.Greater:
                expression = new GreaterComparisonNode(operatorToken.SourceLine);
                break;

            case TokenType.EqualsOrGreater:
                expression = new EqualsOrGreaterComparisonNode(operatorToken.SourceLine);
                break;

            case TokenType.And:
                expression = new LogicalAndNode(operatorToken.SourceLine);
                break;

            case TokenType.Or:
                expression = new LogicalOrNode(operatorToken.SourceLine);
                break;

            default:
                throw new CompilerException($"`{MethodBase.GetCurrentMethod().Name}` called with a bad token. Expected a binary operator, token has type `{operatorToken.Type}` instead.");
            }
            expression.LeftOperand  = leftOperand;
            expression.RightOperand = rightOperand;
            return(expression);
        }
Example #26
0
        public GaussianBlurPS()
        {
            Name             = "GaussianBlurPS";
            Type             = ShaderType.Pixel;
            FeatureLevel     = FeatureLevel.PS_4_0_Level_9_1;
            KeyPart          = new TechniqueKey(ps: PixelShaderFlags.DiffuseMap);
            EnableSeparators = true;
            Struct inputStruct = SpriteVS.VSOut;

            inputStruct.Name = "input";
            InputStruct      = inputStruct;
            var cbStatic           = CBFrame;
            var fOffsetsAndWeights = CBFrame[Param.Floats.BlurOffsetsAndWeights];

            Texture tDiffuse = Texture.Diffuse;
            Sampler sLinear  = Sampler.MinMagMipLinearWrap;

            Add(tDiffuse);
            Add(sLinear);
            Add(cbStatic);

            DeclarationNode nColor        = DeclarationNode.InitNode("color", Shaders.Type.Float4, 0, 0, 0, 0);
            ArrayNode       fOffsetWeight = new ArrayNode {
                Input = fOffsetsAndWeights, Index = "i"
            };

            AdditionNode nBlur = new AdditionNode
            {
                PreCondition = new ForBlock
                {
                    PreCondition   = nColor,
                    StartCondition = new ScalarNode {
                        Value = 0
                    },
                    EndCondition = new ScalarNode {
                        Value = 15
                    }
                },
                OpensBlock = true,
                Input1     = nColor,
                Input2     = new MultiplyNode
                {
                    Input1 = new TextureSampleNode
                    {
                        Texture     = tDiffuse,
                        Sampler     = sLinear,
                        Coordinates = new AdditionNode
                        {
                            Input1 = new ReferenceNode {
                                Value = InputStruct[Param.SemanticVariables.Texture]
                            },
                            Input2 = new SwizzleNode {
                                Input = fOffsetWeight, Swizzle = new [] { Swizzle.X, Swizzle.Y }
                            },
                        }
                    },
                    Input2 = new SwizzleNode {
                        Input = fOffsetWeight, Swizzle = new[] { Swizzle.Z }
                    },
                },
                ClosesBlock    = true,
                IsVerbose      = true,
                Declare        = false,
                AssignToInput1 = true,
                Output         = nColor.Output
            };

            OutputStruct = Struct.PixelShaderOutput;
            Result       = new PSOutputNode
            {
                FinalColor = nBlur,
                Output     = OutputStruct
            };
        }
 public override int Visit(AdditionNode node)
 => Visit(node.Left) + Visit(node.Right);
        private Value Addition(AdditionNode exp)
        {
            try
            {
                Constant      left      = Eval(exp.Left).GetRValue();
                Constant      right     = Eval(exp.Right).GetRValue();
                Constant.Type leftType  = left.ConstantType;
                Constant.Type rightType = right.ConstantType;
                Constant.Type bt        = Max(leftType, rightType);
                switch (bt)
                {
                case Constant.Type.Complex:
                {
                    ComplexValue l = (ComplexValue)Convert(left, bt);
                    ComplexValue r = (ComplexValue)Convert(right, bt);
                    return(ComplexValue.OpAdd(l, r));
                }

                case Constant.Type.Int:
                {
                    IntValue l = (IntValue)Convert(left, bt);
                    IntValue r = (IntValue)Convert(right, bt);
                    return(IntValue.OpAdd(l, r));
                }

                case Constant.Type.Float:
                {
                    FloatValue l = (FloatValue)Convert(left, bt);
                    FloatValue r = (FloatValue)Convert(right, bt);
                    return(FloatValue.OpAdd(l, r));
                }

                case Constant.Type.String:
                {
                    StringValue l = (StringValue)Convert(left, bt);
                    StringValue r = (StringValue)Convert(right, bt);
                    return(StringValue.OpAdd(l, r));
                }
                }
                throw new ModelInterpreterException("Сложение не определено для типа \"" + bt.ToString() + "\".")
                      {
                          Line     = exp.Line,
                          Position = exp.Position
                      };
            }
            catch (TypeConversionError exc)
            {
                throw new ModelInterpreterException($"Не удалось преобразование из  \"{exc.Src}\" в \"{exc.Dst}\"")
                      {
                          Line     = exp.Line,
                          Position = exp.Position
                      };
            }
            catch (ModelInterpreterException exc)
            {
                throw exc;
            }
            catch (Exception exc)
            {
                throw new ModelInterpreterException(exc.Message)
                      {
                          Line     = exp.Line,
                          Position = exp.Position
                      };
            }
        }