private static Task <Document> RefactorAsync(
            Document document,
            IfStatementSyntax ifStatement,
            CancellationToken cancellationToken)
        {
            StatementSyntax  statement = ifStatement.Statement.WithoutTrivia();
            ExpressionSyntax condition = ifStatement.Condition;

            var logicalOr = (BinaryExpressionSyntax)condition;

            BinaryExpressionChain chain = BinaryExpressionChain.Create((BinaryExpressionSyntax)condition);

            var ifStatements = new List <IfStatementSyntax>();

            foreach (ExpressionSyntax expression in chain.Expressions)
            {
                ifStatements.Add(SyntaxFactory.IfStatement(expression.TrimTrivia(), statement).WithFormatterAnnotation());
            }

            ifStatements[0] = ifStatements[0].WithLeadingTrivia(ifStatement.GetLeadingTrivia());
            ifStatements[ifStatements.Count - 1] = ifStatements[ifStatements.Count - 1].WithTrailingTrivia(ifStatement.GetTrailingTrivia());

            if (EmbeddedStatementHelper.IsEmbeddedStatement(ifStatement))
            {
                BlockSyntax block = SyntaxFactory.Block(ifStatements);

                return(document.ReplaceNodeAsync(ifStatement, block, cancellationToken));
            }
            else
            {
                return(document.ReplaceNodeAsync(ifStatement, ifStatements, cancellationToken));
            }
        }
Пример #2
0
        private static void RegisterRefactoring(RefactoringContext context, StatementSyntax statement)
        {
            bool isEmbedded = EmbeddedStatementHelper.IsEmbeddedStatement(statement);

            if (context.IsRefactoringEnabled(RefactoringIdentifiers.RemoveStatement) &&
                !isEmbedded)
            {
                context.RegisterRefactoring(
                    "Remove statement",
                    cancellationToken => context.Document.RemoveStatementAsync(statement, cancellationToken));
            }

            if (context.IsRefactoringEnabled(RefactoringIdentifiers.DuplicateStatement))
            {
                context.RegisterRefactoring(
                    "Duplicate statement",
                    cancellationToken => DuplicateStatementAsync(context.Document, statement, cancellationToken));
            }

            if (context.IsRefactoringEnabled(RefactoringIdentifiers.CommentOutStatement) &&
                !isEmbedded)
            {
                CommentOutRefactoring.RegisterRefactoring(context, statement);
            }
        }
        public static void Analyze(SyntaxNodeAnalysisContext context)
        {
            SyntaxNode node = context.Node;

            if (!node.IsKind(SyntaxKind.IfStatement) ||
                ((IfStatementSyntax)node).IsSimpleIf())
            {
                BlockSyntax block = EmbeddedStatementHelper.AnalyzeBlockToEmbeddedStatement(node);

                if (block != null)
                {
                    SyntaxToken openBrace  = block.OpenBraceToken;
                    SyntaxToken closeBrace = block.CloseBraceToken;

                    if (!openBrace.IsMissing &&
                        !closeBrace.IsMissing &&
                        openBrace.LeadingTrivia.IsEmptyOrWhitespace() &&
                        openBrace.TrailingTrivia.IsEmptyOrWhitespace() &&
                        closeBrace.LeadingTrivia.IsEmptyOrWhitespace() &&
                        closeBrace.TrailingTrivia.IsEmptyOrWhitespace())
                    {
                        string title = node.GetTitle();

                        context.ReportDiagnostic(DiagnosticDescriptors.RemoveBraces, block, title);

                        context.ReportBraces(DiagnosticDescriptors.RemoveBracesFadeOut, block, title);
                    }
                }
            }
        }
 private static bool IsEmbeddableBlock(BlockSyntax block)
 {
     return(EmbeddedStatementHelper.CanContainEmbeddedStatement(block.Parent) &&
            block
            .SingleStatementOrDefault()?
            .IsKind(SyntaxKind.LocalDeclarationStatement, SyntaxKind.LabeledStatement) == false);
 }
 private static void AnalyzeEmbeddedStatement(SyntaxNodeAnalysisContext context, SyntaxToken token, StatementSyntax statement)
 {
     if (statement != null &&
         EmbeddedStatementHelper.IsEmbeddedStatement(statement))
     {
         Analyze(context, token, statement);
     }
 }
