public override SyntaxNode VisitIfStatement(IfStatementSyntax node)
        {
            //check if the condition does not involve realational or equality operators
            //as the main operator between the only two members in that expression

            if (!(node.Condition is BinaryExpressionSyntax))
            {
                if (!node.Condition.ToFullString().Contains("out"))
                {
                    var trueLiteralExpression  = SyntaxFactory.LiteralExpression(SyntaxKind.TrueLiteralExpression);
                    var falseLiteralExpression = SyntaxFactory.LiteralExpression(SyntaxKind.FalseLiteralExpression);

                    var trueConditionNode  = node.ReplaceNode(node.Condition, trueLiteralExpression);
                    var falseConditionNode = node.ReplaceNode(node.Condition, falseLiteralExpression);

                    var classMutatedWithTrueCondition =
                        _classRootNode.ReplaceNode(node, trueConditionNode);
                    _mutantCreator.CreateNewMutant(classMutatedWithTrueCondition, false);

                    var classMutatedWithFalseCondition =
                        _classRootNode.ReplaceNode(node, falseConditionNode);
                    _mutantCreator.CreateNewMutant(classMutatedWithFalseCondition, false);
                }
            }

            return(node);
        }
Exemple #2
0
        private static IfStatementSyntax ExtractExpressionToNestedIf(
            ExpressionSyntax expression,
            IfStatementSyntax ifStatement,
            IfStatementSyntax newIfStatement)
        {
            if (newIfStatement.Statement.IsKind(SyntaxKind.Block))
            {
                var block = (BlockSyntax)newIfStatement.Statement;

                IfStatementSyntax nestedIf = IfStatement(
                    expression.WithoutTrivia(),
                    Block(block.Statements));

                return(newIfStatement.ReplaceNode(
                           block,
                           block.WithStatements(SingletonList <StatementSyntax>(nestedIf))));
            }
            else
            {
                IfStatementSyntax nestedIf = IfStatement(
                    expression.WithoutTrivia(),
                    ifStatement.Statement.WithoutTrivia());

                BlockSyntax block = Block(nestedIf).WithTriviaFrom(ifStatement.Statement);

                return(newIfStatement.WithStatement(block));
            }
        }
Exemple #3
0
        private static Task <Document> RefactorAsync(
            Document document,
            IfStatementSyntax ifStatement,
            StatementListSelection selectedStatements,
            CancellationToken cancellationToken)
        {
            int count = selectedStatements.Count;

            StatementSyntax newStatement;

            if (count == 1 &&
                !ifStatement.AsCascade().Any(f => f.Statement?.Kind() == SyntaxKind.Block))
            {
                newStatement = selectedStatements.First();
            }
            else
            {
                newStatement = SyntaxFactory.Block(selectedStatements);
            }

            ElseClauseSyntax elseClause = SyntaxFactory.ElseClause(newStatement).WithFormatterAnnotation();

            IfStatementSyntax lastIfStatement = ifStatement.AsCascade().Last();

            IfStatementSyntax newIfStatement = ifStatement.ReplaceNode(
                lastIfStatement,
                lastIfStatement.WithElse(elseClause));

            SyntaxList <StatementSyntax> newStatements = selectedStatements
                                                         .UnderlyingList
                                                         .Replace(ifStatement, newIfStatement)
                                                         .RemoveRange(selectedStatements.FirstIndex, count);

            return(document.ReplaceStatementsAsync(SyntaxInfo.StatementListInfo(selectedStatements), newStatements, cancellationToken));
        }
        private static Task <Document> RefactorAsync(
            Document document,
            IfStatementSyntax ifStatement,
            ReturnStatementSyntax returnStatement,
            IStatementContainer container,
            CancellationToken cancellationToken)
        {
            SyntaxList <StatementSyntax> statements = container.Statements;

            IfStatement ifElse = IfStatement.Create(ifStatement);

            StatementSyntax statement = returnStatement;

            if (ifElse.Nodes.Any(f => f.Statement?.IsKind(SyntaxKind.Block) == true))
            {
                statement = SyntaxFactory.Block(statement);
            }

            ElseClauseSyntax elseClause = SyntaxFactory.ElseClause(statement).WithFormatterAnnotation();

            IfStatementSyntax lastIfStatement = ifElse.Nodes.Last();

            IfStatementSyntax newIfStatement = ifStatement.ReplaceNode(
                lastIfStatement,
                lastIfStatement.WithElse(elseClause));

            SyntaxList <StatementSyntax> newStatements = statements
                                                         .Replace(ifStatement, newIfStatement)
                                                         .RemoveAt(statements.IndexOf(returnStatement));

            return(document.ReplaceNodeAsync(container.Node, container.NodeWithStatements(newStatements), cancellationToken));
        }
