コード例 #1
0
 public override IExpression Rewrite(IConditional cond)
 {
     var newCond = new Conditional(cond);
     Switch.On(MutationTarget.PassInfo)
     .Case("to&&", () =>
     {
         newCond.ResultIfTrue = cond.ResultIfFalse;
         newCond.ResultIfFalse = new CompileTimeConstant
         {
             Type = cond.ResultIfTrue.Type,
             Value = false,
         };  
     })
     .Case("to||", () =>
     {
         newCond.ResultIfFalse = cond.ResultIfTrue;
         newCond.ResultIfTrue = new CompileTimeConstant
         {
             Type = cond.ResultIfFalse.Type,
             Value = true,
         };          
     }).ThrowIfNoMatch();
   
     return newCond;
 }
コード例 #2
0
            public override IExpression Rewrite(IConditional cond)
            {
                var newCond = new Conditional(cond);

                Switch.On(MutationTarget.PassInfo)
                .Case("to&&", () =>
                {
                    newCond.ResultIfTrue  = cond.ResultIfFalse;
                    newCond.ResultIfFalse = new CompileTimeConstant
                    {
                        Type  = cond.ResultIfTrue.Type,
                        Value = false,
                    };
                })
                .Case("to||", () =>
                {
                    newCond.ResultIfFalse = cond.ResultIfTrue;
                    newCond.ResultIfTrue  = new CompileTimeConstant
                    {
                        Type  = cond.ResultIfFalse.Type,
                        Value = true,
                    };
                }).ThrowIfNoMatch();

                return(newCond);
            }
コード例 #3
0
            public override void Visit(IConditional cond)
            {
                var passes = new List<string>();
                var boundCondition = cond.Condition as BoundExpression;
                
                if (boundCondition != null && boundCondition.Type.TypeCode == PrimitiveTypeCode.Boolean)
                {
                    var resultTrueBound = cond.ResultIfTrue as BoundExpression;
                    var resultFalseBound = cond.ResultIfFalse as BoundExpression;
                    var resultTrueConstant = cond.ResultIfTrue as CompileTimeConstant;
                    var resultFalseConstant = cond.ResultIfFalse as CompileTimeConstant;

                    if (resultTrueBound != null && resultTrueBound.Type.TypeCode == PrimitiveTypeCode.Boolean
                        && resultFalseConstant != null) // is &&
                    {
                        MarkMutationTarget(cond, "to||");
                    }
                    else if (resultTrueConstant != null && resultFalseBound != null 
                        && resultFalseBound.Type.TypeCode == PrimitiveTypeCode.Boolean) // is ||
                    {
                        MarkMutationTarget(cond, "to&&");
                    }
                }

              
            }
コード例 #4
0
        private void addWriter(IConditional condition, object writer)
        {
            var mediaType = typeof(Media <>).MakeGenericType(_resourceType);
            var media     = Activator.CreateInstance(mediaType, writer, condition ?? Always.Flyweight).As <IMedia>();

            _media.Add(media);
        }
コード例 #5
0
        private void ProcessReply(Reply reply)
        {
            progressTracker.activeReply = reply;
            progressTracker.iCounter++;
            if (reply.GetItem().GetEnumValue().ToString() != "None")
            {
                switch (reply.GetItem().GetEnumValue().ToString())
                {
                case "End":
                    if (conversation.GetArray().Length <= 1)
                    {
                        IConditional stage = (IConditional)conversation.GetArray()[progressTracker.activeStageIndex];
                        stage.MeetCondition();
                        EndConversation();
                        return;
                    }
                    progressTracker.activeStageIndex = 0;
                    progressTracker.iCounter         = 0;
                    progressTracker.useSelectedIndex = true;
                    break;

                case "ChangeStage":
                    progressTracker.activeStageIndex = reply.GetItem().ID;
                    progressTracker.iCounter         = 0;
                    break;

                case "ChangeBranch":
                    progressTracker.activeBranchIndex = reply.GetItem().ID;
                    progressTracker.iCounter          = 0;
                    break;
                }
            }
            DisplayData();
        }
コード例 #6
0
        public static bool TestActive(this IConditional conditional, ActiveFields fields)
        {
            // Test FieldCondition against current active Fields
            bool TestFieldCondition(FieldCondition fieldCondition)
            {
                // Required active field is not active
                if (fieldCondition.condition == true && !fields.baseInstance.Contains(fieldCondition.field))
                {
                    return(false);
                }

                // Required non-active field is active
                else if (fieldCondition.condition == false && fields.baseInstance.Contains(fieldCondition.field))
                {
                    return(false);
                }

                return(true);
            }

            // No FieldConditions
            if (conditional.fieldConditions == null)
            {
                return(true);
            }

            // One or more FieldConditions failed
            if (conditional.fieldConditions.Where(x => !TestFieldCondition(x)).Any())
            {
                return(false);
            }

            // All FieldConditions passed
            return(true);
        }