Пример #6
0
        private void AnalyzeStatement(SyntaxNodeAnalysisContext context)
        {
            StatementSyntax statement = EmbeddedStatementHelper.GetEmbeddedStatement(context.Node, ifInsideElse: false, usingInsideUsing: false);

            if (statement != null)
            {
                context.ReportDiagnostic(
                    DiagnosticDescriptors.AvoidEmbeddedStatement,
                    statement,
                    context.Node.GetTitle());
            }
        }
Пример #7
0
        public static void AnalyzeEmptyStatement(SyntaxNodeAnalysisContext context)
        {
            SyntaxNode emptyStatement = context.Node;

            SyntaxNode parent = emptyStatement.Parent;

            if (parent?.IsKind(SyntaxKind.LabeledStatement) == false &&
                !EmbeddedStatementHelper.CanContainEmbeddedStatement(parent))
            {
                context.ReportDiagnostic(DiagnosticDescriptors.RemoveEmptyStatement, emptyStatement);
            }
        }
Пример #8
0
        private static void Analyze(SyntaxNodeAnalysisContext context, SyntaxNode node)
        {
            StatementSyntax statement = EmbeddedStatementHelper.GetEmbeddedStatement(node);

            if (statement != null)
            {
                context.ReportDiagnostic(
                    DiagnosticDescriptors.AvoidEmbeddedStatementInIfElse,
                    statement,
                    node.GetTitle());
            }
        }
        private static void Analyze(SyntaxNodeAnalysisContext context, SyntaxNode node)
        {
            StatementSyntax statement = EmbeddedStatementHelper.GetEmbeddedStatement(node, ifInsideElse: false, usingInsideUsing: false);

            if (statement != null)
            {
                context.ReportDiagnostic(
                    DiagnosticDescriptors.AddBracesToIfElse,
                    statement,
                    node.GetTitle());
            }
        }
        public static Task <Document> RefactorAsync(
            Document document,
            ForStatementSyntax forStatement,
            CancellationToken cancellationToken)
        {
            var statements = new List <StatementSyntax>();

            VariableDeclarationSyntax declaration = forStatement.Declaration;

            if (declaration != null)
            {
                statements.Add(LocalDeclarationStatement(declaration));
            }
            else
            {
                foreach (ExpressionSyntax initializer in forStatement.Initializers)
                {
                    statements.Add(ExpressionStatement(initializer));
                }
            }

            StatementSyntax statement = forStatement.Statement ?? Block();

            SeparatedSyntaxList <ExpressionSyntax> incrementors = forStatement.Incrementors;

            if (incrementors.Any())
            {
                if (!statement.IsKind(SyntaxKind.Block))
                {
                    statement = Block(statement);
                }

                ExpressionStatementSyntax[] items = incrementors
                                                    .Select(f => ExpressionStatement(f).WithFormatterAnnotation())
                                                    .ToArray();

                statement = ((BlockSyntax)statement).AddStatements(items);
            }

            statements.Add(WhileStatement(forStatement.Condition ?? TrueLiteralExpression(), statement));

            statements[0] = statements[0].WithLeadingTrivia(forStatement.GetLeadingTrivia());

            if (EmbeddedStatementHelper.IsEmbeddedStatement(forStatement))
            {
                return(document.ReplaceNodeAsync(forStatement, Block(statements), cancellationToken));
            }
            else
            {
                return(document.ReplaceNodeAsync(forStatement, statements, cancellationToken));
            }
        }
        private static bool CanRefactor(RefactoringContext context, BlockSyntax block)
        {
            if (context.Span.IsEmptyAndContainedInSpanOrBetweenSpans(block) &&
                IsEmbeddableBlock(block))
            {
                StatementSyntax statement = EmbeddedStatementHelper.GetEmbeddedStatement(block.Statements[0]);

                return(statement == null ||
                       !statement.FullSpan.Contains(context.Span));
            }

            return(false);
        }
Пример #12
0
        private static StatementSyntax GetEmbeddedStatementThatShouldBeInsideBlock(SyntaxNode node)
        {
            StatementSyntax statement = EmbeddedStatementHelper.GetBlockOrEmbeddedStatement(node);

            if (statement?.IsKind(SyntaxKind.Block) == false)
            {
                if (!statement.IsSingleLine() || !EmbeddedStatementHelper.FormattingSupportsEmbeddedStatement(node))
                {
                    return(statement);
                }
            }

            return(null);
        }
