Exemple #1
0
        public override object VisitAssignmentExpression(AssignmentExpression assignment, object data)
        {
            base.VisitAssignmentExpression(assignment, data);
            // Combine "x = x op y" into "x op= y"
            BinaryOperatorExpression binary = assignment.Right as BinaryOperatorExpression;

            if (binary != null && assignment.Operator == AssignmentOperatorType.Assign)
            {
                if (CanConvertToCompoundAssignment(assignment.Left) && assignment.Left.IsMatch(binary.Left))
                {
                    assignment.Operator = GetAssignmentOperatorForBinaryOperator(binary.Operator);
                    if (assignment.Operator != AssignmentOperatorType.Assign)
                    {
                        // If we found a shorter operator, get rid of the BinaryOperatorExpression:
                        assignment.CopyAnnotationsFrom(binary);
                        assignment.Right = binary.Right.WithAnnotation(assignment.Right.GetAllRecursiveILRanges());
                        assignment.AddAnnotation(new RestoreOriginalAssignOperatorAnnotation(binary));
                    }
                }
            }
            if (context.Settings.IntroduceIncrementAndDecrement && (assignment.Operator == AssignmentOperatorType.Add || assignment.Operator == AssignmentOperatorType.Subtract))
            {
                // detect increment/decrement
                if (assignment.Right.IsMatch(new PrimitiveExpression(1)))
                {
                    // only if it's not a custom operator
                    if (assignment.Annotation <IMethod>() == null)
                    {
                        UnaryOperatorType type;
                        // When the parent is an expression statement, pre- or post-increment doesn't matter;
                        // so we can pick post-increment which is more commonly used (for (int i = 0; i < x; i++))
                        if (assignment.Parent is ExpressionStatement)
                        {
                            type = (assignment.Operator == AssignmentOperatorType.Add) ? UnaryOperatorType.PostIncrement : UnaryOperatorType.PostDecrement;
                        }
                        else
                        {
                            type = (assignment.Operator == AssignmentOperatorType.Add) ? UnaryOperatorType.Increment : UnaryOperatorType.Decrement;
                        }
                        assignment.ReplaceWith(new UnaryOperatorExpression(type, assignment.Left.Detach()).CopyAnnotationsFrom(assignment).WithAnnotation(assignment.GetAllRecursiveILRanges()));
                    }
                }
            }
            return(null);
        }