private List<int> GetStatementsToInline(StatementCollection statements)
        {
            List<int> result = new List<int>();

            BlockStatement parent = (BlockStatement)statements[0].Parent;
            if (parent == null)
            {
                throw new NullReferenceException("parent");
            }

            foreach (KeyValuePair<VariableDefinition, DefineUseCount> pair in patternsContext.VariableToDefineUseCountContext)
            {
                if (pair.Value.DefineCount != 1 || pair.Value.UseCount != 1)
                {
                    continue;
                }

                ExpressionStatement defineExpression = patternsContext.VariableToSingleAssignmentMap[pair.Key];
                if (defineExpression.Parent != parent)
                {
                    continue;
                }

                int index = statements.IndexOf(defineExpression);
                if (index == -1)
                {
                    throw new IndexOutOfRangeException("index");
                }

                result.Add(index);
            }

            result.Sort();
            return result;
        }
        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;
        }
        private bool Match()
        {
			if (this.originalStatements.Count == 0)
			{
				return false;
			}

			if (!this.methodContext.Method.IsAsync(out this.stateMachineTypeDef))
			{
				if (!this.methodContext.Method.HasAsyncAttributes() || !IsAsyncFirstAssignmentStatement(this.originalStatements[0], out this.stateMachineTypeDef) ||
					!this.methodContext.Method.HasAsyncStateMachineVariable())
				{
					return false;
				}
			}

            if (!GetBuilderField())
            {
                return false;
            }

			asyncStatements = GetMoveNextStatements();
            if (asyncStatements == null || !TryRemoveOuterTryCatch(asyncStatements))
            {
                return false;
            }

            SetParameterMappings(originalStatements);

            matcherState = MatcherState.FindAwaitExpression;
            asyncStatements = (StatementCollection)Visit(asyncStatements);

			bool result = matcherState == MatcherState.FindAwaitExpression;
            return result;
        }
		public virtual bool TryMatch(StatementCollection statements, out int startIndex, out Statement result, out int replacedStatementsCount)
		{
			startIndex = -1;
			result = null;
			replacedStatementsCount = -1;

			if (statements == null || statements.Count - startIndex < 2)
			{
				return false;
			}

			for (int i = statements.Count - 1; i >= 0; i--)
			{
				if (TryMatchInternal(statements, i, out result, out replacedStatementsCount))
				{
					Expression expression = ((result as ExpressionStatement).Expression as BinaryExpression).Left;
					if (expression.CodeNodeType == CodeNodeType.VariableReferenceExpression)
					{
						FixContext((expression as VariableReferenceExpression).Variable.Resolve(), 0, replacedStatementsCount - 1, null);
					}
					startIndex = i;
					return true;
				}
			}

			return false;
		}
 public UnsafeBlockStatement(StatementCollection statements)
 {
     this.Statements = statements;
     foreach (Statement s in this.Statements)
     {
         s.Parent = this;
     }
 }
        public HashSet<VariableDefinition> Find(StatementCollection statements)
        {
            ResetInternalState();

            this.Visit(statements);

            return this.variablesToNotInline;
        }
        public BlockStatement Process(DecompilationContext context, BlockStatement body)
        {
            this.methodContext = context.MethodContext;
            this.originalStatements = body.Statements;
            if (Match())
            {
                body.Statements = asyncStatements;
            }

            return body;
        }
        private bool Match(StatementCollection statements, int statementIndex)
        {
            PrepareMatcher(statements, statementIndex);

            Statement currentStatement = statements[statementIndex];
            if (currentStatement.CodeNodeType == CodeNodeType.TryStatement)
            {
                @try = currentStatement as TryStatement;
                if (!DetermineWithFlagLockTypeVersion(@try))
                {
                    return false;
                }

                if (this.lockType == LockType.WithFlagV2)
                {
                    if (statementIndex - 2 < 0 || !CheckLockVariableAssignmentExpression(statements[statementIndex - 2]))
                    {
                        return false;
                    }
                }
            }
            else if (currentStatement.CodeNodeType == CodeNodeType.ExpressionStatement &&
                CheckTheMethodInvocation((currentStatement as ExpressionStatement).Expression as MethodInvocationExpression, "Enter"))
            {
                MethodReference methodReference = ((currentStatement as ExpressionStatement).Expression as MethodInvocationExpression).MethodExpression.Method;
                if(methodReference.Parameters.Count != 1)
                {
                    return false;
                }

                if (statementIndex + 1 >= statements.Count || statementIndex - 2 < 0)
                {
                    return false;
                }
                @try = statements[statementIndex + 1] as TryStatement;
                lockType = LockType.Simple;
                if(!CheckTheAssignExpressions(statements[statementIndex - 2], statements[statementIndex - 1]))
                {
                    return false;
                }
                lockingInstructions.AddRange(currentStatement.UnderlyingSameMethodInstructions);
            }

            if (@try == null)
                return false;

            if (!IsLockStatement(@try))
                return false;
            
            this.body = @try.Try;
            
            return true;
        }
		public bool TryMatch(StatementCollection statements,out int startIndex, out Statement result, out int replacedStatementsCount)
		{
			result = null;
			startIndex = 0;
			bool matched = TryMatchArrayAssignmentInternal(statements);
			if (matched)
			{
				replacedStatementsCount = 2;
				return true;
			}
			replacedStatementsCount = 1;
			return TryMatchDirectAssignmentInternal(statements);
		}
        public bool TryMatch(StatementCollection statements, out int startIndex, out Statement result, out int replacedStatementsCount)
        {
            replacedStatementsCount = 0;
            startIndex = -1;
            result = null;
            bool inlinedSuccessfully = false;

            if(statements.Count == 0)
            {
                return false;
            }

            HashSet<VariableDefinition> markedForRemoval = new HashSet<VariableDefinition>();

            List<int> positionsToInline = GetStatementsToInline(statements);

            for (int i = positionsToInline.Count - 1; i >= 0; i--)
            {
                int index = positionsToInline[i];

                ExpressionStatement defineExpression = statements[index] as ExpressionStatement;
                VariableDefinition variable = ((defineExpression.Expression as BinaryExpression).Left as VariableReferenceExpression).Variable.Resolve();

                if (index == statements.Count - 1 || !string.IsNullOrEmpty(defineExpression.Label))
                {
                    markedForRemoval.Add(variable);
                    continue;
                }

                List<Instruction> instructions = new List<Instruction>(defineExpression.Expression.MappedInstructions);
                instructions.AddRange((defineExpression.Expression as BinaryExpression).Left.UnderlyingSameMethodInstructions);
                Expression value = (defineExpression.Expression as BinaryExpression).Right.CloneAndAttachInstructions(instructions);

                ICodeNode resultNode;
                if (inliner.TryInlineVariable(variable, value, statements[index + 1], ShouldInlineAggressively(variable), out resultNode))
                {
                    statements.RemoveAt(index);
                    inlinedSuccessfully = true;
                    markedForRemoval.Add(variable);
                    methodContext.RemoveVariable(variable);
                }
            }

            foreach (VariableDefinition variable in markedForRemoval)
            {
                patternsContext.VariableToSingleAssignmentMap.Remove(variable);
                patternsContext.VariableToDefineUseCountContext.Remove(variable);
            }

            return inlinedSuccessfully;
        }
 public bool TryMatch(StatementCollection statements, out int startIndex, out Statement result, out int replacedStatementsCount)
 {
     result = null;
     replacedStatementsCount = 2;
     for (startIndex = 0; startIndex + 1 < statements.Count; startIndex++)
     {
         bool currentTransform = TryMatchInternal(statements, startIndex, out result);
         if (currentTransform)
         {
             return true;
         }
     }
     return false;
 }
		/// Pattern:
		/// variable = Expression;
		/// field = variable;
		/// where
		/// Expression is either array creation expression, literal constant, consturctor call from another class
		/// or combination of all of the above.
		private bool TryMatchArrayAssignmentInternal(StatementCollection statements)
		{
			if (statements.Count < 2)
			{
				return false;
			}
			ExpressionStatement theStatement = statements[0] as ExpressionStatement;
			if (theStatement == null)
			{
				return false;
			}
			BinaryExpression theAssignment = theStatement.Expression as BinaryExpression;
			VariableReference variable;
			if (theAssignment == null || !IsAssignToVariableExpression(theAssignment, out variable))
			{
				return false;
			}

			/// A check of wheather the assigned value can be used in field declaration context could be performed.
			/// At the moment, no IL samples that violate this rule were found.
			Expression assignedValue = theAssignment.Right;

			ExpressionStatement assignmentStatement = statements[1] as ExpressionStatement;
			if (assignmentStatement == null)
			{
				return false;
			}

			Expression variableReference;
            string memberFullName;
            if (!IsFieldAssignment(assignmentStatement, out variableReference, out memberFullName) &&
                !IsAutoPropertyAssignment(assignmentStatement, out variableReference, out memberFullName))
			{
                return false;
			}

            if (variableReference.CodeNodeType != CodeNodeType.VariableReferenceExpression ||
				(variableReference as VariableReferenceExpression).Variable != variable)
			{
                return false;
			}

            /// The simple name of the field can be used here as well.
            /// Using the full name for consistency with other maps.
            
            return MapAssignmentIntoContext(memberFullName, assignedValue);
		}
        private bool ProcessStatementCollection(StatementCollection statements, IEnumerable<ICodePattern> patternInvokeArray)
        {
            for (int i = 0; i < statements.Count; i++)
            {
                if (statements[i].CodeNodeType == CodeNodeType.IfStatement)
                {
                    IfStatement theIf = statements[i] as IfStatement;
                    ProcessStatementCollection(theIf.Then.Statements, patternInvokeArray);
                    if (theIf.Else != null)
                    {
                        ProcessStatementCollection(theIf.Else.Statements, patternInvokeArray);
                    }
                }
            }

            bool didTransform;
            do
            {
                didTransform = false;

                foreach (ICodePattern pattern in patternInvokeArray)
                {
                    int replacedStatementsCount = -1;
                    Statement resultingStatement;
                    int startIndex;
                    bool currentTransformation = pattern.TryMatch(statements, out startIndex, out resultingStatement, out replacedStatementsCount);
                    didTransform |= currentTransformation;
                    if (currentTransformation)
                    {
                        if (resultingStatement != null)
                        {
                            RemoveRangeAndInsert(statements, startIndex, replacedStatementsCount, resultingStatement);
                        }
                        else
                        {
                            RemoveRange(statements, startIndex, replacedStatementsCount);
                        }
                        break;
                    }
                }
            } while (didTransform);

            return statements.Count == 1;
        }