Пример #13
0
        private static async Task <Document> RefactorAsync(
            Document document,
            ExpressionSyntax expression,
            StatementSyntax statement,
            CancellationToken cancellationToken)
        {
            SemanticModel semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);

            if (EmbeddedStatementHelper.IsEmbeddedStatement(statement))
            {
                return(await document.ReplaceNodeAsync(statement, Block(statement, CreateNullCheck(expression)), cancellationToken).ConfigureAwait(false));
            }
            else
            {
                StatementContainer container;
                if (StatementContainer.TryCreate(statement, out container))
                {
                    SyntaxList <StatementSyntax> statements = container.Statements;

                    int statementIndex = statements.IndexOf(statement);

                    ISymbol symbol = (statement.IsKind(SyntaxKind.LocalDeclarationStatement))
                        ? semanticModel.GetDeclaredSymbol(((LocalDeclarationStatementSyntax)statement).Declaration.Variables.First(), cancellationToken)
                        : semanticModel.GetSymbol(expression, cancellationToken);

                    int lastStatementIndex = IncludeAllReferencesOfSymbol(symbol, expression.Kind(), statements, statementIndex + 1, semanticModel, cancellationToken);

                    if (lastStatementIndex != -1)
                    {
                        if (lastStatementIndex < statements.Count - 1)
                        {
                            lastStatementIndex = IncludeAllReferencesOfVariablesDeclared(statements, statementIndex + 1, lastStatementIndex, semanticModel, cancellationToken);
                        }

                        return(await RefactorAsync(
                                   document,
                                   expression,
                                   statements,
                                   container,
                                   statementIndex,
                                   lastStatementIndex,
                                   cancellationToken).ConfigureAwait(false));
                    }
                }
            }

            return(await document.InsertNodeAfterAsync(statement, CreateNullCheck(expression), cancellationToken).ConfigureAwait(false));
        }
Пример #14
0
        public static void Analyze(SyntaxNodeAnalysisContext context, StatementSyntax statement)
        {
            if (!statement.IsKind(SyntaxKind.IfStatement) ||
                ((IfStatementSyntax)statement).IsSimpleIf())
            {
                StatementSyntax embeddedStatement = EmbeddedStatementHelper.AnalyzeEmbeddedStatementToBlock(statement, ifInsideElse: false, usingInsideUsing: false);

                if (embeddedStatement != null)
                {
                    context.ReportDiagnostic(
                        DiagnosticDescriptors.AddBracesWhenExpressionSpansOverMultipleLines,
                        embeddedStatement,
                        statement.GetTitle());
                }
            }
        }
Пример #15
0
        private static Task <Document> RefactorAsync(
            Document document,
            SyntaxNode node,
            StatementSyntax statement,
            SyntaxNode bodyOrExpressionBody,
            IParameterSymbol parameter,
            SemanticModel semanticModel,
            CancellationToken cancellationToken)
        {
            ExpressionStatementSyntax expressionStatement = SimpleAssignmentStatement(
                IdentifierName(parameter.Name),
                parameter.Type.ToDefaultValueSyntax(semanticModel, bodyOrExpressionBody.Span.End));

            expressionStatement = expressionStatement.WithFormatterAnnotation();

            SyntaxNode newNode = null;

            if (bodyOrExpressionBody.IsKind(SyntaxKind.ArrowExpressionClause))
            {
                newNode = ExpandExpressionBodyRefactoring.Refactor((ArrowExpressionClauseSyntax)bodyOrExpressionBody, semanticModel, cancellationToken);

                newNode = InsertStatement(newNode, expressionStatement);
            }
            else
            {
                if (statement != null)
                {
                    if (EmbeddedStatementHelper.IsEmbeddedStatement(statement))
                    {
                        newNode = node.ReplaceNode(statement, Block(expressionStatement, statement));
                    }
                    else
                    {
                        newNode = node.InsertNodesBefore(statement, new StatementSyntax[] { expressionStatement });
                    }
                }
                else
                {
                    newNode = InsertStatement(node, expressionStatement);
                }
            }

            return(document.ReplaceNodeAsync(node, newNode, cancellationToken));
        }
