Example #1
0
 public virtual AstNode VisitConditional(ConditionalNode n)
 {
     Visit(n.Condition);
     Visit(n.IfTrue);
     Visit(n.IfFalse);
     return(n);
 }
Example #2
0
 public void Transform(ConditionalNode item)
 {
     StripWhiteSpace();
     foreach (var child in item.Children)
     {
         child.Transform(this);
     }
 }
Example #3
0
 public void Transform(ConditionalNode item)
 {
     TrimNewLine = true;
     foreach (var child in item.Children)
     {
         child.Transform(this);
     }
 }
 public void Visit(ConditionalNode node)
 {
     if (!AnalyseExpression(node.Expression))
     {
         this._isValid = false;
     }
     VisitChildren(node);
 }
Example #5
0
    //TODO use NodeType to categorize Types.
    public static BaseNode CreateNode(ActionNodeData aData)
    {
        if (aData.NodeType == null)
        {
            Debug.LogError("Type not set");
            return(null);
        }

        aData.GUID          = string.IsNullOrEmpty(aData.GUID) ? Guid.NewGuid().ToString() : aData.GUID;
        aData.OutputPortIDs = aData.OutputPortIDs ?? new List <string>();

        //The copy prevent the node to modify the list in the ActionNodeData
        List <string> copy = new List <string>();

        foreach (var outputPort in aData.OutputPortIDs)
        {
            copy.Add(outputPort);
        }

        BaseNode node;
        Type     type = Type.GetType(aData.NodeType);

        if (type == typeof(ChangeSceneNode))
        {
            node = ChangeSceneNode.Create("Change Scene", aData.Position, aData.GUID, copy);
        }
        else if (type == typeof(StartNode))
        {
            node = StartNode.Create("Start Node", aData.Position, aData.GUID, copy);
        }
        else if (type == typeof(ConditionalNode))
        {
            node = ConditionalNode.Create("Conditional", aData.Position, aData.GUID, copy);
        }
        else if (type == typeof(MultiNode))
        {
            node = MultiNode.Create("Multi Output", aData.Position, aData.GUID, copy);
        }
        else if (type == typeof(ExitNode))
        {
            node = ExitNode.Create("Exit Node", aData.Position, aData.GUID, copy);
        }
        else if (type == typeof(RandomNode))
        {
            node = RandomNode.Create("Random Node", aData.Position, aData.GUID, copy);
        }
        else if (type == typeof(TakeObjectNode))
        {
            node = TakeObjectNode.Create("Take Object", aData.Position, aData.GUID, copy);
        }
        else
        {
            throw new NotImplementedException($"Node type {type} not handled in NodeFactory");
        }

        node?.SetSerializedScript(aData.SerializedScript);
        return(node);
    }
 public AstNode VisitConditional(ConditionalNode n)
 {
     Visit(n.Condition);
     Append(" ? ");
     Visit(n.IfTrue);
     Append(" : ");
     Visit(n.IfFalse);
     return(n);
 }
Example #7
0
 public void Visit(ConditionalNode conditional)
 {
     conditional.Condition.Parent = conditional;
     conditional.Left.Parent      = conditional;
     conditional.Right.Parent     = conditional;
     conditional.Condition.Accept(this);
     conditional.Left.Accept(this);
     conditional.Right.Accept(this);
 }
Example #8
0
        /// <summary>
        /// Like an action node... but the function can return true/false and is mapped to success/failure.
        /// </summary>
        public BehaviorTreeBuilder If(Func <GameTime, bool> fn)
        {
            var conditionalNode = new ConditionalNode(rootNode, fn);

            parentNodeStack.Peek().AddChild(conditionalNode);
            parentNodeStack.Push(conditionalNode);

            return(this);
        }
Example #9
0
        override public Node Visit(ConditionalNode node)
        {
            if (_conditionalNodeExpectations.Count > 0)
            {
                _conditionalNodeExpectations.Dequeue().Invoke(node);
            }

            return(VisitChildren(node));
        }
