コード例 #1
0
ファイル: xblock.cs プロジェクト: blancosj/dodonet-framework
 internal xfor(For f)
 {
     initializer = parser(f.initializer);
     condition   = parser(f.condition);
     incrementer = parser(f.incrementer);
     body        = parser(f.body);
 }
コード例 #2
0
        protected override object VisitFor(For F)
        {
            target.PushScope();

            // Generate the loop header code.
            Visit(F.Init);

            string name = target.LabelName();

            LinqExprs.LabelTarget begin = LinqExpr.Label("for_" + name + "_begin");
            LinqExprs.LabelTarget end   = LinqExpr.Label("for_" + name + "_end");
            loops.Push(new Loop(LinqExpr.Goto(end), LinqExpr.Goto(begin)));

            // Check the condition, exit if necessary.
            target.Add(LinqExpr.Label(begin));
            target.Add(LinqExpr.IfThen(LinqExpr.Not(target.Compile(F.Condition)), LinqExpr.Goto(end)));

            // Generate the body code.
            Visit(F.Body);

            // Generate the step code.
            Visit(F.Step);
            target.Add(LinqExpr.Goto(begin));

            // Exit point.
            target.Add(LinqExpr.Label(end));

            loops.Pop();
            target.PopScope();

            return(null);
        }