Ejemplo n.º 15
0
        public void TestNonSignificantWhitespaceRegions1()
        {
            Boo.Lang.Compiler.Ast.Module module = ParseTestCase("nonsignificant_ws_regions_1.boo");

            StatementCollection stmts = module.Globals.Statements;

            Assert.AreEqual(2, stmts.Count);

            ExpressionStatement es = (ExpressionStatement)stmts[0];
            BinaryExpression    ae = (BinaryExpression)es.Expression;

            Assert.AreEqual(BinaryOperatorType.Assign, ae.Operator);
            Assert.AreEqual("a", ((ReferenceExpression)ae.Left).Name);
            Assert.AreEqual(2, ((ListLiteralExpression)ae.Right).Items.Count);

            ForStatement fs = (ForStatement)stmts[1];
            MethodInvocationExpression mce = (MethodInvocationExpression)fs.Iterator;

            Assert.AreEqual("map", ((ReferenceExpression)mce.Target).Name);
            Assert.AreEqual(2, mce.Arguments.Count);

            Assert.AreEqual(1, fs.Block.Statements.Count);
        }
        private bool TryGetAssignment(StatementCollection statements, int startIndex, out BinaryExpression binaryExpression)
        {
            binaryExpression = null;

            var statement = statements[startIndex];

            if (statement.CodeNodeType != CodeNodeType.ExpressionStatement)
            {
                return(false);
            }
            Expression firstExpression = (statement as ExpressionStatement).Expression;

            if (firstExpression.CodeNodeType != CodeNodeType.BinaryExpression)
            {
                return(false);
            }
            var result = firstExpression as BinaryExpression;

            if (!result.IsAssignmentExpression)
            {
                return(false);
            }

            if (!(result.Left.CodeNodeType == CodeNodeType.VariableReferenceExpression ||
                  result.Left.CodeNodeType == CodeNodeType.VariableDeclarationExpression ||
                  result.Left.CodeNodeType == CodeNodeType.FieldReferenceExpression ||
                  result.Left.CodeNodeType == CodeNodeType.ThisReferenceExpression ||
                  result.Left.CodeNodeType == CodeNodeType.PropertyReferenceExpression ||
                  result.Left.CodeNodeType == CodeNodeType.ArgumentReferenceExpression ||
                  result.Left.CodeNodeType == CodeNodeType.UnaryExpression && (result.Left as UnaryExpression).Operand.CodeNodeType == CodeNodeType.ArgumentReferenceExpression))
            {
                return(false);
            }

            binaryExpression = result;
            return(true);
        }