Example #10
0
        /// <summary>
        /// Transorms ConditionalNode into a boolean Expression
        /// </summary>
        /// <param name="conditionalNode">Node to parse</param>
        /// <returns>Boolean Expression</returns>
        public ExpressionBool GetCondition(ConditionalNode conditionalNode)
        {
            ExpressionValue expression = ParseExpressionNode(conditionalNode.Expression);

            if (expression.Type != typeof(bool))
            {
                throw new InvalidOperationException(string.Format("Cannot use expression with type of {0} as a condition.", expression.Type));
            }
            return(expression as ExpressionBool);
        }
        public override Node VisitConditional(ConditionalContext context)
        {
            var conditional = new ConditionalNode(context.Start);

            conditional.AddChild(Visit(context.expression()));
            conditional.AddChild(Visit(context.ifBlock()));
            conditional.AddChild(Visit(context.elseBlock()));

            return(conditional);
        }
        public override ASTN VisitIf([NotNull] IfContext context)
        {
            ConditionalNode node = new ConditionalNode(context)
            {
                If   = VisitExpr(context.cond) as ExprNode,
                Then = VisitExpr(context.result) as ExprNode,
                Else = VisitExpr(context.@else) as ExprNode
            };

            return(node);
        }
Example #13
0
 public override QLType Visit(ConditionalNode node)
 {
     foreach (Node child in node.ChildNodes)
     {
         QLType childType = child.Accept(this);
         if (childType != QLType.Boolean && childType != QLType.Undefined)
         {
             TypeErrors.Add(new ConditionalType(childType.ToString(), node.Token.Line));
         }
     }
     return(QLType.Boolean);
 }
Example #14
0
        public void Visit(ConditionalNode node)
        {
            node.If.Accept(this);
            node.Then.Accept(this);
            node.Else.Accept(this);

            if (node.If.staticType.Text != "Bool")
            {
                errors.Add(ErrorSemantic.CannotConvert(node.If, node.If.staticType, scope.GetType("Bool")));
            }

            node.staticType = SemanticAlgorithm.LowerCommonAncestor(node.Then.staticType, node.Else.staticType);
        }
        /// <summary>
        /// Transorms ConditionalNode into a boolean Expression
        /// </summary>
        /// <param name="conditionalNode">Node to parse</param>
        /// <returns>Boolean Expression</returns>
        public ExpressionBool GetCondition(ConditionalNode conditionalNode)
        {
            ExpressionValue expression = ParseExpressionNode(conditionalNode.Expression);

            switch (expression)
            {
            case ExpressionBool boolExpression:
                return(boolExpression);

            default:
                throw new InvalidOperationException(string.Format("Cannot use expression with type of {0} as a condition.", expression.ExpressionType));
            }
        }
Example #16
0
            protected override JSchema VisitConditionalNode(ConditionalNode node)
            {
                var schema       = base.VisitConditionalNode(node);
                var parentSchema = _schemas.Peek();

                //schema.Required = false;
                if (schema.Type == null)
                {
                    schema.Type = JSchemaType.Boolean;
                }

                return(schema);
            }
Example #17
0
        public IEnumerable <ASTNode> Transform(ConditionalNode item)
        {
            yield return(item);

            foreach (var child in TransformAll(item.Expression))
            {
                yield return(child);
            }
            foreach (var child in TransformAll(item.Children))
            {
                yield return(child);
            }
        }