コード例 #7
0
ファイル: HLMethod.cs プロジェクト: Astaelan/Neutron
        private HLLocation ProcessConditionalExpression(IConditional pExpression)
        {
            HLLocation         locationCondition = ProcessExpression(pExpression.Condition);
            HLInstructionBlock blockParent       = mCurrentBlock;

            HLLocation locationResult = HLTemporaryLocation.Create(CreateTemporary(HLDomain.GetOrCreateType(pExpression.Type)));

            HLInstructionBlock blockTrueStart = CreateBlock(CreateLabel());

            mCurrentBlock = blockTrueStart;
            HLLocation locationTrue = ProcessExpression(pExpression.ResultIfTrue);

            mCurrentBlock.EmitAssignment(locationResult, locationTrue);
            HLInstructionBlock blockTrueEnd = mCurrentBlock;

            HLInstructionBlock blockFalseStart = CreateBlock(CreateLabel());

            mCurrentBlock = blockFalseStart;
            HLLocation locationFalse = ProcessExpression(pExpression.ResultIfFalse);

            mCurrentBlock.EmitAssignment(locationResult, locationFalse);
            HLInstructionBlock blockFalseEnd = mCurrentBlock;

            blockParent.EmitBranch(locationCondition, blockTrueStart.StartLabel, blockFalseStart.StartLabel);

            mCurrentBlock = CreateBlock(CreateLabel());
            blockTrueEnd.Terminate(mCurrentBlock.StartLabel);
            blockFalseEnd.Terminate(mCurrentBlock.StartLabel);

            return(locationResult);
        }
コード例 #8
0
    private void Awake()
    {
        conditional            = GetComponentInParent <IConditional>();
        conditional.onTryFire += HandleTryFire;

        OnAwake();
    }
コード例 #9
0
            public override IExpression Rewrite(IConditional cond)
            {
                IExpression result;

                result = cond.Condition;
                return(result);
            }
コード例 #10
0
        public override void TraverseChildren(IConditional conditional)
        {
            base.TraverseChildren(conditional);
            Conditional cond = (Conditional)conditional;

            cond.Condition = ConvertToBoolean(cond.Condition);
            if (!TypeHelper.TypesAreEquivalent(conditional.ResultIfTrue.Type, conditional.ResultIfFalse.Type))
            {
                var mergedType = TypeHelper.MergedType(TypeHelper.StackType(conditional.ResultIfTrue.Type), TypeHelper.StackType(conditional.ResultIfFalse.Type));
                if (mergedType.TypeCode == PrimitiveTypeCode.Int32)
                {
                    if (conditional.ResultIfTrue.Type.TypeCode == PrimitiveTypeCode.Boolean)
                    {
                        cond.ResultIfFalse = ConvertToBoolean(cond.ResultIfFalse);
                        mergedType         = cond.ResultIfTrue.Type;
                    }
                    else if (cond.ResultIfFalse.Type.TypeCode == PrimitiveTypeCode.Boolean)
                    {
                        cond.ResultIfTrue = ConvertToBoolean(cond.ResultIfTrue);
                        mergedType        = cond.ResultIfFalse.Type;
                    }
                }
                cond.Type = mergedType;
            }
        }
コード例 #11
0
        private void InternalProcess(string format, IPrinterElementFactory factory)
        {
            var finishedState = SMState.InvalidState;

            void ProcessIsComplete(SMState state)
            {
                finishedState = state;
            }

            var stateMachine = CreateStateMachine();

#if DEBUG
            //XXX temp while developing
            string s = Stateless.Graph.UmlDotGraph.Format(stateMachine.GetInfo());
#endif
            stateMachine.Fire(processTrigger, format, factory, ProcessIsComplete);

            if (finishedState.ErrorMessage != null)
            {
                throw new ArgumentException(finishedState.ErrorMessage);
            }
            elements = finishedState.Elements;
            if (finishedState.LogConditionals?.Count > 0)
            {
                GlobalConditional = finishedState.LogConditionals[0];
            }
        }
コード例 #12
0
            public bool RenderObjectProperties(GUIContent label)
            {
                bool dataChanged = false;

                _editorFoldout = EditorGUILayout.Foldout(_editorFoldout, "Condition (" + _condition + ")");
                if (_editorFoldout)
                {
                    int origIndent = EditorGUI.indentLevel;
                    EditorGUI.indentLevel++;

                    bool objectChanged;
                    _condition   = SerializedObjectEditorGUILayout.ObjectField(_condition, "Properties", out objectChanged);
                    dataChanged |= objectChanged;

                    EditorGUI.indentLevel = origIndent;
                }

                dataChanged |= _state.RenderObjectProperties(new GUIContent("Go to"));

                EditorGUI.BeginChangeCheck();
                _duration    = EditorGUILayout.FloatField("Time Window", _duration);
                dataChanged |= EditorGUI.EndChangeCheck();

                return(dataChanged);
            }
コード例 #13
0
 public DefaultAddGroupElementCommand(GroupName defaultName, IConditional <string, GroupName> names,
                                      IGroupCollection <T> collection)
     : base(new AddGroupElementCommand <T>(collection, new GroupName <T>(defaultName, names))
            .ToSelect()
            .UnlessIsOf(new GroupingAwareCommand <T>(collection).ToSelect())
            .ToCommand())
 {
 }
コード例 #14
0
        /*public static IFormatter Register<T>(this ISelectFormatter<T> @this)
         *      => FormatterRegistration.Default.Append(@this);*/

        public static IFormatter Append <T>(this IConditional <object, IFormattable> @this, ISelectFormatter <T> parameter)
        {
            var formatter = new Formatter <T>(Compose.Start.A.Selection.Of.Any.AndOf <T>()
                                              .By.Cast.Or.Throw.Select(new Formatters <T>(parameter)));
            var result = new Formatter(@this.Unless(formatter));

            return(result);
        }
