private Activity ParseCore <T>(JsonElement node, CompositeActivityParser compositeParser)
        {
            var values     = node.GetProperty("values").GetString();
            var valueName  = node.GetProperty("valueName").GetString();
            var bodyExists = node.TryGetProperty("body", out var bodyNode);

            var @foreach = new ForEach <T>
            {
                DisplayName = ActivityParseUtil.GetDisplayName(node),
                Values      = new CSharpValue <IEnumerable <T> >(values)
            };

            var activityAction = new ActivityAction <T>
            {
                Argument = new DelegateInArgument <T>(valueName)
            };

            if (bodyExists)
            {
                activityAction.Handler = compositeParser.Parse(bodyNode);
            }

            @foreach.Body = activityAction;
            return(@foreach);
        }
Esempio n. 2
0
        /// <summary>
        /// Execute a for each statement
        /// </summary>
        /// <param name="statement">For each statement to be executed</param>
        public object VisitForeachStatement(ForEach statement)
        {
            // get the list from the for eeach statement
            var list = (List <object>)Evaluate(statement.List);

            try
            {
                for (int i = 0; i < list.Count; i++)
                {
                    // create new environment with old (current) one as parent
                    // add the identiifer to it and execute the block
                    Environment env = new Environment(Environment);
                    env.Add(statement.Identifier.Name.Lexeme, list[i]);
                    ExecuteBlock(statement.Block.Statements, env);
                    // re-assign the new value if it's changed
                    list[i] = env.GetValue(statement.Identifier.Name);
                }
            }
            catch (HlangBreak)
            {
                return(null);
            }

            return(null);
        }
Esempio n. 3
0
 private void ForEachSelectedTask(ForEach Delegate)
 {
     foreach (TaskListViewItem Item in View.CheckedItems)
     {
         Delegate((int)Item.Tag, Item);
     }
 }
 public void PrependValue()
 {
     1.PrependTo(ForEach.In(2, 3))
     .SequenceEqual(ForEach.In(1, 2, 3))
     .Should()
     .BeTrue();
 }
Esempio n. 5
0
        protected StackPanel CreateButtons()
        {
            var panel = new StackPanel();

            var okayButton = new Button();

            okayButton.Content = CreateOkayButtonContent();
            okayButton.Padding = DefaultMargin;
            okayButton.Click  += okayButtonHandler;
            panel.Children.Add(okayButton);

            var cancelButton = new Button();

            cancelButton.Content = CreateCancelButtonContent();
            cancelButton.Padding = DefaultMargin;
            cancelButton.Click  += cancelButtonHandler;
            panel.Children.Add(cancelButton);

            panel.Orientation         = Orientation.Horizontal;
            panel.HorizontalAlignment = HorizontalAlignment.Center;
            ForEach.MatchingType <FrameworkElement>(
                panel.Children,
                element => element.Margin = DefaultMargin
                );
            return(panel);
        }
 public void AppendValue()
 {
     ForEach.In(1, 2).Append(3)
     .SequenceEqual(ForEach.In(1, 2, 3))
     .Should()
     .BeTrue();
 }
Esempio n. 7
0
        static void snippet6()
        {
            //<snippet6>
            DelegateInArgument <string> actionArgument = new DelegateInArgument <string>();

            Activity wf = new ForEach <string>
            {
                Body = new ActivityAction <string>
                {
                    Argument = actionArgument,
                    Handler  = new WriteLine
                    {
                        Text = new InArgument <string>(actionArgument)
                    }
                }
            };

            List <string> items = new List <string>();

            items.Add("Hello");
            items.Add("World.");

            Dictionary <string, object> inputs = new Dictionary <string, object>();

            inputs.Add("Values", items);

            WorkflowInvoker.Invoke(wf, inputs);
            //</snippet6>
        }
Esempio n. 8
0
        public void LoopNoBody()
        {
            var tag = new ForEach();

            tag.Items = new MockAttribute(new Property("AList"));
            Assert.That(tag.Evaluate(new TagModel(this)), Is.EqualTo(String.Empty));
        }
Esempio n. 9
0
        private IEnumerable <Instruction> CopySet(TypeReference type, ValueSource source, ValueTarget target)
        {
            var typeOfArgument = type.GetGenericArguments().Single();

            var list = new List <Instruction>();

            using (new IfNotNull(list, source, target.IsTargetingBase))
            {
                VariableDefinition variable = null;
                if (!target.IsTargetingBase)
                {
                    list.AddRange(NewInstance(type, typeof(ISet <>), typeof(HashSet <>), out variable));
                }

                using (var forEach = new ForEach(this, list, type, source))
                {
                    list.AddRange(Copy(typeOfArgument,
                                       ValueSource.New().Variable(forEach.Current),
                                       ValueTarget.New().Instance(variable).Callvirt(ImportMethod(type.Resolve(), nameof(ISet <object> .Add), typeOfArgument)).Add(OpCodes.Pop)));
                }

                if (!target.IsTargetingBase)
                {
                    list.AddRange(target.Build(variable));
                }
            }

            return(list);
        }
Esempio n. 10
0
        static void snippet7()
        {
            //<snippet7>
            DelegateInArgument <string> actionArgument = new DelegateInArgument <string>();

            WriteLine output = new WriteLine();

            output.Text = new InArgument <string>(actionArgument);

            ActivityAction <string> body = new ActivityAction <string>();

            body.Argument = actionArgument;
            body.Handler  = output;

            ForEach <string> wf = new ForEach <string>();

            wf.Body = body;

            List <string> items = new List <string>();

            items.Add("Hello");
            items.Add("World.");

            Dictionary <string, object> inputs = new Dictionary <string, object>();

            inputs.Add("Values", items);

            WorkflowInvoker.Invoke(wf, inputs);
            //</snippet7>
        }
Esempio n. 11
0
 /// <summary>
 ///     Consume the source async sequence by emitting items and terminal signals via
 ///     the given <see cref="IAsyncConsumer{T}" /> consumer.
 /// </summary>
 /// <typeparam name="TSource">The element type.</typeparam>
 /// <param name="source">The source sequence to consume.</param>
 /// <param name="consumer">The push-awaitable consumer.</param>
 /// <param name="ct">The optional cancellation token to stop the consumption.</param>
 /// <returns>The task that is completed when the consumption terminates.</returns>
 public static ValueTask Consume <TSource>(this IAsyncEnumerable <TSource> source,
                                           IAsyncConsumer <TSource> consumer, CancellationToken ct = default)
 {
     RequireNonNull(source, nameof(source));
     RequireNonNull(consumer, nameof(consumer));
     return(ForEach.Consume(source, consumer, ct));
 }
 public void PairSelectorResults()
 {
     ForEach.In(1, 2, 3)
     .PairedWith(i => i.ToString())
     .All(ir => int.Parse(ir.result) == ir.item)
     .Should()
     .BeTrue();
 }
 public void FilterByType()
 {
     ForEach.In <object>(1, "2", 3)
     .WhereIs <int>()
     .SequenceEqual(ForEach.In(1, 3))
     .Should()
     .BeTrue();
 }
Esempio n. 14
0
        public void LoopNoBody()
        {
            var tag = new ForEach();

            tag.Select = new MockAttribute(new Constant("//value"));
            tag.Source = new MockAttribute(new Constant("xml"));
            Assert.That(tag.Evaluate(_model), Is.EqualTo(String.Empty));
        }
Esempio n. 15
0
        public void LoopWithComplexStatusBody()
        {
            var tag = new ForEach();

            tag.Items = new MockAttribute(new Property("AList"));
            tag.Body  = new TemplateAttribute(new Formatter(ComplexStatusBody).Parse().ParsedTemplate);
            Assert.That(tag.Evaluate(new TagModel(this)), Is.EqualTo("[0/7][1/7][2/7][3/7][4/7][5/7][6/7]"));
        }
 public void SkipIndexOfArray()
 {
     new int[] { 1, 2, 3 }
     .ExceptIndex(1)
     .SequenceEqual(ForEach.In(1, 3))
     .Should()
     .BeTrue();
 }
 public void SkipIndexOfEnumerable()
 {
     ForEach.In(1, 2, 3)
     .ExceptIndex(1)
     .SequenceEqual(ForEach.In(1, 3))
     .Should()
     .BeTrue();
 }
Esempio n. 18
0
        public void LoopWithSimpleBody()
        {
            var tag = new ForEach();

            tag.Items = new MockAttribute(new Property("AList"));
            tag.Body  = new MockAttribute(new Property("Body"));
            Assert.That(tag.Evaluate(new TagModel(this)), Is.EqualTo(Body + Body + Body + Body + Body + Body + Body));
        }
Esempio n. 19
0
        public static Constraint HasParent <TActivity>(Func <Activity, bool> condition, string validationMessage) where TActivity : Activity
        {
            DelegateInArgument <TActivity>         delegateInArgument1 = new DelegateInArgument <TActivity>();
            DelegateInArgument <ValidationContext> delegateInArgument2 = new DelegateInArgument <ValidationContext>();
            Variable <bool> variable                  = new Variable <bool>();
            DelegateInArgument <Activity> parent      = new DelegateInArgument <Activity>();
            Constraint <TActivity>        constraint1 = new Constraint <TActivity>();
            Constraint <TActivity>        constraint2 = constraint1;
            ActivityAction <TActivity, ValidationContext> activityAction1 = new ActivityAction <TActivity, ValidationContext>();

            activityAction1.Argument1 = delegateInArgument1;
            activityAction1.Argument2 = delegateInArgument2;
            ActivityAction <TActivity, ValidationContext> activityAction2 = activityAction1;
            Sequence sequence1 = new Sequence();

            sequence1.Variables.Add((Variable)variable);
            Collection <Activity> activities = sequence1.Activities;
            ForEach <Activity>    forEach1   = new ForEach <Activity>();

            forEach1.Values = (InArgument <IEnumerable <Activity> >)((Activity <IEnumerable <Activity> >) new GetParentChain()
            {
                ValidationContext = (InArgument <ValidationContext>)((DelegateArgument)delegateInArgument2)
            });
            ForEach <Activity>        forEach2        = forEach1;
            ActivityAction <Activity> activityAction3 = new ActivityAction <Activity>();

            activityAction3.Argument = parent;
            ActivityAction <Activity> activityAction4 = activityAction3;
            If if1 = new If();

            if1.Condition = new InArgument <bool>((Expression <Func <ActivityContext, bool> >)(ctx => condition(parent.Get(ctx))));
            if1.Then      = (Activity) new Assign <bool>()
            {
                Value = (InArgument <bool>)true,
                To    = (OutArgument <bool>)((Variable)variable)
            };
            If if2 = if1;

            activityAction4.Handler = (Activity)if2;
            ActivityAction <Activity> activityAction5 = activityAction3;

            forEach2.Body = activityAction5;
            ForEach <Activity> forEach3 = forEach1;

            activities.Add((Activity)forEach3);
            sequence1.Activities.Add((Activity) new AssertValidation()
            {
                Assertion = new InArgument <bool>((Variable)variable),
                Message   = new InArgument <string>(validationMessage)
            });
            Sequence sequence2 = sequence1;

            activityAction2.Handler = (Activity)sequence2;
            ActivityAction <TActivity, ValidationContext> activityAction6 = activityAction1;

            constraint2.Body = activityAction6;
            return((Constraint)constraint1);
        }
Esempio n. 20
0
        public void LoopWithEvaluatingBody()
        {
            var tag = new ForEach();

            tag.Select = new MockAttribute(new Constant("//value"));
            tag.Source = new MockAttribute(new Constant("xml"));
            tag.Body   = new TemplateAttribute(new Formatter("<x:out source=\"Item\" select=\".\"/>").Parse().ParsedTemplate);
            Assert.That(tag.Evaluate(_model), Is.EqualTo("AbCdEfGhIjKlMnOpQrStUvWxYz"));
        }
Esempio n. 21
0
        public void LoopWithStepAndBodyWithFilterInSelect()
        {
            var tag = new ForEach();

            tag.Select = new MockAttribute(new Constant("//value[@flag=\"uppercase\"]"));
            tag.Source = new MockAttribute(new Constant("xml"));
            tag.Body   = new TemplateAttribute(new Formatter("<x:out source=\"Item\" select=\".\"/>").Parse().ParsedTemplate);
            Assert.That(tag.Evaluate(_model), Is.EqualTo("ACEGIKMOQSUWY"));
        }
Esempio n. 22
0
 public object VisitForeachStatement(ForEach statement)
 {
     _callingBodyStack.Push(CallingBody.FOR_EACH);
     Resolve(statement.Identifier);
     Resolve(statement.List);
     Resolve(statement.Block);
     _callingBodyStack.Pop();
     return(null);
 }