Example #18
0
        private bool GetClass(IDataRow row, ConditionalNode node, out string className)
        {
            className = node.Class;
            bool isValid = false;

            var rowValue = row[node.Attribute];
            switch (node.Condition)
            {
                case PredicateCondition.Equal:
                    if (row[node.Attribute].Equals(node.ThreshHold))
                    {
                        isValid = true;
                    }
                    break;
                case PredicateCondition.LessThanOrEqual:
                    if (rowValue == null)
                    {
                        return false;
                    }
                    if (Convert.ToDouble(rowValue) <= Convert.ToDouble(node.ThreshHold))
                    {
                        isValid = true;
                    }
                    break;
                case PredicateCondition.GreaterThan:
                    if (rowValue == null)
                    {
                        return false;
                    }
                    if (Convert.ToDouble(rowValue) > Convert.ToDouble(node.ThreshHold))
                    {
                        isValid = true;
                    }
                    break;
                default:
                    throw new ArgumentOutOfRangeException();
            }

            if (isValid && node.Children != null)
            {
                foreach (var child in node.Children)
                {
                    if (GetClass(row, child, out className))
                    {
                        break;
                    }
                }
            }

            return isValid;
        }
        public IEnumerable <string> Transform(ConditionalNode item)
        {
            _EncounteredOutputStyleBlock = true;
            if (ShouldRender == false)
            {
                yield break;
            }


            foreach (var output in TransformAll(item.Children))
            {
                yield return(output);
            }
        }
            protected override IClientModel VisitConditionalNode(ConditionalNode node)
            {
                var result = this.VisitExpressionNode(node.Expression);

                _clientContext.BeginIf(result);
                this.VisitBlockNode(node.TrueBlock);
                if (node.FalseBlock != null)
                {
                    _clientContext.ElseIf();
                    this.VisitBlockNode(node.FalseBlock);
                }

                _clientContext.EndIf();
                return(null);
            }
Example #21
0
        public DomainId <IConditionalStatementNode> CreateConditional(
            string definition,
            DomainId <IBooleanLogicNode> predicate,
            IEnumerable <DomainId <IStatementNode> > consequent,
            IEnumerable <DomainId <IStatementNode> > alternative)
        {
            var condition = new ConditionalNode(
                m_ids.Next,
                definition,
                predicate,
                consequent,
                alternative);

            return(DomainItemRegistration <IConditionalStatementNode>(condition));
        }
        public void Visit(ConditionalNode node)
        {
            string tag = Code.Count.ToString();

            node.If.Accept(this);

            Code.Add(new CondJumpCodeLine(VariableManager.PeekVariableCounter(), new LabelCodeLine("_else", tag)));

            node.Then.Accept(this);
            Code.Add(new GotoCodeLine(new LabelCodeLine("_endif", tag)));

            Code.Add(new LabelCodeLine("_else", tag));
            node.Else.Accept(this);

            Code.Add(new LabelCodeLine("_endif", tag));
        }
Example #23
0
        protected virtual TResult VisitConditionalNode(ConditionalNode node)
        {
            var expressionResult = this.VisitExpressionNode(node.Expression);

            if (node.TrueBlock != null)
            {
                this.VisitBlockNode(node.TrueBlock);
            }

            if (node.FalseBlock != null)
            {
                this.VisitBlockNode(node.FalseBlock);
            }

            return(expressionResult);
        }
Example #24
0
        public override Node Visit(ConditionalNode conditional)
        {
            Node expressionNode     = conditional.ChildNodes[0];
            var  evaluatedNodeValue = _valueFactory.CreateValueFromString((expressionNode.Accept(this) as LiteralNode).Value, QLType.Boolean);

            if (evaluatedNodeValue.ToBoolean())
            {
                var ifNode = conditional.ChildNodes[1];
                return(ifNode.Accept(this));
            }
            else if (conditional.ChildNodes.Count > 2)
            {
                var elseNode = conditional.ChildNodes[2];
                return(elseNode.Accept(this));
            }

            return(null);
        }
        public void Initialize()
        {
            var firstQuestion  = new QuestionNode(Location.Empty, "Q1", "Do you like puppies?", QValueType.Boolean);
            var secondQuestion = new QuestionNode(Location.Empty, "Q2", "Do you like kittens?", QValueType.Boolean);
            var thirdQuestion  = new ConditionalNode(Location.Empty, null);

            thirdQuestion.AddNode(new FormNode(Location.Empty, "InvalidFormInLowerLayer"));
            var forthQuestion = new QuestionNode(Location.Empty, "Q4", "Is this the forthQuestion?", QValueType.Boolean);

            _validAST = new FormNode(Location.Empty, "TestForm");
            _validAST.AddNode(firstQuestion);
            _validAST.AddNode(secondQuestion);

            _multipleFormAST = new FormNode(Location.Empty, "TestForm");
            _multipleFormAST.AddNode(new FormNode(Location.Empty, "InvalidForm"));

            _multipleFormInLowerNodeAST = new FormNode(Location.Empty, "InvalidForm");
            _multipleFormInLowerNodeAST.AddNode(thirdQuestion);
        }