コード例 #15
0
 public override void Visit(IConditional conditional)
 {
     if (Process(conditional))
     {
         visitor.Visit(conditional);
     }
     base.Visit(conditional);
 }
コード例 #16
0
        //This is for executing other statements
        private void traverseLeft()
        {
            UnityEngine.Debug.Log("traversing left of " + current.id);

            current = current.leftChild();

            if (current == null)
            {
                UnityEngine.Debug.Log("left was null");

                SyntaxNode currentBody = bodies.Peek();
                if (currentBody == null)
                {
                    return;
                }

                if (currentBody is IConditional)
                {
                    IConditional conditional = (IConditional)currentBody;


                    //Because I'm always traversing right, so it needs to check the loop again.
                    if (conditional.Type == ConditionalType.LOOP)
                    {
                        current = currentBody.getParent();
                    }
                    else
                    {
                        currentBody.doneExecuting();
                        //Hmm I don't want it to traverse right again, and can't just et to left child of parent
                        //cause no guarantee it's there, plus would mean skipping it, could set to parent, then recur to this,
                        current = currentBody.getParent();
                        bodies.Pop();
                        traverseLeft();
                    }
                }
                //If it's not a loop then just goes to left node of parent
                else
                {
                    if (currentBody != root)
                    {
                        current = currentBody.getParent().leftChild();
                    }
                }

                if (bodies.Count > 0)
                {
                    bodies.Pop();
                }
            }
            else if (current is IExecute)
            {
                UnityEngine.Debug.Log("Executing " + current.id);
                IExecute executable = (IExecute)current;
                executable.execute(this);
            }
        }
コード例 #17
0
ファイル: ViewAttachmentPolicy.cs プロジェクト: xeno3/fubumvc
        /// <summary>
        /// Create an attachment profile based on a runtime condition.  The original intent of view profiles
        /// was to enable multiple views per action based on the detected device of the user (desktop, tablet, smartphone),
        /// but is not limited to that functionality
        /// </summary>
        /// <param name="condition"></param>
        /// <param name="filter"></param>
        /// <param name="nameCorrection"></param>
        /// <returns></returns>
        public IViewProfile Profile(IConditional condition, Func <IViewToken, bool> filter,
                                    Func <IViewToken, string> nameCorrection)
        {
            _defaultExcludes.Add(filter);
            var profile = new ViewProfile(condition, filter, nameCorrection);

            _profiles.Add(profile);

            return(profile);
        }
コード例 #18
0
            public SMState AddLogConditional(IConditional conditional)
            {
                var clone = (SMState)Clone();

                if (clone.LogConditionals == null)
                {
                    clone.LogConditionals = new List <IConditional>();
                }
                clone.LogConditionals.Add(conditional);
                return(clone);
            }
コード例 #19
0
            public SMState AddConditionalForCurrentElement(IConditional conditional)
            {
                var clone = (SMState)Clone();

                if (clone.CurrentElementConditionals == null)
                {
                    clone.CurrentElementConditionals = new List <IConditional>();
                }
                clone.CurrentElementConditionals.Add(conditional);
                return(clone);
            }
コード例 #20
0
        public void Add(Type mediaWriterType, IConditional condition = null)
        {
            if (!mediaWriterType.Closes(typeof(IMediaWriter <>)) || !mediaWriterType.IsConcreteWithDefaultCtor())
            {
                throw new ArgumentOutOfRangeException("mediaWriterType", "mediaWriterType must implement IMediaWriter<T> and have a default constructor");
            }

            var writerType = mediaWriterType.MakeGenericType(_resourceType);
            var writer     = Activator.CreateInstance(writerType);

            addWriter(condition, writer);
        }
コード例 #21
0
        private static bool ConditionalHandler(YangStatement statement, IConditional partial)
        {
            if (statement.Keyword != "if-feature")
            {
                return(false);
            }

            if (partial.Features == null)
            {
                partial.Features = new List <string>();
            }

            partial.Features.Add(statement.Argument);
            return(true);
        }
コード例 #22
0
        /// <summary>
        /// Set the print mode value to use. This will reset any existing print mode values.
        /// </summary>
        /// <param name="mode">The print mode to use.</param>
        /// <param name="printer">The printer that will be using the print mode.</param>
        public void SetMode(string mode, IPrinter printer)
        {
            if (mode == null)
            {
                throw new ArgumentNullException(nameof(mode));
            }

            logConditional = null;
            elements       = null;

            var factory = printer.ElementFactory ?? new ElementFactory();
            var parser  = PrintModeParser.Parse(mode, factory);

            logConditional = parser.GlobalConditional;
            elements       = parser;
        }
コード例 #23
0
        /// <summary>
        ///   Sets the else action invocation for the event that not conditionals are satisfied
        /// </summary>
        /// <param name="conditional">
        ///   The <see cref="IConditional" /> in which to append
        /// </param>
        /// <param name="method">
        ///   The action to invoke if <paramref name="conditional" /> does not result in a satisfied conditional statement
        /// </param>
        /// <returns>
        ///   <see cref="IConditional" />
        /// </returns>
        public static IConditional Else([NotNull] this IConditional conditional,
                                        [NotNull] Action method)
        {
            if (conditional is null)
            {
                throw new ArgumentNullException(nameof(conditional));
            }

            if (method is null)
            {
                throw new ArgumentNullException(nameof(method));
            }

            conditional.SetElse(method);
            return(conditional);
        }
