protected override bool NumberNodeVisitor_OnVisited(NumberNode node, int level, out List <ParagraphFormatException> exceptions) { exceptions = new List <ParagraphFormatException>(); var m = leftRegex.Match(node.Header); var data = new StringDataView(node.Header); while (m.Success) { data.Position = m.Index + m.Length; var numbers = _numberParser.Consume(data); if (numbers.Any()) { var number = numbers.First(); var afterNumberData = number.DataView; var rightMatch = rightRegex.Match(afterNumberData.CurrentView.ToString()); if (rightMatch.Success) { node.SelectiveDescription = node.Header.Substring( m.Index, afterNumberData.Position + rightMatch.Index + rightMatch.Length - m.Index); node.SelectCount = number.Result.IntNumber; return(false); } } m = m.NextMatch(); } return(true); }
private TreeNode ParseNumber(Token Token) { NumberNode node = new NumberNode(Convert.ToDouble(Token.Value)); nodeStack.Push(node); return(node); }
public void TestIndividualOperations() { var left = new NumberNode(27); var right = new NumberNode(14); var node = new BinNode(left, TokenType.PLUS, right); var actual = new Interpreter().visit(node); var expected = new Number(41); expected.ShouldDeepEqual(actual); node = new BinNode(left, TokenType.MINUS, right); actual = new Interpreter().visit(node); expected = new Number(13); expected.ShouldDeepEqual(actual); node = new BinNode(left, TokenType.MULTIPLY, right); actual = new Interpreter().visit(node); expected = new Number(378); expected.ShouldDeepEqual(actual); node = new BinNode(left, TokenType.DIVIDE, right); actual = new Interpreter().visit(node); expected = new Number(1.9285714285714286); expected.ShouldDeepEqual(actual); }
public static SyntaxNode Simplify(OperatorNode node) { NumberNode lhsNode = (NumberNode)node.Left; NumberNode rhsNode = (NumberNode)node.Right; switch (node.Operator) { case Operator.Addition: return(new NumberNode(lhsNode.Value + rhsNode.Value)); case Operator.Subtraction: return(new NumberNode(lhsNode.Value - rhsNode.Value)); case Operator.Multiplication: return(new NumberNode(lhsNode.Value * rhsNode.Value)); case Operator.Division: return(new NumberNode(lhsNode.Value / rhsNode.Value)); case Operator.Exponentiation: return(new NumberNode(Math.Pow(lhsNode.Value, rhsNode.Value))); default: return(node); } }
private INode <AstNode> Eval(NumberNode node) { int value; var parsed = int.TryParse(node.Number, out value); return(parsed && value > 0 ? (INode <AstNode>) new TrueNode() : new FalseNode()); }
public double evaluate(EvaluationNode node) { if (node == null) { return(0); } else if (node.getNodeType() == EvaluationNodeType.NUMBER) { NumberNode numberNode = (NumberNode)node; return(numberNode.evaluate()); } else if (node.getNodeType() == EvaluationNodeType.VARIABLE) { VariableNode variableNode = (VariableNode)node; return(variableNode.evaluate(x)); } else if (node.getNodeType() == EvaluationNodeType.FUNCTION) { FunctionNode functionNode = (FunctionNode)node; return(functionNode.evaluate(x)); } else { OperatorNode operatorNode = (OperatorNode)node; double a = evaluate(node.left); double b = evaluate(node.right); return(operatorNode.evaluate(a, b)); } }
public void Should_parse_number_when_decimal_separator_is_of_the_current_culture_is_comma() { System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo("bg-BG"); NumberNode result = (NumberNode)Parse("10.5"); Assert.Equal(10.5, result.Value); }
// Parse a leaf node // (For the moment this is just a number) Node ParseLeaf() { // Parenthesis? if (_tokens.Current.Kind == ArithmeticExpressionToken.LParen) { _tokens.MoveNext(); // Parse a top-level expression var node = ParseAddMultiply(); // Check and skip ')' if (_tokens.Current.Kind != ArithmeticExpressionToken.RParen) { throw new InvalidOperationException("Missing close parenthesis"); } _tokens.MoveNext(); // Return return(node); } if (_tokens.Current.Kind == ArithmeticExpressionToken.Number) { var node = new NumberNode(long.Parse(_tokens.Current.Span.ToStringValue())); _tokens.MoveNext(); return(node); } // Don't Understand throw new InvalidOperationException(); }
/** * Returns an array of the numbers that could potentially form a combo. * This eliminates all numbers that can not make up the combo from the original array, * to reduce the amount of numbers we have to consider next. * @param startIndex the index to look from * @param target the target number we're looking for * @return an array of the numbers that could potentially form a combo */ private ShortList FindShortList(int startIndex, int target) { // Get values from the list of number nodes int[] values = GetValues(); // Create the shortlist of numbers List <NumberNode> shortList = new List <NumberNode>(); // Include all consecutive values to the left of startIndex until they exceed target int sum = 0; for (int i = startIndex; i > -1; i--) { // Add the current value to the sum NumberNode node = numberArray[i]; sum += node.value; // If the sum exceeds the target, this number can't be part of the combo and we can stop looking. if (sum > target) { break; } // Else we add it to the shortlist shortList.Add(node); } int newStartIndex = shortList.Count - 1; // Reverse that list so it's in order of original array shortList.Reverse(); // Now add the numbers right of startIndex sum = 0; for (int i = startIndex; i < numberLinkedList.Count; i++) { // Add the current value to the sum NumberNode node = numberArray[i]; sum += node.value; // If the sum exceeds the target, this number can't extend the combo and we can stop looking. if (sum > target) { break; } // Else we add it to the shortlist // (if it's not the start index, since that's already included) else if (i != startIndex) { shortList.Add(node); } } // Now convert the ArrayList into an array of nodes NumberNode[] shortArray = new NumberNode[shortList.Count]; int index = 0; foreach (NumberNode node in shortList) { shortArray[index++] = node; } return(new ShortList(shortArray, newStartIndex)); }
public void TestEmpty() { var node = new NumberNode(51.2); var actual = new Interpreter().visit(node); var expected = new Number(51.2); expected.ShouldDeepEqual(actual); }
public void Should_evaluate_true_for_a_non_zero_number_node() { var inputNode = new NumberNode("1"); var evaluator = new BooleanEvaluator(); var result = evaluator.Eval(inputNode); result.ShouldBeOfType <TrueNode>(); }
public void Should_evaluate_false_for_invalid_number_node() { var inputNode = new NumberNode("abc"); var evaluator = new BooleanEvaluator(); var result = evaluator.Eval(inputNode); result.ShouldBeOfType <FalseNode>(); }
public static bool Contains(NumberNode node) { if (numberList.numberLinkedList.Contains(node)) { return(true); } return(false); }
public void Analyze_NumberValue_ReturnsNumberNode() { SyntaxNode node = new NumberNode(1); node = SemanticAnalyzer.Analyze(node, new Environment()); Assert.AreEqual("1", node.ToString()); }
private static NumberNode Div(NumberNode n1, NumberNode n2) { if (n2.Value == 0) { throw new Exception("Cannot divide by zero"); } return(new NumberNode(n1.Value / n2.Value, n1.Token)); }
// ===== Graph Initialization ===== public Graph LoadGraph(string path) { Debug.ClearDeveloperConsole(); if (path.Equals(BonConfig.DefaultGraphName)) { Graph graph = new Graph(); // create a default grpah programmatically var numberNode01 = new NumberNode(graph.GetUniqueId()); numberNode01.X = 20; numberNode01.Y = 20; numberNode01.Number = 355; graph.AddNode(numberNode01); var numberNode02 = new NumberNode(graph.GetUniqueId()); numberNode02.X = 20; numberNode02.Y = 80; numberNode02.Number = 113; graph.AddNode(numberNode02); var operator01 = new MathOperatorNode(graph.GetUniqueId()); operator01.X = 200; operator01.Y = 40; operator01.SetMode(Operator.Divide); graph.AddNode(operator01); var diplay01 = new MathDisplay(graph.GetUniqueId()); diplay01.X = 330; diplay01.Y = 80; graph.AddNode(diplay01); graph.Link( numberNode01.GetSocket(NumberNode.FloatType, SocketDirection.Output, 0), operator01.GetSocket(NumberNode.FloatType, SocketDirection.Input, 0)); graph.Link( numberNode02.GetSocket(NumberNode.FloatType, SocketDirection.Output, 0), operator01.GetSocket(NumberNode.FloatType, SocketDirection.Input, 1)); graph.Link( operator01.GetSocket(NumberNode.FloatType, SocketDirection.Output, 0), diplay01.GetSocket(NumberNode.FloatType, SocketDirection.Input, 0)); // == test serialization an deserialization == var serializedJSON = graph.ToJson(); var deserializedGraph = Graph.FromJson(serializedJSON, new StandardGraphController()); // ===== return(deserializedGraph); } else { Graph graph = Graph.Load(path, new StandardGraphController()); return(graph); } }
private bool NumberNodeVisitor_OnVisited_CatchException(NumberNode node, int level) { List <ParagraphFormatException> exceptions; var ret = NumberNodeVisitor_OnVisited(node, level, out exceptions); _exceptions.AddRange(exceptions); return(ret); }
public static SyntaxNode Simplify(OperatorNode node, Environment environment) { OperatorNode operatorNode = new OperatorNode(Operator.Multiplication); NumberNode coefficientNode = (NumberNode)node.Right.Left; IdentifierNode leftHandIdentifier = (IdentifierNode)node.Left; operatorNode.Left = new NumberNode(coefficientNode.Value + 1); operatorNode.Right = leftHandIdentifier; return(operatorNode); }
private static void AddAdditionalNodesForUnaryMinus(List <BaseFormulaNode> nodes) { var bracket = new BracketNode(Bracket.Open); var value = new NumberNode(0); var minus = new OperatorNode(Operator.Minus); nodes.Add(bracket); nodes.Add(value); nodes.Add(minus); }
public static SyntaxNode Simplify(OperatorNode node, Environment environment) { OperatorNode operatorNode = new OperatorNode(Operator.Multiplication); NumberNode leftCoefficient = (NumberNode)node.Left.Left; NumberNode rightCoefficient = (NumberNode)node.Right.Left; operatorNode.Left = new NumberNode(leftCoefficient.Value + rightCoefficient.Value); operatorNode.Right = node.Left.Right; return(operatorNode); }
public void Analyze_AmbiguousPredefinedFunction_ReturnsFunctionNode() { IdentifierNode left = new IdentifierNode("sin"); SyntaxNode right = new NumberNode(1); SyntaxNode root = new FunctionOrDistributionNode(left, right); root = SemanticAnalyzer.Analyze(root, new Environment()); Assert.AreEqual("sin(1)", root.ToString()); }
public bool IsTouching(NumberNode otherNode) { if (otherNode != null) { if (circleCollider.IsTouching(otherNode.circleCollider)) { return(true); } } return(false); }
public static int GetMaxNumber(NumberNode node) { var maxN = node.DecoratedNumber.Number.IntNumber; foreach (var child in node.Children) { maxN = Math.Max(maxN, GetMaxNumber(child)); } return(maxN); }
public decimal VisitNumberNode(NumberNode node) { switch (node.token.Type) { case TokenType.CurrencyAmount: return(tokenConverter.ToUSD(node.token as CurrencyAmountToken)); default: throw new InvalidSyntaxException("Error syntax"); } }
public void OnTriggerEnter2D(Collider2D collision) { NumberNode otherNode = collision.GetComponent <NumberNode>(); if (otherNode != null) { if (!NodeManager.Contains(otherNode)) { NodeManager.InsertAtPlaceOf(NodeManager.GetNodes().Find(this), otherNode); } } }
private void VisitNode(NumberNode node, int level) { if (!OnVisited.Invoke(node, level)) { return; } foreach (var child in node.Children) { VisitNode(child, level + 1); } }
private static void OnDispersed() { int index = numberList.GetIndexOfNode(newlyInsertedNode); if (numberList.CheckForComboAt(index, target)) { target = UnityEngine.Random.Range(NumberList.BOUND_LOW, NumberList.BOUND_HIGH); } newlyInsertedNode = null; dispersing = false; }
public int GetIndexOfNode(NumberNode node) { RefreshArray(); for (int i = 0; i < numberArray.Length; i++) { if (numberArray[i] == node) { return(i); } } return(-1); }
public void TestNumber() { var tokens = new List <Token>() { new Token(TokenType.NUMBER, 51.2) }; var expected = new NumberNode(51.2); var actual = new Parser(tokens).Parse(); expected.ShouldDeepEqual(actual); }
public void Should_not_scope_atom_nodes() { var fooNode = new NumberNode("123"); var body = new ListNode(fooNode); var methodDefinitionNode = new MethodDefinitionNode("sayMessage", new ParameterDefinitionNode[] { new ParameterDefinitionNode("message"), }, body); var globalScope = new GlobalScope <SymbolNode>(); var builder = CreateScopeBuilder(globalScope); var resultScope = builder.GetScope(methodDefinitionNode, globalScope); resultScope.Descendants().OfType <BoundScope <SymbolNode> >().Any(scope => scope.Node == fooNode).ShouldBe(false); }
public void NumberNodeTest_FormatError() { StreamLocation expectedLocation = new StreamLocation(3, 2, 1); string testNumber = "34..0"; ValueNode sut = new NumberNode(testNumber, expectedLocation); }
public void NumberNodeTest_Integer() { StreamLocation expectedLocation = new StreamLocation(3, 2, 1); string testNumber = "34"; long? expectedValue = (long?)long.Parse(testNumber); ValueNode sut = new NumberNode(testNumber, expectedLocation); Assert.AreEqual(TNode.NUMBER, sut.NodeType); Assert.AreEqual(expectedLocation, sut.Location); Assert.IsTrue(sut.Description.Contains("NUMBER")); Assert.AreEqual(FieldValueType.INTEGER, sut.ValueType); Assert.IsInstanceOfType(sut.SubExpression, typeof(ConstantExpression)); Assert.AreEqual(ExpressionType.Constant, sut.SubExpression.NodeType); Assert.AreEqual(typeof(long?), sut.SubExpression.Type); Assert.AreEqual(expectedValue, ((ConstantExpression)sut.SubExpression).Value); }
public void RangeNodeTest_CoercedTypes() { StreamLocation expectedLocation = new StreamLocation(3, 2, 1); SimpleValueNode testLowBound = new NumberNode("1", new StreamLocation()); SimpleValueNode testUpperBound = new NumberNode("10.", new StreamLocation()); bool testInclusiveLeft = false; bool testInclusiveRight = true; RangeNode sut = new RangeNode(testLowBound, testInclusiveLeft, testUpperBound, testInclusiveRight, expectedLocation); Assert.AreEqual(TNode.RANGE, sut.NodeType); Assert.AreEqual(expectedLocation, sut.Location); Assert.IsTrue(sut.Description.Contains("RANGE")); Assert.AreEqual(FieldValueType.FLOAT, sut.ValueType); Assert.IsNull(sut.SubExpression); Assert.AreEqual(testLowBound, sut.GetLeft()); Assert.AreEqual(testInclusiveLeft, sut.IsInclusiveLeft()); Assert.AreEqual(testUpperBound, sut.GetRight()); Assert.AreEqual(testInclusiveRight, sut.IsInclusiveRight()); }
public void RangeNodeTest_IncompatibleTypes() { StreamLocation expectedLocation = new StreamLocation(3, 2, 1); SimpleValueNode testLowBound = new NumberNode("1", new StreamLocation()); SimpleValueNode testUpperBound = new StringNode("10", new StreamLocation()); bool testInclusiveLeft = true; bool testInclusiveRight = true; RangeNode sut = new RangeNode(testLowBound, testInclusiveLeft, testUpperBound, testInclusiveRight, expectedLocation); }
public void Visit(NumberNode number) { _stack.Push(number.Number); }
public static Node NewNumber(double d) { NumberNode node = new NumberNode(d); return node; }
public static FScheme.Expression CompileFunction( FunctionDefinition definition, ref IEnumerable<string> inputNames, ref IEnumerable<string> outputNames ) { if (definition == null) return null; // Get the internal nodes for the function dynWorkspaceModel functionWorkspace = definition.Workspace; #region Find outputs // Find output elements for the node IEnumerable<dynNodeModel> outputs = functionWorkspace.Nodes.Where(x => x is dynOutput); var topMost = new List<Tuple<int, dynNodeModel>>(); // if we found output nodes, add select their inputs // these will serve as the function output if (outputs.Any()) { topMost.AddRange( outputs.Where(x => x.HasInput(0)).Select(x => x.Inputs[0])); outputNames = outputs.Select(x => (x as dynOutput).Symbol); } else { // if there are no explicitly defined output nodes // get the top most nodes and set THEM as tht output IEnumerable<dynNodeModel> topMostNodes = functionWorkspace.GetTopMostNodes(); var outNames = new List<string>(); foreach (dynNodeModel topNode in topMostNodes) { foreach (int output in Enumerable.Range(0, topNode.OutPortData.Count)) { if (!topNode.HasOutput(output)) { topMost.Add(Tuple.Create(output, topNode)); outNames.Add(topNode.OutPortData[output].NickName); } } } outputNames = outNames; } #endregion // color the node to define its connectivity foreach (var ele in topMost) { ele.Item2.ValidateConnections(); } //Find function entry point, and then compile the function and add it to our environment IEnumerable<dynNodeModel> variables = functionWorkspace.Nodes.Where(x => x is dynSymbol); inputNames = variables.Select(x => (x as dynSymbol).Symbol); INode top; var buildDict = new Dictionary<dynNodeModel, Dictionary<int, INode>>(); if (topMost.Count > 1) { InputNode node = new ExternalFunctionNode( FScheme.Value.NewList, Enumerable.Range(0, topMost.Count).Select(x => x.ToString())); int i = 0; foreach (var topNode in topMost) { string inputName = i.ToString(); node.ConnectInput(inputName, topNode.Item2.Build(buildDict, topNode.Item1)); i++; } top = node; } else if (topMost.Count == 1) { top = topMost[0].Item2.BuildExpression(buildDict); } else { // if the custom node is empty, it will initially be a number node top = new NumberNode(0); } // if the node has any outputs, we create a BeginNode in order to evaluate all of them // sequentially (begin evaluates a list of expressions) if (outputs.Any()) { var beginNode = new BeginNode(); List<dynNodeModel> hangingNodes = functionWorkspace.GetTopMostNodes().ToList(); foreach (var tNode in hangingNodes.Select((x, index) => new { Index = index, Node = x })) { beginNode.AddInput(tNode.Index.ToString()); beginNode.ConnectInput(tNode.Index.ToString(), tNode.Node.Build(buildDict, 0)); } beginNode.AddInput(hangingNodes.Count.ToString()); beginNode.ConnectInput(hangingNodes.Count.ToString(), top); top = beginNode; } // make the anonymous function FScheme.Expression expression = Utils.MakeAnon(variables.Select(x => x.GUID.ToString()), top.Compile()); return expression; }
// Factor = [ "-" ], Number | Identifier | ParenExpression | FunctionCall private Node ParseFactor() { if (tokenStream.Consume("-")) return new UnaryMinusNode(ParseFactor()); Node factor = null; if (tokenStream.Consume(TokenType.Number)) { Double termValue = Convert.ToDouble(ConsumedToken.Value, CultureInfo.InvariantCulture); factor = new NumberNode(termValue); } else if (CurrentToken.Type == TokenType.Identifier) { var lookAhead = tokenStream.LookAhead(); if (lookAhead != null && lookAhead.Value == "(") return ParseFunctionCall(); tokenStream.Consume(); factor = new IdentifierNode(tokenStream.ConsumedToken.Value); } else if (tokenStream.Consume("(")) { factor = ParseExpression(); tokenStream.Expect(")"); } if (factor == null) throw new Exception("Number, identifier or function call expected"); return factor; }
public void NumberNodeTest_Float_ExponentUC() { StreamLocation expectedLocation = new StreamLocation(3, 2, 1); string testNumber = "34E+3"; double? expectedValue = (double?)double.Parse(testNumber); ValueNode sut = new NumberNode(testNumber, expectedLocation); Assert.AreEqual(TNode.NUMBER, sut.NodeType); Assert.AreEqual(expectedLocation, sut.Location); Assert.IsTrue(sut.Description.Contains("NUMBER")); Assert.AreEqual(FieldValueType.FLOAT, sut.ValueType); Assert.IsInstanceOfType(sut.SubExpression, typeof(ConstantExpression)); Assert.AreEqual(ExpressionType.Constant, sut.SubExpression.NodeType); Assert.AreEqual(typeof(double?), sut.SubExpression.Type); Assert.AreEqual(expectedValue, ((ConstantExpression)sut.SubExpression).Value); }
public void RelationNodeTest_IN_Range_Inclusive() { StreamLocation expectedLocation = new StreamLocation(3, 2, 1); Expression operandA = Expression.Constant(43L, typeof(long?)); SimpleValueNode rangeLow = new NumberNode("34", new StreamLocation()); SimpleValueNode rangeHigh = new NumberNode("68", new StreamLocation()); RelationNode sut = new RelationNode(RelationNode.Operator.IN, new SimpleValueTestNode(operandA, FieldValueType.INTEGER), new RangeNode(rangeLow, true, rangeHigh, true, new StreamLocation()), expectedLocation); Assert.AreEqual(TNode.RELATION, sut.NodeType); Assert.AreEqual(expectedLocation, sut.Location); Assert.IsTrue(sut.Description.Contains("RELATION")); Assert.IsInstanceOfType(sut.SubExpression, typeof(BinaryExpression)); Assert.AreEqual(ExpressionType.And, sut.SubExpression.NodeType); Assert.AreEqual(typeof(bool), sut.SubExpression.Type); { Expression left = ((BinaryExpression)sut.SubExpression).Left; Assert.IsInstanceOfType(left, typeof(BinaryExpression)); Assert.AreEqual(ExpressionType.GreaterThanOrEqual, left.NodeType); Assert.AreEqual(operandA, ((BinaryExpression)left).Left); Assert.AreEqual(rangeLow.SubExpression, ((BinaryExpression)left).Right); } { Expression right = ((BinaryExpression)sut.SubExpression).Right; Assert.IsInstanceOfType(right, typeof(BinaryExpression)); Assert.AreEqual(ExpressionType.LessThanOrEqual, right.NodeType); Assert.AreEqual(operandA, ((BinaryExpression)right).Left); Assert.AreEqual(rangeHigh.SubExpression, ((BinaryExpression)right).Right); } }
public void Visit(NumberNode number) { _resultBuilder.Append(number); }