private bool Match(StatementCollection statements)
        {
            this.statements = statements;

            yieldDeclaringType = GetGeneratedType();

            if (yieldDeclaringType == null)
            {
                return false;
            }

            IEnumerable<Statement> moveNextMethodStatements = GetStatements();
            if (moveNextMethodStatements == null || yieldData == null)
            {
                return false;
            }

            if (statements.Count > 2)
            {
                SetParameterMappings();
                StatementCollection getEnumeratorStatements = GetEnumeratorStatements();
                if (getEnumeratorStatements != null)
                {
                    PostProcessMappings(getEnumeratorStatements);
                }
            }

            newStatements = new StatementCollection();
            foreach (Statement statement in moveNextMethodStatements)
            {
                newStatements.Add(statement);
            }

            return true;
        }
        private StatementCollection GetStatementsForInvocation(out int endIndex, out int startIndex, out bool isBaseCtor)
        {
            startIndex = 0;
            StatementCollection bodyStatements = methodBodyBlock.Statements;
            StatementCollection statements = new StatementCollection();
            isBaseCtor = false;
            int index = 0;
            for (; index < bodyStatements.Count; index++)
            {
                if (IsVariableDeclaration(bodyStatements[index]) && statements.Count == 0)
                {
                    startIndex++;
                    continue;
                }
                statements.Add(bodyStatements[index].Clone());
                if (IsCtorInvocation(bodyStatements[index], out isBaseCtor))
                {
                    if (isBaseCtor)
                    {
                        methodContext.IsBaseConstructorInvokingConstructor = true;
                    }
                    break;
                }
            }

            endIndex = index;

            if (index == bodyStatements.Count)
            {
                endIndex = -1;
                statements = null;
            }

            return statements;
        }
        public void ShouldAddToCollection(IFixture fixture)
        {
            var sut = new StatementCollection(new List <IStatement>());

            sut.Add(fixture.Create <IStatement>());

            sut.Statements.Should().HaveCount(1);
        }
Ejemplo n.º 4
0
        public void ToCodeDomFull(StatementCollection sts)
        {
            // create enumrator and initialize it
            sts.Add(Stm.Comment("<foreach>"));
            sts.Add(Stm.Comment("This loop mimics a foreach call. See C# programming language, pg 247"));
            sts.Add(Stm.Comment("Here, the enumerator is seale and does not implement IDisposable"));
            VariableDeclarationStatement enDecl = Stm.Var(
                typeof(IEnumerator),
                "enumerator",
                this.Collection.Method("GetEnumerator").Invoke()
                );

            sts.Add(enDecl);

            // get expression
            VariableReferenceExpression en = Expr.Var(enDecl);

            // iterate
            IterationStatement iter = Stm.While(en.Method("MoveNext").Invoke());

            sts.Add(iter);
            // get local parameter
            VariableDeclarationStatement localDecl = Stm.Var(
                this.LocalType,
                this.LocalName
                );

            localDecl.InitExpression = (en.Prop("Current")).Cast(this.LocalType);
            iter.Statements.Add(localDecl);

            // add statements
            iter.Statements.Add(Stm.Comment("foreach body"));
            iter.Statements.AddRange(this.body);
            sts.Add(Stm.Comment("</foreach>"));
        }
Ejemplo n.º 5
0
        protected CodeBlockStatement(SerializationInfo info)
            : base(info)
        {
            Label = info.GetString("label");

            Statements = new StatementCollection(this);
            var statements = info.GetValue <SqlStatement[]>("statements");

            foreach (var statement in statements)
            {
                Statements.Add(statement);
            }
        }
Ejemplo n.º 6
0
        private ICollection <SqlStatement> DeserializeObjects(SerializationInfo info)
        {
            var count = info.GetInt32("Statements.Count");

            var list = new StatementCollection(this);

            for (int i = 0; i < count; i++)
            {
                var statement = (SqlStatement)info.GetValue(String.Format("Statement[{0}]", i), typeof(SqlStatement));
                list.Add(statement);
            }

            return(list);
        }