コード例 #24
0
ファイル: Condition.cs プロジェクト: ubaojin/UnityFramework
            public bool RenderObjectProperties(GUIContent label)
            {
                bool dataChanged = false;

                IConditional condition = DrawAddConditionalDropDown("Condition", _condition);

                if (_condition != condition)
                {
                    _condition  = condition;
                    dataChanged = true;
                }

                int origIndent = EditorGUI.indentLevel;

                EditorGUI.indentLevel++;

                if (_condition != null)
                {
                    if (_condition.AllowInverseVariant())
                    {
                        EditorGUI.BeginChangeCheck();
                        _not         = EditorGUILayout.Toggle("Not", _not);
                        dataChanged |= EditorGUI.EndChangeCheck();
                    }
                    else
                    {
                        _not = false;
                    }

                    _editorFoldout = EditorGUILayout.Foldout(_editorFoldout, "Properties");
                    if (_editorFoldout)
                    {
                        EditorGUI.indentLevel++;
                        bool objectChanged;
                        _condition   = SerializedObjectEditorGUILayout.ObjectField(_condition, "", out objectChanged);
                        dataChanged |= objectChanged;

                        EditorGUI.indentLevel--;
                    }
                }

                EditorGUI.indentLevel = origIndent;

                return(dataChanged);
            }
コード例 #25
0
		public ConditionalConverterContext(IConditional conditional, string[] names, Type type, object value, ConditionOperator? @operator = null, object defaultValue = null)
		{
			if(conditional == null)
				throw new ArgumentNullException("conditional");

			if(names == null || names.Length < 1)
				throw new ArgumentNullException("names");

			if(type == null)
				throw new ArgumentNullException("type");

			_conditional = conditional;
			_names = names;
			_type = type;
			_value = value;
			_operator = @operator;
			_defaultValue = defaultValue;
		}
コード例 #26
0
        //This is all body transferring
        private void traverseRight()
        {
            if (current.rightChild() == null)
            {
                traverseLeft();
                return;
            }


            BlockNode newBlock = current.rightChild();

            if (newBlock is IConditional)
            {
                IConditional lop = (IConditional)newBlock;

                if (!lop.didPass(this))
                {
                    if (lop is IfElseNode)
                    {
                        IfElseNode ifElse = (IfElseNode)lop;

                        if (ifElse.Else == null)
                        {
                            traverseLeft();
                        }
                        else
                        {
                            current = ifElse.Else;
                            bodies.Push(current);
                        }
                    }
                    else
                    {
                        traverseLeft();
                    }
                }
                else
                {
                    current = newBlock;
                    bodies.Push(current);
                }
            }
        }
コード例 #27
0
 public void Assign()
 {
     SetSceneParameters();
     for (int i = 0; i < SceneParameters.Length; i++)
     {
         for (int j = 0; j < SceneParameters[i].GetArray().Length; j++)
         {
             if (SceneParameters[i].GetArray()[j] is IConditional)
             {
                 IConditional conditional = (IConditional)SceneParameters[i].GetArray()[j];
                 if (conditional.GetIsConditionMet())
                 {
                     SceneParameters[i].CallInSequence(0);
                     continue;
                 }
             }
         }
     }
 }
コード例 #28
0
        public void Add(object writer, IConditional condition = null)
        {
            var mediaType = typeof(IMedia <>).MakeGenericType(_resourceType);

            if (writer.GetType().CanBeCastTo(mediaType))
            {
                _media.Add(writer.As <IMedia>());
                return;
            }

            var writerType = typeof(IMediaWriter <>).MakeGenericType(_resourceType);

            if (!writerType.IsAssignableFrom(writer.GetType()))
            {
                throw new ArgumentOutOfRangeException("writer", "writer must implement " + writerType.GetFullName());
            }

            addWriter(condition, writer);
        }
コード例 #29
0
        /// <summary>
        ///   Appends an additional conditional statement to the end of all other conditionals
        /// </summary>
        /// <param name="conditional">
        ///   The <see cref="IConditional" /> in which to append
        /// </param>
        /// <param name="condition">
        ///   The conditional function which satisfies whether the condition will be met
        /// </param>
        /// <param name="method">
        ///   The action to invoke if <paramref name="condition" /> results in <see langword="true" />
        /// </param>
        /// <returns>
        ///   <see cref="IConditional" />
        /// </returns>
        public static IConditional ElseIf([NotNull] this IConditional conditional, [NotNull] Func <bool> condition,
                                          [NotNull] Action method)
        {
            if (conditional is null)
            {
                throw new ArgumentNullException(nameof(conditional));
            }

            if (condition is null)
            {
                throw new ArgumentNullException(nameof(condition));
            }

            if (method is null)
            {
                throw new ArgumentNullException(nameof(method));
            }

            conditional.AppendElseIf(condition, method);
            return(conditional);
        }
コード例 #30
0
 public override IExpression Rewrite(IConditional conditional)
 {
     if (conditional.Type.TypeCode == PrimitiveTypeCode.Boolean && ExpressionHelper.IsIntegralZero(conditional.ResultIfTrue))
     {
         var not = new LogicalNot()
         {
             Operand = conditional.Condition,
         };
         var c = new Conditional()
         {
             Condition     = BooleanExpressionHelper.Normalize(not),
             ResultIfTrue  = conditional.ResultIfFalse,
             ResultIfFalse = new CompileTimeConstant()
             {
                 Type = conditional.Type, Value = false,
             },
             Type = conditional.Type,
         };
         return(c);
     }
     return(base.Rewrite(conditional));
 }