コード例 #3
0
        public static Instruction[] ConvertFunction(MethodBody funcMethod, For forLoop)
        {
            var size         = funcMethod.Instructions.Count - 1;
            var result       = new Instruction[size];
            var instructions = funcMethod.Instructions;

            for (var i = 0; i < size; i++)
            {
                ref var res         = ref result[i];
                var     instruction = instructions[i];
                var     opCode      = instruction.OpCode;

                if (opCode == OpCodes.Ldarg_1 || opCode == OpCodes.Ldarga_S)
                {
                    res = LdLoc(forLoop.LocalDefinition);
                    continue;
                }

                if (opCode == OpCodes.Ret)
                {
                    continue;
                }

                res = instruction;
            }
コード例 #4
0
        public void MultipleInstancesYieldsSingleActualInvocationPerDistinctInvocation()
        {
            var instance1 = new ForTestingPurposes();
            var instance2 = new ForTestingPurposes();

            var adapter = new PerInstanceAdapter <IForTestingPurposes>(For.Ever());
            var proxy1  = adapter.Adapt(instance1);
            var proxy2  = adapter.Adapt(instance2);

            proxy1.MethodCall(0, "zero");
            proxy1.MethodCall(0, "zero");
            proxy1.MethodCall(1, "zero");
            proxy1.MethodCall(1, "zero");
            proxy1.MethodCall(2, "zero");
            proxy1.MethodCall(2, "zero");

            proxy2.MethodCall(0, "zero");
            proxy2.MethodCall(0, "zero");
            proxy2.MethodCall(1, "zero");
            proxy2.MethodCall(1, "zero");
            proxy2.MethodCall(2, "zero");
            proxy2.MethodCall(2, "zero");

            Assert.Equal <uint>(3, instance1.MethodCallInvocationCount);
            Assert.Equal <uint>(0, instance2.MethodCallInvocationCount);
        }
コード例 #5
0
ファイル: Parser.cs プロジェクト: chemaguiniga2/chimera
        public Node For()
        {
            var idToken    = Expect(TokenCategory.FOR);
            var identifier = new Identifier()
            {
                AnchorToken = Expect(TokenCategory.IDENTIFIER)
            };

            Expect(TokenCategory.IN);
            var expr = Expression();

            Expect(TokenCategory.DO);
            var stmtList = new StatementList();

            while (firstOfStatement.Contains(CurrentToken))
            {
                stmtList.Add(Statement());
            }
            Expect(TokenCategory.END);
            Expect(TokenCategory.ENDLINE);
            var result = new For()
            {
                identifier, expr, stmtList
            };

            result.AnchorToken = idToken;
            return(result);
            //Si nos estamos refiriendo a FormatException?
        }
コード例 #6
0
        public override void VisitFor(For p)
        {
            var continueLabel = IL.DefineLabel();

            VisitStatement(p.Initializer);

            EmitLoopSkeleton(continueLabel, (breakLabel) =>
            {
                var dofor = IL.DefineLabel();

                IL.MarkLabel(continueLabel);
                VisitExpression(p.Test);
                IL.Emit(OpCodes.Stloc, E);
                IL.Emit(OpCodes.Ldloca, E);
                IL.Emit(OpCodes.Call, isReal);
                IL.Emit(OpCodes.Brtrue, dofor);
                IL.Emit(OpCodes.Ldsfld, typeof(Error).GetField("ExpectedExpression"));
                IL.Emit(OpCodes.Newobj, typeof(ProgramError).GetConstructor(new[] { typeof(Error) }));
                IL.Emit(OpCodes.Throw);

                IL.MarkLabel(dofor);
                IL.Emit(OpCodes.Ldloc, E);
                EmitImplicitConversion(typeof(bool));
                IL.Emit(OpCodes.Brfalse, breakLabel);

                VisitStatement(p.Body);
                VisitStatement(p.Iterator);

                IL.Emit(OpCodes.Br, continueLabel);
            });
        }
コード例 #7
0
        public void ShouldBeAbleToCancelSchedule(WorkType workType)
        {
            var output   = new List <string>();
            var interval = TimeSpan.FromMilliseconds(100);
            var task     = default(Task);

            switch (workType)
            {
            case WorkType.Sync:
                task = _scheduler.Schedule(() => output.Add("one"), interval);
                break;

            case WorkType.Async:
                task = _scheduler.Schedule(async() =>
                {
                    output.Add("one");
                    await Task.Yield();
                }, interval);
                break;

            default:
                throw new Exception($"Unhandled test case {workType}.");
            }

            Within.FiveSeconds(() => output.Should().Equal(Enumerable.Repeat("one", 1)));

            _scheduler.CancelCurrent();

            Within.FiveSeconds(() => task.IsCanceled.Should().BeTrue());

            var marker = output.Count;

            For.OneSecond(() => output.Count.Should().Be(marker));
        }
コード例 #8
0
        public object VisitFor(For node)
        {
            EnterScope(node);
            Visit(node.Init);
            object result = null;

            while ((bool)Visit(node.Condition))
            {
                try
                {
                    result = Visit(node.Body);
                }
                catch (LoopBreakException)
                {
                    break;
                }
                catch (LoopContinueException)
                {
                }

                Visit(node.Update);
            }
            ExitScope();
            return(result);
        }
コード例 #9
0
        public void VisitFor(For statement)
        {
            var finish = Instruction.Create(OpCodes.Nop);
            var start  = Instruction.Create(OpCodes.Nop);

            if (statement.Initializer != null)
            {
                CompileForStatement(statement.Initializer);
            }
            cil.Append(start);

            if (statement.Condition != null)
            {
                var conditionType = CompileExpression(statement.Condition);
                if (conditionType == types.Bool)
                {
                    cil.Emit(OpCodes.Brfalse, finish);
                }
                else
                {
                    throw WrongType(statement.Condition, conditionType, types.Bool);
                }
            }

            CompileBlock(statement.Body);
            CompileForStatement(statement.Iterator);

            cil.Emit(OpCodes.Br, start);

            cil.Append(finish);
        }
コード例 #10
0
        public override void Process(TagHelperContext context, TagHelperOutput output)
        {
            output.TagName = "div";
            output.TagMode = TagMode.StartTagAndEndTag;
            output.Attributes.Add("class", "form-group");

            var required = "";

            if (For.Metadata.IsRequired)
            {
                required = " <span class='required'>*</span>";
            }


            var labeTag = new TagBuilder("label");

            labeTag.Attributes.Add("for", For.GetFullHtmlName(ViewContext));

            var displayName = For.Metadata?.DisplayName ?? For.Name;

            displayName += required;

            labeTag.InnerHtml.AppendHtml(displayName);

            var input         = GetInputTag();
            var validationTag = GetValidationTag();

            output.PreContent.AppendHtml(labeTag);
            output.PreContent.AppendHtml(input);
            output.PreContent.AppendHtml(validationTag);

            base.Process(context, output);
        }
コード例 #11
0
        public void WhenDefineNaturalIdThenRegister()
        {
            var inspector = new ExplicitlyDeclaredModel();
            var mapper    = new ModelMapper(inspector);

            mapper.Class <MyClass>(map =>
            {
                map.Id(x => x.Id, idmap => { });
                map.NaturalId(nidm =>
                {
                    nidm.Property(x => x.Name);
                    nidm.ManyToOne(x => x.Related);
                    nidm.Component(x => x.MyComponent, cmap =>
                    {
                        cmap.Property(y => y.FirstName);
                    });
                    nidm.Any(x => x.Any, typeof(int), anymap => { });
                });
            });

            Assert.That(inspector.IsMemberOfNaturalId(For <MyClass> .Property(x => x.Name)), Is.True);
            Assert.That(inspector.IsMemberOfNaturalId(For <MyClass> .Property(x => x.Related)), Is.True);
            Assert.That(inspector.IsMemberOfNaturalId(For <MyClass> .Property(x => x.MyComponent)), Is.True);
            Assert.That(inspector.IsMemberOfNaturalId(For <MyClass> .Property(x => x.Any)), Is.True);
        }
コード例 #12
0
ファイル: Parser.cs プロジェクト: k3ll3x/chimera-compiler
        public Node For()
        {
            var result = new For()
            {
                AnchorToken = Expect(TokenCategory.FOR)
            };

            result.Add(new Identifier()
            {
                AnchorToken = Expect(TokenCategory.IDENTIFIER)
            });
            Expect(TokenCategory.IN);
            result.Add(Expression());
            var dostatement = new Do()
            {
                AnchorToken = Expect(TokenCategory.DO)
            };

            while (firstOfStatement.Contains(CurrentToken))
            {
                dostatement.Add(Statement());
            }
            Expect(TokenCategory.END);
            Expect(TokenCategory.SEMICOL);
            result.Add(dostatement);
            return(result);
        }
コード例 #13
0
        public void WhenSetSyncWithNullThenDoesNotThrows()
        {
            var mapdoc = new HbmMapping();
            var rc     = new ClassMapper(typeof(EntitySimple), mapdoc, For <EntitySimple> .Property(x => x.Id));

            rc.Executing(x => x.Synchronize(null)).NotThrows();
        }
コード例 #14
0
        public void WhenMapExternalMemberAsComponentIdThenThrows()
        {
            var mapdoc = new HbmMapping();
            var mapper = new ClassMapper(typeof(Person), mapdoc, For <Person> .Property(x => x.Id));

            mapper.Executing(m => m.ComponentAsId(For <User> .Property(x => x.Id), map => map.Access(Accessor.Field))).Throws <ArgumentOutOfRangeException>();
        }
コード例 #15
0
        public void ForNextLoopWithNoVariableAndIntermediateGosubThrowsErrorTest()
        {
            SetupSut();
            var forCmd  = new For(_runEnvironment, _mockExpressionEvaluator.Object, _variableRepository);
            var nextCmd = new Next(_runEnvironment, _variableRepository);

            _mockExpressionEvaluator.SetupSequence(mee => mee.GetExpression())
            .Returns(new Accumulator(1.0))
            .Returns(new Accumulator(4.0));
            var line10 = new ProgramLine(10, new List <IToken> {
                new Token("A"), _equalToken, _toToken, _colonToken
            });
            var line30 = new ProgramLine(30, new List <IToken> {
                new Token("2")
            });

            // Execute for
            _runEnvironment.CurrentLine = line10;
            forCmd.Execute();

            // Pretend we've done a gosub
            _runEnvironment.ProgramStack.Push(new StackEntry());
            line30.CurrentToken         = 0;
            _runEnvironment.CurrentLine = line30;
            Test.Throws <NextWithoutForException>(nextCmd.Execute);
        }
コード例 #16
0
        public void WhenSetSyncWithNullThenDoesNotThrows()
        {
            var mapdoc = new HbmMapping();
            var rc     = new ClassMapper(typeof(EntitySimple), mapdoc, For <EntitySimple> .Property(x => x.Id));

            Assert.That(() => rc.Synchronize(null), Throws.Nothing);
        }
コード例 #17
0
        public void ForNextLoopWithoutVariableTest()
        {
            SetupSut();
            var forCmd  = new For(_runEnvironment, _mockExpressionEvaluator.Object, _variableRepository);
            var nextCmd = new Next(_runEnvironment, _variableRepository);

            _mockExpressionEvaluator.SetupSequence(mee => mee.GetExpression())
            .Returns(new Accumulator(1.0))
            .Returns(new Accumulator(3.0));
            var line10 = new ProgramLine(10, new List <IToken> {
                new Token("A"), _equalToken, _toToken, _colonToken
            });
            var line20 = new ProgramLine(20, new List <IToken> {
                new Token("1")
            });

            _runEnvironment.CurrentLine = line10;

            forCmd.Execute();
            Assert.AreEqual(1.0, _variableRepository.GetOrCreateVariable("A", new short[] { }).GetValue().ValueAsDouble());
            Assert.AreEqual(1, _runEnvironment.ProgramStack.Count);
            var loopBackToken = _runEnvironment.CurrentLine.CurrentToken;

            // Execute next,
            line20.CurrentToken         = 0;
            _runEnvironment.CurrentLine = line20;
            nextCmd.Execute();

            // variable should be 2
            Assert.AreEqual(2.0, _variableRepository.GetOrCreateVariable("A", new short[] { }).GetValue().ValueAsDouble());

            // Should be back to just after for loop.
            Assert.AreEqual(10, _runEnvironment.CurrentLine.LineNumber.Value);
            Assert.AreEqual(loopBackToken, _runEnvironment.CurrentLine.CurrentToken);

            // Execute next, variable should be 3
            line20.CurrentToken         = 0;
            _runEnvironment.CurrentLine = line20;
            nextCmd.Execute();
            Assert.AreEqual(3.0, _variableRepository.GetOrCreateVariable("A", new short[] { }).GetValue().ValueAsDouble());
            Assert.AreEqual(10, _runEnvironment.CurrentLine.LineNumber.Value);
            Assert.AreEqual(loopBackToken, _runEnvironment.CurrentLine.CurrentToken);

            // Execute next
            line20.CurrentToken         = 0;
            _runEnvironment.CurrentLine = line20;
            nextCmd.Execute();

            // So we have exited the loop
            Assert.AreEqual(20, _runEnvironment.CurrentLine.LineNumber.Value);

            // Did we leave behind the token.
            var token = _runEnvironment.CurrentLine.NextToken();

            Assert.AreEqual("1", token.Text);

            // Variable should be 4.0
            Assert.AreEqual(4.0, _variableRepository.GetOrCreateVariable("A", new short[] { }).GetValue().ValueAsDouble());
            Assert.AreEqual(0, _runEnvironment.ProgramStack.Count);
        }
コード例 #18
0
        public override void Process(TagHelperContext context, TagHelperOutput output)
        {
            var labelTag = new TagBuilder("label");

            labelTag.InnerHtml.Append(For.Metadata.Description);
            labelTag.AddCssClass("control-label");

            var pTag = new TagBuilder("p");

            pTag.AddCssClass("form-control-static form-tag-dd");

            if (Pipe == null || Pipe.Length <= 0)
            {
                pTag.InnerHtml.Append("{{" + For.AngularName() + "}}");
            }
            else
            {
                pTag.InnerHtml.Append("{{" + For.AngularName() + "|" + Pipe + "}}");
            }

            output.TagName = "div";
            output.Attributes.Add("class", "form-group");

            output.Content.AppendHtml(labelTag);
            output.Content.AppendHtml(pTag);
        }
コード例 #19
0
        /// <summary>
        /// Generates a for block with the specified loop conditions and body.
        /// </summary>
        /// <param name="init">The optional init statement.</param>
        /// <param name="condition">The optional condition statement.</param>
        /// <param name="post">The optional post statement.</param>
        /// <param name="body">The body of the for loop.</param>
        /// <returns>The root node of the for block AST.</returns>
        public static Node Generate(Node init, Node condition, Node post, IReadOnlyList <Node> body)
        {
            if (init != null || condition != null || post != null)
            {
                throw new NotImplementedException("init, condition and post are NYI");
            }

            if (body == null || body.Count == 0)
            {
                throw new ArgumentException(nameof(body));
            }

            var forBlock = new For();

            var openBrace = new OpenDelimiter(BinaryDelimiterType.Brace);

            foreach (var node in body)
            {
                openBrace.AddChild(node);
            }
            openBrace.AddClosingDelimiter();
            forBlock.AddChild(openBrace);

            return(forBlock);
        }
コード例 #20
0
        public void WhenTwoInterfacesThenReturnMemberInfoOfEachInterface()
        {
            var members = For <Person> .Property(x => x.Something).GetPropertyFromInterfaces();

            Assert.That(members, Contains.Item(For <IEntity> .Property(x => x.Something)));
            Assert.That(members, Contains.Item(For <IHasSomething> .Property(x => x.Something)));
        }
コード例 #21
0
ファイル: TagDdTagHelper.cs プロジェクト: boformer/A2SPA
        public override void Process(TagHelperContext context, TagHelperOutput output)
        {
            var pipe = string.IsNullOrEmpty(Pipe) ? string.Empty : Pipe;

            var labelTag = new TagBuilder("label");

            labelTag.InnerHtml.Append(For.Metadata.Description);
            labelTag.AddCssClass("control-label");

            var pTag = new TagBuilder("p");

            pTag.AddCssClass("form-control-static");

            var dataBindExpression = ((DefaultModelMetadata)For.Metadata).DataTypeName == "Password"
                                                ? "******"
                                                : "{{" + For.CamelizedName() + pipe + "}}";

            pTag.InnerHtml.Append(dataBindExpression);

            output.TagName = "div";
            output.Attributes.Add("class", "form-group");

            output.Content.AppendHtml(labelTag);
            output.Content.AppendHtml(pTag);
        }
コード例 #22
0
        public void WhenTwoInterfacesThenReturnMemberInfoOfEachInterface()
        {
            var members = For <Person> .Property(x => x.Something).GetPropertyFromInterfaces();

            members.Should().Contain(For <IEntity> .Property(x => x.Something));
            members.Should().Contain(For <IHasSomething> .Property(x => x.Something));
        }
コード例 #23
0
        public override string ToString()
        {
            string source = string.Empty;

            if (!From.Equals(string.Empty))
            {
                source += " from " + From + "\r\n ";
            }
            if (!By.Equals(string.Empty))
            {
                source += " by " + By + "\r\n ";
            }
            if (!With.Equals(string.Empty))
            {
                source += " with " + With + "\r\n ";
            }
            if (!For.Equals(string.Empty))
            {
                source += " for " + For + "\r\n ";
            }
            if (!Via.Equals(string.Empty))
            {
                source += " via " + Via + "\r\n ";
            }
            if (!Id.Equals(string.Empty))
            {
                source += " id " + Id + "\r\n ";
            }

            if (string.IsNullOrEmpty(source))
            {
                return("");
            }
            return(source.Remove(0, source.Length - 3) + ";" + Date.ToString("r"));
        }
コード例 #24
0
        public void WhenSplittedPropertiesThenRegister()
        {
            var inspector = new ExplicitlyDeclaredModel();
            var mapper    = new ModelMapper(inspector);

            mapper.Subclass <Inherited>(map =>
            {
                map.Join("MyClassSplit1", mj =>
                {
                    mj.Property(x => x.SomethingA1);
                    mj.Property(x => x.SomethingA2);
                });
                map.Join("MyClassSplit2", mj =>
                {
                    mj.Property(x => x.SomethingB1);
                    mj.Property(x => x.SomethingB2);
                });
                map.Property(x => x.Something0);
            });

            inspector.IsTablePerClassSplit(typeof(MyClass), "MyClassSplit1", For <Inherited> .Property(x => x.Something0)).Should().Be.False();
            inspector.IsTablePerClassSplit(typeof(MyClass), "MyClassSplit2", For <Inherited> .Property(x => x.Something0)).Should().Be.False();

            inspector.IsTablePerClassSplit(typeof(MyClass), "MyClassSplit1", For <Inherited> .Property(x => x.SomethingA1)).Should().Be.True();
            inspector.IsTablePerClassSplit(typeof(MyClass), "MyClassSplit1", For <Inherited> .Property(x => x.SomethingA2)).Should().Be.True();
            inspector.IsTablePerClassSplit(typeof(MyClass), "MyClassSplit2", For <Inherited> .Property(x => x.SomethingB1)).Should().Be.True();
            inspector.IsTablePerClassSplit(typeof(MyClass), "MyClassSplit2", For <Inherited> .Property(x => x.SomethingB2)).Should().Be.True();
        }
コード例 #25
0
        public Grid(int[,] map, float squareSize)
        {
            var nodeCountX = map.GetLength(0);
            var nodeCountY = map.GetLength(1);

            Width  = nodeCountX - 1;
            Height = nodeCountY - 1;
            var mapWidth  = nodeCountX * squareSize;
            var mapHeight = nodeCountY * squareSize;

            var controlNodes = new ControlNode[nodeCountX, nodeCountY];

            For.Xy(nodeCountX, nodeCountY, (x, y) =>
            {
                var position       = new Vector3(-mapWidth / 2 + x * squareSize + squareSize / 2, 0, -mapHeight / 2 + y * squareSize + squareSize / 2);
                controlNodes[x, y] = new ControlNode(position, map[x, y] == 1, squareSize);
            });

            _squares = new Square[Width, Height];

            For.Xy(Width, Height, (x, y) =>
            {
                _squares[x, y] = new Square(
                    controlNodes[x, y + 1],
                    controlNodes[x + 1, y + 1],
                    controlNodes[x + 1, y],
                    controlNodes[x, y]
                    );
            });
        }
コード例 #26
0
ファイル: Parser.cs プロジェクト: BetoVas97/chimera
        public Node For()
        {
            var result = new For()
            {
                AnchorToken = Expect(TokenCategory.FOR)
            };

            result.Add(new Identifier()
            {
                AnchorToken = Expect(TokenCategory.IDENTIFIER)
            });

            Expect(TokenCategory.IN);
            result.Add(Expression());
            Expect(TokenCategory.DO);

            var statementList = new StatementList();

            if (firstOfStatement.Contains(CurrentToken))
            {
                while (firstOfStatement.Contains(CurrentToken))
                {
                    statementList.Add(Statement());
                }
            }
            result.Add(statementList);

            Expect(TokenCategory.END);
            Expect(TokenCategory.SEMICOLON);
            return(result);
        }
コード例 #27
0
        public void AllKernelOfPixel()
        {
            var config   = new Config(6, 6, 3, 3);
            var position = new Position(config, 2, 3);
            var answer   = new[]
            {
                //    new [] { -1, 0 },
                new [] { 0, 0 },
                new [] { 1, 0 },
                new [] { 2, 0 },
                //  new [] { -1, 1 },
                new [] { 0, 1 },
                new [] { 1, 1 },
                new [] { 2, 1 },
                //new [] { -1, 2 },
                new [] { 0, 2 },
                new [] { 1, 2 },
                new [] { 2, 2 },
            };

            int counter = 0;

            For.AllKernelOfPixel(config, position, (c, k) => {
                Assert.AreEqual(k.x, answer[counter][0]);
                Assert.AreEqual(k.y, answer[counter][1]);
                counter++;
            });

            Assert.AreEqual(counter, answer.Length);
        }
コード例 #28
0
        public static DataTable DataOutPut(For @for)
        {
            Dek TB;

            if (FileEx(FilePath))
            {
                TB = DataLoadSave.LoadXML(FilePath);

                DataSet Ds = new DataSet("Students");
                //DataTable DekDataTable = new DataTable("DekDataTable");
                DataTable StudentT = InitealDTStudent();
                DataTable GroupeT  = InitealDTSGrope();
                DataTable RoomT    = InitealDTRoom();
                DataTable HostelT  = InitealDTSHostel();

                Ds.Tables.Add(StudentT);
                Ds.Tables.Add(GroupeT);
                Ds.Tables.Add(RoomT);
                Ds.Tables.Add(HostelT);

                switch (@for)
                {
                case For.Student:
                    foreach (StudentsTable S in TB.Students)
                    {
                        StudentT.Rows.Add(new object[] { S.ID, S.ThirdName_1 + " " + S.Name_2 + " " + S.SurnameName_3,
                                                         GetGroupeNameByID(TB, S.GroupeID), GetRoomNumberByRoomID(TB, S.RoomID), S.TicetNumber, S.FormStudy, S.ContractBudget, S.Description });
                    }
                    return(StudentT);

                case For.Groupe:
                    foreach (GroupeTable G in TB.Groupes)
                    {
                        GroupeT.Rows.Add(new object[] { G.ID, G.GroupeNumber, G.StudentsInGroupe, G.Description });
                    }
                    return(GroupeT);

                case For.Room:
                    foreach (RoomTable R in TB.Roomes)
                    {
                        RoomT.Rows.Add(new object[] { R.ID, GetHostelNameByID(TB, R.HostelID), R.RoomNumber, R.AllPlace, R.FreePlase, R.Description });
                    }
                    return(RoomT);

                case For.Hostel:
                    foreach (HostelNewTable H in TB.HostelsN)
                    {
                        HostelT.Rows.Add(new object[] { H.ID, H.Frame, H.RoomsCount, H.Decription });
                    }
                    return(HostelT);

                default: return(null);
                }
            }
            else
            {
                return(null);
            }
        }
コード例 #29
0
        public void CanSetPersister()
        {
            var mapdoc = new HbmMapping();
            var rc     = new ClassMapper(typeof(EntitySimple), mapdoc, For <EntitySimple> .Property(x => x.Id));

            rc.Persister <SingleTableEntityPersister>();
            Assert.That(mapdoc.RootClasses[0].Persister, Does.Contain("SingleTableEntityPersister"));
        }
コード例 #30
0
        public void WhenSetMoreSyncThenAddAll()
        {
            var mapdoc = new HbmMapping();
            var rc     = new ClassMapper(typeof(EntitySimple), mapdoc, For <EntitySimple> .Property(x => x.Id));

            rc.Synchronize("T1", "T2", "T3", null);
            Assert.That(mapdoc.RootClasses[0].Synchronize.Select(x => x.table), Is.EquivalentTo(new [] { "T1", "T2", "T3" }));
        }
コード例 #31
0
ファイル: ForUI.cs プロジェクト: kvchernyaev/My.Example
 public ForUI([NotNull] UserDTO u, For f)
         : this(u.UserId.ToString())
 {
     Init(f, () =>
                 {
                     Caption = u.UserFio;
                     ToolTip = string.Format("{0} ({1})", u.Login, u.UserId);
                 },
          () => { Caption = string.Format("{0}", u.UserFio); });
 }
コード例 #32
0
ファイル: ForUI.cs プロジェクト: kvchernyaev/My.Example
 public ForUI([NotNull] UserRoleDTO ur, For f)
         : this(ur.UserRoleId)
 {
     Init(f, () =>
                 {
                     Caption = ur.Name;
                     ToolTip = ur.Description.TrimOrNullIfEmpty();
                     ForeColor = ur.Color();
                 },
          () =>
              {
                  string desc = ur.Description.TrimOrNullIfEmpty();
                  Caption = string.Format("{0}{1}", ur.Name, string.IsNullOrEmpty(desc) ? "" : " (" + desc + ")");
              });
 }
コード例 #33
0
        public override void VisitFor(For p)
        {
            var continueLabel = IL.DefineLabel();

            VisitStatement(p.Initializer);

            EmitLoopSkeleton(continueLabel, (breakLabel) =>
            {
                var dofor = IL.DefineLabel();

                IL.MarkLabel(continueLabel);
                VisitExpression(p.Test);
                IL.Emit(OpCodes.Stloc, E);
                IL.Emit(OpCodes.Ldloca, E);
                IL.Emit(OpCodes.Call, isReal);
                IL.Emit(OpCodes.Brtrue, dofor);
                IL.Emit(OpCodes.Ldsfld, typeof(Error).GetField("ExpectedExpression"));
                IL.Emit(OpCodes.Newobj, typeof(ProgramError).GetConstructor(new[] { typeof(Error) }));
                IL.Emit(OpCodes.Throw);

                IL.MarkLabel(dofor);
                IL.Emit(OpCodes.Ldloc, E);
                EmitImplicitConversion(typeof(bool));
                IL.Emit(OpCodes.Brfalse, breakLabel);

                VisitStatement(p.Body);
                VisitStatement(p.Iterator);

                IL.Emit(OpCodes.Br, continueLabel);
            });
        }
コード例 #34
0
    public virtual Differences VisitFor(For for1, For for2){
      Differences differences = new Differences(for1, for2);
      if (for1 == null || for2 == null){
        if (for1 != for2) differences.NumberOfDifferences++; else differences.NumberOfSimilarities++;
        return differences;
      }
      For changes = (For)for2.Clone();
      For deletions = (For)for2.Clone();
      For insertions = (For)for2.Clone();

      Differences diff = this.VisitBlock(for1.Body, for2.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.VisitExpressionList(for1.Invariants, for2.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(for1.Condition, for2.Condition);
      if (diff == null){Debug.Assert(false); return differences;}
      changes.Condition = diff.Changes as Expression;
      deletions.Condition = diff.Deletions as Expression;
      insertions.Condition = diff.Insertions as Expression;
      Debug.Assert(diff.Changes == changes.Condition && diff.Deletions == deletions.Condition && diff.Insertions == insertions.Condition);
      differences.NumberOfDifferences += diff.NumberOfDifferences;
      differences.NumberOfSimilarities += diff.NumberOfSimilarities;

      StatementList statChanges, statDeletions, statInsertions;
      diff = this.VisitStatementList(for1.Incrementer, for2.Incrementer, out statChanges, out statDeletions, out statInsertions);
      if (diff == null){Debug.Assert(false); return differences;}
      changes.Initializer = statChanges;
      deletions.Initializer = statDeletions;
      insertions.Initializer = statInsertions;
      differences.NumberOfDifferences += diff.NumberOfDifferences;
      differences.NumberOfSimilarities += diff.NumberOfSimilarities;

      diff = this.VisitStatementList(for1.Initializer, for2.Initializer, out statChanges, out statDeletions, out statInsertions);
      if (diff == null){Debug.Assert(false); return differences;}
      changes.Initializer = statChanges;
      deletions.Initializer = statDeletions;
      insertions.Initializer = statInsertions;
      differences.NumberOfDifferences += diff.NumberOfDifferences;
      differences.NumberOfSimilarities += diff.NumberOfSimilarities;

      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;
    }
コード例 #35
0
ファイル: StandardVisitor.cs プロジェクト: dbremner/specsharp
 public virtual Statement VisitFor(For For){
   if (For == null) return null;
   For.Initializer = this.VisitStatementList(For.Initializer);
   For.Invariants = this.VisitLoopInvariantList(For.Invariants);
   For.Condition = this.VisitExpression(For.Condition);
   For.Incrementer = this.VisitStatementList(For.Incrementer);
   For.Body = this.VisitBlock(For.Body);
   return For;
 }
コード例 #36
0
ファイル: visit.cs プロジェクト: furesoft/NRefactory
		public virtual object Visit (For forStatement)
		{
			return null;
		}
コード例 #37
0
			public override object Visit (For forStatement)
			{
				var result = new ForStatement ();
				
				var location = LocationsBag.GetLocations (forStatement);
				
				result.AddChild (new CSharpTokenNode (Convert (forStatement.loc), ForStatement.ForKeywordRole), ForStatement.ForKeywordRole);
				if (location != null)
					result.AddChild (new CSharpTokenNode (Convert (location [0]), Roles.LPar), Roles.LPar);
				
				AddStatementOrList (result, forStatement.Initializer, ForStatement.InitializerRole);
				
				if (location != null && location.Count > 1)
					result.AddChild (new CSharpTokenNode (Convert (location [1]), Roles.Semicolon), Roles.Semicolon);
				if (forStatement.Condition != null)
					result.AddChild ((Expression)forStatement.Condition.Accept (this), Roles.Condition);
				if (location != null && location.Count >= 3)
					result.AddChild (new CSharpTokenNode (Convert (location [2]), Roles.Semicolon), Roles.Semicolon);
				
				AddStatementOrList (result, forStatement.Iterator, ForStatement.IteratorRole);
				
				if (location != null && location.Count >= 4)
					result.AddChild (new CSharpTokenNode (Convert (location [3]), Roles.RPar), Roles.RPar);
				
				if (forStatement.Statement != null)
					result.AddChild ((Statement)forStatement.Statement.Accept (this), Roles.EmbeddedStatement);
				
				return result;
			}
コード例 #38
0
ファイル: Checker.cs プロジェクト: hesam/SketchSharp
 public override Statement VisitFor(For For) {
   if (For == null) return null;
   this.loopCount++;
   For.Initializer = this.VisitStatementList(For.Initializer);
   For.Invariants = this.VisitLoopInvariantList(For.Invariants);
   For.Condition = this.VisitBooleanExpression(For.Condition);
   For.Incrementer = this.VisitStatementList(For.Incrementer);
   For.Body = this.VisitBlock(For.Body);
   this.loopCount--;
   return For;
 }
コード例 #39
0
ファイル: Normalizer.cs プロジェクト: dbremner/specsharp
 public override Statement VisitFor(For For){
   if (For == null) return null;
   StatementList statements = new StatementList(6);
   Block forBlock = new Block(statements);
   forBlock.SourceContext = For.SourceContext;
   int n = For.Incrementer.Count;
   StatementList incrStatements = new StatementList(n);
   Block incrBlock = new Block(incrStatements);
   this.continueTargets.Add(incrBlock);
   Block endOfLoop = new Block(null);
   this.exitTargets.Add(endOfLoop);
   this.VisitStatementList(For.Initializer);
   Statement forCondition = null;
   if (For.Condition != null)
     forCondition = this.VisitAndInvertBranchCondition(For.Condition, endOfLoop, For.Condition.SourceContext);
   For.Incrementer = this.VisitStatementList(For.Incrementer);
   this.VisitBlock(For.Body);
   statements.Add(new Block(For.Initializer));
   StatementList conditionStatements = new StatementList(1);
   Block condition = new Block(conditionStatements);
   statements.Add(condition);
   ExpressionList invariants = For.Invariants;
   if (invariants != null && invariants.Count > 0)
     conditionStatements.Add(VisitLoopInvariants(invariants));
   if (forCondition != null) conditionStatements.Add(forCondition);
   statements.Add(For.Body);
   for (int i = 0; i < n; i++) incrStatements.Add(For.Incrementer[i]);
   statements.Add(incrBlock);
   statements.Add(new Branch(null, condition));   
   statements.Add(endOfLoop);
   this.continueTargets.Count--;
   this.exitTargets.Count--;
   return forBlock;
 }
コード例 #40
0
ファイル: Normalizer.cs プロジェクト: dbremner/specsharp
 // 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;
 }
コード例 #41
0
ファイル: Normalizer.cs プロジェクト: dbremner/specsharp
    // {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
    }
コード例 #42
0
ファイル: Inspector.cs プロジェクト: a780201/CodeContracts
 public virtual void VisitFor(For For)
 {
   if (For == null) return;
   this.VisitStatementList(For.Initializer);
   this.VisitLoopInvariantList(For.Invariants);
   this.VisitExpression(For.Condition);
   this.VisitStatementList(For.Incrementer);
   this.VisitBlock(For.Body);
 }
コード例 #43
0
 public override Statement VisitFor(For For)
 {
   throw new ApplicationException("unimplemented");
 }
コード例 #44
0
ファイル: cs-parser.cs プロジェクト: furesoft/NRefactory
void case_936()
#line 6238 "cs-parser.jay"
{
		start_block (GetLocation (yyVals[0+yyTop]));
		current_block.IsCompilerGenerated = true;
		For f = new For (GetLocation (yyVals[-1+yyTop]));
		current_block.AddStatement (f);
		lbag.AddStatement (f, current_block.StartLocation);
		yyVal = f;
	  }
コード例 #45
0
ファイル: _ast.cs プロジェクト: rchandrashekara/main
            internal static stmt Convert(Statement stmt) {
                stmt ast;

                if (stmt is FunctionDefinition)
                    ast = new FunctionDef((FunctionDefinition)stmt);
                else if (stmt is ReturnStatement)
                    ast = new Return((ReturnStatement)stmt);
                else if (stmt is AssignmentStatement)
                    ast = new Assign((AssignmentStatement)stmt);
                else if (stmt is AugmentedAssignStatement)
                    ast = new AugAssign((AugmentedAssignStatement)stmt);
                else if (stmt is DelStatement)
                    ast = new Delete((DelStatement)stmt);
                else if (stmt is PrintStatement)
                    ast = new Print((PrintStatement)stmt);
                else if (stmt is ExpressionStatement)
                    ast = new Expr((ExpressionStatement)stmt);
                else if (stmt is ForStatement)
                    ast = new For((ForStatement)stmt);
                else if (stmt is WhileStatement)
                    ast = new While((WhileStatement)stmt);
                else if (stmt is IfStatement)
                    ast = new If((IfStatement)stmt);
                else if (stmt is WithStatement)
                    ast = new With((WithStatement)stmt);
                else if (stmt is RaiseStatement)
                    ast = new Raise((RaiseStatement)stmt);
                else if (stmt is TryStatement)
                    ast = Convert((TryStatement)stmt);
                else if (stmt is AssertStatement)
                    ast = new Assert((AssertStatement)stmt);
                else if (stmt is ImportStatement)
                    ast = new Import((ImportStatement)stmt);
                else if (stmt is FromImportStatement)
                    ast = new ImportFrom((FromImportStatement)stmt);
                else if (stmt is ExecStatement)
                    ast = new Exec((ExecStatement)stmt);
                else if (stmt is GlobalStatement)
                    ast = new Global((GlobalStatement)stmt);
                else if (stmt is ClassDefinition)
                    ast = new ClassDef((ClassDefinition)stmt);
                else if (stmt is BreakStatement)
                    ast = new Break();
                else if (stmt is ContinueStatement)
                    ast = new Continue();
                else if (stmt is EmptyStatement)
                    ast = new Pass();
                else
                    throw new ArgumentTypeException("Unexpected statement type: " + stmt.GetType());

                ast.GetSourceLocation(stmt);
                return ast;
            }
コード例 #46
0
 void OP_FOR(out pBaseLangObject outObj, pBaseLangObject parent)
 {
     var obj = new For(parent); outObj = obj; pBaseLangObject blo;
     Expect(61);
     Expect(10);
     if (StartOf(19)) {
         CODEINSTRUCTION_SC(out blo, obj);
         obj.forArg1 = blo;
     }
     TERMINATOR();
     if (StartOf(3)) {
         EXPRESSION(out blo, obj);
         obj.forArg2 = blo;
     }
     TERMINATOR();
     if (StartOf(19)) {
         CODEINSTRUCTION_SC(out blo, obj);
         obj.forArg3 = blo;
     }
     Expect(11);
     if (la.kind == 14) {
         Get();
         while (StartOf(21)) {
             if (StartOf(14)) {
                 CODEINSTRUCTION(out blo, obj);
                 obj.addChild(blo);
             } else {
                 OP_BREAK(out blo, obj);
                 obj.addChild(blo);
                 TERMINATOR();
             }
         }
         Expect(15);
     } else if (StartOf(14)) {
         CODEINSTRUCTION(out blo, obj);
         obj.addChild(blo);
     } else SynErr(107);
 }
コード例 #47
0
ファイル: Updater.cs プロジェクト: asvishnyakov/CodeContracts
 public virtual Statement VisitFor(For For, For changes, For deletions, For insertions){
   this.UpdateSourceContext(For, changes);
   if (For == null) return changes;
   if (changes != null){
     if (deletions == null || insertions == null)
       Debug.Assert(false);
     else{
     }
   }else if (deletions != null)
     return null;
   return For;
 }
コード例 #48
0
ファイル: Duplicator.cs プロジェクト: hnlshzx/DotNetOpenAuth
 public override Statement VisitFor(For For)
 {
     if (For == null) return null;
     return base.VisitFor((For)For.Clone());
 }
コード例 #49
0
 public virtual Statement VisitFor(For For1, For For2)
 {
     if (For1 == null) return null;
     if (For2 == null)
     {
         For1.Initializer = this.VisitStatementList(For1.Initializer, null);
         For1.Invariants = this.VisitExpressionList(For1.Invariants, null);
         For1.Condition = this.VisitExpression(For1.Condition, null);
         For1.Incrementer = this.VisitStatementList(For1.Incrementer, null);
         For1.Body = this.VisitBlock(For1.Body, null);
     }
     else
     {
         For1.Initializer = this.VisitStatementList(For1.Initializer, For2.Initializer);
         For1.Invariants = this.VisitExpressionList(For1.Invariants, For2.Invariants);
         For1.Condition = this.VisitExpression(For1.Condition, For2.Condition);
         For1.Incrementer = this.VisitStatementList(For1.Incrementer, For2.Incrementer);
         For1.Body = this.VisitBlock(For1.Body, For2.Body);
     }
     return For1;
 }
コード例 #50
0
void case_875()
#line 6733 "ps-parser.jay"
{
	    lexer.ForInParsing = false;
	  
		var locations = (Tuple<Location,Location>) yyVals[-2+yyTop];

		For f = new For (locations.Item1);
		current_block.AddStatement (f);
		
		var expList = yyVals[-1+yyTop] as List<Expression>;
		if (expList != null) 
			f.Initializer = ExpressionListToStatementList (expList);
		else
			f.Initializer = (Statement) yyVals[-1+yyTop];

		/* Pass the "For" object to the iterator_part4*/
		oob_stack.Push (f);
		
		yyVal = f;
	  }