Ejemplo n.º 17
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);
        }
        /// Pattern:
        /// field = Expression;
        /// where
        /// Expression is either array creation expression, literal constant, consturctor call from another class
        /// or combination of all of the above.
        private bool TryMatchDirectAssignmentInternal(StatementCollection statements)
        {
            ExpressionStatement theStatement = statements[0] as ExpressionStatement;

            if (theStatement == null || !string.IsNullOrEmpty(statements[0].Label))
            {
                return(false);
            }

            string     memberFullName;
            Expression assignedValue;

            if (!IsFieldAssignment(theStatement, out assignedValue, out memberFullName) &&
                !IsAutoPropertyAssignment(theStatement, out assignedValue, out memberFullName))
            {
                return(false);
            }
            /// A check of wheather the assigned value can be used in field declaration context could be performed.
            /// At the moment, no IL samples that violate this rule were found.
            /// The simple name of the field can be used here as well.
            /// Using the full name for consistency with other maps.

            return(MapAssignmentIntoContext(memberFullName, assignedValue));
        }
Ejemplo n.º 19
0
 private void PostProcessMappings(StatementCollection getEnumeratorStatements)
 {
     V_0 = getEnumeratorStatements.GetEnumerator();
     try
     {
         while (V_0.MoveNext())
         {
             V_1 = V_0.get_Current();
             if (V_1.get_CodeNodeType() != 5 || (V_1 as ExpressionStatement).get_Expression().get_CodeNodeType() != 24)
             {
                 continue;
             }
             V_2 = (V_1 as ExpressionStatement).get_Expression() as BinaryExpression;
             if (!V_2.get_IsAssignmentExpression() || V_2.get_Left().get_CodeNodeType() != 30 || V_2.get_Right().get_CodeNodeType() != 30)
             {
                 continue;
             }
             V_3 = (V_2.get_Left() as FieldReferenceExpression).get_Field().Resolve();
             V_4 = (V_2.get_Right() as FieldReferenceExpression).get_Field().Resolve();
             if (!this.parameterMappings.TryGetValue(V_4, out V_5))
             {
                 continue;
             }
             dummyVar0 = this.parameterMappings.Remove(V_4);
             this.parameterMappings.set_Item(V_3, V_5);
         }
     }
     finally
     {
         if (V_0 != null)
         {
             V_0.Dispose();
         }
     }
     return;
 }
        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.º 21
0
        public void TestTuples1()
        {
            Boo.Lang.Ast.Module module = BooTestCaseUtil.ParseTestCase("tuples_1.boo");

            StatementCollection sc = module.Globals.Statements;

            Assert.AreEqual(4, sc.Count);

            BinaryExpression ae = (BinaryExpression)((ExpressionStatement)sc[0]).Expression;

            Assert.AreEqual("names", ((ReferenceExpression)ae.Left).Name);

            TupleLiteralExpression tle = (TupleLiteralExpression)ae.Right;

            Assert.AreEqual(3, tle.Items.Count);

            ae  = (BinaryExpression)((ExpressionStatement)sc[1]).Expression;
            tle = (TupleLiteralExpression)ae.Right;
            Assert.AreEqual(3, tle.Items.Count);

            ae  = (BinaryExpression)((ExpressionStatement)sc[3]).Expression;
            tle = (TupleLiteralExpression)ae.Right;
            Assert.AreEqual(1, tle.Items.Count);
        }
        private List <int> GetStatementsToInline(StatementCollection statements)
        {
            List <int> result = new List <int>();

            BlockStatement parent = (BlockStatement)statements[0].Parent;

            if (parent == null)
            {
                throw new NullReferenceException("parent");
            }

            foreach (KeyValuePair <VariableDefinition, DefineUseCount> pair in patternsContext.VariableToDefineUseCountContext)
            {
                if (pair.Value.DefineCount != 1 || pair.Value.UseCount != 1)
                {
                    continue;
                }

                ExpressionStatement defineExpression = patternsContext.VariableToSingleAssignmentMap[pair.Key];
                if (defineExpression.Parent != parent)
                {
                    continue;
                }

                int index = statements.IndexOf(defineExpression);
                if (index == -1)
                {
                    throw new IndexOutOfRangeException("index");
                }

                result.Add(index);
            }

            result.Sort();
            return(result);
        }