コード例 #31
0
        public ConditionalConverterContext(IConditional conditional, string[] names, Type type, object value, ConditionOperator? @operator = null, object defaultValue = null)
        {
            if (conditional == null)
            {
                throw new ArgumentNullException("conditional");
            }

            if (names == null || names.Length < 1)
            {
                throw new ArgumentNullException("names");
            }

            if (type == null)
            {
                throw new ArgumentNullException("type");
            }

            _conditional  = conditional;
            _names        = names;
            _type         = type;
            _value        = value;
            _operator     = @operator;
            _defaultValue = defaultValue;
        }
コード例 #32
0
ファイル: Condition.cs プロジェクト: ubaojin/UnityFramework
            public static IConditional DrawAddConditionalDropDown(string label, IConditional obj)
            {
                BuildConditionalMap();

                int currIndex = 0;

                if (obj != null)
                {
                    for (int i = 0; i < _conditionals.Length; i++)
                    {
                        if (_conditionals[i] == obj.GetType())
                        {
                            currIndex = i;
                            break;
                        }
                    }
                }

                EditorGUI.BeginChangeCheck();
                int index = EditorGUILayout.Popup(label, currIndex, _conditionalNames);

                //If type has changed create new conditional
                if (currIndex != index)
                {
                    if (index > 0)
                    {
                        obj = Activator.CreateInstance(_conditionals[index]) as IConditional;
                    }
                    else
                    {
                        obj = null;
                    }
                }

                return(obj);
            }
コード例 #33
0
            public override void Visit(IConditional cond)
            {
                var passes         = new List <string>();
                var boundCondition = cond.Condition as BoundExpression;

                if (boundCondition != null && boundCondition.Type.TypeCode == PrimitiveTypeCode.Boolean)
                {
                    var resultTrueBound     = cond.ResultIfTrue as BoundExpression;
                    var resultFalseBound    = cond.ResultIfFalse as BoundExpression;
                    var resultTrueConstant  = cond.ResultIfTrue as CompileTimeConstant;
                    var resultFalseConstant = cond.ResultIfFalse as CompileTimeConstant;

                    if (resultTrueBound != null && resultTrueBound.Type.TypeCode == PrimitiveTypeCode.Boolean &&
                        resultFalseConstant != null)    // is &&
                    {
                        MarkMutationTarget(cond, "to||");
                    }
                    else if (resultTrueConstant != null && resultFalseBound != null &&
                             resultFalseBound.Type.TypeCode == PrimitiveTypeCode.Boolean) // is ||
                    {
                        MarkMutationTarget(cond, "to&&");
                    }
                }
            }
コード例 #34
0
 public override void TraverseChildren(IConditional conditional) {
   base.TraverseChildren(conditional);
   FixUpType((Conditional)conditional);
 }
