public async Task ComputeRefactoringAsync(RefactoringContext context, SelectedStatementsInfo info)
        {
            StatementSyntax statement = info.FirstSelectedNode;

            if (statement?.IsKind(SyntaxKind.LocalDeclarationStatement) == true)
            {
                var localDeclaration = (LocalDeclarationStatementSyntax)statement;
                VariableDeclarationSyntax declaration = localDeclaration.Declaration;

                if (declaration != null)
                {
                    VariableDeclaratorSyntax variable = declaration.SingleVariableOrDefault();

                    if (variable != null &&
                        variable.Initializer?.Value?.IsKind(SyntaxKind.ObjectCreationExpression) == true &&
                        declaration.Type != null)
                    {
                        SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false);

                        ITypeSymbol typeSymbol = semanticModel
                                                 .GetTypeInfo(declaration.Type, context.CancellationToken)
                                                 .Type;

                        if (typeSymbol?.IsNamedType() == true &&
                            ((INamedTypeSymbol)typeSymbol).Implements(SpecialType.System_IDisposable))
                        {
                            context.RegisterRefactoring(
                                $"Using '{variable.Identifier.ValueText}'",
                                cancellationToken => RefactorAsync(context.Document, info, cancellationToken));
                        }
                    }
                }
            }
        }
        public static void ComputeRefactoring(RefactoringContext context, SelectedStatementsInfo info)
        {
            if (info.IsSingleSelected)
            {
                StatementSyntax[] statements = info.SelectedNodes().ToArray();

                StatementSyntax first = statements[0];

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

                    if (IfElseAnalysis.IsTopmostIf(ifStatement) &&
                        CanBeReplacedWithSwitch(ifStatement))
                    {
                        string title = (IfElseAnalysis.IsIsolatedIf(ifStatement))
                            ? "Replace if with switch"
                            : "Replace if-else with switch";

                        context.RegisterRefactoring(
                            title,
                            cancellationToken =>
                        {
                            return(RefactorAsync(
                                       context.Document,
                                       ifStatement,
                                       cancellationToken));
                        });
                    }
                }
            }
        }
Пример #3
0
        public static async Task ComputeRefactoringAsync(RefactoringContext context, SelectedStatementsInfo info)
        {
            if (info.IsAnySelected)
            {
                if (context.IsRefactoringEnabled(RefactoringIdentifiers.WrapInUsingStatement) &&
                    context.SupportsSemanticModel)
                {
                    var refactoring = new WrapInUsingStatementRefactoring();
                    await refactoring.ComputeRefactoringAsync(context, info).ConfigureAwait(false);
                }

                if (context.IsRefactoringEnabled(RefactoringIdentifiers.CollapseToInitializer))
                {
                    await CollapseToInitializerRefactoring.ComputeRefactoringsAsync(context, info).ConfigureAwait(false);
                }

                if (context.IsRefactoringEnabled(RefactoringIdentifiers.MergeIfStatements))
                {
                    MergeIfStatementsRefactoring.ComputeRefactorings(context, info);
                }

                if (context.IsRefactoringEnabled(RefactoringIdentifiers.ReplaceIfElseWithSwitch))
                {
                    ReplaceIfElseWithSwitchRefactoring.ComputeRefactoring(context, info);
                }

                if (context.IsRefactoringEnabled(RefactoringIdentifiers.MergeLocalDeclarations) &&
                    context.SupportsSemanticModel)
                {
                    await MergeLocalDeclarationsRefactoring.ComputeRefactoringsAsync(context, info).ConfigureAwait(false);
                }

                if (context.IsRefactoringEnabled(RefactoringIdentifiers.MergeAssignmentExpressionWithReturnStatement))
                {
                    MergeAssignmentExpressionWithReturnStatementRefactoring.ComputeRefactorings(context, info);
                }

                if (context.IsRefactoringEnabled(RefactoringIdentifiers.WrapInCondition))
                {
                    context.RegisterRefactoring(
                        "Wrap in condition",
                        cancellationToken =>
                    {
                        var refactoring = new WrapInIfStatementRefactoring();
                        return(refactoring.RefactorAsync(context.Document, info, cancellationToken));
                    });
                }

                if (context.IsRefactoringEnabled(RefactoringIdentifiers.WrapInTryCatch))
                {
                    context.RegisterRefactoring(
                        "Wrap in try-catch",
                        cancellationToken =>
                    {
                        var refactoring = new WrapInTryCatchRefactoring();
                        return(refactoring.RefactorAsync(context.Document, info, cancellationToken));
                    });
                }
            }
        }
Пример #4
0
 public static async Task ComputeRefactoringAsync(RefactoringContext context, BlockSyntax block)
 {
     if (SelectedStatementsRefactoring.IsAnyRefactoringEnabled(context))
     {
         SelectedStatementsInfo info = SelectedStatementsInfo.Create(block, context.Span);
         await SelectedStatementsRefactoring.ComputeRefactoringAsync(context, info).ConfigureAwait(false);
     }
 }