Exemple #5
0
 private static IfStatementSyntax GetNewIfStatement(IfStatementSyntax ifStatement, IfStatementSyntax ifStatement2)
 {
     if (ifStatement.Statement.IsKind(SyntaxKind.Block))
     {
         if (ifStatement2.Statement.IsKind(SyntaxKind.Block))
         {
             return(ifStatement.ReplaceNode(ifStatement2, ((BlockSyntax)ifStatement2.Statement).Statements));
         }
         else
         {
             return(ifStatement.ReplaceNode(ifStatement2, ifStatement2.Statement));
         }
     }
     else
     {
         return(ifStatement.ReplaceNode(ifStatement.Statement, ifStatement2.Statement));
     }
 }
 private async Task<Document> AddBracesAsync(Document document, IfStatementSyntax ifStatement, CancellationToken cancellationToken)
 {
     var nonBlockedStatement = ifStatement.Statement as ExpressionStatementSyntax;
     var newBlockedStatement = SyntaxFactory.Block(statements: nonBlockedStatement).WithAdditionalAnnotations(annotations: Formatter.Annotation);
     var newIfStatement = ifStatement.ReplaceNode(oldNode: nonBlockedStatement, newNode: newBlockedStatement);
     var root = await document.GetSyntaxRootAsync();
     var newRoot = root.ReplaceNode(oldNode: ifStatement, newNode: newIfStatement);
     var newDocument = document.WithSyntaxRoot(newRoot);
     return newDocument;
 }
        private static IfStatementSyntax GetUpdatedIfStatement(
            IsPatternExpressionSyntax updatedCondition,
            ImmutableArray <SyntaxTrivia> trivia,
            IfStatementSyntax originalIf,
            IfStatementSyntax currentIf)
        {
            var newIf = currentIf.ReplaceNode(currentIf.Condition, updatedCondition);

            newIf = originalIf.IsParentKind(SyntaxKind.ElseClause)
                ? newIf.ReplaceToken(newIf.CloseParenToken, newIf.CloseParenToken.WithTrailingTrivia(trivia))
                : newIf.WithPrependedLeadingTrivia(trivia);

            return(newIf.WithAdditionalAnnotations(Formatter.Annotation));
        }
        public override SyntaxNode Visit(SyntaxNode node)
        {
            IfStatementSyntax ifNode          = node as IfStatementSyntax;
            StatementSyntax   statementSyntax = ifNode?.Statement;

            if (statementSyntax != null && statementSyntax.Kind() != SyntaxKind.Block)
            {
                StatementSyntax formattedStatement = statementSyntax.WithLeadingTrivia(SyntaxFactory.Space).WithTrailingTrivia(SyntaxFactory.Space);
                BlockSyntax     singleLineBlock    = SyntaxFactory.Block(formattedStatement).WithLeadingTrivia(SyntaxFactory.Space).WithTrailingTrivia(SyntaxFactory.CarriageReturnLineFeed);

                return(ifNode
                       .ReplaceNode(statementSyntax, singleLineBlock)
                       .WithCondition(ifNode.Condition.WithoutTrivia())
                       .WithIfKeyword(ifNode.IfKeyword.WithTrailingTrivia())
                       .WithOpenParenToken(ifNode.OpenParenToken.WithoutTrivia().WithLeadingTrivia(SyntaxFactory.Space))
                       .WithCloseParenToken(ifNode.CloseParenToken.WithoutTrivia()));
            }
            else
            {
                return(base.Visit(node));
            }
        }
        /// <summary>
        /// This is where the magic happens returning a new document with the code fix inside.
        /// </summary>
        /// <param name="document"></param>
        /// <param name="ifStatement"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        private async Task <Document> AddBracesAsync(Document document, IfStatementSyntax ifStatement, CancellationToken cancellationToken)
        {
            // Get our non block statement which we are going to recreate with a block and remove this
            var nonBlockStatement = ifStatement.Statement as ExpressionStatementSyntax;

            // New up a block statement from the existing non-block statement
            var newBlockStatement = SyntaxFactory.Block(nonBlockStatement)
                                    .WithAdditionalAnnotations(Formatter.Annotation);              // Handle formating of code

            // Swap out the nodes and return a new if statement
            var newIfStatement = ifStatement.ReplaceNode(nonBlockStatement, newBlockStatement);

            // Get entire document (compulation unit)
            var root = await document.GetSyntaxRootAsync(cancellationToken);

            var newRoot = root.ReplaceNode(ifStatement, newIfStatement);

            // Create a new document and return the replacement
            var newDocument = document.WithSyntaxRoot(newRoot);

            return(newDocument);
        }