コード例 #35
0
    /// <summary>
    /// There aren't any logical-and expressions or logical-or expressions in CCI.
    /// Instead they are encoded as "x ? y : 0" for "x && y" and "x ? 1 : y"
    /// for "x || y".
    /// TODO:
    /// If it isn't either of these short forms then emit the proper expression!
    /// </summary>
    public override void TraverseChildren(IConditional conditional) {
      /*
      #region Try and reconstruct And, Or, Not expressions
      if (conditional.Type.TypeCode == PrimitiveTypeCode.Boolean) {
        CompileTimeConstant ctc = conditional.ResultIfFalse as CompileTimeConstant;
        if (ctc != null) {
          var v = BooleanValueOfCompileTimeConstant(ctc);
          if (!v) { // x ? y : "false or 0" == x && y
            Visit(conditional.Condition);
            Bpl.Expr x = TranslatedExpressions.Pop();
            x = PossiblyCoerceRefToBool(x);
            Visit(conditional.ResultIfTrue);
            Bpl.Expr y = TranslatedExpressions.Pop();
            y = PossiblyCoerceRefToBool(y);
            TranslatedExpressions.Push(Bpl.Expr.Binary(Bpl.BinaryOperator.Opcode.And, x, y));
            return;
          } else { // x ? y : "true or 1" == !x || y
            Visit(conditional.Condition);
            Bpl.Expr x = TranslatedExpressions.Pop();
            x = PossiblyCoerceRefToBool(x);
            Visit(conditional.ResultIfTrue);
            Bpl.Expr y = TranslatedExpressions.Pop();
            y = PossiblyCoerceRefToBool(y);
            var notX = Bpl.Expr.Unary(conditional.Token(), Bpl.UnaryOperator.Opcode.Not, x);
            TranslatedExpressions.Push(Bpl.Expr.Binary(Bpl.BinaryOperator.Opcode.Or, notX, y));
            return;
          }
        }
        ctc = conditional.ResultIfTrue as CompileTimeConstant;
        if (ctc != null && ctc.Type == BCT.Host.PlatformType.SystemInt32) {
          var v = BooleanValueOfCompileTimeConstant(ctc);
          if (v) { // x ? "true or 1" : y == x || y
            Visit(conditional.Condition);
            Bpl.Expr x = TranslatedExpressions.Pop();
            x = PossiblyCoerceRefToBool(x);
            Visit(conditional.ResultIfFalse);
            Bpl.Expr y = TranslatedExpressions.Pop();
            y = PossiblyCoerceRefToBool(y);
            TranslatedExpressions.Push(Bpl.Expr.Binary(Bpl.BinaryOperator.Opcode.Or, x, y));
            return;
          } else { // x ? "false or 0" : y == !x && y
            Visit(conditional.Condition);
            Bpl.Expr x = TranslatedExpressions.Pop();
            x = PossiblyCoerceRefToBool(x);
            Visit(conditional.ResultIfFalse);
            Bpl.Expr y = TranslatedExpressions.Pop();
            y = PossiblyCoerceRefToBool(y);
            var notX = Bpl.Expr.Unary(conditional.Token(), Bpl.UnaryOperator.Opcode.Not, x);
            TranslatedExpressions.Push(Bpl.Expr.Binary(Bpl.BinaryOperator.Opcode.And, notX, y));
            return;
          }
        }
      }
      #endregion

      #region Just translate it as an if-then-else expression
      base.Visit(conditional);
      var ifFalse = TranslatedExpressions.Pop();
      var ifTrue = TranslatedExpressions.Pop();
      var c = TranslatedExpressions.Pop();
      var tok = conditional.Token();
      TranslatedExpressions.Push(
        new Bpl.NAryExpr(tok, new Bpl.IfThenElse(tok), new List<Bpl.Expr>(c, ifTrue, ifFalse))
          );
      return;
      #endregion
      */


      // TODO is this code actually needed at all? It seems that all this is already being done in the Statement traverser for the conditional
      StatementTraverser thenStmtTraverser = this.StmtTraverser.factory.MakeStatementTraverser(this.sink, this.StmtTraverser.PdbReader, this.contractContext);
      StatementTraverser elseStmtTraverser = this.StmtTraverser.factory.MakeStatementTraverser(this.sink, this.StmtTraverser.PdbReader, this.contractContext);
      ExpressionTraverser thenExprTraverser = this.StmtTraverser.factory.MakeExpressionTraverser(this.sink, thenStmtTraverser, this.contractContext);
      ExpressionTraverser elseExprTraverser = this.StmtTraverser.factory.MakeExpressionTraverser(this.sink, elseStmtTraverser, this.contractContext);
      thenExprTraverser.Traverse(conditional.ResultIfTrue);
      elseExprTraverser.Traverse(conditional.ResultIfFalse);

      this.Traverse(conditional.Condition);
      Bpl.Expr conditionExpr = this.TranslatedExpressions.Pop();

      Bpl.IfCmd ifcmd = new Bpl.IfCmd(conditional.Token(),
          conditionExpr,
          thenStmtTraverser.StmtBuilder.Collect(conditional.ResultIfTrue.Token()),
          null,
          elseStmtTraverser.StmtBuilder.Collect(conditional.ResultIfFalse.Token())
          );

      this.StmtTraverser.StmtBuilder.Add(ifcmd);

      var ifFalse = elseExprTraverser.TranslatedExpressions.Pop();
      var ifTrue = thenExprTraverser.TranslatedExpressions.Pop();
      TranslatedExpressions.Push(new Bpl.NAryExpr(conditional.Token(), new Bpl.IfThenElse(conditional.Token()), new List<Bpl.Expr>(new Bpl.Expr[] {conditionExpr, ifTrue, ifFalse})));
    }
コード例 #36
0
 public WriterChoice(string mimeType, object writer, IConditional condition)
 {
     _mimeType = mimeType;
     _writer = Description.For(writer);
     _condition = Description.For(condition);
 }
コード例 #37
0
ファイル: Expressions.cs プロジェクト: riverar/devtools
 /// <summary>
 /// 
 /// </summary>
 /// <param name="conditional"></param>
 public Conditional(IConditional conditional)
     : base(conditional)
 {
     this.condition = conditional.Condition;
       this.resultIfFalse = conditional.ResultIfFalse;
       this.resultIfTrue = conditional.ResultIfTrue;
 }
コード例 #38
0
 public ConditionalBehavior(IConditional condition)
 {
     _condition = condition;
 }
コード例 #39
0
ファイル: Copier.cs プロジェクト: riverar/devtools
 public void Visit(IConditional conditional)
 {
     this.result = this.copier.Copy(conditional);
 }
コード例 #40
0
 private bool IsLogicalOr(IConditional conditional) {
   return conditional.Type.TypeCode == PrimitiveTypeCode.Boolean && ExpressionHelper.IsIntegralOne(conditional.ResultIfTrue);
 }