Example #26
0
        private void EmitConditional(ConditionalNode node)
        {
            var hasTrueBlock  = node.TrueBlock != null && node.TrueBlock.Nodes.Any();
            var hasFalseBlock = node.FalseBlock != null && node.FalseBlock.Nodes.Any();

            if (!hasTrueBlock && !hasFalseBlock)
            {
                throw new VeilCompilerException("Conditionals must have a True or False block");
            }

            var done = emitter.DefineLabel();

            EvaluateExpression(node.Expression);

            if (node.Expression.ResultType == typeof(object))
            {
                emitter.CallMethod(boolifyMethod);
            }

            if (!hasTrueBlock)
            {
                emitter.BranchIfTrue(done);
                EmitNode(node.FalseBlock);
            }
            else if (!hasFalseBlock)
            {
                emitter.BranchIfFalse(done);
                EmitNode(node.TrueBlock);
            }
            else
            {
                var falseBlock = emitter.DefineLabel();

                emitter.BranchIfFalse(falseBlock);
                EmitNode(node.TrueBlock);
                emitter.Branch(done);

                emitter.MarkLabel(falseBlock);
                EmitNode(node.FalseBlock);
            }

            emitter.MarkLabel(done);
        }
Example #27
0
 public static void PrintSection(ConditionalNode conditional)
 {
     Console.WriteLine("\n" + conditional);
     foreach (QLNode section in conditional.Children)
     {
         if (section.GetType() == typeof(QuestionNode))
         {
             PrintSection(section as QuestionNode);
         }
         else if (section.GetType() == typeof(ComputedNode))
         {
             PrintSection(section as ComputedNode);
         }
         else
         {
             PrintSection(section as ConditionalNode);
         }
     }
 }