Пример #16
0
        private static bool NullCheckExists(ExpressionSyntax expression, StatementSyntax statement)
        {
            if (!EmbeddedStatementHelper.IsEmbeddedStatement(statement))
            {
                StatementContainer container;
                if (StatementContainer.TryCreate(statement, out container))
                {
                    SyntaxList <StatementSyntax> statements = container.Statements;

                    int index = statements.IndexOf(statement);

                    if (index < statements.Count - 1)
                    {
                        StatementSyntax nextStatement = statements[index + 1];

                        if (nextStatement.IsKind(SyntaxKind.IfStatement))
                        {
                            var ifStatement = (IfStatementSyntax)nextStatement;

                            ExpressionSyntax condition = ifStatement.Condition;

                            if (condition?.IsKind(SyntaxKind.NotEqualsExpression) == true)
                            {
                                var notEqualsExpression = (BinaryExpressionSyntax)condition;

                                ExpressionSyntax left = notEqualsExpression.Left;

                                if (left?.IsEquivalentTo(expression, topLevel: false) == true)
                                {
                                    ExpressionSyntax right = notEqualsExpression.Right;

                                    if (right?.IsKind(SyntaxKind.NullLiteralExpression) == true)
                                    {
                                        return(true);
                                    }
                                }
                            }
                        }
                    }
                }
            }

            return(false);
        }
        private static BlockSyntax GetBlockThatCanBeEmbeddedStatement(SyntaxNode node)
        {
            StatementSyntax childStatement = EmbeddedStatementHelper.GetBlockOrEmbeddedStatement(node);

            if (childStatement?.IsKind(SyntaxKind.Block) == true)
            {
                var block = (BlockSyntax)childStatement;

                StatementSyntax statement = block.SingleStatementOrDefault();

                if (statement?.IsKind(SyntaxKind.LocalDeclarationStatement, SyntaxKind.LabeledStatement) == false &&
                    statement.IsSingleLine() &&
                    EmbeddedStatementHelper.FormattingSupportsEmbeddedStatement(node))
                {
                    return(block);
                }
            }

            return(null);
        }
Пример #18
0
        private static bool CanRefactorIfElse(BlockSyntax selectedBlock, IfStatementSyntax topmostIf)
        {
            bool success = false;

            foreach (BlockSyntax block in GetBlockStatements(topmostIf))
            {
                if (block == selectedBlock)
                {
                    continue;
                }
                else if (EmbeddedStatementHelper.IsEmbeddableBlock(block))
                {
                    success = true;
                }
                else
                {
                    return(false);
                }
            }

            return(success);
        }
Пример #19
0
        public static void ComputeRefactoring(RefactoringContext context, BlockSyntax block)
        {
            if (context.IsAnyRefactoringEnabled(
                    RefactoringIdentifiers.RemoveStatement,
                    RefactoringIdentifiers.DuplicateStatement,
                    RefactoringIdentifiers.CommentOutStatement))
            {
                StatementSyntax statement = GetStatement(context, block, block.Parent);

                if (statement != null)
                {
                    if (!EmbeddedStatementHelper.IsEmbeddedStatement(statement) &&
                        statement.IsParentKind(SyntaxKind.Block))
                    {
                        RegisterRefactoring(context, statement);
                    }

                    if (context.IsRefactoringEnabled(RefactoringIdentifiers.CommentOutStatement))
                    {
                        CommentOutRefactoring.RegisterRefactoring(context, statement);
                    }
                }
            }
        }