Exemple #10
0
        private static Task <Document> RefactorAsync(
            Document document,
            IfStatementSyntax ifStatement,
            StatementContainerSelection selectedStatements,
            CancellationToken cancellationToken)
        {
            IfStatement ifElse = IfStatement.Create(ifStatement);

            StatementSyntax newStatement = null;

            if (selectedStatements.Count == 1 &&
                !ifElse.Nodes.Any(f => f.Statement?.IsKind(SyntaxKind.Block) == true))
            {
                newStatement = selectedStatements.First();
            }
            else
            {
                newStatement = SyntaxFactory.Block(selectedStatements);
            }

            ElseClauseSyntax elseClause = SyntaxFactory.ElseClause(newStatement).WithFormatterAnnotation();

            IfStatementSyntax lastIfStatement = ifElse.Nodes.Last();

            IfStatementSyntax newIfStatement = ifStatement.ReplaceNode(
                lastIfStatement,
                lastIfStatement.WithElse(elseClause));

            SyntaxList <StatementSyntax> newStatements = selectedStatements.Statements.Replace(ifStatement, newIfStatement);

            for (int i = newStatements.Count - 1; i >= selectedStatements.StartIndex; i--)
            {
                newStatements = newStatements.RemoveAt(i);
            }

            return(document.ReplaceNodeAsync(selectedStatements.Container.Node, selectedStatements.Container.NodeWithStatements(newStatements), cancellationToken));
        }
        internal static IEnumerable<CodeAction> HandleNegatedCase(SemanticModel ctx, Document document, SyntaxNode root, IfStatementSyntax ifElseStatement, ExpressionSyntax c2, BinaryExpressionSyntax isExpression, out int foundCastCount)
        {
            foundCastCount = 0;

            var condition = isExpression;
            var castToType = isExpression.Right;
            var embeddedStatment = ifElseStatement.Statement;

            var rr = ctx.GetTypeInfo(castToType);
            if (rr.Type == null || !rr.Type.IsReferenceType)
                return Enumerable.Empty<CodeAction>();

            List<SyntaxNode> foundCasts;

            SyntaxNode searchStmt = embeddedStatment;
            if (IsControlFlowChangingStatement(searchStmt))
            {
                searchStmt = ifElseStatement.Parent;
                foundCasts = searchStmt.DescendantNodesAndSelf(n => !IsCast(ctx, n, rr.Type)).Where(arg => arg.SpanStart >= ifElseStatement.SpanStart && IsCast(ctx, arg, rr.Type)).ToList();
                foundCasts.AddRange(ifElseStatement.Condition.DescendantNodesAndSelf(n => !IsCast(ctx, n, rr.Type)).Where(arg => arg.SpanStart > isExpression.Span.End && IsCast(ctx, arg, rr.Type)));
            }
            else
            {
                foundCasts = new List<SyntaxNode>();
            }

            foundCastCount = foundCasts.Count;

            return new[] {
                CodeActionFactory.Create(
                    isExpression.Span,
                    DiagnosticSeverity.Info,
                    GettextCatalog.GetString ("Use 'as' and check for null"),
                    t2 => {
                        var varName = ReplaceAutoPropertyWithPropertyAndBackingFieldCodeRefactoringProvider.GetNameProposal(RefactoringHelpers.GuessNameFromType(rr.Type), ctx, condition);

                        var varDec = SyntaxFactory.LocalDeclarationStatement(
                            SyntaxFactory.VariableDeclaration(
                                SyntaxFactory.ParseTypeName("var"),
                                SyntaxFactory.SeparatedList(new [] {
                                    SyntaxFactory.VariableDeclarator(varName)
                                        .WithInitializer(SyntaxFactory.EqualsValueClause(
                                            SyntaxFactory.BinaryExpression(SyntaxKind.AsExpression, condition.Left, condition.Right)
                                        ))
                                    })
                            ));
                        //var outerIs = isExpression.AncestorsAndSelf().FirstOrDefault(e => !(e.Parent is ParenthesizedExpressionSyntax));
                        var binaryOperatorExpression = SyntaxFactory.BinaryExpression(SyntaxKind.EqualsExpression, SyntaxFactory.IdentifierName(varName), SyntaxFactory.LiteralExpression(SyntaxKind.NullLiteralExpression));
                        SyntaxNode newRoot;
                        if (IsEmbeddedStatement(ifElseStatement)) {
                            var newIf = ifElseStatement.ReplaceNode((SyntaxNode)c2, binaryOperatorExpression.WithAdditionalAnnotations(Formatter.Annotation));

                            foreach (var c in foundCasts) {
                                newIf = newIf.ReplaceNode((SyntaxNode)newIf.GetCurrentNode(c), SyntaxFactory.IdentifierName(varName).WithAdditionalAnnotations(Formatter.Annotation));
                            }

                            var block = SyntaxFactory.Block(new StatementSyntax[] {
                                varDec,
                                newIf
                            });

                            newRoot = root.ReplaceNode((SyntaxNode)ifElseStatement, block.WithAdditionalAnnotations(Formatter.Annotation));
                        } else {
                            newRoot = root.TrackNodes(foundCasts.Concat(new SyntaxNode[] { ifElseStatement, c2 }) );
                            newRoot = newRoot.InsertNodesBefore(newRoot.GetCurrentNode(ifElseStatement), new [] { varDec.WithAdditionalAnnotations(Formatter.Annotation) });
                            newRoot = newRoot.ReplaceNode((SyntaxNode)newRoot.GetCurrentNode(c2), binaryOperatorExpression.WithAdditionalAnnotations(Formatter.Annotation));
                            foreach (var c in foundCasts) {
                                newRoot = newRoot.ReplaceNode((SyntaxNode)newRoot.GetCurrentNode(c), SyntaxFactory.IdentifierName(varName).WithAdditionalAnnotations(Formatter.Annotation));
                            }
                        }

                        return Task.FromResult(document.WithSyntaxRoot(newRoot));
                    }
                )
            };
        }