Ejemplo n.º 7
0
        public static StatementCollection Parse(string content)
        {
            var statements = new StatementCollection();

            statements.Balance = _balance;
            var doc = new HtmlDocument();

            doc.LoadHtml(content);
            var rows = doc.DocumentNode.SelectNodes("/html[1]/body[1]/div[1]/div[4]/div[1]/div[2]/table[1]/tbody[1]/tr[position()>1]");

            if (rows != null)
            {
                for (int i = 0; i < rows.Count - 2; i++)
                {
                    var row    = rows[i];
                    var fields = row.SelectNodes("./td");
                    if (fields == null)
                    {
                        continue;
                    }
                    // data/transaction/debit/credit/balance
                    if (fields.Count == 5)
                    {
                        var statement = new Statement();
                        statement.ID   = RemoveComma(CryptographyHelper.MD5(row.InnerHtml));
                        statement.Date = RemoveComma(ContentHelper.Clear(fields[0].InnerHtml, " "));

                        statement.Description = RemoveComma(ContentHelper.Clear(fields[1].InnerHtml, " "));
                        statement.Debit       = ContentHelper.Clear(fields[2].InnerHtml).Replace(".", "").Replace(",", ".");
                        statement.Credit      = ContentHelper.Clear(fields[3].InnerHtml).Replace(".", "").Replace(",", ".");
                        statement.Balance     = ContentHelper.Clear(fields[4].InnerHtml).Replace(".", "").Replace(",", ".");
                        statements.Add(statement);
                    }
                }
            }

            statements.Balance = (statements[statements.Count - 1] as Statement).Balance;

            return(statements);
        }