Ejemplo n.º 23
0
        private bool Match()
        {
            if (this.originalStatements.Count == 0)
            {
                return(false);
            }

            if (!this.methodContext.Method.IsAsync(out this.stateMachineTypeDef))
            {
                if (!this.methodContext.Method.HasAsyncAttributes() || !IsAsyncFirstAssignmentStatement(this.originalStatements[0], out this.stateMachineTypeDef) ||
                    !this.methodContext.Method.HasAsyncStateMachineVariable())
                {
                    return(false);
                }
            }

            if (!GetBuilderField())
            {
                return(false);
            }

            asyncStatements = GetMoveNextStatements();
            if (asyncStatements == null || !TryRemoveOuterTryCatch(asyncStatements))
            {
                return(false);
            }

            SetParameterMappings(originalStatements);

            matcherState    = MatcherState.FindAwaitExpression;
            asyncStatements = (StatementCollection)Visit(asyncStatements);

            bool result = matcherState == MatcherState.FindAwaitExpression;

            return(result);
        }
		private bool TryGetAssignment(StatementCollection statements, int startIndex, out BinaryExpression binaryExpression)
		{
			binaryExpression = null;

			var statement = statements[startIndex];
			if (statement.CodeNodeType != CodeNodeType.ExpressionStatement)
			{
				return false;
			}
			Expression firstExpression = (statement as ExpressionStatement).Expression;

			if (firstExpression.CodeNodeType != CodeNodeType.BinaryExpression)
			{
				return false;
			}
			var result = firstExpression as BinaryExpression;

			if (!result.IsAssignmentExpression)
			{
				return false;
			}

			if (!(result.Left.CodeNodeType == CodeNodeType.VariableReferenceExpression ||
				  result.Left.CodeNodeType == CodeNodeType.VariableDeclarationExpression ||
				  result.Left.CodeNodeType == CodeNodeType.FieldReferenceExpression ||
				  result.Left.CodeNodeType == CodeNodeType.ThisReferenceExpression ||
				  result.Left.CodeNodeType == CodeNodeType.PropertyReferenceExpression ||
				  result.Left.CodeNodeType == CodeNodeType.ArgumentReferenceExpression ||
				  result.Left.CodeNodeType == CodeNodeType.UnaryExpression && (result.Left as UnaryExpression).Operand.CodeNodeType == CodeNodeType.ArgumentReferenceExpression))
			{
				return false;
			}

			binaryExpression = result;
			return true;
		}
 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 void PostProcessMappings(StatementCollection getEnumeratorStatements)
        {
            foreach (Statement statement in getEnumeratorStatements)
            {
                if (statement.CodeNodeType == CodeNodeType.ExpressionStatement &&
                    (statement as ExpressionStatement).Expression.CodeNodeType == CodeNodeType.BinaryExpression)
                {
                    BinaryExpression binaryExpression = (statement as ExpressionStatement).Expression as BinaryExpression;
                    if (binaryExpression.IsAssignmentExpression && binaryExpression.Left.CodeNodeType == CodeNodeType.FieldReferenceExpression &&
                        binaryExpression.Right.CodeNodeType == CodeNodeType.FieldReferenceExpression)
                    {
                        FieldDefinition leftFieldDef  = (binaryExpression.Left as FieldReferenceExpression).Field.Resolve();
                        FieldDefinition rightFieldDef = (binaryExpression.Right as FieldReferenceExpression).Field.Resolve();

                        Expression fieldValue;
                        if (parameterMappings.TryGetValue(rightFieldDef, out fieldValue))
                        {
                            parameterMappings.Remove(rightFieldDef);
                            parameterMappings[leftFieldDef] = fieldValue;
                        }
                    }
                }
            }
        }
 protected abstract bool TryMatchInternal(StatementCollection statements, int startIndex, out Statement result, out int replacedStatementsCount);
 protected override bool TryMatchInternal(StatementCollection statements, int startIndex, out Statement result, out int replacedStatementsCount)
 {
     result = null;
     replacedStatementsCount = 0;
     if (!this.TryGetObjectCreation(statements, startIndex, out V_0, out V_1))
     {
         return(false);
     }
     V_2 = new ExpressionCollection();
     V_3 = new HashSet <string>();
     if (V_0.get_Initializer() != null)
     {
         if (V_0.get_Initializer().get_InitializerType() != 1)
         {
             return(false);
         }
         V_4 = V_0.get_Initializer().get_Expressions().GetEnumerator();
         try
         {
             while (V_4.MoveNext())
             {
                 V_5       = V_4.get_Current();
                 V_6       = this.GetName((V_5 as BinaryExpression).get_Left());
                 dummyVar0 = V_3.Add(V_6);
             }
         }
         finally
         {
             if (V_4 != null)
             {
                 V_4.Dispose();
             }
         }
     }
     V_7 = startIndex + 1;
     while (V_7 < statements.get_Count() && this.TryGetNextExpression(statements.get_Item(V_7), out V_8))
     {
         V_9 = V_8 as BinaryExpression;
         if (!this.IsObjectPropertyOrFieldAssignment(V_9, V_1))
         {
             break;
         }
         V_10 = null;
         if (V_9.get_Left().get_CodeNodeType() != 42)
         {
             if (V_9.get_Left().get_CodeNodeType() == 30)
             {
                 V_13 = (V_9.get_Left() as FieldReferenceExpression).get_Field().Resolve();
                 if (!this.Visit(V_13.get_Name(), V_3))
                 {
                     break;
                 }
                 V_10 = new FieldInitializerExpression(V_13, V_13.get_FieldType(), V_9.get_Left().get_UnderlyingSameMethodInstructions());
             }
         }
         else
         {
             V_12 = (V_9.get_Left() as PropertyReferenceExpression).get_Property();
             if (!this.Visit(V_12.get_Name(), V_3))
             {
                 break;
             }
             V_10 = new PropertyInitializerExpression(V_12, V_12.get_PropertyType(), V_9.get_Left().get_UnderlyingSameMethodInstructions());
         }
         V_11 = new BinaryExpression(26, V_10, V_9.get_Right().Clone(), this.typeSystem, null, false);
         V_2.Add(V_11);
         V_7 = V_7 + 1;
     }
     if (V_2.get_Count() == 0)
     {
         return(false);
     }
     if (V_0.get_Initializer() != null)
     {
         V_4 = V_2.GetEnumerator();
         try
         {
             while (V_4.MoveNext())
             {
                 V_15 = V_4.get_Current();
                 V_0.get_Initializer().get_Expressions().Add(V_15);
             }
         }
         finally
         {
             if (V_4 != null)
             {
                 V_4.Dispose();
             }
         }
     }
     else
     {
         V_14 = new InitializerExpression(V_2, 1);
         V_14.set_IsMultiLine(true);
         V_0.set_Initializer(V_14);
     }
     result = statements.get_Item(startIndex);
     replacedStatementsCount = V_2.get_Count() + 1;
     return(true);
 }
		/// Pattern:
		/// field = Expression;
		/// where
		/// Expression is either array creation expression, literal constant, consturctor call from another class
		/// or combination of all of the above.
		private bool TryMatchDirectAssignmentInternal(StatementCollection statements)
		{
			ExpressionStatement theStatement = statements[0] as ExpressionStatement;
			if (theStatement == null || !string.IsNullOrEmpty(statements[0].Label))
			{
				return false;
			}

			string memberFullName;
			Expression assignedValue;
            if (!IsFieldAssignment(theStatement, out assignedValue, out memberFullName) &&
                !IsAutoPropertyAssignment(theStatement, out assignedValue, out memberFullName))
            {
                return false;
			}
            /// A check of wheather the assigned value can be used in field declaration context could be performed.
            /// At the moment, no IL samples that violate this rule were found.
            /// The simple name of the field can be used here as well.
            /// Using the full name for consistency with other maps.
            
            return MapAssignmentIntoContext(memberFullName, assignedValue);
		}
 public BlockExpression()
 {
     Body = new StatementCollection();
 }
Ejemplo n.º 31
0
 public CodePatternsContext(StatementCollection statements)
 {
     this();
     (new CodePatternsContext.VariableDefineUseCounter(this)).Visit(statements);
     return;
 }