Esempio n. 23
0
        public void DrawGlyphsAtPoints(ForEach <char> glyphs, TestFont font, ForEach <PointF> points, Structures.Color?color)
        {
            var zipped = glyphs.Zip(points);
            var bounds = TestTypesettingContexts.Instance.GlyphBoundsProvider.GetBoundingRectsForGlyphs(font, glyphs, zipped.Count);

            foreach (var((glyph, point), bound) in zipped.Zip(bounds, ValueTuple.Create))
            {
                Checker.ConsoleDrawRectangle(new Rectangle((int)(point.X + trans.X), (int)(point.Y + trans.Y), (int)bound.Width, (int)bound.Height), glyph, color);
            }
        }
Esempio n. 24
0
        public void LoopWithComplexStatusBody()
        {
            var tag = new ForEach();

            tag.Select = new MockAttribute(new Constant("//value"));
            tag.Source = new MockAttribute(new Constant("xml"));
            tag.End    = new MockAttribute(new Constant("7"));
            tag.Body   = new TemplateAttribute(new Formatter("[${Status.Index}/${Status.Count}]").Parse().ParsedTemplate);
            Assert.That(tag.Evaluate(_model), Is.EqualTo("[0/26][1/26][2/26][3/26][4/26][5/26][6/26]"));
        }
 public void SkipIndexOfList()
 {
     new List <int> {
         1, 2, 3
     }
     .ExceptIndex(1)
     .SequenceEqual(ForEach.In(1, 3))
     .Should()
     .BeTrue();
 }
        public IEnumerable <RectangleF> GetBoundingRectsForGlyphs(TFont font, ForEach <TGlyph> glyphs, int nVariants)
        {
            var glyphArray = new TGlyph[nVariants];

            glyphs.CopyTo(glyphArray);
            var rects = new CGRect[nVariants];

            font.CtFont.GetBoundingRects(CTFontOrientation.Horizontal, glyphArray, rects, nVariants);
            return(rects.Select(rect => (RectangleF)rect));
        }
Esempio n. 27
0
 protected override RunStatus Yield(BehaviorObject obj)
 {
     Debug.Log("CrowdBehaviorEvent: Yielding " + obj.ToString());
     if (this.participants.Contains(obj))
     {
         ForEach <T> root = (ForEach <T>) this.treeRoot;
         return(root.RemoveParticipant(this.behaviorObjToParticipant[obj]));
     }
     return(RunStatus.Success);
 }
Esempio n. 28
0
        public void DebugWriteLine(ForEach <TGlyph> glyphs, ForEach <PointF> points)
        {
            var glyphStrings = glyphs.Select(g => ((int)g).ToString());
            var pointStrings = points.Select(pt => $@"{pt.X} {pt.Y}");

            for (int i = 0; i < glyphStrings.Count; i++)
            {
                Debug.WriteLine($"    {glyphStrings[i]} {pointStrings[i]}");
            }
            Debug.WriteLine($"glyphs {glyphStrings} {pointStrings}");
        }
Esempio n. 29
0
        public virtual void ForEach <TSource>(IObservable <TSource> source, Action <TSource> onNext)
        {
            using var sink = new ForEach <TSource> .Observer(onNext);

            using (source.SubscribeSafe(sink))
            {
                sink.Wait();
            }

            sink.Error?.Throw();
        }
Esempio n. 30
0
        public void LoopWithFirstEndAndStepComplexBody()
        {
            var tag = new ForEach();

            tag.Items = new MockAttribute(new Property("AList"));
            tag.Begin = new MockAttribute(new Constant("1"));
            tag.End   = new MockAttribute(new Constant("6"));
            tag.Step  = new MockAttribute(new Constant("2"));
            tag.Body  = new TemplateAttribute(new Formatter(ComplexBody).Parse().ParsedTemplate);
            Assert.That(tag.Evaluate(new TagModel(this)), Is.EqualTo("[2][4][6]"));
        }
Esempio n. 31
0
    protected Node BuildTreeRoot()
    {
        ForEach<GameObject> dance = new ForEach<GameObject>((daniel) =>
        {
            return new DecoratorLoop(this.ST_Gesture(daniel, 2));
        }, eaters);

        Sequence Eating = new Sequence(
            new DecoratorLoop(
             new SelectorParallel(
                this.ST_pickUpAndEatFood(eff[1], obj[0], locations[0], 0, objReset[0], locations[1]),
                this.ST_pickUpAndEatFood(eff[1], obj[1], locations[2], 1, objReset[1], locations[1]),
                this.ST_pickUpAndEatFood(eff[1], obj[2], locations[3], 2, objReset[2], locations[4]),
                this.ST_pickUpAndEatFood(eff[1], obj[3], locations[5], 3, objReset[3], locations[4]),
                this.ST_pickUpAndEatFood(eff[1], obj[4], locations[6], 4, objReset[4], locations[7]),
                this.ST_pickUpAndEatFood(eff[1], obj[5], locations[8], 5, objReset[5], locations[7])

            )));

        ForEach<GameObject> middleStory = new ForEach<GameObject>((daniel) =>
        {

            return new Sequence(

                 new DecoratorLoop(

                    new SequenceShuffle(

                        this.ST_ApproachAndWait(daniel, locations[9]),
                        this.ST_ApproachAndWait(daniel, locations[10]),
                        this.ST_ApproachAndWait(daniel, locations[13]),
                        this.ST_ApproachAndWait(daniel, locations[14]),
                        this.ST_ApproachAndWait(daniel, locations[15]),
                        this.ST_Gesture(daniel, 2))));

            }, wanderers);

        return new SequenceParallel(middleStory, Eating, dance);
    }
Esempio n. 32
0
 public override Expression VisitApplyToAll(ApplyToAll applyToAll){
   if (applyToAll == null) return null;
   CollectionEnumerator cEnumerator = applyToAll.Operand1 as CollectionEnumerator;
   AnonymousNestedFunction func = applyToAll.Operand2 as AnonymousNestedFunction;
   if (func != null) this.VisitAnonymousNestedFunction(func);
   Expression cc = this.currentClosureLocal;
   if (cEnumerator == null) {
     Debug.Assert(cc != null, "VisitApplyToAll: no closure");  
     Debug.Assert(func != null, "VisitApplyToAll: no function");
     if (cc == null || func == null) return null;
     cc = this.GetBindingPath(cc, func.Method.DeclaringType);
     return new MethodCall(new MemberBinding(cc, func.Method), new ExpressionList(this.VisitExpression(applyToAll.Operand1)),
       NodeType.Call, func.Method.ReturnType, cc.SourceContext);
   }
   Debug.Assert(cEnumerator.Collection != null, "VisitApplyToAll: no collection");
   if (cEnumerator.Collection == null) return null;
   Method method = applyToAll.ResultIterator;
   if (method != null) {
     Debug.Assert(cc != null, "VisitApplyToAll: no closure");
     if (cc == null) return null;
     cc = this.GetBindingPath(cc, method.DeclaringType);
     this.VisitMethod(method);
     Expression coll = this.VisitExpression(cEnumerator.Collection);
     if (coll == null) return null;
     if (func != null)
       return new MethodCall(new MemberBinding(cc, method), new ExpressionList(coll, cc), NodeType.Call, applyToAll.Type);
     else
       return new MethodCall(new MemberBinding(cc, method), new ExpressionList(coll), NodeType.Call, applyToAll.Type);
   }
   ForEach forEach = new ForEach();
   forEach.SourceContext = applyToAll.SourceContext;
   forEach.SourceEnumerable = cEnumerator;
   if (func != null) {
     MemberBinding mb = new MemberBinding(cc, func.Method);
     MethodCall call = new MethodCall(mb, new ExpressionList(cEnumerator.ElementLocal), NodeType.Call, func.Method.ReturnType, cc.SourceContext);
     forEach.Body = new Block(new StatementList(new ExpressionStatement(call)));
   }
   else {
     BlockExpression be = applyToAll.Operand2 as BlockExpression;
     Debug.Assert(be != null, "VisitApplyToAll: Bad operand type");
     if (be == null) return null;
     Block b = new Block(new StatementList(2));
     b.Statements.Add(new AssignmentStatement(applyToAll.ElementLocal, cEnumerator.ElementLocal));
     b.Statements.Add(be.Block);
     forEach.Body = b;
   }
   forEach.ScopeForTemporaryVariables = new BlockScope(this.currentMethod.Scope, forEach.Body);
   return this.VisitBlockExpression(new BlockExpression(new Block(new StatementList(forEach)), SystemTypes.Void));
 }
    protected Node BuildTreeRoot()
    {
        daniels = GameObject.FindGameObjectsWithTag ("Daniel");

        Sequence beginStory = new Sequence (
            this.SetCamera(0),
            this.ShowAct(0),
            new SequenceParallel (
                this.ST_ApproachAndWait (benchGuy1, this.wander2),
                this.ST_ApproachAndWait (benchGuy2, this.wander2)
            ),
            this.LookAt (benchGuy2, benchGuy1),
            this.Quote ("Hey man, I wanted to use that."),
            new LeafWait(2000),
            this.Quote ("Pssh, get out of my way."),
            new LeafWait(2000),
            this.Quote ("Unfortunately for you, I have inverse kinematic punches enabled."),
            new DecoratorLoop(3, new Sequence(
                this.Punch (benchGuy1, benchGuy2),
                this.Punch (benchGuy2, benchGuy1)
            )),
            this.Quote ("Yeah that's what I thought."),
            this.ST_ApproachAndWait (benchGuy1, this.wander1)
        );

        ForEach<GameObject> middleStory = new ForEach<GameObject> (
            (daniel) => {
            return new Sequence (
                this.ShowAct(1),
                this.SetCamera(2),
                this.Quote ("Now it's time to work out!"),
                new DecoratorLoop(6, new SequenceShuffle(
                    this.Squat (daniel),
                    this.Punch (daniel, punchee)
                )),
                new LeafWait(1000),
                this.BecomeCrab (daniel),
                new LeafWait(1000)
                );
        }
        , daniels);

        ForEach<GameObject> endStory = new ForEach<GameObject> (
            (daniel) => {
            return new Sequence(
                this.ShowAct(2),
                this.SetCamera (1),
                this.Quote ("The time has come to choose a new Crab God."),
                new LeafWait(1000),
                this.ST_ApproachAndWaitDemonFire(daniel),
                this.CheckFirstGuy(daniel),
                this.Quote ("HAHA! I am the new Crab God now, bow to me lesser beings!"),
                new LeafWait(1000),
                this.ShowAct(3)
                );
        }, daniels );

        return new Sequence(beginStory, middleStory, endStory);
    }
Esempio n. 34
0
 public override Statement VisitForEach(ForEach forEach){
   if (forEach == null) return null;
   Scope savedScope = this.scope;
   Scope scope = this.scope = forEach.ScopeForTemporaryVariables = new BlockScope(savedScope, forEach.Body);
   this.AddToAllScopes(this.scope);
   forEach.TargetVariableType = this.VisitTypeReference(forEach.TargetVariableType, true);
   forEach.SourceEnumerable = this.VisitExpression(forEach.SourceEnumerable);
   Identifier inductionVariableId = forEach.InductionVariable as Identifier;
   if (inductionVariableId != null){
     Local inductionVariable =
       new Local(
       inductionVariableId,
       OptionalModifier.For(SystemTypes.NonNullType, SystemTypes.GenericList.GetGenericTemplateInstance(this.currentModule, new TypeNodeList(forEach.TargetVariableType))),
       inductionVariableId.SourceContext);
     forEach.InductionVariable = inductionVariable;
     if (forEach.Invariants != null){
       StandardVisitor visitor = new ReplaceInductionVariable(inductionVariable);
       forEach.Invariants = visitor.VisitLoopInvariantList(forEach.Invariants);
     }
   }
   forEach.Invariants = this.VisitLoopInvariantList(forEach.Invariants);
   Identifier targetId = forEach.TargetVariable as Identifier;
   if (targetId != null){
     Field f = new Field();
     f.DeclaringType = scope;
     f.Flags = FieldFlags.CompilerControlled|FieldFlags.InitOnly;
     f.Name = targetId;
     f.Type = forEach.TargetVariableType;
     scope.Members.Add(f);
     forEach.TargetVariable = new MemberBinding(new ImplicitThis(scope, 0), f);
     forEach.TargetVariable.SourceContext = targetId.SourceContext;
     this.AddNodePositionAndInfo(targetId, forEach.TargetVariable, IdentifierContexts.AllContext);
   }
   forEach.Body = this.VisitBlock(forEach.Body);
   if (forEach.Body != null) forEach.Body.HasLocals = true;
   this.scope = savedScope;
   return forEach;
 }