Пример #5
0
        public static void ComputeRefactorings(RefactoringContext context, SelectedStatementsInfo info)
        {
            List <IfStatementSyntax> ifStatements = GetIfStatements(info.SelectedNodes());

            if (ifStatements?.Count > 1)
            {
                context.RegisterRefactoring(
                    "Merge if statements",
                    cancellationToken =>
                {
                    return(RefactorAsync(
                               context.Document,
                               info.Container,
                               ifStatements.ToImmutableArray(),
                               cancellationToken));
                });
            }
        }
Пример #6
0
        public async Task <Document> RefactorAsync(
            Document document,
            SelectedStatementsInfo info,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            SyntaxNode root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);

            StatementContainer container = info.Container;

            StatementSyntax[] statements = info.SelectedNodes().ToArray();

            int index = info.FirstSelectedNodeIndex;

            SyntaxTriviaList leadingTrivia  = statements[0].GetLeadingTrivia();
            SyntaxTriviaList trailingTrivia = statements[statements.Length - 1].GetTrailingTrivia();

            statements[0] = statements[0].WithLeadingTrivia();
            statements[statements.Length - 1] = statements[statements.Length - 1].WithTrailingTrivia();

            SyntaxList <StatementSyntax> newStatements = container.Statements;

            int cnt = statements.Length;

            while (cnt > 0)
            {
                newStatements = newStatements.RemoveAt(index);
                cnt--;
            }

            TStatement statement = CreateStatement(statements.ToImmutableArray());

            statement = statement
                        .WithLeadingTrivia(leadingTrivia)
                        .WithTrailingTrivia(trailingTrivia)
                        .WithFormatterAnnotation();

            newStatements = newStatements.Insert(index, statement);

            root = root.ReplaceNode(container.Node, container.NodeWithStatements(newStatements));

            return(document.WithSyntaxRoot(root));
        }
Пример #7
0
        public static void ComputeRefactorings(RefactoringContext context, SelectedStatementsInfo info)
        {
            using (IEnumerator <StatementSyntax> en = info.SelectedNodes().GetEnumerator())
            {
                if (en.MoveNext() &&
                    en.Current.IsKind(SyntaxKind.ExpressionStatement))
                {
                    var statement = (ExpressionStatementSyntax)en.Current;

                    if (statement.Expression?.IsKind(SyntaxKind.SimpleAssignmentExpression) == true &&
                        en.MoveNext() &&
                        en.Current.IsKind(SyntaxKind.ReturnStatement))
                    {
                        var returnStatement = (ReturnStatementSyntax)en.Current;

                        if (returnStatement.Expression != null &&
                            !en.MoveNext())
                        {
                            var assignment = (AssignmentExpressionSyntax)statement.Expression;

                            if (assignment.Left?.IsMissing == false &&
                                assignment.Right?.IsMissing == false &&
                                assignment.Left.IsEquivalentTo(returnStatement.Expression, topLevel: false))
                            {
                                context.RegisterRefactoring(
                                    "Merge statements",
                                    cancellationToken =>
                                {
                                    return(RefactorAsync(
                                               context.Document,
                                               statement,
                                               returnStatement,
                                               cancellationToken));
                                });
                            }
                        }
                    }
                }
            }
        }
        public static async Task <Document> RefactorAsync(
            Document document,
            ObjectCreationExpressionSyntax objectCreation,
            SelectedStatementsInfo info,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            SyntaxNode root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);

            StatementContainer container = info.Container;

            ExpressionStatementSyntax[] expressionStatements = info
                                                               .SelectedNodes()
                                                               .Skip(1)
                                                               .Cast <ExpressionStatementSyntax>()
                                                               .ToArray();

            StatementSyntax firstNode = info.FirstSelectedNode;

            SyntaxList <StatementSyntax> newStatements = container.Statements.Replace(
                firstNode,
                firstNode.ReplaceNode(
                    objectCreation,
                    objectCreation.WithInitializer(CreateInitializer(objectCreation, expressionStatements))));

            int count = expressionStatements.Length;
            int index = info.FirstSelectedNodeIndex + 1;

            while (count > 0)
            {
                newStatements = newStatements.RemoveAt(index);
                count--;
            }

            SyntaxNode newRoot = root.ReplaceNode(
                container.Node,
                container.NodeWithStatements(newStatements));

            return(document.WithSyntaxRoot(newRoot));
        }
        public static async Task ComputeRefactoringsAsync(RefactoringContext context, SelectedStatementsInfo info)
        {
            StatementSyntax firstStatement = info.FirstSelectedNode;
            SemanticModel   semanticModel  = null;
            ISymbol         symbol         = null;
            ObjectCreationExpressionSyntax objectCreation = null;

            if (info.AreManySelected)
            {
                SyntaxKind kind = firstStatement.Kind();

                if (kind == SyntaxKind.LocalDeclarationStatement)
                {
                    var localDeclaration = (LocalDeclarationStatementSyntax)firstStatement;

                    VariableDeclarationSyntax declaration = localDeclaration.Declaration;

                    if (declaration != null)
                    {
                        SeparatedSyntaxList <VariableDeclaratorSyntax> variables = declaration.Variables;

                        if (variables.Count == 1)
                        {
                            VariableDeclaratorSyntax variable = variables[0];

                            objectCreation = variable.Initializer?.Value as ObjectCreationExpressionSyntax;

                            if (objectCreation != null)
                            {
                                semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false);

                                symbol = semanticModel.GetDeclaredSymbol(variable, context.CancellationToken);
                            }
                        }
                    }
                }
                else if (kind == SyntaxKind.ExpressionStatement)
                {
                    var expressionStatement = (ExpressionStatementSyntax)firstStatement;

                    var assignment = expressionStatement.Expression as AssignmentExpressionSyntax;

                    if (assignment != null)
                    {
                        objectCreation = assignment.Right as ObjectCreationExpressionSyntax;

                        if (objectCreation != null)
                        {
                            semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false);

                            symbol = semanticModel.GetSymbolInfo(assignment.Left, context.CancellationToken).Symbol;
                        }
                    }
                }

                if (objectCreation != null &&
                    symbol?.IsErrorType() == false &&
                    info
                    .SelectedNodes()
                    .Skip(1)
                    .All(f => IsValidAssignmentStatement(f, symbol, semanticModel, context.CancellationToken)))
                {
                    context.RegisterRefactoring(
                        "Collapse to initializer",
                        cancellationToken =>
                    {
                        return(RefactorAsync(
                                   context.Document,
                                   objectCreation,
                                   info,
                                   cancellationToken));
                    });
                }
            }
        }