Пример #20
0
        private static async Task <Document> RefactorAsync(
            Document document,
            StringConcatenationExpression concatenation,
            StatementSyntax statement,
            CancellationToken cancellationToken)
        {
            SemanticModel semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);

            string name = NameGenerator.Default.EnsureUniqueLocalName(DefaultNames.StringBuilderVariable, semanticModel, statement.SpanStart, cancellationToken: cancellationToken);

            IdentifierNameSyntax stringBuilderName = IdentifierName(name);

            TypeSyntax type = semanticModel.GetTypeByMetadataName(MetadataNames.System_Text_StringBuilder).ToMinimalTypeSyntax(semanticModel, statement.SpanStart);

            var statements = new List <StatementSyntax>()
            {
                LocalDeclarationStatement(VarType(), Identifier(name).WithRenameAnnotation(), ObjectCreationExpression(type, ArgumentList())).WithLeadingTrivia(statement.GetLeadingTrivia())
            };

            ImmutableArray <ExpressionSyntax> expressions = concatenation.Expressions;

            ExpressionSyntax newInvocation = null;

            for (int i = 0; i < expressions.Length; i++)
            {
                if (expressions[i].IsKind(SyntaxKind.InterpolatedStringExpression))
                {
                    var interpolatedString = (InterpolatedStringExpressionSyntax)expressions[i];

                    bool isVerbatim = interpolatedString.IsVerbatim();

                    SyntaxList <InterpolatedStringContentSyntax> contents = interpolatedString.Contents;

                    for (int j = 0; j < contents.Count; j++)
                    {
                        InterpolatedStringContentConversion conversion = InterpolatedStringContentConversion.Create(contents[j], isVerbatim);

                        newInvocation = SimpleMemberInvocationExpression(
                            newInvocation ?? stringBuilderName,
                            IdentifierName(conversion.Name),
                            ArgumentList(conversion.Arguments));
                    }
                }
                else
                {
                    newInvocation = SimpleMemberInvocationExpression(
                        newInvocation ?? stringBuilderName,
                        IdentifierName("Append"),
                        Argument(expressions[i].WithoutTrivia()));
                }
            }

            statements.Add(ExpressionStatement(newInvocation));

            statements.Add(statement
                           .ReplaceNode(concatenation.OriginalExpression, SimpleMemberInvocationExpression(stringBuilderName, IdentifierName("ToString")))
                           .WithTrailingTrivia(statement.GetTrailingTrivia())
                           .WithoutLeadingTrivia());

            if (EmbeddedStatementHelper.IsEmbeddedStatement(statement))
            {
                BlockSyntax block = Block(statements).WithFormatterAnnotation();

                return(await document.ReplaceNodeAsync(statement, block, cancellationToken).ConfigureAwait(false));
            }
            else
            {
                for (int i = 0; i < statements.Count; i++)
                {
                    statements[i] = statements[i].WithFormatterAnnotation();
                }

                return(await document.ReplaceNodeAsync(statement, statements, cancellationToken).ConfigureAwait(false));
            }
        }
Пример #21
0
        public static async Task <Document> RefactorAsync(
            Document document,
            ReturnStatementSyntax returnStatement,
            CancellationToken cancellationToken)
        {
            SemanticModel semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);

            SyntaxToken      returnKeyword = returnStatement.ReturnKeyword;
            ExpressionSyntax expression    = returnStatement.Expression;

            switch (GetReplacementKind(returnStatement, null, semanticModel, cancellationToken))
            {
            case SyntaxKind.YieldReturnStatement:
            {
                YieldStatementSyntax yieldReturnStatement = YieldStatement(
                    SyntaxKind.YieldReturnStatement,
                    Token(returnKeyword.LeadingTrivia, SyntaxKind.YieldKeyword, TriviaList(Space)),
                    returnKeyword.WithoutLeadingTrivia(),
                    expression,
                    returnStatement.SemicolonToken);

                return(await document.ReplaceNodeAsync(returnStatement, yieldReturnStatement, cancellationToken).ConfigureAwait(false));
            }

            case SyntaxKind.ForEachStatement:
            {
                string name = NameGenerator.Default.EnsureUniqueLocalName(
                    DefaultNames.ForEachVariable,
                    semanticModel,
                    returnStatement.SpanStart,
                    cancellationToken: cancellationToken);

                YieldStatementSyntax yieldReturnStatement = YieldStatement(
                    SyntaxKind.YieldReturnStatement,
                    Token(default(SyntaxTriviaList), SyntaxKind.YieldKeyword, TriviaList(Space)),
                    returnKeyword.WithoutLeadingTrivia(),
                    IdentifierName(name),
                    returnStatement.SemicolonToken.WithoutTrailingTrivia());

                StatementSyntax newNode = ForEachStatement(
                    VarType(),
                    name,
                    expression,
                    Block(yieldReturnStatement));

                if (EmbeddedStatementHelper.IsEmbeddedStatement(returnStatement))
                {
                    newNode = Block(newNode);
                }

                newNode = newNode.WithTriviaFrom(returnStatement);

                return(await document.ReplaceNodeAsync(returnStatement, newNode, cancellationToken).ConfigureAwait(false));
            }

            default:
            {
                Debug.Fail("");
                return(document);
            }
            }
        }
Пример #22
0
 private static bool CanRefactor(RefactoringContext context, StatementSyntax statement)
 {
     return(context.Span.IsEmptyAndContainedInSpanOrBetweenSpans(statement) &&
            EmbeddedStatementHelper.IsEmbeddedStatement(statement));
 }