Esempio n. 35
0
    // {1,2,3} ==>
    //     { [ / (IList/IDictionary) t = new T(); ] 
    //       [ yield return 1 / t.Add(1) ];
    //       ...
    //       [  / return (T) t ];
    //     }
    // { T1 x in A, P(x); B(x) ; default } ==> 
    //     {  [ /(IList/IDictionary) t = new T(); ]
    //        bool empty = true; // only for compr. with default
    //        foreach(T1 x in A) { if P(x){ empty = false; [ yield return B(x) / t.Add(B(x)) ];} }
    //        if (empty) [ yield return default / t.Add(default) ]; // only for compr. with default
    //        [ / return (T)t];
    //     }
    public override Expression VisitComprehension(Comprehension comprehension){
      if (comprehension == null) return null;
      Block b = new Block(new StatementList()); // return value from this visitor
      Expression empty = null; // will be either a local or a field
      #region Local variables used when in a non-Enumerable context.
      // TODO: could be a structure, not a class!! (at least write some test cases)
      TypeNode nonEnumClass = null;
      Local retVal = null;
      Method addMethod = null;
      NodeType addMethodCallType = NodeType.Callvirt; // assume virtual calls
      bool useIListMethods = false;
      // use a local so it is evaluated only once in case of side-effects for get_Key and get_Value
      Local de = null;
      Method keyMethod = null;
      Method valueMethod = null;
      #endregion

      bool defaultIsPresent = !comprehension.IsDisplay && comprehension.Elements.Count > 1;
      bool notEnumContext = comprehension.nonEnumerableTypeCtor != null;

      #region Set non-Enumerable locals to the appropriate values.
      // TODO: Look for these things in Checker and if it can't find them, issue diagnostics
      if (notEnumContext){
        Method tempM = comprehension.nonEnumerableTypeCtor as Method;
        addMethod = comprehension.AddMethod;
        if (!addMethod.IsVirtual)
          addMethodCallType = NodeType.Call;
        keyMethod = SystemTypes.DictionaryEntry.GetMethod(Identifier.For("get_Key"));
        valueMethod = SystemTypes.DictionaryEntry.GetMethod(Identifier.For("get_Value"));
 

        if (tempM != null)
          nonEnumClass = (Class) tempM.DeclaringType;
        else
          nonEnumClass = (TypeNode) comprehension.nonEnumerableTypeCtor;
        TypeNode elementType = TypeNode.StripModifiers(comprehension.TemporaryHackToHoldType).TemplateArguments[0];
        if (this.GetTypeView(nonEnumClass).IsAssignableTo(SystemTypes.IList)){
          retVal = new Local(Identifier.For("SS$retVal"),SystemTypes.IList,b);
          useIListMethods = true;
        } else if ((comprehension.Elements.Count == 0 || this.GetTypeView(elementType).IsAssignableTo(SystemTypes.DictionaryEntry)) && this.GetTypeView(nonEnumClass).IsAssignableTo(SystemTypes.IDictionary)){
          retVal = new Local(Identifier.For("SS$retVal"),SystemTypes.IDictionary,b);
          useIListMethods = false; // means "use IDictionary methods"
          de = new Local(Identifier.For("SS$dictionaryEntry"),SystemTypes.DictionaryEntry,b);
          Debug.Assert(de != null && keyMethod != null && valueMethod != null);
        } else if ((comprehension.Elements.Count == 0 || this.GetTypeView(elementType).IsAssignableTo(SystemTypes.DictionaryEntry)) && addMethod != null && addMethod.GetParameterTypes().Length == 2){
          retVal = new Local(Identifier.For("SS$retVal"),nonEnumClass,b);
          useIListMethods = false; // means "use IDictionary methods"
          de = new Local(Identifier.For("SS$dictionaryEntry"),SystemTypes.DictionaryEntry,b);
          Debug.Assert(de != null && keyMethod != null && valueMethod != null);
        } else if (addMethod != null){
          retVal = new Local(Identifier.For("SS$retVal"),nonEnumClass,b);
          useIListMethods = true;
        }
        Debug.Assert(retVal != null && addMethod != null);
      }
      if (defaultIsPresent){
        if (notEnumContext){
          empty = new Local(Identifier.For("SS$empty"),SystemTypes.Boolean,b);
        }else{
          Field emptyField = new Field(Identifier.Empty);
          Class scope = null;
          // defaultIsPresent ==> comprehension.Elements != null
          for (int i = 0, n = comprehension.Elements.Count; i < n; i++){
            // really it should always be the first one, but better be careful
            ComprehensionBinding cb = comprehension.BindingsAndFilters[i] as ComprehensionBinding;
            if (cb != null){
              scope = cb.ScopeForTemporaryVariables.ClosureClass;
              break;
            }
          }
          Debug.Assert(scope != null); //TODO: this assert actually fires
          emptyField.DeclaringType = scope;
          emptyField.Flags = FieldFlags.CompilerControlled;
          emptyField.Name = Identifier.For("SS$empty: "+comprehension.GetHashCode());
          emptyField.Type = SystemTypes.Boolean;
          scope.Members.Add(emptyField);
          empty = new MemberBinding(new ImplicitThis(scope, 0), emptyField);
        }
      }
      #endregion

      #region retVal := new T();
      if (notEnumContext){
        Method m = comprehension.nonEnumerableTypeCtor as Method;
        if (m != null)
          b.Statements.Add(new AssignmentStatement(retVal,
            new Construct(new MemberBinding(null,m),new ExpressionList(),nonEnumClass)));
        else{
          TypeNode structure = comprehension.nonEnumerableTypeCtor as TypeNode;
          b.Statements.Add(new AssignmentStatement(retVal, new Local(StandardIds.NewObj,nonEnumClass))); // !!!! Local normalizes to a pseudo-ctor call for a structure!
        }
      }
      #endregion
      #region bool empty := true;
      if (defaultIsPresent){
        b.Statements.Add(new AssignmentStatement(empty,new Literal(true,SystemTypes.Boolean)));
      }
      #endregion
      #region Generate code for Displays
      if (comprehension.IsDisplay){
        for (int i = 0, n = comprehension.Elements.Count; i < n; i++){
          //          Statement s =
          //            notEnumContext ?
          //            new ExpressionStatement(new MethodCall(new MemberBinding(retVal,addMethod),new ExpressionList(Box(comprehension.Elements[i])),
          //            (retVal.Type.IsValueType ? NodeType.Call : NodeType.Callvirt),
          //            SystemTypes.Int32,comprehension.SourceContext))
          //            :
          //            new Yield(comprehension.Elements[i])
          //            ;
          if (useIListMethods){
            if (notEnumContext)
              b.Statements.Add(new ExpressionStatement(new MethodCall(new MemberBinding(retVal,addMethod),new ExpressionList(Box(comprehension.Elements[i])),
                addMethodCallType, SystemTypes.Int32,comprehension.SourceContext)));
            else
              b.Statements.Add(new Yield(comprehension.Elements[i]));

          }else{ // assume IDictionary!
            if (notEnumContext) {
              b.Statements.Add(new AssignmentStatement(de,comprehension.Elements[i]));
              //retval.Add(de.Key,de.Value) (actually, it is "reval.Add(de.get_Key(),de.get_Value())")
              b.Statements.Add(
                new ExpressionStatement(
                new MethodCall(new MemberBinding(retVal,addMethod),
                new ExpressionList(
                new MethodCall(new MemberBinding(de,keyMethod),new ExpressionList(),NodeType.Call,SystemTypes.Object),
                new MethodCall(new MemberBinding(de,valueMethod),new ExpressionList(),NodeType.Call,SystemTypes.Object)),
                addMethodCallType,SystemTypes.Void)));
            } else
              b.Statements.Add(new Yield(comprehension.Elements[i]));
          }
        }
        if (notEnumContext){
          if (retVal.Type.IsValueType){
            b.Statements.Add(new ExpressionStatement(retVal));
          }else{
            b.Statements.Add(new ExpressionStatement(new BinaryExpression(retVal,new Literal(nonEnumClass, SystemTypes.Type), NodeType.Castclass,nonEnumClass)));
          }
        }
        if (notEnumContext)
          return this.VisitExpression(new BlockExpression(b,retVal.Type));
        else
          return new BlockExpression(this.VisitBlock(b),SystemTypes.Void);
      }
      #endregion
      #region Generate code for "true" Comprehensions
      Block newBlock = new Block(new StatementList(4));
      newBlock.HasLocals = true;
      TypeNode t = null;

      #region empty := false
      if (defaultIsPresent){
        newBlock.Statements.Add(new AssignmentStatement(empty,new Literal(false,SystemTypes.Boolean)));
      }
      #endregion
      #region either "yield return T(x)" or "t.Add(T(x))"
      if (notEnumContext){
        if (useIListMethods){
          if (comprehension.Elements[0]== null)
            return null;
          newBlock.Statements.Add(
            new ExpressionStatement(
            new MethodCall(new MemberBinding(retVal,addMethod),new ExpressionList(Box(comprehension.Elements[0])),addMethodCallType,SystemTypes.Int32,comprehension.Elements[0].SourceContext)));
        }else{ // assume IDictionary!
          newBlock.Statements.Add(new AssignmentStatement(de,comprehension.Elements[0]));
          //retval.Add(de.Key,de.Value) (actually, it is "reval.Add(de.get_Key(),de.get_Value())")
          newBlock.Statements.Add(
            new ExpressionStatement(
            new MethodCall(new MemberBinding(retVal,addMethod),
            new ExpressionList(
            new MethodCall(new MemberBinding(de,keyMethod),new ExpressionList(),NodeType.Call,SystemTypes.Object),
            new MethodCall(new MemberBinding(de,valueMethod),new ExpressionList(),NodeType.Call,SystemTypes.Object)),
            addMethodCallType,SystemTypes.Void)));
        }
      }else{
        newBlock.Statements.Add(new Yield(comprehension.Elements[0]));
      }
      #endregion
      #region Generate the "foreach" and "if P(x)" parts
      for (int i = comprehension.BindingsAndFilters.Count - 1; i >= 0; i--) {
        ComprehensionBinding qb = comprehension.BindingsAndFilters[i] as ComprehensionBinding ;
        if (qb != null){
          Expression forEachTargetVariable = qb.TargetVariable;
          if (qb.SourceEnumerable== null) 
            return null;
          if (qb.AsTargetVariableType != null){
            Local l = new Local(Identifier.For("SS$dummyForEachVar"),qb.SourceEnumerable.Type,newBlock);
            forEachTargetVariable = l;
            Block b2 = new Block(new StatementList(2));
            b2.Statements.Add(new AssignmentStatement(qb.TargetVariable,
              new BinaryExpression(l,new MemberBinding(null,qb.AsTargetVariableType),NodeType.Isinst,qb.AsTargetVariableType)));
            b2.Statements.Add(new If(new BinaryExpression(qb.TargetVariable,new Literal(null,SystemTypes.Type),NodeType.Ne),
              newBlock,null));
            newBlock = b2;
          }
          CollectionEnumerator ce = qb.SourceEnumerable as CollectionEnumerator;
          UnaryExpression u = ce == null ? null : ce.Collection as UnaryExpression;
          BinaryExpression be = u == null ? null : u.Operand as BinaryExpression;
          if (be != null && be.NodeType == NodeType.Range){
            // implement Range with a for-loop
            AssignmentStatement init = new AssignmentStatement(forEachTargetVariable,be.Operand1);
            AssignmentStatement incr = new AssignmentStatement(forEachTargetVariable,
              new BinaryExpression(forEachTargetVariable,new Literal(1,SystemTypes.Int32),NodeType.Add,SystemTypes.Int32));
            Expression cond = new BinaryExpression(forEachTargetVariable,be.Operand2,NodeType.Le,SystemTypes.Boolean);
            For forloop = new For(new StatementList(init),cond,new StatementList(incr),newBlock);
            newBlock = new Block(new StatementList(forloop));
          }else{
            // Just use the source enumerable as an IEnumerable in a foreach loop
            ForEach fe = new ForEach(qb.SourceEnumerable.Type,forEachTargetVariable,qb.SourceEnumerable,newBlock);
            fe.ScopeForTemporaryVariables = qb.ScopeForTemporaryVariables;
            newBlock = new Block(new StatementList(fe));
          }
        }else{ // it's a filter
          newBlock = new Block(new StatementList(new If(comprehension.BindingsAndFilters[i],newBlock,null)));
        }
      }
      // Need to normalize any foreach loop and if-stmt we just generated
      newBlock = this.VisitBlock(newBlock);
      b.Statements.Add(newBlock);
      #endregion
      if ( comprehension.Mode == ComprehensionMode.Comprehension ) {
        #region if (empty) [ yield return default / t.Add(default) ];
        if (defaultIsPresent){
          Expression addArg = comprehension.Elements[1];
              
          if (useIListMethods){
            if (notEnumContext){
              newBlock.Statements.Add(
                this.VisitIf( // need to normalize it
                new If(new BinaryExpression(empty,new Literal(true,SystemTypes.Boolean),NodeType.Eq),
                new Block(new StatementList(new ExpressionStatement(
                new MethodCall(new MemberBinding(retVal,addMethod),new ExpressionList(Box(addArg)),addMethodCallType,SystemTypes.Int32,comprehension.Elements[0].SourceContext))))
                ,null)));
            }else{
              newBlock.Statements.Add(
                this.VisitIf( // need to normalize it
                new If(new BinaryExpression(empty,new Literal(true,SystemTypes.Boolean),NodeType.Eq),
                new Block(new StatementList(new Yield(addArg))),
                null)));
            }
          } else { //assume IDictionary!
            if (notEnumContext){
              newBlock.Statements.Add(
                this.VisitIf( // need to normalize it
                new If(new BinaryExpression(empty,new Literal(true,SystemTypes.Boolean),NodeType.Eq),
                new Block(new StatementList(new ExpressionStatement(
                new MethodCall(new MemberBinding(retVal,addMethod),
                new ExpressionList(
                new MethodCall(new MemberBinding(addArg,keyMethod),new ExpressionList(),NodeType.Call,SystemTypes.Object),
                new MethodCall(new MemberBinding(addArg,valueMethod),new ExpressionList(),NodeType.Call,SystemTypes.Object)),
                addMethodCallType,SystemTypes.Void)))),
                null)));
            } else {
              newBlock.Statements.Add(
                this.VisitIf( // need to normalize it
                new If(new BinaryExpression(empty,new Literal(true,SystemTypes.Boolean),NodeType.Eq),
                new Block(new StatementList(new Yield(addArg))),
                null)));
            }
          }
        }
        #endregion
        #region [ / return t];
        if (notEnumContext){
          if (retVal.Type.IsValueType)
            b.Statements.Add(new ExpressionStatement(retVal));
          else
            b.Statements.Add(new ExpressionStatement(new BinaryExpression(retVal,new Literal(nonEnumClass, SystemTypes.Type), NodeType.Castclass,nonEnumClass)));
        }
        #endregion
      }else{
        #region Reduction
        Method getValMethod = this.GetTypeView(t).GetMethod(Identifier.For("get_Value"),null);
        MethodCall getValCall = new MethodCall(new MemberBinding(new UnaryExpression(retVal, NodeType.AddressOf, retVal.Type.GetReferenceType()),getValMethod),new ExpressionList(),NodeType.Callvirt,SystemTypes.Object,comprehension.Elements[0].SourceContext);
        Expression e = null;
        if (comprehension.Elements[0].Type.IsValueType) {
          e = Unbox(getValCall,comprehension.Elements[0].Type);
        }else{
          e = new BinaryExpression(getValCall,new Literal(comprehension.Elements[0].Type, SystemTypes.Type), NodeType.Castclass);
        }
        newBlock.Statements.Add(new ExpressionStatement(e));
        #endregion
      }
      if (notEnumContext)
        return this.VisitExpression(new BlockExpression(b,retVal.Type,comprehension.SourceContext));
      else
        return new BlockExpression(b,SystemTypes.Void,comprehension.SourceContext);
      #endregion
    }
