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); }
// 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); }
public void Subtraction_Optimize_FullyConstantCollapses() { var originalnode = new SubtractionNode(new ShortValueNode(1), new ShortValueNode(1)); var optimizednode = originalnode.Optimize(NoVariables); Assert.IsInstanceOfType(optimizednode, typeof(ConstantNode)); }
public void Subtraction_Optimize_UnknownVariableRemains() { var originalnode = new SubtractionNode(new ShortValueNode(1), new VariableValueNode("x")); var optimizednode = originalnode.Optimize(NoVariables); Assert.IsInstanceOfType(optimizednode, typeof(SubtractionNode)); }
public void Subtraction_Optimize_FullyConstant_Value() { var originalnode = new SubtractionNode(new ShortValueNode(1), new ShortValueNode(1)); var optimizednode = originalnode.Optimize(NoVariables); Assert.AreEqual(0, optimizednode.GetValue()); }
private Value Subtraction(SubtractionNode 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.OpSub(l, r)); } case Constant.Type.Int: { IntValue l = (IntValue)Convert(left, bt); IntValue r = (IntValue)Convert(right, bt); return(IntValue.OpSub(l, r)); } case Constant.Type.Float: { FloatValue l = (FloatValue)Convert(left, bt); FloatValue r = (FloatValue)Convert(right, bt); return(FloatValue.OpSub(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 (Exception exc) { throw new ModelInterpreterException(exc.Message) { Line = exp.Line, Position = exp.Position }; } }
private object SubtractionNode(SubtractionNode s) { var l = Evaluate(s.l); var r = Evaluate(s.r); if (l is decimal && r is decimal) { return((decimal)l - (decimal)r); } throw(new Exception($"Can't subtract {l.GetType()} and {r.GetType()}")); }
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(); } } } }
public void Subtraction_Optimize_RecursiveReduction() { var originalnode = new SubtractionNode( new VariableValueNode("a"), new VariableValueNode("b") ); var optimizednode = originalnode.Optimize(new Dictionary <string, ushort> { { "a", 1 }, { "b", 1 } }); Assert.IsInstanceOfType(optimizednode, typeof(ConstantNode)); }
public override Expression Visit(SubtractionNode node) { var left = Visit(node.Left); var right = Visit(node.Right); var negatedRightTerms = new List <Term>(); foreach (var term in right.Terms) { negatedRightTerms.Add(term.Multiply(-1)); } return(new Expression(left.Terms, negatedRightTerms)); }
public void Visit_SubtractionNode_EmitsCorrectCode() { // Arrange SubtractionNode subtractionNode = new SubtractionNode(DummySrcPos); IntegerLiteral left = new IntegerLiteral("10", DummySrcPos); IntegerLiteral right = new IntegerLiteral("5", DummySrcPos); subtractionNode.Left = left; subtractionNode.Right = right; string expectedResult = "10 - 5"; // Act string actualResult = CodeGenerator.Visit(subtractionNode); // Assert Assert.AreEqual(expectedResult, actualResult); }
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); }
public PhongPS() { Name = "PhongPS"; Type = ShaderType.Pixel; KeyPart = new TechniqueKey(ps: PixelShaderFlags.Diffuse | PixelShaderFlags.Specular); FeatureLevel = FeatureLevel.PS_4_0_Level_9_1; EnableSeparators = true; var input = Struct.VertexPositionNormalTextureOut; input.Name = "input"; InputStruct = input; OutputStruct = Struct.PixelShaderOutput; Structs.ConstantBuffer cbStatic = CBLight; Structs.ConstantBuffer cbFrame = CBFrame; Structs.ConstantBuffer cbInstance = ConstantBuffer.CBMaterial; Struct pointLight = (Struct)cbStatic[Param.Struct.PointLight]; Struct material = (Struct)cbInstance[Param.Struct.Material]; Add(cbStatic); Add(cbFrame); Add(cbInstance); CastNode vWorldPos = new CastNode { Input = new SwizzleNode { Input = new ReferenceNode { Value = InputStruct[Param.SemanticVariables.WorldPosition] } , Swizzle = new[] { Swizzle.X, Swizzle.Y, Swizzle.Z } }, Output = new Vector { Type = Shaders.Type.Float3, Name = "vWorldPos", }, IsVerbose = true }; SubtractionNode vLightDirection = new SubtractionNode { Input1 = new ReferenceNode { Value = pointLight[Param.Light.Position] }, Input2 = vWorldPos, }; SubtractionNode vViewDirection = new SubtractionNode { Input1 = new ReferenceNode { Value = cbFrame[Param.Vectors.CameraPosition] }, Input2 = vWorldPos, }; ReferenceNode nNormal = new ReferenceNode { Value = InputStruct[Param.SemanticVariables.Normal] }; UnaryFunctionNode normalizeNormal = new UnaryFunctionNode { Input1 = nNormal, Function = HlslIntrinsics.Normalize, Output = new Vector { Type = nNormal.Output.Type, Name = "vNormal" }, IsVerbose = true, }; UnaryFunctionNode normalizeViewDirection = new UnaryFunctionNode { Input1 = vViewDirection, Function = HlslIntrinsics.Normalize, Output = new Vector { Type = vViewDirection.Output.Type, Name = "vViewDirection" }, IsVerbose = true, }; UnaryFunctionNode normalizeLightDirection = new UnaryFunctionNode { Input1 = vLightDirection, Function = HlslIntrinsics.Normalize, Output = new Vector { Type = vLightDirection.Output.Type, Name = "vLightDirection" }, IsVerbose = true, }; InvertNode vLightDirectionInv = new InvertNode { Input = normalizeLightDirection, //Output = new Vector { Type = Shaders.Type.Float3, Name = "vLightDirection" }, }; PhongLightingNode nPhongLighting = new PhongLightingNode { Light = new ReferenceNode { Value = pointLight }, Material = new ReferenceNode { Value = material }, ViewDirection = normalizeViewDirection, Normal = normalizeNormal, LightDirection = vLightDirectionInv, Specular = true, }; Result = new PSOutputNode { FinalColor = nPhongLighting, Output = OutputStruct }; }
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."); } }
public abstract T Visit(SubtractionNode node);
public void CalculateCorrectly() { var subtractionNode = new SubtractionNode(new NumberNode(54), new NumberNode(42)); subtractionNode.Calculate().Should().Be(12); }
public void PrintCorrectly() { var subtractionNode = new SubtractionNode(new NumberNode(54), new NumberNode(42)); subtractionNode.Print().Should().Be("(- 54 42)"); }
/// <summary> /// 減算ノードの評価 /// </summary> /// <param name="node">減算ノード</param> /// <returns>演算後の数値(Double)</returns> public override object Visit(SubtractionNode node) { return((double)Visit(node.Left) - (double)Visit(node.Right)); }