コード例 #41
0
    public override void TraverseChildren(IConditional conditional) {

      var needsParen = LowerPrecedenceThanParentExpression(conditional);
      var savedCurrentPrecedence = this.currentPrecedence;
      this.currentPrecedence = this.Precedence(conditional);

      if (needsParen) this.sourceEmitterOutput.Write("(");

      if (conditional.Type.TypeCode == PrimitiveTypeCode.Boolean) {
        if (ExpressionHelper.IsIntegralOne(conditional.ResultIfTrue)) {
          this.Traverse(conditional.Condition);
          this.sourceEmitterOutput.Write(" || ");
          this.Traverse(conditional.ResultIfFalse);
          goto Ret;
        }
        if (ExpressionHelper.IsIntegralZero(conditional.ResultIfFalse)) {
          this.Traverse(conditional.Condition);
          this.sourceEmitterOutput.Write(" && ");
          this.Traverse(conditional.ResultIfTrue);
          goto Ret;
        }
        if (ExpressionHelper.IsIntegralOne(conditional.ResultIfFalse)) {
          this.Traverse(conditional.Condition);
          this.sourceEmitterOutput.Write(" && ");
          var ln = conditional.ResultIfTrue as ILogicalNot;
          if (ln != null)
            this.Traverse(ln.Operand);
          else {
            this.sourceEmitterOutput.Write("!");
            var x = this.currentPrecedence;
            this.currentPrecedence = 13; // precedence of unary negation
            this.Traverse(conditional.ResultIfTrue);
            this.currentPrecedence = x;
          }
          goto Ret;
        }
        if (ExpressionHelper.IsIntegralZero(conditional.ResultIfTrue)) {
          var ln = conditional.Condition as ILogicalNot;
          if (ln != null) {
            this.Traverse(ln.Operand);
          } else {
            this.sourceEmitterOutput.Write("!");
            var x = this.currentPrecedence;
            this.currentPrecedence = 13; // precedence of unary negation
            this.Traverse(conditional.Condition);
            this.currentPrecedence = x;
          }
          this.sourceEmitterOutput.Write(" && ");
          this.Traverse(conditional.ResultIfFalse);
          goto Ret;
        }
      }
      this.Traverse(conditional.Condition);
      this.sourceEmitterOutput.Write(" ? ");
      this.Traverse(conditional.ResultIfTrue);
      this.sourceEmitterOutput.Write(" : ");
      this.Traverse(conditional.ResultIfFalse);

      Ret:
      if (needsParen) this.sourceEmitterOutput.Write(")");
      this.currentPrecedence = savedCurrentPrecedence;
    }
コード例 #42
0
ファイル: Visitors.cs プロジェクト: Refresh06/visualmutator
 /// <summary>
 /// Traverses the children of the conditional expression.
 /// </summary>
 public virtual void TraverseChildren(IConditional conditional)
 {
     Contract.Requires(conditional != null);
       this.TraverseChildren((IExpression)conditional);
       if (this.StopTraversal) return;
       this.Traverse(conditional.Condition);
       if (this.StopTraversal) return;
       this.Traverse(conditional.ResultIfTrue);
       if (this.StopTraversal) return;
       this.Traverse(conditional.ResultIfFalse);
 }
コード例 #43
0
ファイル: Visitors.cs プロジェクト: Refresh06/visualmutator
 public void Visit(IConditional conditional)
 {
     this.traverser.Traverse(conditional);
 }
コード例 #44
0
ファイル: Visitors.cs プロジェクト: Refresh06/visualmutator
 /// <summary>
 /// Traverses the conditional expression.
 /// </summary>
 public void Traverse(IConditional conditional)
 {
     Contract.Requires(conditional != null);
       if (this.preorderVisitor != null) this.preorderVisitor.Visit(conditional);
       if (this.StopTraversal) return;
       this.TraverseChildren(conditional);
       if (this.StopTraversal) return;
       if (this.postorderVisitor != null) this.postorderVisitor.Visit(conditional);
 }
コード例 #45
0
ファイル: Visitors.cs プロジェクト: Refresh06/visualmutator
 /// <summary>
 /// Performs some computation with the given conditional expression.
 /// </summary>
 /// <param name="conditional"></param>
 public virtual void Visit(IConditional conditional)
 {
 }
コード例 #46
0
ファイル: Copier.cs プロジェクト: Refresh06/visualmutator
    /// <summary>
    /// Returns a deep copy of the given conditional expression.
    /// </summary>
    /// <param name="conditional"></param>
    public Conditional Copy(IConditional conditional) {
      Contract.Requires(conditional != null);
      Contract.Ensures(Contract.Result<Conditional>() != null);

      var mutableCopy = this.shallowCopier.Copy(conditional);
      this.CopyChildren((Expression)mutableCopy);
      mutableCopy.Condition = this.Copy(mutableCopy.Condition);
      mutableCopy.ResultIfTrue = this.Copy(mutableCopy.ResultIfTrue);
      mutableCopy.ResultIfFalse = this.Copy(mutableCopy.ResultIfFalse);
      return mutableCopy;
    }
コード例 #47
0
 public static IViewToken ViewFor(this IOutputNode node, IConditional conditional)
 {
     var media = node.Media().Where(x => x.Writer is IViewWriter && x.Condition == conditional).FirstOrDefault();
     return media == null ? null : media.Writer.As<IViewWriter>().View;
 }
コード例 #48
0
ファイル: Copier.cs プロジェクト: Refresh06/visualmutator
    /// <summary>
    /// Returns a shallow copy of the given conditional expression.
    /// </summary>
    /// <param name="conditional"></param>
    public Conditional Copy(IConditional conditional) {
      Contract.Requires(conditional != null);
      Contract.Ensures(Contract.Result<Conditional>() != null);

      return new Conditional(conditional);
    }
コード例 #49
0
        public static void AddView(this IOutputNode node, IViewToken token, IConditional conditional)
        {
            var writer = typeof (ViewWriter<>).CloseAndBuildAs<object>(token, node.ResourceType);

            node.Add(writer, conditional);
        }