Esempio n. 36
0
 public override Statement VisitForEach(ForEach forEach)
 {
     if (forEach == null) return null;
     return base.VisitForEach((ForEach)forEach.Clone());
 }
Esempio n. 37
0
 public virtual Statement VisitForEach(ForEach forEach){
   if (forEach == null) return null;
   forEach.TargetVariableType = this.VisitTypeReference(forEach.TargetVariableType);
   forEach.TargetVariable = this.VisitTargetExpression(forEach.TargetVariable);
   forEach.SourceEnumerable = this.VisitExpression(forEach.SourceEnumerable);
   forEach.InductionVariable = this.VisitTargetExpression(forEach.InductionVariable);
   forEach.Invariants = this.VisitLoopInvariantList(forEach.Invariants);
   forEach.Body = this.VisitBlock(forEach.Body);
   return forEach;
 }
Esempio n. 38
0
 public override Expression VisitApplyToAll(ApplyToAll applyToAll) {
   if (applyToAll == null) return null;
   Expression collection = applyToAll.Operand1;
   if (collection == null) { Debug.Assert(false); return null; }
   TypeNode elemType = this.typeSystem.GetStreamElementType(collection.Type, this.TypeViewer);
   bool singleTon = elemType == collection.Type;
   Local loc = applyToAll.ElementLocal;
   if (loc == null) loc = new Local(elemType);
   if (singleTon)
     applyToAll.Operand1 = this.VisitExpression(collection);
   else
     applyToAll.Operand1 = this.VisitEnumerableCollection(collection, loc.Type);
   if (applyToAll.Operand1 == null) return null;
   AnonymousNestedFunction func = applyToAll.Operand2 as AnonymousNestedFunction;
   Expression expr = applyToAll.Operand2 as BlockExpression;
   if (func != null || expr != null) {
     this.VisitAnonymousNestedFunction(func);
     if (singleTon || applyToAll.Type == SystemTypes.Void) return applyToAll;
     //Create an iterator to compute stream that results from ApplyToAll
     Class closureClass = this.currentMethod.Scope.ClosureClass;
     Method method = new Method();
     method.Name = Identifier.For("Function:"+method.UniqueKey);
     method.SourceContext = collection.SourceContext;
     method.Flags = MethodFlags.CompilerControlled;
     method.CallingConvention = CallingConventionFlags.HasThis;
     method.InitLocals = true;
     method.DeclaringType = closureClass;
     closureClass.Members.Add(method);
     method.Scope = new MethodScope(new TypeScope(null, closureClass), null);
     Parameter coll = new Parameter(StandardIds.Collection, collection.Type);
     ParameterField fcoll = new ParameterField(method.Scope, null, FieldFlags.CompilerControlled, StandardIds.Collection, collection.Type, null);
     fcoll.Parameter = coll;
     method.Scope.Members.Add(fcoll);
     Parameter closure = new Parameter(StandardIds.Closure, closureClass);
     ParameterField fclosure = new ParameterField(method.Scope, null, FieldFlags.CompilerControlled, StandardIds.Closure, closureClass, null);
     fclosure.Parameter = closure;
     if (func != null) {
       method.Scope.Members.Add(fclosure);
       method.Parameters = new ParameterList(coll, closure);
     } else
       method.Parameters = new ParameterList(coll);
     method.ReturnType = applyToAll.Type;
     ForEach forEach = new ForEach();
     forEach.TargetVariable = loc;
     forEach.TargetVariableType = loc.Type;
     forEach.SourceEnumerable = new MemberBinding(new ImplicitThis(), fcoll);
     if (func != null) {
       MemberBinding mb = new MemberBinding(new MemberBinding(new ImplicitThis(), fclosure), func.Method);
       expr = new MethodCall(mb, new ExpressionList(loc), NodeType.Call, func.Method.ReturnType, func.SourceContext);
     } else
       expr = this.VisitExpression(expr);
     expr = this.typeSystem.ImplicitCoercion(expr, this.typeSystem.GetStreamElementType(applyToAll.Type, this.TypeViewer), this.TypeViewer);
     if (expr == null) return null;
     BlockExpression bExpr = expr as BlockExpression;
     if (bExpr != null && bExpr.Type == SystemTypes.Void)
       forEach.Body = bExpr.Block;
     else
       forEach.Body = new Block(new StatementList(new Yield(expr)));
     forEach.ScopeForTemporaryVariables = new BlockScope(method.Scope, forEach.Body);
     method.Body = new Block(new StatementList(forEach));
     applyToAll.ResultIterator = this.VisitMethod(method);
     return applyToAll;
   }
   Debug.Assert(false);
   return null;
 }
Esempio n. 39
0
 public override Statement VisitForEach(ForEach forEach){
   if (forEach == null) return null;
   this.VisitResolvedTypeReference(forEach.TargetVariableType, forEach.TargetVariableTypeExpression);
   return base.VisitForEach(forEach);
 }
Esempio n. 40
0
    protected Node BuildTreeRoot()
    {
        //Func<bool> act = () => (zombies[8].transform.position.z > -25);
        //Node trigger = new DecoratorLoop(new LeafAssert(act));
        ForEach<GameObject> crowdFlee = new ForEach<GameObject>((crowdmem) =>
        {
            return new Sequence(

                this.ST_ApproachAndWaitCrowd(crowdmem, locations[16]));

        }, crowd);

        ForEach<GameObject> zombieAttack = new ForEach<GameObject>((zombie) =>
        {
            return new DecoratorLoop(
             new SequenceShuffle(
                this.ST_ApproachAndWaitZombie(zombie, locations[0]),
                this.ST_ApproachAndWaitZombie(zombie, locations[1]),
                this.ST_ApproachAndWaitZombie(zombie, locations[2]),
                this.ST_ApproachAndWaitZombie(zombie, locations[3]),
                this.ST_ApproachAndWaitZombie(zombie, locations[4]),
                this.ST_ApproachAndWaitZombie(zombie, locations[5]),
                this.ST_ApproachAndWaitZombie(zombie, locations[6]),
                this.ST_ApproachAndWaitZombie(zombie, locations[7]),
                this.ST_ApproachAndWaitZombie(zombie, locations[8]),
                this.ST_ApproachAndWaitZombie(zombie, locations[9]),
                this.ST_ApproachAndWaitZombie(zombie, locations[10]),
                this.ST_ApproachAndWaitZombie(zombie, locations[11])

                ));

        }, zombies);

            Sequence beginStory = new Sequence(

            this.ST_ApproachAndOrient(locations[0], numberOfParticipants[0].gameObject.transform, locations[1], numberOfParticipants[1].gameObject.transform),
            this.SetCamera(1),
            this.ST_ShakeHands(obj[0], eff[0], eff[0]),
            //this.ST_ShakeHands(numberOfParticipants[0].GetComponent<InteractionObject>(), eff[0], eff[0]),
            new SequenceParallel(
                new DecoratorLoop(5,
                this.Converse()),
                new Sequence(
                    this.Quote("Hey man, good to see you."),
                    new LeafWait(2000),
                    this.Quote("Isn't this a great party!"),
                    new LeafWait(2000),
                    this.Quote("Yeah, but lets see if we can kick it up a notch."),
                    new LeafWait(3000),
                    this.Quote("What do you mean?"),
                    new LeafWait(2000),
                    this.Quote("You heard the rumor about the abandoned shack over there right?"),
                    new LeafWait(3000),
                    this.Quote("No, tell me."),
                    new LeafWait(2000),
                    this.Quote("They say the owner was a deranged serial killer who would take his victims to that shack and do horrible things!"),
                    new LeafWait(4000),
                    this.Quote("When he was done he would store their bodies in that barn."),
                    new LeafWait(3000),
                    this.Quote("What that is crazy. I do not beleive it."),
                    new LeafWait(3000),
                    this.Quote("Well then I dare you go check out the barn."),
                    new LeafWait(3000),
                    this.Quote("All right let's do this!"),
                    new LeafWait(2000),
                    new LeafInvoke(() => {
                        numberOfParticipants[2].SetActive(false);
                    }, () => { })

        )));

        Sequence middleStory = new Sequence(
            this.SetCamera(2),
            this.ST_ApproachAndOrient(locations[2], numberOfParticipants[0].gameObject.transform, locations[3], numberOfParticipants[1].gameObject.transform),
            this.SetCamera(3),
             new SequenceParallel(
                new DecoratorLoop(2,
                this.Converse()),
                new Sequence(
                    this.Quote("Here it is."),
                    new LeafWait(2000),
                    this.Quote("Just open the door and see what is inside."),
                    new LeafWait(2000),
                    this.Quote("All right, but I am telling you it is nothing."),
                    new LeafWait(2000),
                     new LeafInvoke(() =>
                     {
                         numberOfParticipants[2].SetActive(false);
                     }, () => { })

                )),
             this.ST_PushButton(eff[0], obj[1], locations[4], 0),
                new Sequence(
                    this.Quote("What is that?"),
                    new LeafWait(2000),
                    this.Quote("Oh no ZOMBIES!!!!!!"),
                    new LeafWait(2000),
                    this.Quote("Let's get out of here!"),
                    new LeafWait(2000),
                     new LeafInvoke(() =>
                     {
                         numberOfParticipants[2].SetActive(false);
                     }, () => { })

                 ));

        SequenceParallel endStory = new SequenceParallel(

               zombieAttack,

               this.ST_ApproachAndWait(numberOfParticipants[0], locations[15]),
               this.ST_ApproachAndWait(numberOfParticipants[1], locations[15]),
               new Sequence(
                    this.Quote("Everybody RUN!!!"),
                    new LeafWait(2000),
                    this.Quote("AHHHHH!!!"),
                    new LeafWait(2000),
                    this.Quote("AGGGHHHHYYY!!!!!"),
                    new LeafWait(2000),
                     new LeafInvoke(() =>
                     {
                         numberOfParticipants[2].SetActive(false);
                         partyBool.mainEvent = true;
                         //Debug.Log("Setting part bool");
                     }, () => { }),
                     new SequenceParallel(
                        this.SetCamera(4),
                        crowdFlee
                     )
                )
               );

        return new Sequence(  beginStory, middleStory,
            endStory

            );
    }
Esempio n. 41
0
 protected virtual void ForeachBodyHook(ForEach forEach, StatementList sl, Expression enumerator, Expression index) {
 }