Exemple #12
0
        internal static IEnumerable <CodeAction> HandleNegatedCase(SemanticModel ctx, Document document, SyntaxNode root, IfStatementSyntax ifElseStatement, ExpressionSyntax c2, BinaryExpressionSyntax isExpression, out int foundCastCount)
        {
            foundCastCount = 0;

            var condition        = isExpression;
            var castToType       = isExpression.Right;
            var embeddedStatment = ifElseStatement.Statement;

            var rr = ctx.GetTypeInfo(castToType);

            if (rr.Type == null || !rr.Type.IsReferenceType)
            {
                return(Enumerable.Empty <CodeAction>());
            }

            List <SyntaxNode> foundCasts;

            SyntaxNode searchStmt = embeddedStatment;

            if (IsControlFlowChangingStatement(searchStmt))
            {
                searchStmt = ifElseStatement.Parent;
                foundCasts = searchStmt.DescendantNodesAndSelf(n => !IsCast(ctx, n, rr.Type)).Where(arg => arg.SpanStart >= ifElseStatement.SpanStart && IsCast(ctx, arg, rr.Type)).ToList();
                foundCasts.AddRange(ifElseStatement.Condition.DescendantNodesAndSelf(n => !IsCast(ctx, n, rr.Type)).Where(arg => arg.SpanStart > isExpression.Span.End && IsCast(ctx, arg, rr.Type)));
            }
            else
            {
                foundCasts = new List <SyntaxNode>();
            }

            foundCastCount = foundCasts.Count;

            return(new[] {
                CodeActionFactory.Create(
                    isExpression.Span,
                    DiagnosticSeverity.Info,
                    GettextCatalog.GetString("Use 'as' and check for null"),
                    t2 => {
                    var varName = GetNameProposal(RefactoringHelpers.GuessNameFromType(rr.Type), ctx, condition);

                    var varDec = SyntaxFactory.LocalDeclarationStatement(
                        SyntaxFactory.VariableDeclaration(
                            SyntaxFactory.ParseTypeName("var"),
                            SyntaxFactory.SeparatedList(new [] {
                        SyntaxFactory.VariableDeclarator(varName)
                        .WithInitializer(SyntaxFactory.EqualsValueClause(
                                             SyntaxFactory.BinaryExpression(SyntaxKind.AsExpression, condition.Left, condition.Right)
                                             ))
                    })
                            ));
                    //var outerIs = isExpression.AncestorsAndSelf().FirstOrDefault(e => !(e.Parent is ParenthesizedExpressionSyntax));
                    var binaryOperatorExpression = SyntaxFactory.BinaryExpression(SyntaxKind.EqualsExpression, SyntaxFactory.IdentifierName(varName), SyntaxFactory.LiteralExpression(SyntaxKind.NullLiteralExpression));
                    SyntaxNode newRoot;
                    if (IsEmbeddedStatement(ifElseStatement))
                    {
                        var newIf = ifElseStatement.ReplaceNode((SyntaxNode)c2, binaryOperatorExpression.WithAdditionalAnnotations(Formatter.Annotation));

                        foreach (var c in foundCasts)
                        {
                            newIf = newIf.ReplaceNode((SyntaxNode)newIf.GetCurrentNode(c), SyntaxFactory.IdentifierName(varName).WithAdditionalAnnotations(Formatter.Annotation));
                        }

                        var block = SyntaxFactory.Block(new StatementSyntax[] {
                            varDec,
                            newIf
                        });

                        newRoot = root.ReplaceNode((SyntaxNode)ifElseStatement, block.WithAdditionalAnnotations(Formatter.Annotation));
                    }
                    else
                    {
                        newRoot = root.TrackNodes(foundCasts.Concat(new SyntaxNode[] { ifElseStatement, c2 }));
                        newRoot = newRoot.InsertNodesBefore(newRoot.GetCurrentNode(ifElseStatement), new [] { varDec.WithAdditionalAnnotations(Formatter.Annotation) });
                        newRoot = newRoot.ReplaceNode((SyntaxNode)newRoot.GetCurrentNode(c2), binaryOperatorExpression.WithAdditionalAnnotations(Formatter.Annotation));
                        foreach (var c in foundCasts)
                        {
                            newRoot = newRoot.ReplaceNode((SyntaxNode)newRoot.GetCurrentNode(c), SyntaxFactory.IdentifierName(varName).WithAdditionalAnnotations(Formatter.Annotation));
                        }
                    }

                    return Task.FromResult(document.WithSyntaxRoot(newRoot));
                }
                    )
            });
        }