コード例 #50
0
ファイル: Copier.cs プロジェクト: riverar/devtools
 /// <summary>
 /// Returns a deep copy of the given conditional expression.
 /// </summary>
 /// <param name="conditional"></param>
 public Conditional Copy(IConditional conditional)
 {
     var mutableCopy = this.shallowCopier.Copy(conditional);
       this.CopyChildren((Expression)mutableCopy);
       mutableCopy.Condition = this.Copy(mutableCopy.Condition);
       mutableCopy.ResultIfTrue = this.Copy(mutableCopy.ResultIfTrue);
       mutableCopy.ResultIfFalse = this.Copy(mutableCopy.ResultIfFalse);
       return mutableCopy;
 }
コード例 #51
0
ファイル: Copier.cs プロジェクト: riverar/devtools
 /// <summary>
 /// Returns a shallow copy of the given conditional expression.
 /// </summary>
 /// <param name="conditional"></param>
 public Conditional Copy(IConditional conditional)
 {
     return new Conditional(conditional);
 }
コード例 #52
0
 /// <summary>
 /// There aren't any logical-and expressions or logical-or expressions in CCI.
 /// Instead they are encoded as "x ? y : 0" for "x && y" and "x ? 1 : y"
 /// for "x || y".
 /// TODO:
 /// If it isn't either of these short forms then emit the proper expression!
 /// </summary>
 public override void Visit(IConditional conditional) {
   CompileTimeConstant ctc = conditional.ResultIfFalse as CompileTimeConstant;
   if (ctc != null && ctc.Type == BCT.Host.PlatformType.SystemInt32) {
     int v = (int)ctc.Value;
     if (v == 0) {
       Visit(conditional.Condition);
       Bpl.Expr x = TranslatedExpressions.Pop();
       Visit(conditional.ResultIfTrue);
       Bpl.Expr y = TranslatedExpressions.Pop();
       TranslatedExpressions.Push(Bpl.Expr.Binary(Bpl.BinaryOperator.Opcode.And, x, y));
       return;
     }
   }
   ctc = conditional.ResultIfTrue as CompileTimeConstant;
   if (ctc != null && ctc.Type == BCT.Host.PlatformType.SystemInt32) {
     int v = (int)ctc.Value;
     if (v == 1) {
       Visit(conditional.Condition);
       Bpl.Expr x = TranslatedExpressions.Pop();
       Visit(conditional.ResultIfFalse);
       Bpl.Expr y = TranslatedExpressions.Pop();
       TranslatedExpressions.Push(Bpl.Expr.Binary(Bpl.BinaryOperator.Opcode.Or, x, y));
       return;
     }
   }
   base.Visit(conditional);
 }
コード例 #53
0
ファイル: Visitors.cs プロジェクト: Refresh06/visualmutator
 /// <summary>
 /// Performs some computation with the given conditional expression.
 /// </summary>
 /// <param name="conditional"></param>
 public virtual void Visit(IConditional conditional)
 {
     this.Visit((IExpression)conditional);
 }
コード例 #54
0
        public override void TraverseChildren(IConditional conditional)
{ MethodEnter(conditional);
            base.TraverseChildren(conditional);
     MethodExit();   }
コード例 #55
0
 private bool IsLogicalAnd(IConditional conditional) {
   if (conditional.Type.TypeCode == PrimitiveTypeCode.Boolean) {
     if (ExpressionHelper.IsIntegralZero(conditional.ResultIfFalse)) return true; // A ? B : false is code-model for conjunction
     if (ExpressionHelper.IsIntegralZero(conditional.ResultIfTrue)) return true; // A ? false : B is handled as !(A) && B in the traverser for conditionals
   }
   return false;
 }
コード例 #56
0
ファイル: Visitors.cs プロジェクト: Refresh06/visualmutator
 public void Visit(IConditional conditional)
 {
     Contract.Requires(conditional != null);
       throw new NotImplementedException();
 }
コード例 #57
0
 public virtual void onASTElement(IConditional conditional) { }
コード例 #58
0
ファイル: Visitors.cs プロジェクト: Refresh06/visualmutator
 //^ ensures this.path.Count == old(this.path.Count);
 /// <summary>
 /// Traverses the given conditional expression.
 /// </summary>
 /// <param name="conditional"></param>
 public virtual void Visit(IConditional conditional)
 {
     if (this.stopTraversal) return;
       //^ int oldCount = this.path.Count;
       this.path.Push(conditional);
       this.Visit(conditional.Condition);
       this.Visit(conditional.ResultIfTrue);
       this.Visit(conditional.ResultIfFalse);
       //^ assume this.path.Count == oldCount+1; //True because all of the virtual methods of this class promise not to decrease this.path.Count.
       this.path.Pop();
 }
コード例 #59
0
ファイル: Visitors.cs プロジェクト: Refresh06/visualmutator
 public void Visit(IConditional conditional)
 {
     throw new NotImplementedException();
 }
コード例 #60
0
ファイル: Copier.cs プロジェクト: riverar/devtools
 /// <summary>
 /// Visits the specified conditional.
 /// </summary>
 /// <param name="conditional">The conditional.</param>
 public override void Visit(IConditional conditional)
 {
     Conditional mutableConditional = new Conditional(conditional);
     this.resultExpression = this.myCodeCopier.DeepCopy(mutableConditional);
 }