Esempio n. 42
0
 public virtual Statement BuildClosureForEach(Expression source, ref Expression target, out Block body, BlockScope scope) {
   source = this.GetInnerExpression(source);
   if (source is QueryExpression) {
     QueryYielder yielder = new QueryYielder();
     yielder.Source = source;
     yielder.Body = body = new Block(new StatementList(1));
     if (target == null) target = this.NewClosureLocal(this.typeSystem.GetStreamElementType(source, this.TypeViewer), scope);
     yielder.Target = target;
     yielder.State = this.NewClosureLocal(SystemTypes.Int32, scope);
     return yielder;
   }else{
     if (target == null){
       TypeNode elementType = this.typeSystem.GetStreamElementType(source, this.TypeViewer);
       target = target = this.NewClosureLocal(elementType, scope);
     }
     Literal tmpSource = new Literal(null, source.Type);
     ForEach fe = new ForEach(target.Type, target, tmpSource, new Block(new StatementList(1)));
     fe.ScopeForTemporaryVariables = scope;
     Checker checker = new Checker(null, this.typeSystem, null, null, null);
     checker.currentType = this.typeSystem.currentType = (scope.CapturedForClosure ? scope.ClosureClass : this.currentMethod.DeclaringType);
     checker.VisitForEach(fe);
     Debug.Assert(fe.SourceEnumerable != null);
     if (fe.SourceEnumerable != null){
       Debug.Assert(fe.SourceEnumerable is CollectionEnumerator, "SourceEnumerable == "+fe.SourceEnumerable.GetType());
       CollectionEnumerator ce = (CollectionEnumerator)fe.SourceEnumerable;
       ce.Collection = source;
     }
     body = fe.Body;
     return fe;
   }
 }
Esempio n. 43
0
    static void ImplementInitFrameSetsMethod(TypeNode outerType){
      // private void InitFrameSets(){
      //   #if some base type T implements a Frame getter
      //     this.frame.AddRepFrame(this.T::get_Frame());
      //   #endif
      //   #foreach non-static field f declared in this type
      //     #if f is a rep field
      //     #if f.Type is a possibly-null reference type
      //       if (this.f != null)
      //         this.frame.AddRepObject(this.f);
      //     #elseif f.Type is a non-null reference type
      //       this.frame.AddRepObject(this.f);
      //     #elseif f.Type is a value type that implements IEnumerable
      //       foreach (object o in this.f)
      //         this.frame.AddRepObject(o);
      //     #endif
      //     #elseif f carries a SharedAttribute
      //     #if f.Type is a possibly-null reference type
      //       if (this.f != null)
      //         this.frame.AddSharedObject(this.f);
      //     #elseif f.Type is a non-null reference type
      //       this.frame.AddSharedObject(this.f);
      //     #elseif f.Type is a value type that implements IEnumerable
      //       foreach (object o in this.f)
      //         this.frame.AddSharedObject(o);
      //     #endif
      //     #endif
      //   #endforeach
      // }
      
      // Possible extension:
      // We might choose to support fields f annotated with an OwnedAttribute(Depth=n)
      // indicating that the references contained in f up to depth n are rep references of this.
      // references contained in f at depth 0 = references contained in f
      // references contained in f at depth n + 1 = the union of, for each reference r contained in f at depth n,
      // the set of rep references of object r.

      Method m = outerType.Contract.InitFrameSetsMethod;
      Method frameGetter = outerType.Contract.FramePropertyGetter;
      Expression frame = new MethodCall(new MemberBinding(m.ThisParameter, frameGetter), null, NodeType.Call, frameGetter.ReturnType);

      StatementList statements = new StatementList();

      if (outerType.BaseType != SystemTypes.Object){
        statements.Add(
          new ExpressionStatement(new MethodCall(new MemberBinding(frame, SystemTypes.Guard.GetMethod(Identifier.For("AddRepFrame"), SystemTypes.Object, SystemTypes.Type)),
          new ExpressionList(m.ThisParameter, new UnaryExpression(new Literal(outerType.BaseType, SystemTypes.Type), NodeType.Typeof, SystemTypes.Type)))));
      }

      Method addRepObjectMethod = SystemTypes.Guard.GetMethod(Identifier.For("AddRepObject"), SystemTypes.Object);
      Method addLockProtectedObjectMethod = SystemTypes.Guard.GetMethod(Identifier.For("AddObjectLockProtectedCertificate"), SystemTypes.Object);
      Method addImmutableObjectMethod = SystemTypes.Guard.GetMethod(Identifier.For("AddObjectImmutableCertificate"), SystemTypes.Object);

      MemberList members = outerType.Members;
      for (int i = 0; i < members.Count; i++){
        Member member = members[i];
        Field field = member as Field;
        if (field != null && !field.IsStatic){
          Method addMethod;
          switch (field.ReferenceSemantics & ReferenceFieldSemantics.SemanticsMask){
            case ReferenceFieldSemantics.Rep: addMethod = addRepObjectMethod; break;
            case ReferenceFieldSemantics.LockProtected: addMethod = addLockProtectedObjectMethod; break;
            case ReferenceFieldSemantics.Immutable: addMethod = addImmutableObjectMethod; break;
            default: addMethod = null; break;
          }
          if (addMethod != null){
            MemberBinding addMethodBinding = new MemberBinding(frame, addMethod);
            MemberBinding fieldBinding = new MemberBinding(m.ThisParameter, field);
            TypeNode fieldType = field.Type == null ? SystemTypes.Object : field.Type;
            if (fieldType.NodeType == NodeType.NonNullTypeExpression){
              statements.Add(new ExpressionStatement(new MethodCall(addMethodBinding, new ExpressionList(fieldBinding))));
            } else if (fieldType.IsValueType){
              // TODO: Check that this.GetTypeView(field.Type).IsAssignableTo(SystemTypes.IEnumerable); otherwise, generate a compiler error.
              Local repRef = new Local(SystemTypes.Object);
              ForEach forEach = new ForEach(SystemTypes.Object, repRef, fieldBinding,
                new Block(new StatementList(
                new ExpressionStatement(new MethodCall(addMethodBinding,
                new ExpressionList(repRef))))));
              forEach.StatementTerminatesNormallyIfEnumerableIsNull = false;
              forEach.StatementTerminatesNormallyIfEnumerableIsNull = false;
              forEach.ScopeForTemporaryVariables = new BlockScope();
              statements.Add(forEach);
            } else {
              statements.Add(new ExpressionStatement(new MethodCall(addMethodBinding, new ExpressionList(fieldBinding))));
            }
          }
        }
      }

      m.CallingConvention = CallingConventionFlags.HasThis;
      m.Flags = MethodFlags.Private;
      m.Body = new Block(statements);
      outerType.Members.Add(m);
    }
Esempio n. 44
0
    public virtual Differences VisitForEach(ForEach forEach1, ForEach forEach2){
      Differences differences = new Differences(forEach1, forEach2);
      if (forEach1 == null || forEach2 == null){
        if (forEach1 != forEach2) differences.NumberOfDifferences++; else differences.NumberOfSimilarities++;
        return differences;
      }
      ForEach changes = (ForEach)forEach2.Clone();
      ForEach deletions = (ForEach)forEach2.Clone();
      ForEach insertions = (ForEach)forEach2.Clone();

      Differences diff = this.VisitBlock(forEach1.Body, forEach2.Body);
      if (diff == null){Debug.Assert(false); return differences;}
      changes.Body = diff.Changes as Block;
      deletions.Body = diff.Deletions as Block;
      insertions.Body = diff.Insertions as Block;
      Debug.Assert(diff.Changes == changes.Body && diff.Deletions == deletions.Body && diff.Insertions == insertions.Body);
      differences.NumberOfDifferences += diff.NumberOfDifferences;
      differences.NumberOfSimilarities += diff.NumberOfSimilarities;

      diff = this.VisitExpression(forEach1.SourceEnumerable, forEach2.SourceEnumerable);
      if (diff == null){Debug.Assert(false); return differences;}
      changes.SourceEnumerable = diff.Changes as Expression;
      deletions.SourceEnumerable = diff.Deletions as Expression;
      insertions.SourceEnumerable = diff.Insertions as Expression;
      Debug.Assert(diff.Changes == changes.SourceEnumerable && diff.Deletions == deletions.SourceEnumerable && diff.Insertions == insertions.SourceEnumerable);
      differences.NumberOfDifferences += diff.NumberOfDifferences;
      differences.NumberOfSimilarities += diff.NumberOfSimilarities;

      diff = this.VisitExpressionList(forEach1.Invariants, forEach2.Invariants, out changes.Invariants, out deletions.Invariants, out insertions.Invariants);
      if (diff == null){Debug.Assert(false); return differences;}
      differences.NumberOfDifferences += diff.NumberOfDifferences;
      differences.NumberOfSimilarities += diff.NumberOfSimilarities;

      diff = this.VisitExpression(forEach1.InductionVariable, forEach2.InductionVariable);
      if (diff == null){Debug.Assert(false); return differences;}
      changes.InductionVariable = diff.Changes as Expression;
      deletions.InductionVariable = diff.Deletions as Expression;
      insertions.InductionVariable = diff.Insertions as Expression;
      Debug.Assert(diff.Changes == changes.InductionVariable && diff.Deletions == deletions.InductionVariable && diff.Insertions == insertions.InductionVariable);
      differences.NumberOfDifferences += diff.NumberOfDifferences;
      differences.NumberOfSimilarities += diff.NumberOfSimilarities;

      diff = this.VisitExpression(forEach1.TargetVariable, forEach2.TargetVariable);
      if (diff == null){Debug.Assert(false); return differences;}
      changes.TargetVariable = diff.Changes as Expression;
      deletions.TargetVariable = diff.Deletions as Expression;
      insertions.TargetVariable = diff.Insertions as Expression;
      Debug.Assert(diff.Changes == changes.TargetVariable && diff.Deletions == deletions.TargetVariable && diff.Insertions == insertions.TargetVariable);
      differences.NumberOfDifferences += diff.NumberOfDifferences;
      differences.NumberOfSimilarities += diff.NumberOfSimilarities;

      diff = this.VisitTypeNode(forEach1.TargetVariableType, forEach2.TargetVariableType);
      if (diff == null){Debug.Assert(false); return differences;}
      changes.TargetVariableType = diff.Changes as TypeNode;
      deletions.TargetVariableType = diff.Deletions as TypeNode;
      insertions.TargetVariableType = diff.Insertions as TypeNode;
      //Debug.Assert(diff.Changes == changes.TargetVariableType && diff.Deletions == deletions.TargetVariableType && diff.Insertions == insertions.TargetVariableType);
      differences.NumberOfDifferences += diff.NumberOfDifferences;
      differences.NumberOfSimilarities += diff.NumberOfSimilarities;

      if (forEach1.StatementTerminatesNormallyIfEnumerableIsNull == forEach2.StatementTerminatesNormallyIfEnumerableIsNull) differences.NumberOfSimilarities++; else differences.NumberOfDifferences++;
      if (forEach1.StatementTerminatesNormallyIfEnumeratorIsNull == forEach2.StatementTerminatesNormallyIfEnumeratorIsNull) differences.NumberOfSimilarities++; else differences.NumberOfDifferences++;

      if (differences.NumberOfDifferences == 0){
        differences.Changes = null;
        differences.Deletions = null;
        differences.Insertions = null;
      }else{
        differences.Changes = changes;
        differences.Deletions = deletions;
        differences.Insertions = insertions;
      }
      return differences;
    }
Esempio n. 45
0
 public override Statement VisitForEach(ForEach forEach){
   if (forEach == null) return null;
   forEach.InductionVariable = this.VisitTargetExpression(forEach.InductionVariable);
   forEach.Invariants = this.VisitLoopInvariantList(forEach.Invariants);
   forEach.TargetVariableType = this.VisitTypeReference(forEach.TargetVariableType);
   forEach.TargetVariable = this.VisitTargetExpression(forEach.TargetVariable);
   Expression e = forEach.SourceEnumerable = this.VisitExpression(forEach.SourceEnumerable);
   if (e != null && e.NodeType == NodeType.AnonymousNestedFunction){
     AnonymousNestedFunction func = (AnonymousNestedFunction)e;
     Method invoker = func.Method;
     if (invoker != null){
       Expression ob = invoker.IsStatic ? null : new CurrentClosure(invoker, invoker.DeclaringType);
       e = new MethodCall(new MemberBinding(ob, invoker), null, NodeType.Call, invoker.ReturnType, e.SourceContext);
       func.Invocation = e;
       func.Type = invoker.ReturnType;
     }
   }
   if (forEach.TargetVariableType == null){
     MemberBinding mb = forEach.TargetVariable as MemberBinding;
     if (mb != null){
       Field f = mb.BoundMember as Field;
       if (f != null && e != null){
         TypeNode st = TypeNode.StripModifiers(e.Type); //HACK
         while (st is TypeAlias) st = TypeNode.StripModifiers(((TypeAlias)st).AliasedType);
         if (st != e.Type)
           f.Type = this.typeSystem.GetStreamElementType(st, this.TypeViewer);
         else
           f.Type = this.typeSystem.GetStreamElementType(e, this.TypeViewer);
         mb.Type = f.Type;
         forEach.TargetVariableType = f.Type;
       }
     }
   }
   forEach.Body = this.VisitBlock(forEach.Body);
   return forEach;
 }