Example #28
0
 /**
  * Recursive method which executes a node but the node method might execute its own nodes first
  */
 private INode Execute(INode node)
 {
     try
     {
         return(node switch
         {
             DeclareIntVarNode declarerNode => declarerNode.Execute(declarerNode.Left as ReferenceNode,
                                                                    Execute(declarerNode.Right) as IntNode),
             IntOpNode opNode => opNode.Execute(Execute(opNode.Left) as IntNode,
                                                Execute(opNode.Right) as IntNode),
             ReferenceNode identity => new IntNode(identity.Value),
             FuncCallNode call => ExecuteFunctionCall(call),
             IntNode intNode => intNode,
             MethodNode method => ExecuteDeclareMethod(method),
             LoopNode loop => ExecuteLoopNode(loop),
             ConditionalNode conditional => ExecuteConditional(conditional),
             _ => new IntNode(-1)
         });
     }
        private Expression HandleConditional(ConditionalNode node)
        {
            var hasTrueBlock  = node.TrueBlock != null && node.TrueBlock.Nodes.Any();
            var hasFalseBlock = node.FalseBlock != null && node.FalseBlock.Nodes.Any();

            if (!hasTrueBlock && !hasFalseBlock)
            {
                throw new VeilCompilerException("Conditionals must have a True or False block", node);
            }

            var valueToCheck = ParseExpression(node.Expression);
            var booleanCheck = BoolifyExpression(valueToCheck);

            //var returnTarget = Expression.Label(typeof(Task));
            //var labelExpression = Expression.Label(returnTarget, Expression.Constant(null, typeof(Task)));

            if (!hasFalseBlock)
            {
                return(Expression.IfThen(booleanCheck, HandleAsync(HandleNode(node.TrueBlock))));

                //return Expression.Block(
                //    Expression.IfThen(
                //        booleanCheck,
                //        Expression.Return(returnTarget, HandleNode(node.TrueBlock))),
                //    labelExpression);
            }
            else if (!hasTrueBlock)
            {
                return(Expression.IfThen(Expression.IsFalse(booleanCheck), HandleAsync(HandleNode(node.FalseBlock))));
                //return Expression.Block(
                //    Expression.IfThen(
                //        Expression.IsFalse(booleanCheck),
                //        Expression.Return(returnTarget, HandleNode(node.FalseBlock))),
                //    labelExpression);
            }

            return(Expression.IfThenElse(booleanCheck, HandleAsync(HandleNode(node.TrueBlock)), HandleAsync(HandleNode(node.FalseBlock))));
            //return Expression.Block(
            //    Expression.IfThenElse(booleanCheck,
            //        Expression.Return(returnTarget, HandleNode(node.TrueBlock)),
            //        Expression.Return(returnTarget, HandleNode(node.FalseBlock))),
            //    labelExpression);
        }
Example #30
0
        public void ParseConditional()
        {
            bool b = false;
            Expression <Func <int> > f = () => b ? 1 : 2;
            var node = NaturalExpressionParser.Parse(f.Body);

            var expected = new ConditionalNode
            {
                Condition = new ConstantNode {
                    Text = "b", Value = "False"
                },
                TrueValue = new ConstantNode {
                    Text = "1"
                },
                FalseValue = new ConstantNode {
                    Text = "2"
                },
            };

            Assert.AreEqual(expected, node);
        }
        /// <summary>
        /// Add a Continue Condition node to the end of the chain.
        /// </summary>
        /// <param name="continueCondition">The condition required in order to continue</param>
        /// <param name="nodeName"></param>
        /// <param name="triggerOverrides">Triggers to use for transitions out of this node in liu of the configured machine-wide triggers.</param>
        protected void AddContinueCondition(IUmlConstraint continueCondition, string nodeName, params IUmlTrigger[] triggerOverrides)
        {
            if (!_isEditable)
            {
                throw new ActivityMachineException("Assembly can only be done while the machine is in an edit mode.");
            }

            WaitCount++;
            // Resulting Continue Guard: (DefaultContinueConstraint && condition)
            // Resulting Quit Guard:     (DefaultQuitConstraint)
            //TODO: use smarter way of sensing when previous node was a WAIT and therefore has to be followed by a constraint guarded transition
            var conditionalNode = new ConditionalNode(nodeName, Name, continueCondition)
            {
                LogType = LogType
            };

            // Give the node any overriding triggers. These will be the triggers that evaluate the conditional node's
            // constraint because the constraint becomes the Guard of the Continue Transition out of the new node.
            conditionalNode.OverridingTriggers.AddRange(triggerOverrides);
            AddNode(conditionalNode);
        }
Example #32
0
        private int ParseConditional(CompilationContext compilationContext, List<Token> tokens, int index,
                                     ref IActionNode currentParent)
        {
            Token currentToken;
            currentToken = tokens[++index]; // Open Bracket
            AssertExpectedTokenValue(currentToken, "(", "Expected Open Bracket");

            currentToken = tokens[++index]; // Parameters

            // Parse logical expression
            Expression expression;
            int skipTokens = ParseExpression(index - 1, tokens, compilationContext, out expression);
            index += (skipTokens - 2);
            currentToken = tokens[index]; // Close Bracket
            AssertExpectedTokenValue(currentToken, ")", "Expected Close Bracket");

            // Obtain consequence block
            var blockStream = new List<Token>();
            skipTokens = GetInnerBlock(index, tokens, ref blockStream);

            // Compile consequence
            IActionNode consequnce = Compile(blockStream, compilationContext);

            // Jump ahead in the Token stream
            index += skipTokens;
            if (index >= tokens.Count)
                throw new GossipScriptException("Unexpected end of input");

            currentToken = tokens[index];

            // Obtain Else consequence
            IActionNode elseConsequnce = null;
            if (tokens[index + 1].Value == "else")
            {
                var elseBlockStream = new List<Token>();
                skipTokens = GetInnerBlock(index + 1, tokens, ref elseBlockStream);
                elseConsequnce = Compile(elseBlockStream, compilationContext);

                // Jump ahead in the Token stream
                index += (skipTokens + 1);
                currentToken = tokens[index];
            }

            var conditionalCommand = new ConditionalNode(expression, consequnce, elseConsequnce);
            currentParent.Next = conditionalCommand;
            currentParent = currentParent.Next;
            return index;
        }