Ejemplo n.º 32
0
        public ExpressionStatement LastExpressionStatement(Method method)
        {
            StatementCollection statements = method.Body.Statements;

            return((statements.Count != 0) ? (statements[-1] as ExpressionStatement) : null);
        }
        private void RemoveFirstStatements(StatementCollection statements, int count)
        {
            for (int i = 0; i + count < statements.Count; i++)
            {
                statements[i] = statements[i + count];
            }

            while (count-- > 0)
            {
                statements.RemoveAt(statements.Count - 1);
            }
        }
		protected bool TryGetArrayCreation(StatementCollection statements, int startIndex, out ArrayCreationExpression creation, out Expression assignee)
		{
			assignee = null;
			creation = null;

			BinaryExpression binaryExpression;
			if (!TryGetAssignment(statements, startIndex, out binaryExpression))
			{
				return false;
			}

			if (binaryExpression.Right.CodeNodeType != CodeNodeType.ArrayCreationExpression)
			{
				return false;
			}

			var arrayCreation = binaryExpression.Right as ArrayCreationExpression;

			if (!(binaryExpression.Right.HasType && binaryExpression.Right.ExpressionType.IsArray))
			{
				return false;
			}

			/// Implemented for 1-dimentional arrays only.
			/// This covers most of the cases, and is far easier to implement than support
			/// for n-dimentional arrays.
			if (arrayCreation.Dimensions.Count != 1)
			{
				return false;
			}

			foreach (Expression dimention in arrayCreation.Dimensions)
			{
				if (dimention.CodeNodeType != CodeNodeType.LiteralExpression)
				{
					return false;
				}
			}

			creation = binaryExpression.Right as ArrayCreationExpression;
			assignee = binaryExpression.Left;
			return true;
		}
        private void RemoveRange(StatementCollection statements, int startIndex, int length)
        {
            if (length == 0)
            {
                return;
            }
            int count = statements.Count;
            for (int i = startIndex; i + length < count; i++)
            {
                statements[i] = statements[i + length];
            }

            while (length > 0)
            {
                statements.RemoveAt(--count);
                length--;
            }
        }
		private bool HasNoEmptyStatements(StatementCollection statements)
		{
			foreach (Statement statement in statements)
			{
				if (!(statement is EmptyStatement))
				{
					return true;
				}
			}
			return false;
		}
Ejemplo n.º 37
0
 private bool TryMatchInternal(StatementCollection statements, int startIndex, out Statement result)
 {
     result = null;
     if (startIndex + 1 >= statements.get_Count())
     {
         return(false);
     }
     if (statements.get_Item(startIndex).get_CodeNodeType() != 5 || statements.get_Item(startIndex + 1).get_CodeNodeType() != 3)
     {
         return(false);
     }
     V_0 = statements.get_Item(startIndex) as ExpressionStatement;
     if (V_0.get_Expression().get_CodeNodeType() != 24)
     {
         return(false);
     }
     V_1 = V_0.get_Expression() as BinaryExpression;
     if (V_1.get_Left().get_CodeNodeType() != 26 || V_1.get_Right().get_CodeNodeType() != 48)
     {
         return(false);
     }
     V_2 = V_1.get_Left() as VariableReferenceExpression;
     V_3 = V_1.get_Right() as EventReferenceExpression;
     V_4 = statements.get_Item(startIndex + 1) as IfStatement;
     if (V_4.get_Then() == null || V_4.get_Else() != null || V_4.get_Condition().get_CodeNodeType() != 24)
     {
         return(false);
     }
     V_5 = V_4.get_Condition() as BinaryExpression;
     if (V_5.get_Left().get_CodeNodeType() != 26 || V_5.get_Right().get_CodeNodeType() != 22 || V_5.get_Operator() != 10)
     {
         return(false);
     }
     V_6 = V_5.get_Left() as VariableReferenceExpression;
     if ((object)V_2.get_Variable() != (object)V_6.get_Variable())
     {
         return(false);
     }
     if ((V_5.get_Right() as LiteralExpression).get_Value() != null)
     {
         return(false);
     }
     V_7 = V_4.get_Then().get_Statements();
     if (V_7.get_Count() != 1 || V_7.get_Item(0).get_CodeNodeType() != 5)
     {
         return(false);
     }
     V_8 = V_7.get_Item(0) as ExpressionStatement;
     if (V_8.get_Expression().get_CodeNodeType() != 51)
     {
         return(false);
     }
     V_9 = V_8.get_Expression() as DelegateInvokeExpression;
     if (V_9.get_Target() == null || V_9.get_Target().get_CodeNodeType() != 26)
     {
         return(false);
     }
     V_10 = V_9.get_Target() as VariableReferenceExpression;
     if ((object)V_10.get_Variable() != (object)V_2.get_Variable())
     {
         return(false);
     }
     V_11 = new List <Instruction>();
     V_11.AddRange(V_0.get_UnderlyingSameMethodInstructions());
     V_11.AddRange(V_5.get_UnderlyingSameMethodInstructions());
     V_11.AddRange(V_9.get_MappedInstructions());
     V_11.AddRange(V_10.get_UnderlyingSameMethodInstructions());
     result = new ExpressionStatement(new RaiseEventExpression(V_3.get_Event(), V_9.get_InvokeMethodReference(), V_9.get_Arguments(), V_11));
     return(true);
 }