Esempio n. 46
0
 public virtual Statement VisitForEach(ForEach forEach1, ForEach forEach2)
 {
     if (forEach1 == null) return null;
     if (forEach2 == null)
     {
         forEach1.TargetVariableType = this.VisitTypeReference(forEach1.TargetVariableType, null);
         forEach1.TargetVariable = this.VisitTargetExpression(forEach1.TargetVariable, null);
         forEach1.SourceEnumerable = this.VisitExpression(forEach1.SourceEnumerable, null);
         forEach1.InductionVariable = this.VisitTargetExpression(forEach1.InductionVariable, null);
         forEach1.Invariants = this.VisitExpressionList(forEach1.Invariants, null);
         forEach1.Body = this.VisitBlock(forEach1.Body, null);
     }
     else
     {
         forEach1.TargetVariableType = this.VisitTypeReference(forEach1.TargetVariableType, forEach2.TargetVariableType);
         forEach1.TargetVariable = this.VisitTargetExpression(forEach1.TargetVariable, forEach2.TargetVariable);
         forEach1.SourceEnumerable = this.VisitExpression(forEach1.SourceEnumerable, forEach2.SourceEnumerable);
         forEach1.InductionVariable = this.VisitTargetExpression(forEach1.InductionVariable, forEach2.InductionVariable);
         forEach1.Invariants = this.VisitExpressionList(forEach1.Invariants, forEach2.Invariants);
         forEach1.Body = this.VisitBlock(forEach1.Body, forEach2.Body);
     }
     return forEach1;
 }
Esempio n. 47
0
 public override Statement VisitForEach(ForEach forEach) {
   if (forEach == null) return null;
   forEach.InductionVariable = this.VisitTargetExpression(forEach.InductionVariable);
   this.loopCount++;
   forEach.Invariants = this.VisitLoopInvariantList(forEach.Invariants);
   forEach.TargetVariableType = this.VisitTypeReference(forEach.TargetVariableType);
   forEach.TargetVariable = this.VisitTargetExpression(forEach.TargetVariable);
   forEach.SourceEnumerable = this.VisitEnumerableCollection(forEach.SourceEnumerable, forEach.TargetVariableType);
   if (forEach.TargetVariableType == null) {
     this.loopCount--;
     return null;
   }
   forEach.Body = this.VisitBlock(forEach.Body);
   MemberBinding mb = forEach.TargetVariable as MemberBinding;
   if (mb != null) {
     Field f = mb.BoundMember as Field;
     if (f != null)
       f.Flags &= ~FieldFlags.InitOnly;
   }
   this.loopCount--;
   return forEach;
 }
Esempio n. 48
0
    public override Statement VisitForEach(ForEach forEach) {
      if (forEach == null || forEach.Body == null) return null;
      //First transform
      Block continueTarget = new Block(new StatementList(0));
      Block exitTarget = new Block(new StatementList(0));
      StatementList statements = new StatementList(16);
      StatementList generatedInvariants = new StatementList(1);
      Block result = new Block(statements);
      result.HasLocals = true;
      //initialize and update induction variable
      if (forEach.InductionVariable != null) {
        TypeNode inductionVariableType = ((OptionalModifier)forEach.InductionVariable.Type).ModifiedType;
        TypeNode inductionVariableTypeView = this.GetTypeView(inductionVariableType);
        statements.Add(new AssignmentStatement(forEach.InductionVariable, new Construct(new MemberBinding(null, inductionVariableTypeView.GetConstructor()), null, inductionVariableType)));
        forEach.Body.Statements.Add(new ExpressionStatement(new MethodCall(new MemberBinding(forEach.InductionVariable, inductionVariableTypeView.GetMethod(StandardIds.Add, forEach.TargetVariableType)), new ExpressionList(forEach.TargetVariable), NodeType.Call, SystemTypes.Void)));
      }
      //get enumerator. Either call getEnumerator, or use the object itself. 
      CollectionEnumerator cEnumerator = forEach.SourceEnumerable as CollectionEnumerator;
      if (cEnumerator == null || cEnumerator.Collection == null) return null;
      TypeNode tt = forEach.TargetVariable == null || forEach.TargetVariable.Type == null ? null : forEach.TargetVariable.Type.Template;
      bool suppressNullElements = tt != null && tt == SystemTypes.GenericNonNull;
      Expression enumerator;
      Expression length = null;
      Expression index = null;
      BlockScope tempScope = forEach.ScopeForTemporaryVariables;
      Method getEnumerator = cEnumerator.GetEnumerator;
      if (getEnumerator != null && this.currentMethod.Scope != null && this.currentMethod.Scope.CapturedForClosure) {
        TypeNode geDT = this.currentMethod.Scope.FixTypeReference(getEnumerator.DeclaringType);
        if (geDT != getEnumerator.DeclaringType) {
          getEnumerator = cEnumerator.GetEnumerator = geDT.GetMethod(getEnumerator.Name);
        }
      }
      Identifier id = null;

      TypeNode collectionType = cEnumerator.Collection.Type;
      ArrayType arrType = null;
      if (collectionType != null) {
        arrType = this.typeSystem.GetUnderlyingType(collectionType) as ArrayType;
        if (arrType != null) {
          collectionType = arrType;
        }
      }
      if (this.currentMethod.Scope != null && this.currentMethod.Scope.CapturedForClosure) 
        collectionType = this.currentMethod.Scope.FixTypeReference(collectionType);

      if (getEnumerator != null) {
        Local ctemp = new Local(Identifier.Empty, collectionType, result);
        Expression e = this.VisitExpression(cEnumerator.Collection);
        if (e.Type is Reference)
          e = new AddressDereference(e, arrType);
        AssignmentStatement assignCollection = new AssignmentStatement(ctemp, e);
        assignCollection.SourceContext = forEach.SourceContext;
        assignCollection.SourceContext.EndPos = forEach.SourceContext.StartPos + this.foreachLength;
        statements.Add(assignCollection);


        if (!ctemp.Type.IsValueType && forEach.StatementTerminatesNormallyIfEnumerableIsNull)
          statements.Add(new Branch(new UnaryExpression(this.Box(ctemp), NodeType.LogicalNot), exitTarget));
        MemberBinding mb = new MemberBinding(ctemp, getEnumerator);
        if (ctemp.Type.IsValueType)
          mb.TargetObject = new UnaryExpression(ctemp, NodeType.AddressOf, ctemp.Type.GetReferenceType());
        else if (ctemp.Type is ITypeParameter)
          mb.TargetObject = this.Box(ctemp);
        MethodCall callGetEnumerator = new MethodCall(mb, null, getEnumerator.IsVirtualAndNotDeclaredInStruct ? NodeType.Callvirt : NodeType.Call);
        callGetEnumerator.Type = getEnumerator.ReturnType;
        callGetEnumerator.SourceContext = cEnumerator.Collection.SourceContext;
        id = Identifier.For("foreachEnumerator: " +forEach.GetHashCode());
        if (tempScope.CapturedForClosure) {
          Field f = new Field(tempScope, null, FieldFlags.CompilerControlled | FieldFlags.SpecialName, id, this.currentMethod.Scope.FixTypeReference(getEnumerator.ReturnType), null);
          if (f.Type != SystemTypes.String) { // Should be any immutable type, but string is the only one so far!
            f.Attributes.Add(
              new AttributeNode(new MemberBinding(null, SystemTypes.PeerAttribute.GetConstructor()),null, AttributeTargets.Field));
          }
          enumerator = this.VisitMemberBinding(new MemberBinding(new ImplicitThis(), f));
        } else
          enumerator = new Local(id, getEnumerator.ReturnType, result);
        if (enumerator == null) return null;
        statements.Add(new AssignmentStatement(enumerator, callGetEnumerator, NodeType.Nop, callGetEnumerator.SourceContext));
        if (!enumerator.Type.IsValueType && forEach.StatementTerminatesNormallyIfEnumeratorIsNull)
          statements.Add(new Branch(new UnaryExpression(enumerator, NodeType.LogicalNot), exitTarget));

        CompilerOptions options = this.currentCompilation == null ? null : this.currentCompilation.CompilerParameters as CompilerOptions;
        if (options != null && !options.DisableInternalContractsMetadata && !options.DisableGuardedClassesChecks && !tempScope.CapturedForClosure) {
          // Add loop invariants that the compiler knows about because it is generating the code
          // Don't generate any runtime checks for them, just the serialized form the static verification needs to see
          //
          // Don't do this for value types: they can't have invariants anyway (and translation fails for box expressions anyway)
          if (!enumerator.Type.IsValueType) {
            MemberList ms = SystemTypes.Guard.GetMembersNamed(Runtime.IsPeerConsistentId);
            if (ms != null && ms.Count == 1) {
              Method isConsistent = (Method)ms[0];
              Expression arg = enumerator;
              if (arg.NodeType == NodeType.Local) {
                Local l = (Local)arg;
                // all user-written locals are represented as memberbindings of a particular form
                // Boogie has built that assumption in so that the only true "Locals" that it sees
                // it considers special, like "return value".
                Field f = new Field(forEach.ScopeForTemporaryVariables, null, FieldFlags.CompilerControlled, l.Name, l.Type, Literal.Null);
                arg = new MemberBinding(null, f);
              }
              MethodCall mc = new MethodCall(new MemberBinding(null, isConsistent), new ExpressionList(arg), NodeType.Call, SystemTypes.Boolean);
              Assertion assertion = new Assertion(mc);
              assertion.SourceContext = assignCollection.SourceContext;
              foreach (Statement s in this.SerializeAssertion(this.currentModule, mc, "Foreach enumerator must be peer consistent.", assignCollection.SourceContext, "LoopInvariant")) {
                generatedInvariants.Add(s);
              }
            }
          }
        }

      } else if (cEnumerator.MoveNext == null) {
        Identifier indexId = Identifier.For("foreachIndex: " + forEach.GetHashCode());
        if (tempScope.CapturedForClosure) {
          id = Identifier.For("foreachLength: " + forEach.GetHashCode());
          Field f = new Field(tempScope, null, FieldFlags.CompilerControlled, id, SystemTypes.Int32, null);
          length = this.VisitMemberBinding(new MemberBinding(new ImplicitThis(), f));
          f = new Field(tempScope, null, FieldFlags.CompilerControlled, indexId, SystemTypes.Int32, null);
          index = this.VisitMemberBinding(new MemberBinding(new ImplicitThis(), f));
          id = Identifier.For("foreachEnumerator: " + forEach.GetHashCode());
          f = new Field(tempScope, null, FieldFlags.CompilerControlled | FieldFlags.SpecialName, id, collectionType, null);
          enumerator = this.VisitMemberBinding(new MemberBinding(new ImplicitThis(), f, cEnumerator.SourceContext));
          if (enumerator == null) return null;  // this is happening when foreach encloses anon delegate. just fixing the crash.
        } else {
          length = new Local(Identifier.Empty, SystemTypes.Int32);
          index = new Local(indexId, SystemTypes.Int32, result);
          enumerator = new Local(Identifier.Empty, collectionType, cEnumerator.SourceContext);
        }

        if (!(this.currentCompilation != null && this.currentCompilation.CompilerParameters is CompilerOptions && ((CompilerOptions)this.currentCompilation.CompilerParameters).DisableInternalContractsMetadata)) {
          // Add loop invariants that the compiler knows about because it is generating the code
          // Don't generate any runtime checks for them, just the serialized form the static verification needs to see
          //
          Expression arg = index;
          if (index.NodeType == NodeType.Local) {
            Local l = (Local)index;
            // all user-written locals are represented as memberbindings of a particular form
            // Boogie has built that assumption in so that the only true "Locals" that it sees
            // it considers special, like "return value".
            Field f = new Field(forEach.ScopeForTemporaryVariables, null, FieldFlags.CompilerControlled, l.Name, l.Type, Literal.Null);
            arg = new MemberBinding(null, f);
          }
          Assertion assertion = new Assertion(new BinaryExpression(arg, new Literal(0, SystemTypes.Int32), NodeType.Ge, SystemTypes.Boolean));
          assertion.SourceContext = forEach.SourceContext;
          assertion.SourceContext.EndPos = forEach.SourceContext.StartPos + this.foreachLength;
          foreach (Statement s in this.SerializeAssertion(this.currentModule, assertion.Condition, "Foreach loop index must be at least zero.", assertion.SourceContext, "LoopInvariant")) {
            generatedInvariants.Add(s);
          }
        }

        Expression e = this.VisitExpression(cEnumerator.Collection);
        if (e.Type is Reference)
          e = new AddressDereference(e, arrType);
        AssignmentStatement assignEnumerator = new AssignmentStatement(enumerator, e);
        assignEnumerator.SourceContext = forEach.SourceContext;
        if (forEach.SourceContext.StartPos != cEnumerator.SourceContext.StartPos || forEach.SourceContext.EndPos != cEnumerator.SourceContext.EndPos)
          assignEnumerator.SourceContext.EndPos = forEach.SourceContext.StartPos + this.foreachLength;
        statements.Add(assignEnumerator);
        statements.Add(new Branch(new UnaryExpression(enumerator, NodeType.LogicalNot), exitTarget));
        TypeNode et = this.ForeachArrayElementType(cEnumerator);
        if (et != null)
          statements.Add(new AssignmentStatement(length, new UnaryExpression(new UnaryExpression(enumerator, NodeType.Ldlen, SystemTypes.IntPtr), NodeType.Conv_I4,SystemTypes.Int32)));
        else {
          Debug.Assert(false);
          return null;
        }
        statements.Add(new AssignmentStatement(index, new Literal(0, SystemTypes.Int32)));
      } else {
        Field f = null;
        id = Identifier.For("foreachEnumerator: " + forEach.GetHashCode());
        if (tempScope.CapturedForClosure) {
          f = new Field(tempScope, null, FieldFlags.Private | FieldFlags.SpecialName, id, collectionType, null);
          enumerator = this.VisitMemberBinding(new MemberBinding(new ImplicitThis(), f));
          if (enumerator == null) return null;  // this can happen. See above for similar statement
        } else {
          f = new Field(tempScope, null, FieldFlags.Private | FieldFlags.SpecialName, id, collectionType, null);
          enumerator = this.VisitMemberBinding(new MemberBinding(new ImplicitThis(), f));
          //enumerator = new Local(id, collectionType);
        }
        AssignmentStatement assignEnumerator = new AssignmentStatement(enumerator, this.VisitExpression(cEnumerator.Collection));
        assignEnumerator.SourceContext = forEach.SourceContext;
        if (forEach.SourceContext.StartPos != cEnumerator.SourceContext.StartPos || forEach.SourceContext.EndPos != cEnumerator.SourceContext.EndPos)
          assignEnumerator.SourceContext.EndPos = forEach.SourceContext.StartPos + this.foreachLength;
        statements.Add(assignEnumerator);
        if (!enumerator.Type.IsValueType)
          statements.Add(new Branch(new UnaryExpression(enumerator, NodeType.LogicalNot), exitTarget));

        if (!(this.currentCompilation != null && this.currentCompilation.CompilerParameters is CompilerOptions && ((CompilerOptions)this.currentCompilation.CompilerParameters).DisableInternalContractsMetadata)) {
          // Add loop invariants that the compiler knows about because it is generating the code
          // Don't generate any runtime checks for them, just the serialized form the static verification needs to see
        }
      }
      //continueTarget
      statements.Add(continueTarget);

      if (generatedInvariants.Count > 0) {
        foreach (Statement s in generatedInvariants)
          statements.Add(s);
      }
      if (forEach.Invariants != null)
        statements.Add(this.VisitLoopInvariants(forEach.Invariants));

      if (length != null) {
        //if index >= length goto exitTarget
        Branch b = (index.Type.IsPrimitiveUnsignedInteger && length.Type.IsPrimitiveUnsignedInteger)?
          new Branch(new BinaryExpression(index, length, NodeType.Ge), exitTarget, exitTarget.SourceContext, true):
          new Branch(new BinaryExpression(index, length, NodeType.Ge), exitTarget);
        if (forEach.TargetVariable != null) {
          b.SourceContext = forEach.TargetVariable.SourceContext;
          if (forEach.SourceEnumerable.SourceContext.EndPos > b.SourceContext.EndPos)
            b.SourceContext.EndPos = forEach.SourceEnumerable.SourceContext.EndPos;
        }
        statements.Add(b);
        this.ForeachBodyHook(forEach, statements, enumerator, index);
        //target = enumerator[index]
        Debug.Assert(cEnumerator.ElementLocal != null);
        Expression target = cEnumerator.ElementLocal;
        ExpressionList args = new ExpressionList(1);
        args.Add(index);
        TypeNode et = this.ForeachArrayElementType(cEnumerator);
        if (et != null) {
          Expression elem = new Indexer(enumerator, args, et);
          if (et.IsValueType && !et.IsPrimitive)
            elem = new AddressDereference(new UnaryExpression(elem, NodeType.AddressOf, elem.Type.GetReferenceType()), et);
          AssignmentStatement indexIntoArray = new AssignmentStatement(target, elem);
          indexIntoArray.SourceContext = forEach.TargetVariable.SourceContext;
          if (forEach.SourceEnumerable.SourceContext.EndPos > indexIntoArray.SourceContext.EndPos)
            indexIntoArray.SourceContext.EndPos = forEach.SourceEnumerable.SourceContext.EndPos;
          statements.Add(indexIntoArray);
        }else{
          Debug.Assert(false);
          return null;
        }
        statements.Add(new AssignmentStatement(index, new BinaryExpression(index, new Literal(1, SystemTypes.Int32), NodeType.Add)));
      } else {
        //if !enumerator.MoveNext() goto exitTarget
        Method moveNext = cEnumerator.MoveNext;
        MemberBinding mb = new MemberBinding(enumerator, moveNext);
        MethodCall callMoveNext = new MethodCall(mb, null, moveNext.IsVirtualAndNotDeclaredInStruct ? NodeType.Callvirt : NodeType.Call);
        callMoveNext.Type = SystemTypes.Boolean;
        if (this.useGenerics && mb.TargetObject != null && mb.TargetObject.Type is ITypeParameter) {
          callMoveNext.Constraint = mb.TargetObject.Type;
          mb.TargetObject = new UnaryExpression(mb.TargetObject, NodeType.AddressOf, mb.TargetObject.Type.GetReferenceType());
        } else if (mb.TargetObject.Type.IsValueType) {
          mb.TargetObject = new UnaryExpression(mb.TargetObject, NodeType.AddressOf, mb.TargetObject.Type.GetReferenceType());
        }
        Branch b = new Branch(new UnaryExpression(callMoveNext, NodeType.LogicalNot), exitTarget);
        if (forEach.TargetVariable != null) {
          b.SourceContext = forEach.TargetVariable.SourceContext;
          if (forEach.SourceEnumerable.SourceContext.EndPos > b.SourceContext.EndPos)
            b.SourceContext.EndPos = forEach.SourceEnumerable.SourceContext.EndPos;
        }
        statements.Add(b);
        //target = enumerator.Current
        Debug.Assert(cEnumerator.GetCurrent != null);
        Method getCurrent = cEnumerator.GetCurrent;
        if (this.currentMethod.Scope != null && this.currentMethod.Scope.CapturedForClosure) {
          TypeNode gcDT = this.currentMethod.Scope.FixTypeReference(getCurrent.DeclaringType);
          if (gcDT != getCurrent.DeclaringType) {
            getCurrent = cEnumerator.GetCurrent = gcDT.GetMethod(getCurrent.Name);
            cEnumerator.ElementLocal.Type = getCurrent.ReturnType;
          }
        }
        mb = new MemberBinding(enumerator, getCurrent);
        MethodCall callGetCurrent = new MethodCall(mb, null, getCurrent.IsVirtualAndNotDeclaredInStruct ?  NodeType.Callvirt : NodeType.Call);
        if (this.useGenerics && mb.TargetObject != null && mb.TargetObject.Type is ITypeParameter) {
          callGetCurrent.Constraint = mb.TargetObject.Type;
          mb.TargetObject = new UnaryExpression(mb.TargetObject, NodeType.AddressOf, mb.TargetObject.Type.GetReferenceType());
        } else if (mb.TargetObject.Type.IsValueType) {
          mb.TargetObject = new UnaryExpression(mb.TargetObject, NodeType.AddressOf, mb.TargetObject.Type.GetReferenceType());
        }
        Debug.Assert(cEnumerator.ElementLocal != null);
        statements.Add(new AssignmentStatement(cEnumerator.ElementLocal, callGetCurrent, forEach.TargetVariable.SourceContext));
        //loop back if element null
        if (suppressNullElements)
          statements.Add(new Branch(new UnaryExpression(cEnumerator.ElementLocal, NodeType.LogicalNot), continueTarget));
      }
      if (forEach.TargetVariable != null) {
        Debug.Assert(cEnumerator.ElementCoercion != null);
        statements.Add(new AssignmentStatement(this.VisitTargetExpression(forEach.TargetVariable),
          this.VisitExpression(cEnumerator.ElementCoercion),forEach.TargetVariable.SourceContext));
      }
      //body
      this.continueTargets.Add(continueTarget);
      this.exitTargets.Add(exitTarget);
      statements.Add(this.VisitBlock(forEach.Body));
      this.continueTargets.Count--;
      this.exitTargets.Count--;
      //loop back
      statements.Add(new Branch(null, continueTarget));
      //exitTarget
      statements.Add(exitTarget);
      return result;
    }