Пример #10
0
        public static async Task ComputeRefactoringsAsync(RefactoringContext context, SelectedStatementsInfo info)
        {
            if (info.SelectedCount > 1)
            {
                SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false);

                if (AreLocalDeclarations(info.SelectedNodes(), semanticModel, context.CancellationToken))
                {
                    context.RegisterRefactoring(
                        "Merge local declarations",
                        cancellationToken =>
                    {
                        return(RefactorAsync(
                                   context.Document,
                                   info.Container,
                                   info.SelectedNodes().Cast <LocalDeclarationStatementSyntax>().ToArray(),
                                   cancellationToken));
                    });
                }
            }
        }
Пример #11
0
        public static async Task ComputeRefactoringsAsync(RefactoringContext context, SwitchSectionSyntax switchSection)
        {
            if (SelectedStatementsRefactoring.IsAnyRefactoringEnabled(context))
            {
                SelectedStatementsInfo info = SelectedStatementsInfo.Create(switchSection, context.Span);
                await SelectedStatementsRefactoring.ComputeRefactoringAsync(context, info).ConfigureAwait(false);
            }

            if (context.Span.IsEmpty &&
                context.IsAnyRefactoringEnabled(
                    RefactoringIdentifiers.AddBracesToSwitchSection,
                    RefactoringIdentifiers.AddBracesToSwitchSections,
                    RefactoringIdentifiers.RemoveBracesFromSwitchSection,
                    RefactoringIdentifiers.RemoveBracesFromSwitchSections))
            {
                var switchStatement = (SwitchStatementSyntax)switchSection.Parent;

                SyntaxList <SwitchSectionSyntax> sections = switchStatement.Sections;

                switch (SwitchStatementAnalysis.AnalyzeSection(switchSection))
                {
                case SwitchSectionAnalysisResult.AddBraces:
                {
                    if (context.IsRefactoringEnabled(RefactoringIdentifiers.AddBracesToSwitchSection))
                    {
                        context.RegisterRefactoring(
                            AddBracesToSwitchSectionRefactoring.Title,
                            cancellationToken => AddBracesToSwitchSectionRefactoring.RefactorAsync(context.Document, switchSection, cancellationToken));
                    }

                    if (context.IsRefactoringEnabled(RefactoringIdentifiers.AddBracesToSwitchSections) &&
                        sections.Any(f => f != switchSection && SwitchStatementAnalysis.CanAddBraces(f)))
                    {
                        context.RegisterRefactoring(
                            AddBracesToSwitchSectionsRefactoring.Title,
                            cancellationToken => AddBracesToSwitchSectionsRefactoring.RefactorAsync(context.Document, switchStatement, null, cancellationToken));
                    }

                    break;
                }

                case SwitchSectionAnalysisResult.RemoveBraces:
                {
                    if (context.IsRefactoringEnabled(RefactoringIdentifiers.RemoveBracesFromSwitchSection))
                    {
                        context.RegisterRefactoring(
                            RemoveBracesFromSwitchSectionRefactoring.Title,
                            cancellationToken => RemoveBracesFromSwitchSectionRefactoring.RefactorAsync(context.Document, switchSection, cancellationToken));
                    }

                    if (context.IsRefactoringEnabled(RefactoringIdentifiers.RemoveBracesFromSwitchSections) &&
                        sections.Any(f => f != switchSection && SwitchStatementAnalysis.CanRemoveBraces(f)))
                    {
                        context.RegisterRefactoring(
                            RemoveBracesFromSwitchSectionsRefactoring.Title,
                            cancellationToken => RemoveBracesFromSwitchSectionsRefactoring.RefactorAsync(context.Document, switchStatement, null, cancellationToken));
                    }

                    break;
                }
                }
            }
        }