Ejemplo n.º 38
0
 public For()
 {
     Next = new StatementCollection();
 }
 private void RemoveRangeAndInsert(StatementCollection statements, int startIndex, int length, Statement newStatement)
 {
     statements.set_Item(startIndex, newStatement);
     this.RemoveRange(statements, startIndex + 1, length - 1);
     return;
 }
		protected bool TryGetObjectCreation(StatementCollection statements, int startIndex, out ObjectCreationExpression creation, out Expression assignee)
		{
			assignee = null;
			creation = null;

			BinaryExpression binaryExpression;
			if (!TryGetAssignment(statements, startIndex, out binaryExpression))
			{
				return false;
			}

			if (binaryExpression.Right.CodeNodeType != CodeNodeType.ObjectCreationExpression)
			{
				return false;
			}

			assignee = binaryExpression.Left;
			creation = binaryExpression.Right as ObjectCreationExpression;
			return true;
		}
		// Person person = new Person { Name = "John", Age = 20 };
		// 
		// ==
		// 
		// Person person = new Person();
		// person.Name = "John";
		// person.Age = 20;

		protected override bool TryMatchInternal(StatementCollection statements, int startIndex, out Statement result, out int replacedStatementsCount)
		{
			result = null;
			replacedStatementsCount = 0;

			ObjectCreationExpression objectCreation;
			Expression assignee;
			if (!TryGetObjectCreation(statements, startIndex, out objectCreation, out assignee))
			{
				return false;
			}

			ExpressionCollection inlinedExpressions = new ExpressionCollection();
			HashSet<string> visitedPropertyNames = new HashSet<string>();

			if (objectCreation.Initializer != null)
			{
				if (objectCreation.Initializer.InitializerType != InitializerType.ObjectInitializer)
				{
					return false;
				}

				foreach (var item in objectCreation.Initializer.Expressions)
				{
					string name = GetName((item as BinaryExpression).Left);
					visitedPropertyNames.Add(name);
				}
			}

			for (int i = startIndex + 1; i < statements.Count; i++)
			{
				Expression expression;
				if (!TryGetNextExpression(statements[i], out expression))
				{
					break;
				}

				BinaryExpression assignment = expression as BinaryExpression;
				if (!IsObjectPropertyOrFieldAssignment(assignment, assignee))
				{
					break;
				}

				Expression initializer = null;

				if (assignment.Left.CodeNodeType == CodeNodeType.PropertyReferenceExpression)
				{
					PropertyDefinition property = (assignment.Left as PropertyReferenceExpression).Property;
					if (!Visit(property.Name, visitedPropertyNames))
					{
						break;
					}
					initializer = new PropertyInitializerExpression(property, property.PropertyType,
						assignment.Right.UnderlyingSameMethodInstructions);
				}
				else if (assignment.Left.CodeNodeType == CodeNodeType.FieldReferenceExpression)
				{
					FieldDefinition field = (assignment.Left as FieldReferenceExpression).Field.Resolve();
					if (!Visit(field.Name, visitedPropertyNames))
					{
						break;
					}
					initializer = new FieldInitializerExpression(field, field.FieldType,
						assignment.Right.UnderlyingSameMethodInstructions);
				}

				var inlinedAssignment = new BinaryExpression(BinaryOperator.Assign,
					initializer, assignment.Right.Clone(), this.typeSystem, null);
				inlinedExpressions.Add(inlinedAssignment);
			}

			if (inlinedExpressions.Count == 0)
			{
				return false;
			}

			if (objectCreation.Initializer == null)
			{
				var initializer = new InitializerExpression(inlinedExpressions, InitializerType.ObjectInitializer);
				initializer.IsMultiLine = true;
				objectCreation.Initializer = initializer;
			}
			else
			{
				foreach (var item in inlinedExpressions)
				{
					objectCreation.Initializer.Expressions.Add(item);
				}
			}

			result = statements[startIndex];
			replacedStatementsCount = inlinedExpressions.Count + 1;
			return true;
		}
 /// <summary>
 /// Creates a new parse tree for a constructor declaration.
 /// </summary>
 /// <param name="attributes">The attributes for the parse tree.</param>
 /// <param name="modifiers">The modifiers for the parse tree.</param>
 /// <param name="keywordLocation">The location of the keyword.</param>
 /// <param name="name">The name of the declaration.</param>
 /// <param name="parameters">The parameters of the declaration.</param>
 /// <param name="statements">The statements in the declaration.</param>
 /// <param name="endDeclaration">The end block declaration, if any.</param>
 /// <param name="span">The location of the parse tree.</param>
 /// <param name="comments">The comments for the parse tree.</param>
 public ConstructorDeclaration(AttributeBlockCollection attributes, ModifierCollection modifiers, Location keywordLocation, SimpleName name, ParameterCollection parameters, StatementCollection statements, EndBlockDeclaration endDeclaration, Span span, IList <Comment> comments) : base(TreeType.ConstructorDeclaration, attributes, modifiers, keywordLocation, name, null, parameters, Location.Empty, null, null,
                                                                                                                                                                                                                                                                                             null, null, statements, endDeclaration, span, comments)
 {
 }
Ejemplo n.º 43
0
 public virtual ICollection <Statement> Visit(StatementCollection node)
 {
     return(Visit <StatementCollection, Statement>(node));
 }
Ejemplo n.º 44
0
        // Person person = new Person { Name = "John", Age = 20 };
        //
        // ==
        //
        // Person person = new Person();
        // person.Name = "John";
        // person.Age = 20;

        protected override bool TryMatchInternal(StatementCollection statements, int startIndex, out Statement result, out int replacedStatementsCount)
        {
            result = null;
            replacedStatementsCount = 0;

            ObjectCreationExpression objectCreation;
            Expression assignee;

            if (!TryGetObjectCreation(statements, startIndex, out objectCreation, out assignee))
            {
                return(false);
            }

            ExpressionCollection inlinedExpressions   = new ExpressionCollection();
            HashSet <string>     visitedPropertyNames = new HashSet <string>();

            if (objectCreation.Initializer != null)
            {
                if (objectCreation.Initializer.InitializerType != InitializerType.ObjectInitializer)
                {
                    return(false);
                }

                foreach (var item in objectCreation.Initializer.Expressions)
                {
                    string name = GetName((item as BinaryExpression).Left);
                    visitedPropertyNames.Add(name);
                }
            }

            for (int i = startIndex + 1; i < statements.Count; i++)
            {
                Expression expression;
                if (!TryGetNextExpression(statements[i], out expression))
                {
                    break;
                }

                BinaryExpression assignment = expression as BinaryExpression;
                if (!IsObjectPropertyOrFieldAssignment(assignment, assignee))
                {
                    break;
                }

                Expression initializer = null;

                if (assignment.Left.CodeNodeType == CodeNodeType.PropertyReferenceExpression)
                {
                    PropertyDefinition property = (assignment.Left as PropertyReferenceExpression).Property;
                    if (!Visit(property.Name, visitedPropertyNames))
                    {
                        break;
                    }
                    initializer = new PropertyInitializerExpression(property, property.PropertyType,
                                                                    assignment.Left.UnderlyingSameMethodInstructions);
                }
                else if (assignment.Left.CodeNodeType == CodeNodeType.FieldReferenceExpression)
                {
                    FieldDefinition field = (assignment.Left as FieldReferenceExpression).Field.Resolve();
                    if (!Visit(field.Name, visitedPropertyNames))
                    {
                        break;
                    }
                    initializer = new FieldInitializerExpression(field, field.FieldType,
                                                                 assignment.Left.UnderlyingSameMethodInstructions);
                }

                var inlinedAssignment = new BinaryExpression(BinaryOperator.Assign,
                                                             initializer, assignment.Right.Clone(), this.typeSystem, null);
                inlinedExpressions.Add(inlinedAssignment);
            }

            if (inlinedExpressions.Count == 0)
            {
                return(false);
            }

            if (objectCreation.Initializer == null)
            {
                var initializer = new InitializerExpression(inlinedExpressions, InitializerType.ObjectInitializer);
                initializer.IsMultiLine    = true;
                objectCreation.Initializer = initializer;
            }
            else
            {
                foreach (var item in inlinedExpressions)
                {
                    objectCreation.Initializer.Expressions.Add(item);
                }
            }

            result = statements[startIndex];
            replacedStatementsCount = inlinedExpressions.Count + 1;
            return(true);
        }