Esempio n. 49
0
 public override Statement VisitYield(Yield Yield) {
   if (Yield == null) return null;
   if (this.currentFinallyClause != null) {
     this.HandleError(Yield, Error.BadFinallyLeave);
     return null;
   }
   if (this.insideCatchClause) {
     this.HandleError(Yield, Error.CannotYieldFromCatchClause);
     return null;
   }
   if (this.returnNode != null) {
     this.HandleError(this.returnNode, Error.ReturnNotAllowed);
     this.returnNode = null;
   }
   if (this.currentMethod == null) {
     Debug.Assert(false);
     return null;
   }
   if (Yield.Expression == null) {
     this.yieldNode = Yield;
     return Yield;
   }
   Expression e = Yield.Expression = this.VisitExpression(Yield.Expression);
   if (e == null) return null;
   TypeNode returnType = TypeNode.StripModifiers(this.currentMethod.ReturnType);
   if (returnType == null) return null;
   if (returnType.Template != SystemTypes.GenericIEnumerable && returnType.Template != SystemTypes.GenericIEnumerator &&
     returnType != SystemTypes.IEnumerable && returnType != SystemTypes.IEnumerator) {
     this.HandleError(Yield, Error.WrongReturnTypeForIterator, this.GetMethodSignature(this.currentMethod), this.GetTypeName(returnType));
     return null;
   }
   this.yieldNode = Yield;
   TypeNode eType = e.Type;
   TypeNode elemType;
   if (returnType == SystemTypes.IEnumerable || returnType == SystemTypes.IEnumerator)
     elemType = SystemTypes.Object;
   else
     elemType = this.typeSystem.GetStreamElementType(returnType, this.TypeViewer);
   Expression testCoercion = this.typeSystem.TryImplicitCoercion(e, elemType, this.TypeViewer);
   if (testCoercion != null || eType is TupleType || elemType == SystemTypes.Object)
     Yield.Expression = this.typeSystem.ImplicitCoercion(e, elemType, this.TypeViewer);
   else {
     e = this.typeSystem.ImplicitCoercion(e, returnType, this.TypeViewer);
     Local loc = new Local(elemType);
     ForEach forEach = new ForEach();
     forEach.TargetVariable = loc;
     forEach.TargetVariableType = loc.Type;
     forEach.SourceEnumerable = this.VisitEnumerableCollection(new Local(returnType), loc.Type);
     ((CollectionEnumerator)forEach.SourceEnumerable).Collection = e;
     forEach.Body = new Block(new StatementList(new Yield(loc)));
     forEach.ScopeForTemporaryVariables = new BlockScope(this.currentMethod.Scope, forEach.Body);
     return forEach;
   }
   return Yield;
 }
 public override Statement VisitForEach(ForEach forEach)
 {
   throw new ApplicationException("unimplemented");
 }
Esempio n. 51
0
 protected Node event2()
 {
     ForEach<GameObject> converse = new ForEach<GameObject>((daniel) =>
     {
         return
         new DecoratorPrintResult(
             new Sequence(
             wanderers[0].GetComponent<BehaviorMecanim>().ST_PlayGesture("ACKNOWLEDGE", AnimationLayer.Face, 1000),
             wanderers[0].GetComponent<BehaviorMecanim>().ST_PlayGesture("HEADSHAKE", AnimationLayer.Face, 1000),
             wanderers[0].GetComponent<BehaviorMecanim>().ST_PlayGesture("BEINGCOCKY", AnimationLayer.Hand, 1000),
             wanderers[0].GetComponent<BehaviorMecanim>().ST_PlayGesture("HEADNOD", AnimationLayer.Face, 1000)));
     }, wanderers);
     return new Sequence(converse);
 }
Esempio n. 52
0
 public virtual void VisitForEach(ForEach forEach)
 {
   if (forEach == null) return;
   this.VisitTypeReference(forEach.TargetVariableType);
   this.VisitTargetExpression(forEach.TargetVariable);
   this.VisitExpression(forEach.SourceEnumerable);
   this.VisitTargetExpression(forEach.InductionVariable);
   this.VisitLoopInvariantList(forEach.Invariants);
   this.VisitBlock(forEach.Body);
 }
Esempio n. 53
0
 public virtual Statement VisitForEach(ForEach forEach, ForEach changes, ForEach deletions, ForEach insertions){
   this.UpdateSourceContext(forEach, changes);
   if (forEach == null) return changes;
   if (changes != null){
     if (deletions == null || insertions == null)
       Debug.Assert(false);
     else{
     }
   }else if (deletions != null)
     return null;
   return forEach;
 }