Ejemplo n.º 8
0
        private StatementCollection GetStatementsForInvocation(out int endIndex, out int startIndex, out bool isBaseCtor)
        {
            startIndex = 0;
            StatementCollection bodyStatements = methodBodyBlock.Statements;
            StatementCollection statements     = new StatementCollection();

            isBaseCtor = false;
            int index = 0;

            for (; index < bodyStatements.Count; index++)
            {
                if (IsVariableDeclaration(bodyStatements[index]) && statements.Count == 0)
                {
                    startIndex++;
                    continue;
                }
                statements.Add(bodyStatements[index].Clone());
                if (IsCtorInvocation(bodyStatements[index], out isBaseCtor))
                {
                    if (isBaseCtor)
                    {
                        methodContext.IsBaseConstructorInvokingConstructor = true;
                    }
                    break;
                }
            }

            endIndex = index;

            if (index == bodyStatements.Count)
            {
                endIndex   = -1;
                statements = null;
            }

            return(statements);
        }
 private StatementCollection GetStatementsForInvocation(out int endIndex, out int startIndex, out bool isBaseCtor)
 {
     startIndex = 0;
     V_0        = this.methodBodyBlock.get_Statements();
     V_1        = new StatementCollection();
     isBaseCtor = false;
     V_2        = 0;
     while (V_2 < V_0.get_Count())
     {
         if (!this.IsVariableDeclaration(V_0.get_Item(V_2)) || V_1.get_Count() != 0)
         {
             V_1.Add(V_0.get_Item(V_2).Clone());
             if (this.IsCtorInvocation(V_0.get_Item(V_2), out isBaseCtor))
             {
                 if (!isBaseCtor)
                 {
                     break;
                 }
                 this.methodContext.set_IsBaseConstructorInvokingConstructor(true);
                 break;
             }
         }
         else
         {
             startIndex = startIndex + 1;
         }
         V_2 = V_2 + 1;
     }
     endIndex = V_2;
     if (V_2 == V_0.get_Count())
     {
         endIndex = -1;
         V_1      = null;
     }
     return(V_1);
 }
        private bool Match(StatementCollection statements)
        {
            this.statements = statements;

            yieldDeclaringType = GetGeneratedType();

            if (yieldDeclaringType == null)
            {
                return(false);
            }

            IEnumerable <Statement> moveNextMethodStatements = GetStatements();

            if (moveNextMethodStatements == null || yieldData == null)
            {
                return(false);
            }

            if (statements.Count > 2)
            {
                SetParameterMappings();
                StatementCollection getEnumeratorStatements = GetEnumeratorStatements();
                if (getEnumeratorStatements != null)
                {
                    PostProcessMappings(getEnumeratorStatements);
                }
            }

            newStatements = new StatementCollection();
            foreach (Statement statement in moveNextMethodStatements)
            {
                newStatements.Add(statement);
            }

            return(true);
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Coppies the block that is targeted from the goto if it matches the case
        /// 
        /// ... some code
        /// goto: label0;
        /// 
        /// ...
        /// ...
        /// label0: statement1
        /// *statements*
        /// return;
        /// ...
        /// </summary>
        /// <param name="labeledStatement">The targeted statement.</param>
        /// <param name="gotoStatement">The goto statement.</param>
        /// <returns>Returns True if the targeted block was coppied.</returns>
        private bool TryCopyTargetedBlock(Statement labeledStatement, GotoStatement gotoStatement)
        {
            StatementCollection toCopy = new StatementCollection();
            StatementCollection originalStatements = new StatementCollection();
            BlockStatement targetParent = labeledStatement.Parent as BlockStatement;
            if (targetParent == null)
            {
                return false;
            }
            int targetIndex = targetParent.Statements.IndexOf(labeledStatement);
            originalStatements.Add(labeledStatement);
            Statement labeledClone = labeledStatement.CloneStatementOnly();
            labeledClone.Label = string.Empty;
            toCopy.Add(labeledClone);

			int maxStatementsToCopy = MaximumStatementsToCopy;

            if (ContainsLabel(labeledClone))
            {
                return false;
            }

			maxStatementsToCopy -= GetStatementsCount(labeledClone);
			if (maxStatementsToCopy < 0)
			{
				return false;
			}

            if (!IsReturnStatement(labeledClone) && !IsThrowStatement(labeledClone))
            {
                ///Collect all statements, until a return is reached.
                int index;
                for (index = targetIndex + 1; index < targetParent.Statements.Count; index++)
                {
                    Statement nextStatement = targetParent.Statements[index];
                    if (ContainsLabel(nextStatement))
                    {
                        return false;
                    }

					maxStatementsToCopy -= GetStatementsCount(nextStatement);
					if (maxStatementsToCopy < 0)
					{
						return false;
					}

                    originalStatements.Add(nextStatement);
                    Statement clone = nextStatement.CloneStatementOnly();
                    toCopy.Add(clone);
                    if (IsReturnStatement(nextStatement) || IsThrowStatement(nextStatement))
                    {
                        break;
                    }
                }
                if (index == targetParent.Statements.Count)
                {
                    ///all the statements were traversed and no 'return' statement was found
                    return false;
                }
            }
            ///Move the coppied statements on the place of the goto statement.
            MoveStatements(gotoStatement, toCopy);

            ///Clean up the label from the targeted statement if possible, and remove the targeted statement if it cannot be reached anymore
            if (!Targeted(labeledStatement.Label))
            {
                UpdateUntargetedStatement(labeledStatement, originalStatements);
            }

            return true;
        }
Ejemplo n.º 12
0
        private void GenerateEntity(NamespaceDeclaration ns, Entity entity)
        {
            var type = ns.AddType(new ClassDeclaration(entity.Name));

            AddDocumentationComments(type, entity.Documentation);
            type.Modifiers = Modifiers.Public | Modifiers.Partial;
            type.BaseType  = entity.BaseType ?? ModelRef.GitLabObject;

            // Add default constructor
            var ctor = type.AddMember(new ConstructorDeclaration()
            {
                Arguments =
                {
                    new MethodArgumentDeclaration(typeof(JObject), "obj")
                },
                Modifiers   = Modifiers.Internal,
                Initializer = new ConstructorBaseInitializer(new ArgumentReferenceExpression("obj"))
            });

            var internalCtor = type.AddMember(new ConstructorDeclaration()
            {
                Modifiers   = Modifiers.Internal,
                Initializer = new ConstructorBaseInitializer(new NewObjectExpression(typeof(JObject)))
            });

            // Add properties
            foreach (var prop in entity.Properties)
            {
                var propertyMember = type.AddMember(new PropertyDeclaration(ToPropertyName(prop.Name), GetPropertyTypeRef(prop.Type))
                {
                    Modifiers = Modifiers.Public,
                    Getter    = new StatementCollection
                    {
                        new ReturnStatement(new ThisExpression().CreateInvokeMethodExpression("GetValueOrDefault",
                                                                                              new TypeReference[]
                        {
                            GetPropertyTypeRef(prop.Type)
                        },
                                                                                              new Expression[]
                        {
                            prop.SerializationName ?? prop.Name,
                            new DefaultValueExpression(GetPropertyTypeRef(prop.Type)),
                        }))
                    },
                    Setter = new PropertyAccessorDeclaration
                    {
                        Modifiers  = Modifiers.Internal,
                        Statements = new StatementCollection
                        {
                            new ThisExpression().CreateInvokeMethodExpression("SetValue",
                                                                              new Expression[]
                            {
                                prop.SerializationName ?? prop.Name,
                                new ValueArgumentExpression(),
                            })
                        }
                    },
                });

                AddDocumentationComments(propertyMember, prop.Documentation);

                if (prop.Type == ModelRef.Date || prop.Type == ModelRef.NullableDate)
                {
                    propertyMember.CustomAttributes.Add(new CustomAttribute(typeof(SkipUtcDateValidationAttribute))
                    {
                        Arguments = { new CustomAttributeArgument("Does not contain time nor timezone (e.g. 2018-01-01)") }
                    });
                }

                propertyMember.CustomAttributes.Add(new CustomAttribute(typeof(MappedPropertyAttribute))
                {
                    Arguments = { new CustomAttributeArgument(prop.SerializationName ?? prop.Name) }
                });
            }

            // Generate Equals members (Equals, GetHashCode, ==, !=, IEquatable<T>)
            var displayProperty = entity.Properties.FirstOrDefault(p => p.IsDisplayName);
            var keyProperties   = entity.Properties.Where(p => p.IsKey).ToList();

            if (keyProperties.Count > 0)
            {
                type.Implements.Add(new TypeReference(typeof(IEquatable <>)).MakeGeneric(type));

                GenerateEqualMethod();
                GenerateEqualTypedMethod();
                GenerateGetHashCode();
                GenerateEqualityOperator();
            }

            // Generate EntityDisplayName (DebuggerDisplay, ToString)
            if (displayProperty != null)
            {
                GenerateDebuggerDisplay();
            }

            void GenerateEqualMethod()
            {
                var equal = type.AddMember(new MethodDeclaration(nameof(object.Equals)));

                equal.Modifiers  = Modifiers.Public | Modifiers.Override;
                equal.ReturnType = typeof(bool);
                var objArg     = equal.AddArgument("obj", typeof(object));
                var statements = new StatementCollection();

                equal.Statements = statements;

                var typedVariable = new VariableDeclarationStatement(type, "a", new ConvertExpression(objArg, type));

                statements.Add(typedVariable);
                statements.Add(new ReturnStatement(new ThisExpression().CreateInvokeMethodExpression("Equals", typedVariable)));
            }

            void GenerateEqualTypedMethod()
            {
                var equal = type.AddMember(new MethodDeclaration(nameof(object.Equals)));

                equal.Modifiers  = Modifiers.Public | Modifiers.Virtual;
                equal.ReturnType = typeof(bool);
                var objArg = equal.AddArgument("obj", type);

                var returnExpression = new BinaryExpression(BinaryOperator.NotEquals, objArg, new LiteralExpression(null));

                foreach (var key in keyProperties)
                {
                    var typeRef = GetPropertyTypeRef(key.Type);
                    var expr    = new BinaryExpression(BinaryOperator.Equals,
                                                       new ThisExpression().CreateMemberReferenceExpression(ToPropertyName(key.Name)),
                                                       objArg.CreateMemberReferenceExpression(ToPropertyName(key.Name)));

                    returnExpression = new BinaryExpression(BinaryOperator.And, returnExpression, expr);
                }

                equal.Statements = new ReturnStatement(returnExpression);
            }

            void GenerateGetHashCode()
            {
                var equal = type.AddMember(new MethodDeclaration(nameof(object.GetHashCode)));

                equal.Modifiers  = Modifiers.Public | Modifiers.Override;
                equal.ReturnType = typeof(int);

                var statements = new StatementCollection();
                var hashCode   = new VariableDeclarationStatement(typeof(int), "hashCode", new LiteralExpression(574293967));

                statements.Add(hashCode);

                foreach (var key in keyProperties)
                {
                    var typeRef = Type.GetType(GetPropertyTypeRef(key.Type).ClrFullTypeName);
                    if (typeRef.IsValueType)
                    {
                        statements.Add(new AssignStatement(hashCode,
                                                           new BinaryExpression(BinaryOperator.Add,
                                                                                new BinaryExpression(BinaryOperator.Multiply, hashCode, new LiteralExpression(-1521134295)),
                                                                                new ThisExpression().CreateMemberReferenceExpression(ToPropertyName(key.Name)).CreateInvokeMethodExpression(nameof(GetHashCode)))));
                    }
                    else
                    {
                        statements.Add(new AssignStatement(hashCode,
                                                           new BinaryExpression(BinaryOperator.Add,
                                                                                new BinaryExpression(BinaryOperator.Multiply, hashCode, new LiteralExpression(-1521134295)),
                                                                                new TypeReference(typeof(EqualityComparer <>)).MakeGeneric(key.Type).CreateMemberReferenceExpression("Default").CreateInvokeMethodExpression("GetHashCode", ToPropertyName(key.Name)))));
                    }
                }

                statements.Add(new ReturnStatement(hashCode));
                equal.Statements = statements;
            }

            void GenerateEqualityOperator()
            {
                var equal = type.AddMember(new OperatorDeclaration("=="));

                equal.Modifiers  = Modifiers.Public | Modifiers.Static;
                equal.ReturnType = typeof(bool);
                equal.Arguments.Add(new MethodArgumentDeclaration(type, "a"));
                equal.Arguments.Add(new MethodArgumentDeclaration(type, "b"));
                equal.Statements.Add(new ReturnStatement(new TypeReference(typeof(EqualityComparer <>)).MakeGeneric(type).CreateMemberReferenceExpression("Default").CreateInvokeMethodExpression("Equals",
                                                                                                                                                                                                  new ArgumentReferenceExpression("a"),
                                                                                                                                                                                                  new ArgumentReferenceExpression("b"))));

                var notEqual = type.AddMember(new OperatorDeclaration("!="));

                notEqual.Modifiers  = Modifiers.Public | Modifiers.Static;
                notEqual.ReturnType = typeof(bool);
                notEqual.Arguments.Add(new MethodArgumentDeclaration(type, "a"));
                notEqual.Arguments.Add(new MethodArgumentDeclaration(type, "b"));
                notEqual.Statements.Add(new ReturnStatement(new UnaryExpression(UnaryOperator.Not, new BinaryExpression(BinaryOperator.Equals, new ArgumentReferenceExpression("a"), new ArgumentReferenceExpression("b")))));
            }

            void GenerateDebuggerDisplay()
            {
                var properties = new[] { displayProperty }.Concat(keyProperties).Where(p => p != null);

                type.CustomAttributes.Add(new CustomAttribute(typeof(DebuggerDisplayAttribute))
                {
                    Arguments =
                    {
                        new CustomAttributeArgument(new LiteralExpression("{GetType().Name,nq} " + string.Join(", ", properties.Select(v => $"{ToPropertyName(v.Name)}={{{ToPropertyName(v.Name)}}}")))),
                    }
                });
            }
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Coppies the block that is targeted from the goto if it matches the case
        ///
        /// ... some code
        /// goto: label0;
        ///
        /// ...
        /// ...
        /// label0: statement1
        /// *statements*
        /// return;
        /// ...
        /// </summary>
        /// <param name="labeledStatement">The targeted statement.</param>
        /// <param name="gotoStatement">The goto statement.</param>
        /// <returns>Returns True if the targeted block was coppied.</returns>
        private bool TryCopyTargetedBlock(Statement labeledStatement, GotoStatement gotoStatement)
        {
            StatementCollection toCopy             = new StatementCollection();
            StatementCollection originalStatements = new StatementCollection();
            BlockStatement      targetParent       = labeledStatement.Parent as BlockStatement;

            if (targetParent == null)
            {
                return(false);
            }
            int targetIndex = targetParent.Statements.IndexOf(labeledStatement);

            originalStatements.Add(labeledStatement);
            Statement labeledClone = labeledStatement.CloneStatementOnly();

            labeledClone.Label = string.Empty;
            toCopy.Add(labeledClone);

            int maxStatementsToCopy = MaximumStatementsToCopy;

            if (ContainsLabel(labeledClone))
            {
                return(false);
            }

            maxStatementsToCopy -= GetStatementsCount(labeledClone);
            if (maxStatementsToCopy < 0)
            {
                return(false);
            }

            if (!IsReturnStatement(labeledClone) && !IsThrowStatement(labeledClone))
            {
                ///Collect all statements, until a return is reached.
                int index;
                for (index = targetIndex + 1; index < targetParent.Statements.Count; index++)
                {
                    Statement nextStatement = targetParent.Statements[index];
                    if (ContainsLabel(nextStatement))
                    {
                        return(false);
                    }

                    maxStatementsToCopy -= GetStatementsCount(nextStatement);
                    if (maxStatementsToCopy < 0)
                    {
                        return(false);
                    }

                    originalStatements.Add(nextStatement);
                    Statement clone = nextStatement.CloneStatementOnly();
                    toCopy.Add(clone);
                    if (IsReturnStatement(nextStatement) || IsThrowStatement(nextStatement))
                    {
                        break;
                    }
                }
                if (index == targetParent.Statements.Count)
                {
                    ///all the statements were traversed and no 'return' statement was found
                    return(false);
                }
            }
            ///Move the coppied statements on the place of the goto statement.
            MoveStatements(gotoStatement, toCopy);

            ///Clean up the label from the targeted statement if possible, and remove the targeted statement if it cannot be reached anymore
            if (!Targeted(labeledStatement.Label))
            {
                UpdateUntargetedStatement(labeledStatement, originalStatements);
            }

            return(true);
        }