Ejemplo n.º 45
0
 public HashSet <VariableDefinition> Find(StatementCollection statements)
 {
     return(new HashSet <VariableDefinition>());
 }
 private static UnifiedBlock CreateStatementCollection(StatementCollection statements)
 {
     return(statements.SelectMany(CreateStatement).ToBlock());
 }
Ejemplo n.º 47
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;
        }
        /// <summary>
        /// Constructs a new parse tree for a property accessor.
        /// </summary>
        /// <param name="attributes">The attributes for the parse tree.</param>
        /// <param name="raiseEventLocation">The location of the 'RaiseEvent'.</param>
        /// <param name="parameters">The parameters of the declaration.</param>
        /// <param name="statements">The statements in the declaration.</param>
        /// <param name="endStatement">The end block declaration, if any.</param>
        /// <param name="span">The location of the parse tree.</param>
        /// <param name="comments">The comments for the parse tree.</param>
        public RaiseEventAccessorDeclaration(AttributeBlockCollection attributes, Location raiseEventLocation, ParameterCollection parameters, StatementCollection statements, EndBlockDeclaration endStatement, Span span, IList <Comment> comments) : base(TreeType.RaiseEventAccessorDeclaration, attributes, null, span, comments)
        {
            SetParent(parameters);
            SetParent(statements);
            SetParent(endStatement);

            _Parameters         = parameters;
            _RaiseEventLocation = raiseEventLocation;
            _Statements         = statements;
            _EndStatement       = endStatement;
        }
Ejemplo n.º 49
0
 public Switch()
 {
     Default = new StatementCollection();
 }
        public void ShouldSetCollection(IEnumerable <IStatement> statements)
        {
            var sut = new StatementCollection(statements);

            sut.Statements.Should().NotBeNullOrEmpty().And.HaveCount(statements.Count());
        }
 public ConstructorDeclaration()
 {
     Arguments  = new CodeObjectCollection <MethodArgumentDeclaration>(this);
     Statements = new StatementCollection(this);
 }
		protected abstract bool TryMatchInternal(StatementCollection statements, int startIndex, out Statement result, out int replacedStatementsCount);
 private void RemoveStatement(StatementCollection collection, Statement statement)
 {
     collection.Remove(statement);
 }
Ejemplo n.º 54
0
        public List<FoldMarker> GenerateFoldMarkers(IDocument document, string fileName, object parseInformation)
        {
            List<FoldMarker> list = new List<FoldMarker>();
            try
            {
                StatementCollection coll = new StatementCollection((parseInformation as Interpreter).StatementsTree, false);
                foreach (Statement st in coll)
                    if (st is FunctionDefinitionStatement)
                    {
                        LineSegment startLine = document.GetLineSegment(st.LineNumber);
                        LineSegment endLine = document.GetLineSegment(st.LastLineNumber - 1);

                        while (endLine.Words.Count == 0)
                            endLine = document.GetLineSegment(endLine.LineNumber - 1);

                        if (startLine.LineNumber + 3 < endLine.LineNumber)
                            list.Add(new FoldMarker(document, startLine.LineNumber, startLine.Length - 1, endLine.LineNumber, endLine.Length));
                    }
            }
            catch { }
            return list;
        }
 //Removes statements from index to index + length - 1
 //Inserts newStatement at index
 private void RemoveRangeAndInsert(StatementCollection statements, int startIndex, int length, Statement newStatement)
 {
     statements[startIndex] = newStatement;
     RemoveRange(statements, startIndex + 1, length - 1);
 }
        public static IEnumerable <T> WithExpressionStatementOfType <T>(this StatementCollection source) where T : Expression
        {
            var found = source.OfType <ExpressionStatement>().Where(stmt => stmt.Expression.GetType() == typeof(T));

            return(found.Select(stmt => (T)stmt.Expression));
        }