Esempio n. 54
0
 // TODO: Handle default values in the comprehension
 // Q{U i in enumerable, P(i); T(i)}
 public override Expression VisitQuantifier(Quantifier quantifier) {
   if (quantifier == null) return null;
   Comprehension comprehension = quantifier.Comprehension;
   if (comprehension == null) return null;
   Block block = new Block(new StatementList());
   block.HasLocals = true;
   #region Create local to act as accumulator for the quantifier
   Local b = null;
   switch (quantifier.QuantifierType){
     case NodeType.Forall:
       b = new Local(Identifier.Empty,SystemTypes.Boolean,block);
       break;
     case NodeType.Exists:
       b = new Local(Identifier.Empty,SystemTypes.Boolean,block);
       break;
     case NodeType.ExistsUnique:
     case NodeType.Count:
     case NodeType.Max:
     case NodeType.Min:
     case NodeType.Product:
     case NodeType.Sum:
       b = new Local(Identifier.Empty,SystemTypes.Int32,block);
       break;
     default:
       Debug.Assert(false);
       return null;
   }
   #endregion Create local to act as accumulator for the quantifier
   
   if (comprehension.IsDisplay){
     #region Display: Generate a separate if-statement for each element
     Block endBlock = new Block(new StatementList());
     for(int i = 0, n = comprehension.Elements == null ? 0 : comprehension.Elements.Count; i < n; i++){
       #region assign the value of the term to b
       Statement updateB = null;
       switch (quantifier.QuantifierType){
         case NodeType.Forall:
           updateB = new AssignmentStatement(b,comprehension.Elements[i]);
           break;
         case NodeType.Exists:
           updateB = new AssignmentStatement(b,comprehension.Elements[i]);
           break;
         case NodeType.ExistsUnique:
         case NodeType.Count:
           // b := b + (T(i) ? 1 : 0)
           updateB = new AssignmentStatement(b,
             new BinaryExpression(b,
             new TernaryExpression(comprehension.Elements[i], Literal.Int32One, Literal.Int32Zero, NodeType.Conditional, SystemTypes.Int32),
             NodeType.Add));
           break;
         case NodeType.Product:
           // b := b * T(i)
           updateB = new AssignmentStatement(b, new BinaryExpression(b, comprehension.Elements[i], NodeType.Mul));
           break;
         case NodeType.Sum:
           // b := b + T(i)
           updateB = new AssignmentStatement(b, new BinaryExpression(b, comprehension.Elements[i], NodeType.Add));
           break;
         case NodeType.Max:
           // b := b < T(i) ? T(i) : b
           updateB = new AssignmentStatement(b,
             new TernaryExpression(new BinaryExpression(b, comprehension.Elements[i], NodeType.Lt, SystemTypes.Boolean),
             comprehension.Elements[i], b, NodeType.Conditional, SystemTypes.Int32));
           break;
         case NodeType.Min:
           // b := b > T(i) ? T(i) : b
           updateB = new AssignmentStatement(b,
             new TernaryExpression(new BinaryExpression(b, comprehension.Elements[i], NodeType.Gt, SystemTypes.Boolean),
             comprehension.Elements[i], b, NodeType.Conditional, SystemTypes.Int32));
           break;
         default:
           Debug.Assert(false);
           return null;
       }
       block.Statements.Add(updateB);
       #endregion assign the value of the term to b
       #region Test to see if loop should terminate early
       Expression condition = null;
       switch (quantifier.QuantifierType){
         case NodeType.Forall:
           condition = new UnaryExpression(b, NodeType.LogicalNot, SystemTypes.Boolean);
           block.Statements.Add(new Branch(condition, endBlock));
           break;
         case NodeType.Exists:
           condition = b;
           block.Statements.Add(new Branch(condition, endBlock));
           break;
         case NodeType.ExistsUnique:
           condition = new BinaryExpression(b,Literal.Int32One,NodeType.Gt,SystemTypes.Boolean);
           break;
         case NodeType.Count:
         case NodeType.Max:
         case NodeType.Min:
         case NodeType.Product:
         case NodeType.Sum:
           condition = Literal.False; // no short-circuit!! Need to evaluate all of the terms!
           break;
         default:
           Debug.Assert(false);
           return null;
       }
       #endregion Test to see if loop should terminate early
     }
     block.Statements.Add(endBlock);
     #endregion Display: Generate a separate if-statement for each element
   }else {
     #region "True" comprehension
     #region assign the value of the term to the accumulator
     Statement updateB = null;
     switch (quantifier.QuantifierType){
       case NodeType.Forall:
         // b := T(i);
         updateB = new AssignmentStatement(b,comprehension.Elements[0]);
         break;
       case NodeType.Exists:
         // b := T(i);
         updateB = new AssignmentStatement(b,comprehension.Elements[0]);
         break;
       case NodeType.ExistsUnique:
       case NodeType.Count:
         // b := b + T(i) ? 1 : 0; // TODO: is it better to try and generate "b += ..."?
         updateB = new AssignmentStatement(b,
           new BinaryExpression(b,
           new TernaryExpression(comprehension.Elements[0],Literal.Int32One,Literal.Int32Zero,NodeType.Conditional,SystemTypes.Int32),
           NodeType.Add));
         break;
       case NodeType.Product:
         // b := b * T(i)
         updateB = new AssignmentStatement(b,
           new BinaryExpression(b, comprehension.Elements[0], NodeType.Mul));
         break;
       case NodeType.Sum:
         // b := b + T(i)
         updateB = new AssignmentStatement(b,
           new BinaryExpression(b, comprehension.Elements[0], NodeType.Add));
         break;
       case NodeType.Max:
         // b := b < T(i) ? T(i) : b
         updateB = new AssignmentStatement(b,
           new TernaryExpression(new BinaryExpression(b, comprehension.Elements[0], NodeType.Lt, SystemTypes.Boolean),
           comprehension.Elements[0], b, NodeType.Conditional, SystemTypes.Int32));
         break;
       case NodeType.Min:
         // b := b > T(i) ? T(i) : b
         updateB = new AssignmentStatement(b,
           new TernaryExpression(new BinaryExpression(b, comprehension.Elements[0], NodeType.Gt, SystemTypes.Boolean),
           comprehension.Elements[0], b, NodeType.Conditional, SystemTypes.Int32));
         break;
       default:
         Debug.Assert(false);
         return null;
     }
     block.Statements.Add(updateB);
     #endregion assign the value of the term to the accumulator
     #region Generate the "foreach" and "if P(x)" parts
     for (int i = comprehension.BindingsAndFilters.Count - 1; i >= 0; i--) {
       ComprehensionBinding binding = comprehension.BindingsAndFilters[i] as ComprehensionBinding ;
       if (binding != null){
         #region Test to see if loop should terminate early
         Expression condition = null;
         switch (quantifier.QuantifierType){
           case NodeType.Forall:
             condition = new UnaryExpression(b,NodeType.LogicalNot,SystemTypes.Boolean);
             break;
           case NodeType.Exists:
             condition = b;
             break;
           case NodeType.ExistsUnique:
             condition = new BinaryExpression(b,Literal.Int32One,NodeType.Gt,SystemTypes.Boolean);
             break;
           case NodeType.Count:
           case NodeType.Max:
           case NodeType.Min:
           case NodeType.Product:
           case NodeType.Sum:
             condition = Literal.False; // no short-circuit!! Need to evaluate all of the terms!
             break;
           default:
             Debug.Assert(false);
             return null;
         }
         block.Statements.Add(new If(condition,new Block(new StatementList(new Exit())),null));
         #endregion Test to see if loop should terminate early
         #region Wrap everything so far into a loop (either for or foreach)
         Expression forEachTargetVariable = binding.TargetVariable;
         if (binding.AsTargetVariableType != null){
           Local l = new Local(Identifier.For("SS$dummyForEachVar"),binding.SourceEnumerable.Type,block);
           forEachTargetVariable = l;
           Block b2 = new Block(new StatementList(2));
           b2.Statements.Add(new AssignmentStatement(binding.TargetVariable,
             new BinaryExpression(l,new MemberBinding(null,binding.AsTargetVariableType),NodeType.Isinst,binding.AsTargetVariableType)));
           b2.Statements.Add(new If(new BinaryExpression(binding.TargetVariable,new Literal(null,SystemTypes.Type),NodeType.Ne),
             block,null));
           block = b2;
         }
         if (binding.SourceEnumerable== null) 
           return null;
         CollectionEnumerator ce = binding.SourceEnumerable as CollectionEnumerator;
         UnaryExpression u = ce == null ? null : ce.Collection as UnaryExpression;
         BinaryExpression be = u == null ? null : u.Operand as BinaryExpression;
         if (be != null && be.NodeType == NodeType.Range){
           // implement Range with a for-loop
           AssignmentStatement init = new AssignmentStatement(forEachTargetVariable,be.Operand1);
           AssignmentStatement incr = new AssignmentStatement(forEachTargetVariable,
             new BinaryExpression(forEachTargetVariable,new Literal(1,SystemTypes.Int32),NodeType.Add,SystemTypes.Int32));
           Expression cond = new BinaryExpression(forEachTargetVariable,be.Operand2,NodeType.Le,SystemTypes.Boolean);
           #region Add loop invariant "be.Operand1 <= forEachTargetVariable"
           Block invariantBlock = new Block(new StatementList());
           Assertion assertion = new Assertion(new BinaryExpression(be.Operand1, forEachTargetVariable, NodeType.Le, SystemTypes.Boolean));
           assertion.SourceContext = be.SourceContext;
           foreach (Statement s in this.SerializeAssertion(this.currentModule, assertion.Condition, "For loop index must be at least first operand of range.", assertion.SourceContext, "LoopInvariant")) {
             invariantBlock.Statements.Add(s);
           }
           // need to put the generated invariants in the for-loop's condition because that's where VisitFor
           // puts any user-declared invariants.
           invariantBlock.Statements.Add(new ExpressionStatement(cond, cond.SourceContext));
           cond = new BlockExpression(invariantBlock, SystemTypes.Boolean);
           #endregion
           For forloop = new For(new StatementList(init),cond,new StatementList(incr),block);
           block = new Block(new StatementList(forloop));
         }else{
           // Just use the source enumerable as an IEnumerable in a foreach loop
           ForEach fe = new ForEach(binding.SourceEnumerable.Type,forEachTargetVariable,binding.SourceEnumerable,block);
           fe.ScopeForTemporaryVariables = binding.ScopeForTemporaryVariables;
           block = new Block(new StatementList(fe));
         }
         #endregion Wrap everything so far into a loop (either for or foreach)
       }else{ // it's a filter
         block = new Block(new StatementList(new If(comprehension.BindingsAndFilters[i],block,null)));
       }
     }
     #endregion
     #endregion
   }
   #region Choose initial value for accumulator
   Literal initialValue = null;
   switch (quantifier.QuantifierType){
     case NodeType.Forall:
       initialValue = Literal.True;
       break;
     case NodeType.Exists:
       initialValue = Literal.False;
       break;
     case NodeType.ExistsUnique:
     case NodeType.Count:
     case NodeType.Sum:
       initialValue = Literal.Int32Zero;
       break;
     case NodeType.Product:
       initialValue = Literal.Int32One;
       break;
     case NodeType.Max:
       initialValue = new Literal(Int32.MinValue, SystemTypes.Int32);
       break;
     case NodeType.Min:
       initialValue = new Literal(Int32.MaxValue, SystemTypes.Int32);
       break;
     default:
       Debug.Assert(false);
       return null;
   }
   #endregion Choose initial value for accumulator
   #region Set the return value of the quantifier
   Expression valueToReturn = null;
   switch (quantifier.QuantifierType){
     case NodeType.Forall:
       valueToReturn = b;
       break;
     case NodeType.Exists:
       valueToReturn = b;
       break;
     case NodeType.ExistsUnique:
       valueToReturn = new BinaryExpression(b,Literal.Int32One,NodeType.Eq,SystemTypes.Boolean);
       break;
     case NodeType.Count:
     case NodeType.Max:
     case NodeType.Min:
     case NodeType.Product:
     case NodeType.Sum:
       valueToReturn = b;
       break;
     default:
       Debug.Assert(false);
       return null;
   }
   #endregion Set the boolean to return as the value of the quantifier
   BlockExpression returnBlock = new BlockExpression(
     new Block(new StatementList(
     new AssignmentStatement(b,initialValue),
     block,
     new ExpressionStatement(valueToReturn))),
     SystemTypes.Boolean,comprehension.SourceContext);
   if (this.quantifiedVarStack == null) this.quantifiedVarStack = new System.Collections.Generic.Stack<ExpressionList>();
   this.quantifiedVarStack.Push(comprehension.BindingsAndFilters);
   Expression result = this.VisitBlockExpression(returnBlock);
   this.quantifiedVarStack.Pop();
   return result;
 }