Ejemplo n.º 57
0
        /// <summary>
        /// Constructs a new parse tree for a property accessor.
        /// </summary>
        /// <param name="attributes">The attributes for the parse tree.</param>
        /// <param name="modifiers">The modifiers for the parse tree.</param>
        /// <param name="setLocation">The location of the 'Set'.</param>
        /// <param name="parameters">The parameters of the declaration.</param>
        /// <param name="statements">The statements in the declaration.</param>
        /// <param name="endDeclaration">The end block declaration, if any.</param>
        /// <param name="span">The location of the parse tree.</param>
        /// <param name="comments">The comments for the parse tree.</param>
        public SetAccessorDeclaration(AttributeBlockCollection attributes, ModifierCollection modifiers, Location setLocation, ParameterCollection parameters, StatementCollection statements, EndBlockDeclaration endDeclaration, Span span, IList <Comment> comments) : base(TreeType.SetAccessorDeclaration, attributes, modifiers, span, comments)
        {
            SetParent(parameters);
            SetParent(statements);
            SetParent(endDeclaration);

            _Parameters     = parameters;
            _SetLocation    = setLocation;
            _Statements     = statements;
            _EndDeclaration = endDeclaration;
        }
        //a0 = a1 = a2 = ... = aN;
        //
        //==
        //
        //x = aN;
        //aN-1 = x;
        //...
        //a1 = x;
        //a0 = x;
        //
        //x - phi variable
        //a(0 - N-1) - phi variables or parameters
        //aN - expression
        //result -> x = a0 = a1 = a2 = ... = aN
        //it will be used for inlining in a method invocation
        private bool TryMatchInternal(StatementCollection statements, int startIndex, out Statement result, out int replacedStatementsCount, out VariableDefinition xVariableDef)
        {
            result = null;
            replacedStatementsCount = 0;
            xVariableDef            = null;

            if (statements.Count < 1 || statements[startIndex].CodeNodeType != CodeNodeType.ExpressionStatement)
            {
                return(false);
            }

            VariableReference xVariableReference;
            Expression        theAssignedExpression;

            BinaryExpression valueToXAssignExpression = (statements[startIndex] as ExpressionStatement).Expression as BinaryExpression;

            if (!IsAssignToVariableExpression(valueToXAssignExpression, out xVariableReference) ||
                !this.methodContext.StackData.VariableToDefineUseInfo.ContainsKey(xVariableReference.Resolve()))
            {
                return(false);
            }

            theAssignedExpression = valueToXAssignExpression.Right;

            int currentIndex = startIndex + 1;

            for (; currentIndex < statements.Count; currentIndex++)
            {
                Statement currentStatement = statements[currentIndex];
                if (currentStatement.CodeNodeType != CodeNodeType.ExpressionStatement || !string.IsNullOrEmpty(currentStatement.Label))
                {
                    break;
                }

                BinaryExpression xToVarAssignExpression = (currentStatement as ExpressionStatement).Expression as BinaryExpression;

                if (xToVarAssignExpression == null || !xToVarAssignExpression.IsAssignmentExpression ||
                    xToVarAssignExpression.Right.CodeNodeType != CodeNodeType.VariableReferenceExpression ||
                    (xToVarAssignExpression.Right as VariableReferenceExpression).Variable != xVariableReference)
                {
                    break;
                }

                if (xToVarAssignExpression.Left.CodeNodeType == CodeNodeType.FieldReferenceExpression)
                {
                    return(false);
                }

                if (xToVarAssignExpression.Left.CodeNodeType == CodeNodeType.VariableReferenceExpression)
                {
                    VariableDefinition assignedVariable = (xToVarAssignExpression.Left as VariableReferenceExpression).Variable.Resolve();

                    if (assignedVariable == xVariableReference)
                    {
                        return(false);
                    }

                    variablesToRemove.Add(assignedVariable);
                }

                theAssignedExpression = new BinaryExpression(BinaryOperator.Assign, xToVarAssignExpression.Left, theAssignedExpression, typeSystem, null);
            }

            replacedStatementsCount = currentIndex - startIndex;
            if (replacedStatementsCount == 1)
            {
                return(false);
            }

            BinaryExpression inlinedAssign = new BinaryExpression(BinaryOperator.Assign,
                                                                  new VariableReferenceExpression(xVariableReference, null), theAssignedExpression, typeSystem, null);

            result = new ExpressionStatement(inlinedAssign)
            {
                Parent = statements[startIndex].Parent
            };
            xVariableDef = xVariableReference.Resolve();

            return(true);
        }
        public ClassDefinition GetContextFieldDeclaration()
        {
            Field field;
            Field field2;
            ParameterDeclaration      declaration;
            MemberReferenceExpression expression;
            ReferenceExpression       expression2;
            BinaryExpression          expression3;
            ReferenceExpression       expression4;
            ReferenceExpression       expression5;
            MemberReferenceExpression expression6;
            BinaryExpression          expression7;
            Block           block;
            Constructor     constructor;
            ClassDefinition definition;
            Type            type        = this._evaluationContext.GetType();
            Type            type2       = this._evaluationContext.ScriptContainer.GetType();
            ClassDefinition definition1 = definition = new ClassDefinition(LexicalInfo.Empty);
            string          text1       = definition.Name = "_";

            TypeMember[]  items      = new TypeMember[3];
            Field         field1     = field = new Field(LexicalInfo.Empty);
            int           num1       = (int)(field.Modifiers = TypeMemberModifiers.Static | TypeMemberModifiers.Public);
            string        text2      = field.Name = "ScriptContainer";
            TypeReference reference1 = field.Type = TypeReference.Lift(type2);
            int           num2       = (int)(field.IsVolatile = false);

            items[0] = field;
            Field         field3     = field2 = new Field(LexicalInfo.Empty);
            string        text3      = field2.Name = "EvaluationContext";
            TypeReference reference4 = field2.Type = TypeReference.Lift(type);
            int           num3       = (int)(field2.IsVolatile = false);

            items[1] = field2;
            Constructor constructor1 = constructor = new Constructor(LexicalInfo.Empty);
            string      text4        = constructor.Name = "constructor";

            ParameterDeclaration[] parameters   = new ParameterDeclaration[1];
            ParameterDeclaration   declaration1 = declaration = new ParameterDeclaration(LexicalInfo.Empty);
            string        text5      = declaration.Name = "context";
            TypeReference reference5 = declaration.Type = TypeReference.Lift(type);

            parameters[0] = declaration;
            ParameterDeclarationCollection collection1 = constructor.Parameters = ParameterDeclarationCollection.FromArray(false, parameters);
            Block block1 = block = new Block(LexicalInfo.Empty);

            Statement[]      statementArray1 = new Statement[2];
            BinaryExpression expression1     = expression3 = new BinaryExpression(LexicalInfo.Empty);
            int num4 = (int)(expression3.Operator = BinaryOperatorType.Assign);
            MemberReferenceExpression expression14 = expression = new MemberReferenceExpression(LexicalInfo.Empty);
            string text6 = expression.Name = "EvaluationContext";
            SelfLiteralExpression     expression15 = expression.Target = new SelfLiteralExpression(LexicalInfo.Empty);
            MemberReferenceExpression expression16 = expression3.Left = expression;
            ReferenceExpression       expression17 = expression2 = new ReferenceExpression(LexicalInfo.Empty);
            string text7 = expression2.Name = "context";
            ReferenceExpression expression18 = expression3.Right = expression2;

            statementArray1[0] = Statement.Lift(expression3);
            BinaryExpression expression19 = expression7 = new BinaryExpression(LexicalInfo.Empty);
            int num5 = (int)(expression7.Operator = BinaryOperatorType.Assign);
            ReferenceExpression expression20 = expression4 = new ReferenceExpression(LexicalInfo.Empty);
            string text8 = expression4.Name = "ScriptContainer";
            ReferenceExpression       expression21 = expression7.Left = expression4;
            MemberReferenceExpression expression22 = expression6 = new MemberReferenceExpression(LexicalInfo.Empty);
            string text9 = expression6.Name = "ScriptContainer";
            ReferenceExpression expression23 = expression5 = new ReferenceExpression(LexicalInfo.Empty);
            string text10 = expression5.Name = "context";
            ReferenceExpression       expression24 = expression6.Target = expression5;
            MemberReferenceExpression expression25 = expression7.Right = expression6;

            statementArray1[1] = Statement.Lift(expression7);
            StatementCollection collection2 = block.Statements = StatementCollection.FromArray(statementArray1);
            Block block3 = constructor.Body = block;

            items[2] = constructor;
            TypeMemberCollection collection3 = definition.Members = TypeMemberCollection.FromArray(items);

            return(definition);
        }
		public bool TryMatch(StatementCollection statements,out int startIndex, out Statement result, out int replacedStatementsCount)
		{
			result = null;
			replacedStatementsCount = 1;
			for (startIndex = 0; startIndex < statements.Count; startIndex++)
			{
				if (statements[startIndex].CodeNodeType != CodeNodeType.IfStatement)
				{
					continue;
				}

                if (TryMatchInternal(statements[startIndex] as IfStatement, out result))
				{
					return true;
				}
			}
			return false;
		}