Exemple #1
0
        public static async Task ComputeRefactoringsAsync(RefactoringContext context, MethodDeclarationSyntax methodDeclaration)
        {
            if (context.IsRefactoringEnabled(RefactoringIdentifiers.ChangeMethodReturnTypeToVoid) &&
                context.Span.IsEmptyAndContainedInSpan(methodDeclaration))
            {
                await ChangeMethodReturnTypeToVoidRefactoring.ComputeRefactoringAsync(context, methodDeclaration).ConfigureAwait(false);
            }

            if (context.IsRefactoringEnabled(RefactoringIdentifiers.AddTypeParameter))
            {
                AddTypeParameterRefactoring.ComputeRefactoring(context, methodDeclaration);
            }

            if (context.IsRefactoringEnabled(RefactoringIdentifiers.ReplaceMethodWithProperty) &&
                methodDeclaration.HeaderSpan().Contains(context.Span) &&
                ReplaceMethodWithPropertyRefactoring.CanRefactor(methodDeclaration))
            {
                context.RegisterRefactoring(
                    $"Replace '{methodDeclaration.Identifier.ValueText}' with property",
                    cancellationToken => ReplaceMethodWithPropertyRefactoring.RefactorAsync(context.Document, methodDeclaration, cancellationToken),
                    RefactoringIdentifiers.ReplaceMethodWithProperty);
            }

            if (context.IsRefactoringEnabled(RefactoringIdentifiers.UseExpressionBodiedMember) &&
                context.SupportsCSharp6 &&
                UseExpressionBodiedMemberRefactoring.CanRefactor(methodDeclaration, context.Span))
            {
                context.RegisterRefactoring(
                    UseExpressionBodiedMemberRefactoring.Title,
                    cancellationToken => UseExpressionBodiedMemberRefactoring.RefactorAsync(context.Document, methodDeclaration, cancellationToken),
                    RefactoringIdentifiers.UseExpressionBodiedMember);
            }

            if (context.IsRefactoringEnabled(RefactoringIdentifiers.MakeMemberAbstract) &&
                context.Span.IsEmptyAndContainedInSpan(methodDeclaration.Identifier))
            {
                MakeMethodAbstractRefactoring.ComputeRefactoring(context, methodDeclaration);
            }

            if (context.IsRefactoringEnabled(RefactoringIdentifiers.MakeMemberVirtual) &&
                methodDeclaration.HeaderSpan().Contains(context.Span))
            {
                MakeMethodVirtualRefactoring.ComputeRefactoring(context, methodDeclaration);
            }

            if (context.IsRefactoringEnabled(RefactoringIdentifiers.CopyDocumentationCommentFromBaseMember) &&
                methodDeclaration.HeaderSpan().Contains(context.Span) &&
                !methodDeclaration.HasDocumentationComment())
            {
                SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false);

                CopyDocumentationCommentFromBaseMemberRefactoring.ComputeRefactoring(context, methodDeclaration, semanticModel);
            }

            if (context.IsRefactoringEnabled(RefactoringIdentifiers.RenameMethodAccordingToTypeName))
            {
                await RenameMethodAccoringToTypeNameAsync(context, methodDeclaration).ConfigureAwait(false);
            }

            if (context.IsRefactoringEnabled(RefactoringIdentifiers.AddParameterToInterfaceMember) &&
                context.Span.IsEmptyAndContainedInSpanOrBetweenSpans(methodDeclaration.Identifier))
            {
                SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false);

                foreach (CodeAction codeAction in AddParameterToInterfaceMemberRefactoring.ComputeRefactoringForImplicitImplementation(
                             new CommonFixContext(context.Document, RefactoringIdentifiers.AddParameterToInterfaceMember, semanticModel, context.CancellationToken),
                             methodDeclaration))
                {
                    context.RegisterRefactoring(codeAction);
                }
            }

            if (context.IsRefactoringEnabled(RefactoringIdentifiers.AddMemberToInterface) &&
                context.Span.IsEmptyAndContainedInSpanOrBetweenSpans(methodDeclaration.Identifier))
            {
                SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false);

                AddMemberToInterfaceRefactoring.ComputeRefactoring(context, methodDeclaration, semanticModel);
            }
        }
Exemple #2
0
        public static async Task ComputeRefactoringAsync(RefactoringContext context, MemberDeclarationListSelection selectedMembers)
        {
            if (context.IsRefactoringEnabled(RefactoringIdentifiers.ChangeAccessibility) &&
                !selectedMembers.Parent.IsKind(SyntaxKind.InterfaceDeclaration))
            {
                SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false);

                AccessibilityFilter validAccessibilities = ChangeAccessibilityAnalysis.GetValidAccessibilityFilter(selectedMembers, semanticModel, context.CancellationToken);

                if (validAccessibilities != AccessibilityFilter.None)
                {
                    bool canHaveMultipleDeclarations = CanHaveMultipleDeclarations();

                    TryRegisterRefactoring(validAccessibilities, Accessibility.Public, canHaveMultipleDeclarations);
                    TryRegisterRefactoring(validAccessibilities, Accessibility.Internal, canHaveMultipleDeclarations);
                    TryRegisterRefactoring(validAccessibilities, Accessibility.Protected, canHaveMultipleDeclarations);
                    TryRegisterRefactoring(validAccessibilities, Accessibility.Private, canHaveMultipleDeclarations);
                }
            }

            if (context.IsAnyRefactoringEnabled(
                    RefactoringIdentifiers.UseExpressionBodiedMember,
                    RefactoringIdentifiers.ExpandExpressionBody))
            {
                InvertBodyAndExpressionBodyRefactoring.ComputeRefactoring(context, selectedMembers);
            }

            if (context.IsRefactoringEnabled(RefactoringIdentifiers.InitializeFieldFromConstructor) &&
                !selectedMembers.Parent.IsKind(SyntaxKind.InterfaceDeclaration))
            {
                InitializeFieldFromConstructorRefactoring.ComputeRefactoring(context, selectedMembers);
            }

            if (context.IsRefactoringEnabled(RefactoringIdentifiers.AddEmptyLineBetweenDeclarations))
            {
                AddEmptyLineBetweenDeclarationsRefactoring.ComputeRefactoring(context, selectedMembers);
            }

            void TryRegisterRefactoring(AccessibilityFilter accessibilities, Accessibility accessibility, bool canHaveMultipleDeclarations)
            {
                if ((accessibilities & accessibility.GetAccessibilityFilter()) != 0)
                {
                    if (canHaveMultipleDeclarations)
                    {
                        context.RegisterRefactoring(
                            ChangeAccessibilityRefactoring.GetTitle(accessibility),
                            async cancellationToken =>
                        {
                            SemanticModel semanticModel = await context.Document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
                            return(await ChangeAccessibilityRefactoring.RefactorAsync(context.Document.Solution(), selectedMembers, accessibility, semanticModel, cancellationToken).ConfigureAwait(false));
                        },
                            _accessiblityIdentifierMap[accessibility]);
                    }
                    else
                    {
                        context.RegisterRefactoring(
                            ChangeAccessibilityRefactoring.GetTitle(accessibility),
                            cancellationToken => ChangeAccessibilityRefactoring.RefactorAsync(context.Document, selectedMembers, accessibility, cancellationToken),
                            EquivalenceKey.Join(RefactoringIdentifiers.ChangeAccessibility, accessibility.ToString()));
                    }
                }
            }

            bool CanHaveMultipleDeclarations()
            {
                foreach (MemberDeclarationSyntax member in selectedMembers)
                {
                    switch (member.Kind())
                    {
                    case SyntaxKind.ClassDeclaration:
                    {
                        if (((ClassDeclarationSyntax)member).Modifiers.Contains(SyntaxKind.PartialKeyword))
                        {
                            return(true);
                        }

                        break;
                    }

                    case SyntaxKind.InterfaceDeclaration:
                    {
                        if (((InterfaceDeclarationSyntax)member).Modifiers.Contains(SyntaxKind.PartialKeyword))
                        {
                            return(true);
                        }

                        break;
                    }

                    case SyntaxKind.StructDeclaration:
                    {
                        if (((StructDeclarationSyntax)member).Modifiers.Contains(SyntaxKind.PartialKeyword))
                        {
                            return(true);
                        }

                        break;
                    }

                    case SyntaxKind.MethodDeclaration:
                    {
                        if (((MethodDeclarationSyntax)member).Modifiers.ContainsAny(SyntaxKind.PartialKeyword, SyntaxKind.AbstractKeyword, SyntaxKind.VirtualKeyword, SyntaxKind.OverrideKeyword))
                        {
                            return(true);
                        }

                        break;
                    }

                    case SyntaxKind.PropertyDeclaration:
                    {
                        if (((PropertyDeclarationSyntax)member).Modifiers.ContainsAny(SyntaxKind.AbstractKeyword, SyntaxKind.VirtualKeyword, SyntaxKind.OverrideKeyword))
                        {
                            return(true);
                        }

                        break;
                    }

                    case SyntaxKind.IndexerDeclaration:
                    {
                        if (((IndexerDeclarationSyntax)member).Modifiers.ContainsAny(SyntaxKind.AbstractKeyword, SyntaxKind.VirtualKeyword, SyntaxKind.OverrideKeyword))
                        {
                            return(true);
                        }

                        break;
                    }

                    case SyntaxKind.EventDeclaration:
                    {
                        if (((EventDeclarationSyntax)member).Modifiers.ContainsAny(SyntaxKind.AbstractKeyword, SyntaxKind.VirtualKeyword, SyntaxKind.OverrideKeyword))
                        {
                            return(true);
                        }

                        break;
                    }

                    case SyntaxKind.EventFieldDeclaration:
                    {
                        if (((EventFieldDeclarationSyntax)member).Modifiers.ContainsAny(SyntaxKind.AbstractKeyword, SyntaxKind.VirtualKeyword, SyntaxKind.OverrideKeyword))
                        {
                            return(true);
                        }

                        break;
                    }
                    }
                }

                return(false);
            }
        }
        public static async Task ComputeRefactoringAsync(RefactoringContext context, StatementContainerSelection selectedStatements)
        {
            if (selectedStatements.Any())
            {
                if (context.IsRefactoringEnabled(RefactoringIdentifiers.WrapInUsingStatement))
                {
                    var refactoring = new WrapInUsingStatementRefactoring();
                    await refactoring.ComputeRefactoringAsync(context, selectedStatements).ConfigureAwait(false);
                }

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

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

                if (context.IsAnyRefactoringEnabled(
                        RefactoringIdentifiers.UseCoalesceExpressionInsteadOfIf,
                        RefactoringIdentifiers.UseConditionalExpressionInsteadOfIf,
                        RefactoringIdentifiers.SimplifyIf))
                {
                    SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false);

                    var options = new IfAnalysisOptions(
                        useCoalesceExpression: context.IsRefactoringEnabled(RefactoringIdentifiers.UseCoalesceExpressionInsteadOfIf),
                        useConditionalExpression: context.IsRefactoringEnabled(RefactoringIdentifiers.UseConditionalExpressionInsteadOfIf),
                        useBooleanExpression: context.IsRefactoringEnabled(RefactoringIdentifiers.SimplifyIf));

                    foreach (IfRefactoring refactoring in IfRefactoring.Analyze(selectedStatements, options, semanticModel, context.CancellationToken))
                    {
                        context.RegisterRefactoring(
                            refactoring.Title,
                            cancellationToken => refactoring.RefactorAsync(context.Document, cancellationToken));
                    }
                }

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

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

                if (context.IsRefactoringEnabled(RefactoringIdentifiers.CheckExpressionForNull))
                {
                    await CheckExpressionForNullRefactoring.ComputeRefactoringAsync(context, selectedStatements).ConfigureAwait(false);
                }

                if (context.IsRefactoringEnabled(RefactoringIdentifiers.ReplaceWhileWithFor))
                {
                    await ReplaceWhileWithForRefactoring.ComputeRefactoringAsync(context, selectedStatements).ConfigureAwait(false);
                }

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

                if (context.IsRefactoringEnabled(RefactoringIdentifiers.WrapInTryCatch))
                {
                    context.RegisterRefactoring(
                        "Wrap in try-catch",
                        cancellationToken =>
                    {
                        var refactoring = new WrapInTryCatchRefactoring();
                        return(refactoring.RefactorAsync(context.Document, selectedStatements, cancellationToken));
                    });
                }
            }
        }
        public static async Task ComputeRefactoringsAsync(RefactoringContext context, PropertyDeclarationSyntax propertyDeclaration)
        {
            if (context.IsRefactoringEnabled(RefactoringIdentifiers.MarkMemberAsStatic) &&
                propertyDeclaration.Span.Contains(context.Span) &&
                MarkMemberAsStaticRefactoring.CanRefactor(propertyDeclaration))
            {
                context.RegisterRefactoring(
                    "Mark property as static",
                    cancellationToken => MarkMemberAsStaticRefactoring.RefactorAsync(context.Document, propertyDeclaration, cancellationToken));

                MarkAllMembersAsStaticRefactoring.RegisterRefactoring(context, (ClassDeclarationSyntax)propertyDeclaration.Parent);
            }

            if (context.IsRefactoringEnabled(RefactoringIdentifiers.ReplacePropertyWithMethod) &&
                propertyDeclaration.HeaderSpan().Contains(context.Span) &&
                ReplacePropertyWithMethodRefactoring.CanRefactor(context, propertyDeclaration))
            {
                string propertyName = propertyDeclaration.Identifier.ValueText;

                string title = $"Replace '{propertyName}' with method";

                if (propertyDeclaration.AccessorList.Accessors.Count > 1)
                {
                    title += "s";
                }

                context.RegisterRefactoring(
                    title,
                    cancellationToken => ReplacePropertyWithMethodRefactoring.RefactorAsync(context.Document, propertyDeclaration, cancellationToken));
            }

            if (context.IsRefactoringEnabled(RefactoringIdentifiers.UseExpressionBodiedMember) &&
                propertyDeclaration.AccessorList?.Span.Contains(context.Span) == true &&
                context.SupportsCSharp6 &&
                UseExpressionBodiedMemberRefactoring.CanRefactor(propertyDeclaration))
            {
                context.RegisterRefactoring(
                    "Use expression-bodied member",
                    cancellationToken => UseExpressionBodiedMemberRefactoring.RefactorAsync(context.Document, propertyDeclaration, cancellationToken));
            }

            if (context.IsRefactoringEnabled(RefactoringIdentifiers.RemovePropertyInitializer) &&
                RemovePropertyInitializerRefactoring.CanRefactor(context, propertyDeclaration))
            {
                context.RegisterRefactoring(
                    "Remove property initializer",
                    cancellationToken => RemovePropertyInitializerRefactoring.RefactorAsync(context.Document, propertyDeclaration, cancellationToken));
            }

            if (context.SupportsSemanticModel)
            {
                if (context.IsAnyRefactoringEnabled(
                        RefactoringIdentifiers.ExpandProperty,
                        RefactoringIdentifiers.ExpandPropertyAndAddBackingField) &&
                    propertyDeclaration.Span.Contains(context.Span) &&
                    ExpandPropertyRefactoring.CanRefactor(propertyDeclaration))
                {
                    if (context.IsRefactoringEnabled(RefactoringIdentifiers.ExpandProperty))
                    {
                        context.RegisterRefactoring(
                            "Expand property",
                            cancellationToken => ExpandPropertyRefactoring.RefactorAsync(context.Document, propertyDeclaration, cancellationToken));
                    }

                    if (context.IsRefactoringEnabled(RefactoringIdentifiers.ExpandPropertyAndAddBackingField))
                    {
                        context.RegisterRefactoring(
                            "Expand property and add backing field",
                            cancellationToken => ExpandPropertyAndAddBackingFieldRefactoring.RefactorAsync(context.Document, propertyDeclaration, context.Settings.PrefixFieldIdentifierWithUnderscore, cancellationToken));
                    }
                }

                if (context.IsRefactoringEnabled(RefactoringIdentifiers.NotifyPropertyChanged) &&
                    await NotifyPropertyChangedRefactoring.CanRefactorAsync(context, propertyDeclaration).ConfigureAwait(false))
                {
                    context.RegisterRefactoring(
                        "Notify property changed",
                        cancellationToken =>
                    {
                        return(NotifyPropertyChangedRefactoring.RefactorAsync(
                                   context.Document,
                                   propertyDeclaration,
                                   context.SupportsCSharp6,
                                   cancellationToken));
                    });
                }
            }

            if (context.IsRefactoringEnabled(RefactoringIdentifiers.MakeMemberAbstract) &&
                propertyDeclaration.HeaderSpan().Contains(context.Span) &&
                MakeMemberAbstractRefactoring.CanRefactor(propertyDeclaration))
            {
                context.RegisterRefactoring(
                    "Make property abstract",
                    cancellationToken => MakeMemberAbstractRefactoring.RefactorAsync(context.Document, propertyDeclaration, cancellationToken));
            }

            if (context.IsRefactoringEnabled(RefactoringIdentifiers.CopyDocumentationCommentFromBaseMember) &&
                propertyDeclaration.HeaderSpan().Contains(context.Span))
            {
                await CopyDocumentationCommentFromBaseMemberRefactoring.ComputeRefactoringAsync(context, propertyDeclaration).ConfigureAwait(false);
            }

            if (context.IsRefactoringEnabled(RefactoringIdentifiers.RenamePropertyAccordingToTypeName) &&
                context.SupportsSemanticModel &&
                propertyDeclaration.Type != null &&
                propertyDeclaration.Identifier.Span.Contains(context.Span))
            {
                SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false);

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

                if (typeSymbol?.IsErrorType() == false)
                {
                    string newName = SyntaxUtility.CreateIdentifier(typeSymbol);

                    if (!string.IsNullOrEmpty(newName))
                    {
                        newName = TextUtility.FirstCharToUpper(newName);

                        if (!string.Equals(newName, propertyDeclaration.Identifier.ValueText, StringComparison.Ordinal))
                        {
                            ISymbol symbol = semanticModel.GetDeclaredSymbol(propertyDeclaration, context.CancellationToken);

                            context.RegisterRefactoring(
                                $"Rename property to '{newName}'",
                                cancellationToken => SymbolRenamer.RenameAsync(context.Document, symbol, newName, cancellationToken));
                        }
                    }
                }
            }
        }
        public static async Task ComputeRefactoringsAsync(RefactoringContext context, LocalFunctionStatementSyntax localFunctionStatement)
        {
            if (localFunctionStatement.IsParentKind(SyntaxKind.Block))
            {
                BlockSyntax body = localFunctionStatement.Body;

                if (body != null)
                {
                    if (body.OpenBraceToken.Span.Contains(context.Span) ||
                        body.CloseBraceToken.Span.Contains(context.Span))
                    {
                        if (context.IsRefactoringEnabled(RefactoringDescriptors.RemoveMemberDeclaration))
                        {
                            context.RegisterRefactoring(CodeActionFactory.RemoveStatement(context.Document, localFunctionStatement, equivalenceKey: EquivalenceKey.Create(RefactoringDescriptors.RemoveMemberDeclaration)));
                        }

                        if (context.IsRefactoringEnabled(RefactoringDescriptors.CopyMemberDeclaration))
                        {
                            context.RegisterRefactoring(
                                "Copy local function",
                                ct => CopyMemberDeclarationRefactoring.RefactorAsync(
                                    context.Document,
                                    localFunctionStatement,
                                    copyAfter: body.CloseBraceToken.Span.Contains(context.Span),
                                    ct),
                                RefactoringDescriptors.CopyMemberDeclaration);
                        }

                        if (context.IsRefactoringEnabled(RefactoringDescriptors.CommentOutMemberDeclaration))
                        {
                            CommentOutRefactoring.RegisterRefactoring(context, localFunctionStatement);
                        }
                    }
                }
            }

            if (context.IsRefactoringEnabled(RefactoringDescriptors.ChangeMethodReturnTypeToVoid) &&
                context.Span.IsEmptyAndContainedInSpan(localFunctionStatement))
            {
                await ChangeMethodReturnTypeToVoidRefactoring.ComputeRefactoringAsync(context, localFunctionStatement).ConfigureAwait(false);
            }

            if (context.IsRefactoringEnabled(RefactoringDescriptors.AddGenericParameterToDeclaration))
            {
                AddGenericParameterToDeclarationRefactoring.ComputeRefactoring(context, localFunctionStatement);
            }

            if (context.IsRefactoringEnabled(RefactoringDescriptors.ConvertBlockBodyToExpressionBody) &&
                ConvertBlockBodyToExpressionBodyRefactoring.CanRefactor(localFunctionStatement, context.Span))
            {
                context.RegisterRefactoring(
                    ConvertBlockBodyToExpressionBodyRefactoring.Title,
                    ct => ConvertBlockBodyToExpressionBodyRefactoring.RefactorAsync(context.Document, localFunctionStatement, ct),
                    RefactoringDescriptors.ConvertBlockBodyToExpressionBody);
            }

            if (context.IsRefactoringEnabled(RefactoringDescriptors.MoveUnsafeContextToContainingDeclaration))
            {
                MoveUnsafeContextToContainingDeclarationRefactoring.ComputeRefactoring(context, localFunctionStatement);
            }
        }
        public static void ComputeRefactorings(RefactoringContext context, SwitchStatementSyntax switchStatement)
        {
            bool fRemoveStatements = context.IsRefactoringEnabled(RefactoringDescriptors.MergeSwitchSections);
            bool fAddBraces        = context.IsRefactoringEnabled(RefactoringDescriptors.AddBracesToSwitchSections);
            bool fRemoveBraces     = context.IsRefactoringEnabled(RefactoringDescriptors.RemoveBracesFromSwitchSections);

            if (!fRemoveStatements && !fAddBraces && !fRemoveBraces)
            {
                return;
            }

            if (!SyntaxListSelection <SwitchSectionSyntax> .TryCreate(switchStatement.Sections, context.Span, out SyntaxListSelection <SwitchSectionSyntax> selectedSections))
            {
                return;
            }

            if (fAddBraces || fRemoveBraces)
            {
                var addBraces    = new List <SwitchSectionSyntax>();
                var removeBraces = new List <SwitchSectionSyntax>();

                foreach (SwitchSectionSyntax section in selectedSections)
                {
                    if (addBraces.Count > 0 &&
                        removeBraces.Count > 0)
                    {
                        break;
                    }

                    BracesAnalysis analysis = BracesAnalysis.AnalyzeBraces(section);

                    if (analysis.AddBraces)
                    {
                        addBraces.Add(section);
                    }
                    else if (analysis.RemoveBraces)
                    {
                        removeBraces.Add(section);
                    }
                }

                if (fAddBraces && addBraces.Count > 0)
                {
                    string title = AddBracesToSwitchSectionRefactoring.Title;

                    if (addBraces.Count > 1)
                    {
                        title += "s";
                    }

                    context.RegisterRefactoring(
                        title,
                        ct =>
                    {
                        return(AddBracesToSwitchSectionsRefactoring.RefactorAsync(
                                   context.Document,
                                   switchStatement,
                                   addBraces.ToArray(),
                                   ct));
                    },
                        RefactoringDescriptors.AddBracesToSwitchSections);
                }

                if (fRemoveBraces &&
                    removeBraces.Count > 0)
                {
                    string title = RemoveBracesFromSwitchSectionRefactoring.Title;

                    if (removeBraces.Count > 1)
                    {
                        title += "s";
                    }

                    context.RegisterRefactoring(
                        title,
                        ct =>
                    {
                        return(RemoveBracesFromSwitchSectionsRefactoring.RefactorAsync(
                                   context.Document,
                                   switchStatement,
                                   removeBraces.ToArray(),
                                   ct));
                    },
                        RefactoringDescriptors.RemoveBracesFromSwitchSections);
                }
            }

            if (fRemoveStatements)
            {
                var title = "Remove statements from section";

                if (selectedSections.Count > 1)
                {
                    title += "s";
                }

                context.RegisterRefactoring(
                    title,
                    ct =>
                {
                    return(MergeSwitchSectionsRefactoring.RefactorAsync(
                               context.Document,
                               switchStatement,
                               selectedSections.ToImmutableArray(),
                               ct));
                },
                    RefactoringDescriptors.MergeSwitchSections);
            }
        }
Exemple #7
0
        public static void ComputeRefactorings(RefactoringContext context, InterpolatedStringExpressionSyntax interpolatedString)
        {
            if (context.IsRefactoringEnabled(RefactoringIdentifiers.InsertStringInterpolation) &&
                context.Span.IsEmpty &&
                InsertInterpolationRefactoring.CanRefactor(context, interpolatedString))
            {
                context.RegisterRefactoring("Insert interpolation",
                                            cancellationToken =>
                {
                    return(InsertInterpolationRefactoring.RefactorAsync(
                               context.Document,
                               interpolatedString,
                               context.Span,
                               addNameOf: false,
                               cancellationToken: cancellationToken));
                },
                                            RefactoringIdentifiers.InsertStringInterpolation);
            }

            if (context.IsRefactoringEnabled(RefactoringIdentifiers.ConvertInterpolatedStringToStringLiteral) &&
                ReplaceInterpolatedStringWithStringLiteralAnalysis.IsFixable(interpolatedString))
            {
                context.RegisterRefactoring("Remove '$'",
                                            cancellationToken =>
                {
                    return(ConvertInterpolatedStringToStringLiteralRefactoring.RefactorAsync(
                               context.Document,
                               interpolatedString,
                               cancellationToken));
                },
                                            RefactoringIdentifiers.ConvertInterpolatedStringToStringLiteral);
            }

            if (context.IsRefactoringEnabled(RefactoringIdentifiers.ReplaceInterpolatedStringWithInterpolationExpression) &&
                interpolatedString.Span.Contains(context.Span) &&
                ReplaceInterpolatedStringWithInterpolationExpressionRefactoring.CanRefactor(interpolatedString))
            {
                ExpressionSyntax expression = ((InterpolationSyntax)(interpolatedString.Contents[0])).Expression;

                context.RegisterRefactoring(
                    $"Replace interpolated string with '{expression}'",
                    cancellationToken =>
                {
                    return(ReplaceInterpolatedStringWithInterpolationExpressionRefactoring.RefactorAsync(
                               context.Document,
                               interpolatedString,
                               cancellationToken));
                },
                    RefactoringIdentifiers.ReplaceInterpolatedStringWithInterpolationExpression);
            }

            if (context.IsRefactoringEnabled(RefactoringIdentifiers.ConvertInterpolatedStringToConcatenation) &&
                context.Span.IsEmptyAndContainedInSpanOrBetweenSpans(interpolatedString))
            {
                ConvertInterpolatedStringToConcatenationRefactoring.ComputeRefactoring(context, interpolatedString);
            }

            if (context.IsRefactoringEnabled(RefactoringIdentifiers.ConvertInterpolatedStringToStringFormat) &&
                context.Span.IsEmptyAndContainedInSpanOrBetweenSpans(interpolatedString))
            {
                ConvertInterpolatedStringToStringFormatRefactoring.ComputeRefactoring(context, interpolatedString);
            }
        }
Exemple #8
0
        public static async Task ComputeRefactoringsAsync(RefactoringContext context, BinaryExpressionSyntax binaryExpression)
        {
            if (context.IsRefactoringEnabled(RefactoringIdentifiers.NegateOperator))
            {
                SyntaxToken operatorToken = binaryExpression.OperatorToken;

                if (operatorToken.Span.Contains(context.Span) &&
                    NegateOperatorRefactoring.CanBeNegated(operatorToken))
                {
                    context.RegisterRefactoring(
                        "Negate operator",
                        cancellationToken => NegateOperatorRefactoring.RefactorAsync(context.Document, operatorToken, cancellationToken));
                }
            }

            if (context.IsRefactoringEnabled(RefactoringIdentifiers.AddBooleanComparison) &&
                binaryExpression.IsKind(SyntaxKind.LogicalAndExpression, SyntaxKind.LogicalOrExpression) &&
                binaryExpression.Left?.IsMissing == false &&
                binaryExpression.Right?.IsMissing == false &&
                context.SupportsSemanticModel)
            {
                if (binaryExpression.Left.Span.Contains(context.Span))
                {
                    await AddBooleanComparisonRefactoring.ComputeRefactoringAsync(context, binaryExpression.Left).ConfigureAwait(false);
                }
                else if (binaryExpression.Right.Span.Contains(context.Span))
                {
                    await AddBooleanComparisonRefactoring.ComputeRefactoringAsync(context, binaryExpression.Right).ConfigureAwait(false);
                }
            }

            if (context.IsRefactoringEnabled(RefactoringIdentifiers.FormatBinaryExpression))
            {
                FormatBinaryExpressionRefactoring.ComputeRefactorings(context, binaryExpression);
            }

            if (context.IsRefactoringEnabled(RefactoringIdentifiers.NegateBinaryExpression))
            {
                NegateBinaryExpressionRefactoring.ComputeRefactoring(context, binaryExpression);
            }

            if (context.IsRefactoringEnabled(RefactoringIdentifiers.ExpandCoalesceExpression) &&
                binaryExpression.OperatorToken.Span.Contains(context.Span) &&
                ExpandCoalesceExpressionRefactoring.CanRefactor(binaryExpression))
            {
                context.RegisterRefactoring(
                    "Expand ??",
                    cancellationToken =>
                {
                    return(ExpandCoalesceExpressionRefactoring.RefactorAsync(
                               context.Document,
                               binaryExpression,
                               cancellationToken));
                });
            }

            if (context.IsAnyRefactoringEnabled(
                    RefactoringIdentifiers.MergeStringLiterals,
                    RefactoringIdentifiers.MergeStringLiteralsIntoMultilineStringLiteral) &&
                MergeStringLiteralsRefactoring.CanRefactor(context, binaryExpression))
            {
                if (context.IsRefactoringEnabled(RefactoringIdentifiers.MergeStringLiterals))
                {
                    context.RegisterRefactoring(
                        "Merge string literals",
                        cancellationToken => MergeStringLiteralsRefactoring.RefactorAsync(context.Document, binaryExpression, cancellationToken: cancellationToken));
                }

                if (context.IsRefactoringEnabled(RefactoringIdentifiers.MergeStringLiteralsIntoMultilineStringLiteral) &&
                    binaryExpression
                    .DescendantTrivia(binaryExpression.Span)
                    .Any(f => f.IsKind(SyntaxKind.EndOfLineTrivia)))
                {
                    context.RegisterRefactoring(
                        "Merge string literals into multiline string literal",
                        cancellationToken => MergeStringLiteralsRefactoring.RefactorAsync(context.Document, binaryExpression, multiline: true, cancellationToken: cancellationToken));
                }
            }

            if (context.IsRefactoringEnabled(RefactoringIdentifiers.SwapExpressionsInBinaryExpression) &&
                SwapExpressionsRefactoring.CanRefactor(binaryExpression) &&
                context.Span.IsBetweenSpans(binaryExpression))
            {
                context.RegisterRefactoring(
                    "Swap expressions",
                    cancellationToken =>
                {
                    return(SwapExpressionsRefactoring.RefactorAsync(
                               context.Document,
                               binaryExpression,
                               cancellationToken));
                });
            }

            if (context.IsRefactoringEnabled(RefactoringIdentifiers.ReplaceAsWithCast))
            {
                ReplaceAsWithCastRefactoring.ComputeRefactoring(context, binaryExpression);
            }

            if (context.Span.IsContainedInSpanOrBetweenSpans(binaryExpression.OperatorToken) &&
                context.IsAnyRefactoringEnabled(
                    RefactoringIdentifiers.ReplaceEqualsExpressionWithStringEquals,
                    RefactoringIdentifiers.ReplaceEqualsExpressionWithStringIsNullOrWhiteSpace))
            {
                await ReplaceEqualsExpressionRefactoring.ComputeRefactoringsAsync(context, binaryExpression).ConfigureAwait(false);
            }
        }
Exemple #9
0
        public static void ComputeRefactoring(RefactoringContext context, MemberDeclarationSyntax member)
        {
            MemberDeclarationListInfo info = SyntaxInfo.MemberDeclarationListInfo(member.Parent);

            if (!info.Success)
            {
                return;
            }

            SyntaxList <MemberDeclarationSyntax> members = info.Members;

            if (members.Count <= 1)
            {
                return;
            }

            int index = IndexOfMemberToSwap(member, members, context.Span);

            if (index == -1)
            {
                return;
            }

            SyntaxTree tree = member.SyntaxTree;

            FileLinePositionSpan fileLinePositionSpan = tree.GetLineSpan(context.Span, context.CancellationToken);

            int startLine = fileLinePositionSpan.StartLine();
            int endLine   = fileLinePositionSpan.EndLine();

            if (startLine <= tree.GetEndLine(members[index].TrimmedSpan(), context.CancellationToken))
            {
                return;
            }

            if (endLine >= tree.GetStartLine(members[index + 1].TrimmedSpan(), context.CancellationToken))
            {
                return;
            }

            if (context.IsRefactoringEnabled(RefactoringIdentifiers.RemoveMemberDeclarations))
            {
                context.RegisterRefactoring(
                    "Remove members above",
                    ct => ReplaceMembersAsync(context.Document, info, members.Skip(index + 1), ct),
                    EquivalenceKey.Join(RefactoringIdentifiers.RemoveMemberDeclarations, "Above"));

                context.RegisterRefactoring(
                    "Remove members below",
                    ct => ReplaceMembersAsync(context.Document, info, members.Take(index + 1), ct),
                    EquivalenceKey.Join(RefactoringIdentifiers.RemoveMemberDeclarations, "Below"));
            }

            if (context.IsRefactoringEnabled(RefactoringIdentifiers.SwapMemberDeclarations))
            {
                context.RegisterRefactoring(
                    "Swap members",
                    ct => SwapMembersAsync(context.Document, info, index, ct),
                    RefactoringIdentifiers.SwapMemberDeclarations);
            }
        }
Exemple #10
0
        public static async Task ComputeRefactoringsAsync(RefactoringContext context, IfStatementSyntax ifStatement)
        {
            if (ifStatement.IsTopmostIf() &&
                (context.Span.IsEmptyAndContainedInSpan(ifStatement.IfKeyword) || context.Span.IsBetweenSpans(ifStatement)))
            {
                if (context.IsAnyRefactoringEnabled(
                        RefactoringIdentifiers.UseCoalesceExpressionInsteadOfIf,
                        RefactoringIdentifiers.UseConditionalExpressionInsteadOfIf,
                        RefactoringIdentifiers.SimplifyIf))
                {
                    SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false);

                    IfAnalysisOptions options = GetIfAnalysisOptions(context);

                    foreach (IfAnalysis analysis in IfAnalysis.Analyze(ifStatement, options, semanticModel, context.CancellationToken))
                    {
                        string refactoringId = GetRefactoringIdentifier(analysis);

                        if (context.IsRefactoringEnabled(refactoringId))
                        {
                            context.RegisterRefactoring(
                                analysis.Title,
                                cancellationToken => IfRefactoring.RefactorAsync(context.Document, analysis, cancellationToken),
                                equivalenceKey: refactoringId);
                        }
                    }
                }

                if (context.IsRefactoringEnabled(RefactoringIdentifiers.SwapIfElse))
                {
                    SwapIfElseRefactoring.ComputeRefactoring(context, ifStatement);
                }

                if (context.IsRefactoringEnabled(RefactoringIdentifiers.ReplaceIfWithSwitch))
                {
                    await ReplaceIfWithSwitchRefactoring.ComputeRefactoringAsync(context, ifStatement).ConfigureAwait(false);
                }

                if (context.IsRefactoringEnabled(RefactoringIdentifiers.SplitIfStatement))
                {
                    SplitIfStatementRefactoring.ComputeRefactoring(context, ifStatement);
                }

                if (context.IsRefactoringEnabled(RefactoringIdentifiers.MergeIfWithParentIf) &&
                    context.Span.IsEmptyAndContainedInSpan(ifStatement.IfKeyword))
                {
                    MergeIfWithParentIfRefactoring.ComputeRefactoring(context, ifStatement);
                }
            }

            if (context.IsRefactoringEnabled(RefactoringIdentifiers.ReduceIfNesting) &&
                context.Span.IsEmptyAndContainedInSpanOrBetweenSpans(ifStatement.IfKeyword))
            {
                SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false);

                ReduceIfNestingAnalysisResult analysis = ReduceIfNestingAnalysis.Analyze(
                    ifStatement,
                    semanticModel,
                    options: ReduceIfNestingOptions.AllowNestedFix
                    | ReduceIfNestingOptions.AllowIfInsideIfElse
                    | ReduceIfNestingOptions.AllowLoop
                    | ReduceIfNestingOptions.AllowSwitchSection,
                    taskSymbol: semanticModel.GetTypeByMetadataName(MetadataNames.System_Threading_Tasks_Task),
                    cancellationToken: context.CancellationToken);

                if (analysis.Success)
                {
                    context.RegisterRefactoring(
                        "Reduce if nesting",
                        cancellationToken => ReduceIfNestingRefactoring.RefactorAsync(context.Document, ifStatement, analysis.JumpKind, false, cancellationToken),
                        RefactoringIdentifiers.ReduceIfNesting);

                    if (ReduceIfNestingAnalysis.IsFixableRecursively(ifStatement, analysis.JumpKind))
                    {
                        context.RegisterRefactoring(
                            "Reduce if nesting (recursively)",
                            cancellationToken => ReduceIfNestingRefactoring.RefactorAsync(context.Document, ifStatement, analysis.JumpKind, true, cancellationToken),
                            EquivalenceKey.Join(RefactoringIdentifiers.ReduceIfNesting, "Recursive"));
                    }
                }
            }

            if (context.IsRefactoringEnabled(RefactoringIdentifiers.SplitIfElse) &&
                context.Span.IsEmptyAndContainedInSpanOrBetweenSpans(ifStatement.IfKeyword))
            {
                SplitIfElseRefactoring.ComputeRefactoring(context, ifStatement);
            }
        }
Exemple #11
0
        public static async Task ComputeRefactoringsAsync(RefactoringContext context, SwitchSectionSyntax switchSection)
        {
            if (SelectedStatementsRefactoring.IsAnyRefactoringEnabled(context) &&
                StatementListSelection.TryCreate(switchSection, context.Span, out StatementListSelection selectedStatements))
            {
                await SelectedStatementsRefactoring.ComputeRefactoringAsync(context, selectedStatements).ConfigureAwait(false);
            }

            if (context.IsRefactoringEnabled(RefactoringIdentifiers.SplitSwitchLabels))
            {
                SplitSwitchLabelsRefactoring.ComputeRefactoring(context, switchSection);
            }

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

                SyntaxList <SwitchSectionSyntax> sections = switchStatement.Sections;

                BracesAnalysis analysis = BracesAnalysis.AnalyzeBraces(switchSection);

                if (analysis.AddBraces)
                {
                    if (context.IsRefactoringEnabled(RefactoringIdentifiers.AddBracesToSwitchSection))
                    {
                        context.RegisterRefactoring(
                            AddBracesToSwitchSectionRefactoring.Title,
                            cancellationToken => AddBracesToSwitchSectionRefactoring.RefactorAsync(context.Document, switchSection, cancellationToken),
                            RefactoringIdentifiers.AddBracesToSwitchSection);
                    }

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

                    if (context.IsRefactoringEnabled(RefactoringIdentifiers.RemoveBracesFromSwitchSections) &&
                        sections.Any(f => f != switchSection && RemoveBracesFromSwitchSectionRefactoring.CanRemoveBraces(f)))
                    {
                        context.RegisterRefactoring(
                            RemoveBracesFromSwitchSectionsRefactoring.Title,
                            cancellationToken => RemoveBracesFromSwitchSectionsRefactoring.RefactorAsync(context.Document, switchStatement, null, cancellationToken),
                            RefactoringIdentifiers.RemoveBracesFromSwitchSections);
                    }
                }
            }
        }
Exemple #12
0
        public static async Task ComputeRefactoringsAsync(RefactoringContext context, PropertyDeclarationSyntax propertyDeclaration)
        {
            if (context.IsRefactoringEnabled(RefactoringIdentifiers.ReplacePropertyWithMethod) &&
                propertyDeclaration.HeaderSpan().Contains(context.Span))
            {
                ReplacePropertyWithMethodRefactoring.ComputeRefactoring(context, propertyDeclaration);
            }

            if (context.IsRefactoringEnabled(RefactoringIdentifiers.RemovePropertyInitializer) &&
                RemovePropertyInitializerRefactoring.CanRefactor(context, propertyDeclaration))
            {
                context.RegisterRefactoring(
                    "Remove property initializer",
                    cancellationToken => RemovePropertyInitializerRefactoring.RefactorAsync(context.Document, propertyDeclaration, cancellationToken));
            }

            if (context.IsAnyRefactoringEnabled(
                    RefactoringIdentifiers.ExpandProperty,
                    RefactoringIdentifiers.ExpandPropertyAndAddBackingField) &&
                propertyDeclaration.Span.Contains(context.Span) &&
                ExpandPropertyRefactoring.CanRefactor(propertyDeclaration))
            {
                if (context.IsRefactoringEnabled(RefactoringIdentifiers.ExpandProperty))
                {
                    context.RegisterRefactoring(
                        "Expand property",
                        cancellationToken => ExpandPropertyRefactoring.RefactorAsync(context.Document, propertyDeclaration, cancellationToken));
                }

                if (context.IsRefactoringEnabled(RefactoringIdentifiers.ExpandPropertyAndAddBackingField))
                {
                    context.RegisterRefactoring(
                        "Expand property and add backing field",
                        cancellationToken => ExpandPropertyAndAddBackingFieldRefactoring.RefactorAsync(context.Document, propertyDeclaration, context.Settings.PrefixFieldIdentifierWithUnderscore, cancellationToken));
                }
            }

            if (context.IsRefactoringEnabled(RefactoringIdentifiers.NotifyPropertyChanged) &&
                await NotifyPropertyChangedRefactoring.CanRefactorAsync(context, propertyDeclaration).ConfigureAwait(false))
            {
                context.RegisterRefactoring(
                    "Notify property changed",
                    cancellationToken =>
                {
                    return(NotifyPropertyChangedRefactoring.RefactorAsync(
                               context.Document,
                               propertyDeclaration,
                               context.SupportsCSharp6,
                               cancellationToken));
                });
            }

            if (context.IsRefactoringEnabled(RefactoringIdentifiers.MakeMemberAbstract) &&
                propertyDeclaration.HeaderSpan().Contains(context.Span))
            {
                MakePropertyAbstractRefactoring.ComputeRefactoring(context, propertyDeclaration);
            }

            if (context.IsRefactoringEnabled(RefactoringIdentifiers.MakeMemberVirtual) &&
                propertyDeclaration.HeaderSpan().Contains(context.Span))
            {
                MakePropertyVirtualRefactoring.ComputeRefactoring(context, propertyDeclaration);
            }

            if (context.IsRefactoringEnabled(RefactoringIdentifiers.CopyDocumentationCommentFromBaseMember) &&
                propertyDeclaration.HeaderSpan().Contains(context.Span))
            {
                await CopyDocumentationCommentFromBaseMemberRefactoring.ComputeRefactoringAsync(context, propertyDeclaration).ConfigureAwait(false);
            }

            if (context.IsRefactoringEnabled(RefactoringIdentifiers.RenamePropertyAccordingToTypeName))
            {
                await RenamePropertyAccodingToTypeName(context, propertyDeclaration).ConfigureAwait(false);
            }

            if (context.IsRefactoringEnabled(RefactoringIdentifiers.AddMemberToInterface) &&
                context.Span.IsEmptyAndContainedInSpanOrBetweenSpans(propertyDeclaration.Identifier))
            {
                SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false);

                AddMemberToInterfaceRefactoring.ComputeRefactoring(context, propertyDeclaration, semanticModel);
            }
        }
        public static async Task ComputeRefactoringsAsync(RefactoringContext context, VariableDeclarationSyntax variableDeclaration)
        {
            TypeSyntax type = variableDeclaration.Type;

            if (type?.Span.Contains(context.Span) == true &&
                context.IsAnyRefactoringEnabled(
                    RefactoringIdentifiers.ChangeExplicitTypeToVar,
                    RefactoringIdentifiers.ChangeVarToExplicitType,
                    RefactoringIdentifiers.ChangeTypeAccordingToExpression))
            {
                SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false);

                TypeAnalysis analysis = CSharpTypeAnalysis.AnalyzeType(variableDeclaration, semanticModel, context.CancellationToken);

                if (analysis.IsExplicit)
                {
                    if (analysis.SupportsImplicit &&
                        context.IsRefactoringEnabled(RefactoringIdentifiers.ChangeExplicitTypeToVar))
                    {
                        context.RegisterRefactoring(CodeActionFactory.ChangeTypeToVar(context.Document, type, equivalenceKey: RefactoringIdentifiers.ChangeExplicitTypeToVar));
                    }

                    if (!variableDeclaration.ContainsDiagnostics &&
                        context.IsRefactoringEnabled(RefactoringIdentifiers.ChangeTypeAccordingToExpression))
                    {
                        ChangeTypeAccordingToExpression(context, variableDeclaration, analysis.Symbol, semanticModel);
                    }
                }
                else if (analysis.SupportsExplicit &&
                         context.IsRefactoringEnabled(RefactoringIdentifiers.ChangeVarToExplicitType))
                {
                    ITypeSymbol typeSymbol = semanticModel.GetTypeSymbol(type, context.CancellationToken);

                    VariableDeclaratorSyntax variableDeclarator = variableDeclaration.Variables.SingleOrDefault(shouldThrow: false);

                    if (variableDeclarator?.Initializer?.Value != null &&
                        typeSymbol.OriginalDefinition.EqualsOrInheritsFromTaskOfT())
                    {
                        Func <CancellationToken, Task <Document> > createChangedDocument = DocumentRefactoringFactory.ChangeTypeAndAddAwait(
                            context.Document,
                            variableDeclaration,
                            variableDeclarator,
                            typeSymbol,
                            semanticModel,
                            context.CancellationToken);

                        if (createChangedDocument != null)
                        {
                            ITypeSymbol typeArgument = ((INamedTypeSymbol)typeSymbol).TypeArguments[0];

                            context.RegisterRefactoring(
                                $"Change type to '{SymbolDisplay.ToMinimalDisplayString(typeArgument, semanticModel, type.SpanStart)}' and add 'await'",
                                createChangedDocument,
                                EquivalenceKey.Join(RefactoringIdentifiers.ChangeVarToExplicitType, "AddAwait"));
                        }
                    }

                    context.RegisterRefactoring(CodeActionFactory.ChangeType(context.Document, type, typeSymbol, semanticModel, equivalenceKey: RefactoringIdentifiers.ChangeVarToExplicitType));
                }
            }
        }
        public static async Task ComputeRefactoringsAsync(RefactoringContext context, MethodDeclarationSyntax methodDeclaration)
        {
            if (methodDeclaration.Span.Contains(context.Span))
            {
                await ChangeMethodReturnTypeToVoidRefactoring.ComputeRefactoringAsync(context, methodDeclaration).ConfigureAwait(false);
            }

            if (context.IsRefactoringEnabled(RefactoringIdentifiers.AddTypeParameter))
            {
                AddTypeParameterRefactoring.ComputeRefactoring(context, methodDeclaration);
            }

            if (context.IsRefactoringEnabled(RefactoringIdentifiers.ReplaceMethodWithProperty) &&
                methodDeclaration.HeaderSpan().Contains(context.Span) &&
                ReplaceMethodWithPropertyRefactoring.CanRefactor(methodDeclaration))
            {
                context.RegisterRefactoring(
                    $"Replace '{methodDeclaration.Identifier.ValueText}' with property",
                    cancellationToken => ReplaceMethodWithPropertyRefactoring.RefactorAsync(context.Document, methodDeclaration, cancellationToken));
            }

            if (context.IsRefactoringEnabled(RefactoringIdentifiers.UseExpressionBodiedMember) &&
                methodDeclaration.Body?.Span.Contains(context.Span) == true &&
                context.SupportsCSharp6 &&
                UseExpressionBodiedMemberRefactoring.CanRefactor(methodDeclaration))
            {
                context.RegisterRefactoring(
                    "Use expression-bodied member",
                    cancellationToken => UseExpressionBodiedMemberRefactoring.RefactorAsync(context.Document, methodDeclaration, cancellationToken));
            }

            if (context.IsRefactoringEnabled(RefactoringIdentifiers.MakeMemberAbstract) &&
                methodDeclaration.HeaderSpan().Contains(context.Span))
            {
                MakeMethodAbstractRefactoring.ComputeRefactoring(context, methodDeclaration);
            }

            if (context.IsRefactoringEnabled(RefactoringIdentifiers.MakeMemberVirtual) &&
                methodDeclaration.HeaderSpan().Contains(context.Span))
            {
                MakeMethodVirtualRefactoring.ComputeRefactoring(context, methodDeclaration);
            }

            if (context.IsRefactoringEnabled(RefactoringIdentifiers.CopyDocumentationCommentFromBaseMember) &&
                methodDeclaration.HeaderSpan().Contains(context.Span))
            {
                await CopyDocumentationCommentFromBaseMemberRefactoring.ComputeRefactoringAsync(context, methodDeclaration).ConfigureAwait(false);
            }

            if (context.IsRefactoringEnabled(RefactoringIdentifiers.RenameMethodAccordingToTypeName))
            {
                await RenameMethodAccoringToTypeNameAsync(context, methodDeclaration).ConfigureAwait(false);
            }

            if (context.IsRefactoringEnabled(RefactoringIdentifiers.AddMemberToInterface) &&
                context.Span.IsEmptyAndContainedInSpanOrBetweenSpans(methodDeclaration.Identifier))
            {
                SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false);

                AddMemberToInterfaceRefactoring.ComputeRefactoring(context, methodDeclaration, semanticModel);
            }

            if (context.IsRefactoringEnabled(RefactoringIdentifiers.UseListInsteadOfYield) &&
                methodDeclaration.Identifier.Span.Contains(context.Span))
            {
                SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false);

                UseListInsteadOfYieldRefactoring.ComputeRefactoring(context, methodDeclaration, semanticModel);
            }
        }
Exemple #15
0
        public static async Task ComputeRefactoringAsync(RefactoringContext context, SelectedStatementCollection selectedStatements)
        {
            if (selectedStatements.Any())
            {
                if (context.IsRefactoringEnabled(RefactoringIdentifiers.WrapInUsingStatement))
                {
                    var refactoring = new WrapInUsingStatementRefactoring();
                    await refactoring.ComputeRefactoringAsync(context, selectedStatements).ConfigureAwait(false);
                }

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

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

                if (context.IsRefactoringEnabled(RefactoringIdentifiers.ReplaceIfStatementWithReturnStatement))
                {
                    ReplaceIfAndReturnWithReturnRefactoring.ComputeRefactoring(context, selectedStatements);
                }

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

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

                if (context.IsRefactoringEnabled(RefactoringIdentifiers.CheckExpressionForNull))
                {
                    await CheckExpressionForNullRefactoring.ComputeRefactoringAsync(context, selectedStatements).ConfigureAwait(false);
                }

                if (context.IsRefactoringEnabled(RefactoringIdentifiers.ReplaceWhileWithFor))
                {
                    await ReplaceWhileWithForRefactoring.ComputeRefactoringAsync(context, selectedStatements).ConfigureAwait(false);
                }

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

                if (context.IsRefactoringEnabled(RefactoringIdentifiers.WrapInTryCatch))
                {
                    context.RegisterRefactoring(
                        "Wrap in try-catch",
                        cancellationToken =>
                    {
                        var refactoring = new WrapInTryCatchRefactoring();
                        return(refactoring.RefactorAsync(context.Document, selectedStatements, cancellationToken));
                    });
                }
            }
        }
Exemple #16
0
        public static async Task ComputeRefactoringsAsync(RefactoringContext context, SyntaxNode node)
        {
            if (context.IsAnyRefactoringEnabled(
                    RefactoringIdentifiers.WrapInRegion,
                    RefactoringIdentifiers.WrapInIfDirective,
                    RefactoringIdentifiers.RemoveEmptyLines))
            {
                SyntaxNode root = context.Root;
                TextSpan   span = context.Span;

                if (!IsFullLineSpan(node, span))
                {
                    return;
                }

                Document   document   = context.Document;
                SourceText sourceText = await document.GetTextAsync(context.CancellationToken).ConfigureAwait(false);

                if (!TextLineCollectionSelection.TryCreate(sourceText.Lines, span, out TextLineCollectionSelection selectedLines))
                {
                    return;
                }

                if (!IsInMultiLineDocumentationComment(root, span.Start) &&
                    !IsInMultiLineDocumentationComment(root, span.End))
                {
                    if (context.IsRefactoringEnabled(RefactoringIdentifiers.WrapInRegion))
                    {
                        context.RegisterRefactoring(
                            "Wrap in region",
                            ct => WrapInRegionRefactoring.Instance.RefactorAsync(document, selectedLines, ct),
                            RefactoringIdentifiers.WrapInRegion);
                    }

                    if (context.IsRefactoringEnabled(RefactoringIdentifiers.WrapInIfDirective))
                    {
                        context.RegisterRefactoring(
                            "Wrap in #if",
                            ct => WrapInIfDirectiveRefactoring.Instance.RefactorAsync(document, selectedLines, ct),
                            RefactoringIdentifiers.WrapInIfDirective);
                    }
                }

                if (context.IsRefactoringEnabled(RefactoringIdentifiers.RemoveEmptyLines))
                {
                    bool containsEmptyLine = false;

                    foreach (TextLine line in selectedLines)
                    {
                        context.ThrowIfCancellationRequested();

                        if (line.IsEmptyOrWhiteSpace() &&
                            root.FindTrivia(line.End, findInsideTrivia: true).IsEndOfLineTrivia())
                        {
                            containsEmptyLine = true;
                            break;
                        }
                    }

                    if (containsEmptyLine)
                    {
                        context.RegisterRefactoring(
                            "Remove empty lines",
                            ct =>
                        {
                            ct.ThrowIfCancellationRequested();

                            IEnumerable <TextChange> textChanges = selectedLines
                                                                   .Where(line => line.IsEmptyOrWhiteSpace() && root.FindTrivia(line.End, findInsideTrivia: true).IsEndOfLineTrivia())
                                                                   .Select(line => new TextChange(line.SpanIncludingLineBreak, ""));

                            return(document.WithTextChangesAsync(textChanges, ct));
                        },
                            RefactoringIdentifiers.RemoveEmptyLines);
                    }
                }
            }
        }
Exemple #17
0
        public static async Task ComputeRefactoringsAsync(RefactoringContext context, BinaryExpressionSyntax binaryExpression)
        {
            if (context.IsRefactoringEnabled(RefactoringIdentifiers.NegateOperator))
            {
                SyntaxToken operatorToken = binaryExpression.OperatorToken;

                if (operatorToken.Span.Contains(context.Span) &&
                    NegateOperatorRefactoring.CanBeNegated(operatorToken))
                {
                    context.RegisterRefactoring(
                        "Negate operator",
                        cancellationToken => NegateOperatorRefactoring.RefactorAsync(context.Document, operatorToken, cancellationToken));
                }
            }

            if (context.IsRefactoringEnabled(RefactoringIdentifiers.FormatBinaryExpression))
            {
                FormatBinaryExpressionRefactoring.ComputeRefactorings(context, binaryExpression);
            }

            if (context.IsRefactoringEnabled(RefactoringIdentifiers.NegateBinaryExpression))
            {
                NegateBinaryExpressionRefactoring.ComputeRefactoring(context, binaryExpression);
            }

            if (context.IsRefactoringEnabled(RefactoringIdentifiers.ExpandCoalesceExpression) &&
                binaryExpression.OperatorToken.Span.Contains(context.Span))
            {
                ExpandCoalesceExpressionRefactoring.ComputeRefactoring(context, binaryExpression);
            }

            if (context.IsAnyRefactoringEnabled(
                    RefactoringIdentifiers.JoinStringExpressions,
                    RefactoringIdentifiers.UseStringBuilderInsteadOfConcatenation) &&
                context.Span.IsBetweenSpans(binaryExpression) &&
                binaryExpression.IsKind(SyntaxKind.AddExpression))
            {
                SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false);

                StringConcatenationExpression concatenation;
                if (StringConcatenationExpression.TryCreate(binaryExpression, semanticModel, out concatenation, context.CancellationToken))
                {
                    if (context.IsRefactoringEnabled(RefactoringIdentifiers.JoinStringExpressions))
                    {
                        JoinStringExpressionsRefactoring.ComputeRefactoring(context, concatenation);
                    }

                    if (context.IsRefactoringEnabled(RefactoringIdentifiers.UseStringBuilderInsteadOfConcatenation))
                    {
                        UseStringBuilderInsteadOfConcatenationRefactoring.ComputeRefactoring(context, concatenation);
                    }
                }
            }

            if (context.IsRefactoringEnabled(RefactoringIdentifiers.SwapExpressionsInBinaryExpression) &&
                context.Span.IsBetweenSpans(binaryExpression))
            {
                SwapExpressionsInBinaryExpressionRefactoring.ComputeRefactoring(context, binaryExpression);
            }

            if (context.IsRefactoringEnabled(RefactoringIdentifiers.ReplaceAsWithCast) &&
                context.Span.IsEmptyAndContainedInSpanOrBetweenSpans(binaryExpression))
            {
                ReplaceAsWithCastRefactoring.ComputeRefactoring(context, binaryExpression);
            }

            if (context.IsRefactoringEnabled(RefactoringIdentifiers.NegateIsExpression))
            {
                NegateIsExpressionRefactoring.ComputeRefactoring(context, binaryExpression);
            }

            if (context.Span.IsContainedInSpanOrBetweenSpans(binaryExpression.OperatorToken))
            {
                if (context.IsRefactoringEnabled(RefactoringIdentifiers.ReplaceEqualsExpressionWithStringEquals))
                {
                    await ReplaceEqualsExpressionWithStringEqualsRefactoring.ComputeRefactoringAsync(context, binaryExpression).ConfigureAwait(false);
                }

                if (context.IsAnyRefactoringEnabled(
                        RefactoringIdentifiers.ReplaceEqualsExpressionWithStringIsNullOrEmpty,
                        RefactoringIdentifiers.ReplaceEqualsExpressionWithStringIsNullOrWhiteSpace))
                {
                    await ReplaceEqualsExpressionRefactoring.ComputeRefactoringsAsync(context, binaryExpression).ConfigureAwait(false);
                }
            }

            if (!context.Span.IsBetweenSpans(binaryExpression) &&
                context.IsAnyRefactoringEnabled(
                    RefactoringIdentifiers.ExtractExpressionFromCondition,
                    RefactoringIdentifiers.JoinStringExpressions))
            {
                BinaryExpressionSelection binaryExpressionSelection = BinaryExpressionSelection.Create(binaryExpression, context.Span);

                if (binaryExpressionSelection.Expressions.Length > 1)
                {
                    if (context.IsRefactoringEnabled(RefactoringIdentifiers.ExtractExpressionFromCondition))
                    {
                        ExtractConditionRefactoring.ComputeRefactoring(context, binaryExpressionSelection);
                    }

                    if (context.IsRefactoringEnabled(RefactoringIdentifiers.JoinStringExpressions) &&
                        binaryExpression.IsKind(SyntaxKind.AddExpression))
                    {
                        SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false);

                        StringConcatenationExpression concatenation;
                        if (StringConcatenationExpression.TryCreate(binaryExpressionSelection, semanticModel, out concatenation, context.CancellationToken))
                        {
                            JoinStringExpressionsRefactoring.ComputeRefactoring(context, concatenation);
                        }
                    }
                }
            }
        }
        public static async Task ComputeRefactoringsAsync(RefactoringContext context, BinaryExpressionSyntax binaryExpression)
        {
            SyntaxToken operatorToken = binaryExpression.OperatorToken;

            if (context.IsRefactoringEnabled(RefactoringIdentifiers.InvertOperator) &&
                context.Span.IsEmptyAndContainedInSpanOrBetweenSpans(operatorToken) &&
                InvertOperatorRefactoring.CanBeInverted(operatorToken))
            {
                context.RegisterRefactoring(
                    "Invert operator",
                    cancellationToken => InvertOperatorRefactoring.RefactorAsync(context.Document, operatorToken, cancellationToken),
                    RefactoringIdentifiers.InvertOperator);
            }

            if (context.Span.IsEmptyAndContainedInSpan(operatorToken))
            {
                if (context.IsRefactoringEnabled(RefactoringIdentifiers.InvertBinaryExpression))
                {
                    InvertBinaryExpressionRefactoring.ComputeRefactoring(context, binaryExpression);
                }

                if (context.IsRefactoringEnabled(RefactoringIdentifiers.SwapBinaryOperands))
                {
                    SwapBinaryOperandsRefactoring.ComputeRefactoring(context, binaryExpression);
                }
            }

            if (context.IsRefactoringEnabled(RefactoringIdentifiers.WrapBinaryExpression))
            {
                WrapBinaryExpressionRefactoring.ComputeRefactorings(context, binaryExpression);
            }

            if (context.IsRefactoringEnabled(RefactoringIdentifiers.ExpandCoalesceExpression) &&
                operatorToken.Span.Contains(context.Span))
            {
                ExpandCoalesceExpressionRefactoring.ComputeRefactoring(context, binaryExpression);
            }

            if (context.IsAnyRefactoringEnabled(
                    RefactoringIdentifiers.ExtractExpressionFromCondition,
                    RefactoringIdentifiers.JoinStringExpressions,
                    RefactoringIdentifiers.UseStringBuilderInsteadOfConcatenation) &&
                !context.Span.IsEmpty &&
                binaryExpression.IsKind(SyntaxKind.AddExpression, SyntaxKind.LogicalAndExpression, SyntaxKind.LogicalOrExpression))
            {
                ExpressionChain chain = binaryExpression.AsChain(context.Span);

                ExpressionChain.Enumerator en = chain.GetEnumerator();

                if (en.MoveNext() &&
                    en.MoveNext())
                {
                    if (context.IsRefactoringEnabled(RefactoringIdentifiers.ExtractExpressionFromCondition))
                    {
                        ExtractConditionRefactoring.ComputeRefactoring(context, chain);
                    }

                    if (binaryExpression.IsKind(SyntaxKind.AddExpression))
                    {
                        SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false);

                        StringConcatenationExpressionInfo concatenationInfo = SyntaxInfo.StringConcatenationExpressionInfo(chain, semanticModel, context.CancellationToken);
                        if (concatenationInfo.Success)
                        {
                            if (context.IsRefactoringEnabled(RefactoringIdentifiers.JoinStringExpressions))
                            {
                                JoinStringExpressionsRefactoring.ComputeRefactoring(context, concatenationInfo);
                            }

                            if (context.IsRefactoringEnabled(RefactoringIdentifiers.UseStringBuilderInsteadOfConcatenation))
                            {
                                UseStringBuilderInsteadOfConcatenationRefactoring.ComputeRefactoring(context, concatenationInfo);
                            }
                        }
                    }
                }
            }

            if (context.IsRefactoringEnabled(RefactoringIdentifiers.ReplaceAsWithCast) &&
                context.Span.IsEmptyAndContainedInSpanOrBetweenSpans(binaryExpression))
            {
                SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false);

                if (ReplaceAsWithCastAnalysis.IsFixable(binaryExpression, semanticModel, context.CancellationToken))
                {
                    context.RegisterRefactoring(
                        ReplaceAsWithCastRefactoring.Title,
                        cancellationToken => ReplaceAsWithCastRefactoring.RefactorAsync(context.Document, binaryExpression, cancellationToken),
                        RefactoringIdentifiers.ReplaceAsWithCast);
                }
            }

            if (context.IsRefactoringEnabled(RefactoringIdentifiers.InvertIsExpression))
            {
                InvertIsExpressionRefactoring.ComputeRefactoring(context, binaryExpression);
            }

            if (context.Span.IsContainedInSpanOrBetweenSpans(operatorToken))
            {
                if (context.IsRefactoringEnabled(RefactoringIdentifiers.ReplaceEqualsExpressionWithStringEquals))
                {
                    await ReplaceEqualsExpressionWithStringEqualsRefactoring.ComputeRefactoringAsync(context, binaryExpression).ConfigureAwait(false);
                }

                if (context.IsAnyRefactoringEnabled(
                        RefactoringIdentifiers.ReplaceEqualsExpressionWithStringIsNullOrEmpty,
                        RefactoringIdentifiers.ReplaceEqualsExpressionWithStringIsNullOrWhiteSpace))
                {
                    await ReplaceEqualsExpressionRefactoring.ComputeRefactoringsAsync(context, binaryExpression).ConfigureAwait(false);
                }
            }
        }
        public static async Task ComputeRefactoringsAsync(RefactoringContext context, MethodDeclarationSyntax methodDeclaration)
        {
            if (methodDeclaration.Span.Contains(context.Span))
            {
                if (context.IsRefactoringEnabled(RefactoringIdentifiers.MarkMemberAsStatic) &&
                    MarkMemberAsStaticRefactoring.CanRefactor(methodDeclaration))
                {
                    context.RegisterRefactoring(
                        "Mark method as static",
                        cancellationToken => MarkMemberAsStaticRefactoring.RefactorAsync(context.Document, methodDeclaration, cancellationToken));
                }

                await ChangeMethodReturnTypeToVoidRefactoring.ComputeRefactoringAsync(context, methodDeclaration).ConfigureAwait(false);
            }

            if (context.IsRefactoringEnabled(RefactoringIdentifiers.MarkContainingClassAsAbstract) &&
                methodDeclaration.HeaderSpan().Contains(context.Span) &&
                MarkContainingClassAsAbstractRefactoring.CanRefactor(methodDeclaration))
            {
                context.RegisterRefactoring(
                    "Mark containing class as abstract",
                    cancellationToken => MarkContainingClassAsAbstractRefactoring.RefactorAsync(context.Document, methodDeclaration, cancellationToken));
            }

            if (context.IsRefactoringEnabled(RefactoringIdentifiers.ReplaceMethodWithProperty) &&
                methodDeclaration.HeaderSpan().Contains(context.Span) &&
                ReplaceMethodWithPropertyRefactoring.CanRefactor(methodDeclaration))
            {
                context.RegisterRefactoring(
                    $"Replace '{methodDeclaration.Identifier.ValueText}' with property",
                    cancellationToken => ReplaceMethodWithPropertyRefactoring.RefactorAsync(context.Document, methodDeclaration, cancellationToken));
            }

            if (context.IsRefactoringEnabled(RefactoringIdentifiers.UseExpressionBodiedMember) &&
                methodDeclaration.Body?.Span.Contains(context.Span) == true &&
                context.SupportsCSharp6 &&
                UseExpressionBodiedMemberRefactoring.CanRefactor(methodDeclaration))
            {
                context.RegisterRefactoring(
                    "Use expression-bodied member",
                    cancellationToken => UseExpressionBodiedMemberRefactoring.RefactorAsync(context.Document, methodDeclaration, cancellationToken));
            }

            if (context.IsRefactoringEnabled(RefactoringIdentifiers.MakeMemberAbstract) &&
                methodDeclaration.HeaderSpan().Contains(context.Span) &&
                MakeMemberAbstractRefactoring.CanRefactor(methodDeclaration))
            {
                context.RegisterRefactoring(
                    "Make method abstract",
                    cancellationToken => MakeMemberAbstractRefactoring.RefactorAsync(context.Document, methodDeclaration, cancellationToken));
            }

            if (context.IsRefactoringEnabled(RefactoringIdentifiers.MakeMemberVirtual) &&
                methodDeclaration.HeaderSpan().Contains(context.Span))
            {
                MakeMemberVirtualRefactoring.ComputeRefactoring(context, methodDeclaration);
            }

            if (context.IsRefactoringEnabled(RefactoringIdentifiers.CopyDocumentationCommentFromBaseMember) &&
                methodDeclaration.HeaderSpan().Contains(context.Span))
            {
                await CopyDocumentationCommentFromBaseMemberRefactoring.ComputeRefactoringAsync(context, methodDeclaration).ConfigureAwait(false);
            }

            if (context.IsRefactoringEnabled(RefactoringIdentifiers.RenameMethodAccordingToTypeName))
            {
                await RenameMethodAccoringToTypeNameAsync(context, methodDeclaration).ConfigureAwait(false);
            }
        }
Exemple #20
0
 public static bool IsAnyRefactoringEnabled(RefactoringContext context)
 {
     return(context.IsRefactoringEnabled(RefactoringDescriptors.WrapStatementsInUsingStatement) ||
            context.IsRefactoringEnabled(RefactoringDescriptors.UseObjectInitializer) ||
            context.IsRefactoringEnabled(RefactoringDescriptors.MergeIfStatements) ||
            context.IsRefactoringEnabled(RefactoringDescriptors.ConvertStatementsToIfElse) ||
            context.IsRefactoringEnabled(RefactoringDescriptors.MergeLocalDeclarations) ||
            context.IsRefactoringEnabled(RefactoringDescriptors.WrapStatementsInCondition) ||
            context.IsRefactoringEnabled(RefactoringDescriptors.WrapLinesInTryCatch) ||
            context.IsRefactoringEnabled(RefactoringDescriptors.UseCoalesceExpressionInsteadOfIf) ||
            context.IsRefactoringEnabled(RefactoringDescriptors.ConvertIfToConditionalExpression) ||
            context.IsRefactoringEnabled(RefactoringDescriptors.SimplifyIf) ||
            context.IsRefactoringEnabled(RefactoringDescriptors.CheckExpressionForNull) ||
            context.IsRefactoringEnabled(RefactoringDescriptors.ConvertWhileToFor));
 }
        public static async Task ComputeRefactoringsAsync(RefactoringContext context, MemberDeclarationSyntax member)
        {
            SyntaxKind kind = member.Kind();

            switch (kind)
            {
            case SyntaxKind.MethodDeclaration:
            case SyntaxKind.IndexerDeclaration:
            case SyntaxKind.PropertyDeclaration:
            case SyntaxKind.OperatorDeclaration:
            case SyntaxKind.ConversionOperatorDeclaration:
            case SyntaxKind.ConstructorDeclaration:
            case SyntaxKind.EventDeclaration:
            case SyntaxKind.NamespaceDeclaration:
            case SyntaxKind.ClassDeclaration:
            case SyntaxKind.StructDeclaration:
            case SyntaxKind.InterfaceDeclaration:
            case SyntaxKind.EnumDeclaration:
            {
                if (context.IsAnyRefactoringEnabled(
                        RefactoringIdentifiers.RemoveMember,
                        RefactoringIdentifiers.DuplicateMember,
                        RefactoringIdentifiers.CommentOutMember) &&
                    BraceContainsSpan(member, context.Span))
                {
                    if (member.IsParentKind(
                            SyntaxKind.NamespaceDeclaration,
                            SyntaxKind.ClassDeclaration,
                            SyntaxKind.StructDeclaration,
                            SyntaxKind.InterfaceDeclaration,
                            SyntaxKind.CompilationUnit))
                    {
                        if (context.IsRefactoringEnabled(RefactoringIdentifiers.RemoveMember))
                        {
                            context.RegisterRefactoring(
                                "Remove " + CSharpFacts.GetTitle(member),
                                cancellationToken => context.Document.RemoveMemberAsync(member, cancellationToken),
                                RefactoringIdentifiers.RemoveMember);
                        }

                        if (context.IsRefactoringEnabled(RefactoringIdentifiers.DuplicateMember))
                        {
                            context.RegisterRefactoring(
                                "Duplicate " + CSharpFacts.GetTitle(member),
                                cancellationToken => DuplicateMemberDeclarationRefactoring.RefactorAsync(context.Document, member, cancellationToken),
                                RefactoringIdentifiers.DuplicateMember);
                        }
                    }

                    if (context.IsRefactoringEnabled(RefactoringIdentifiers.CommentOutMember))
                    {
                        CommentOutRefactoring.RegisterRefactoring(context, member);
                    }
                }

                break;
            }
            }

            if (context.IsRefactoringEnabled(RefactoringIdentifiers.RemoveAllStatements))
            {
                RemoveAllStatementsRefactoring.ComputeRefactoring(context, member);
            }

            if (context.IsRefactoringEnabled(RefactoringIdentifiers.RemoveAllMemberDeclarations))
            {
                RemoveAllMemberDeclarationsRefactoring.ComputeRefactoring(context, member);
            }

            if (context.IsAnyRefactoringEnabled(
                    RefactoringIdentifiers.SwapMemberDeclarations,
                    RefactoringIdentifiers.RemoveMemberDeclarations) &&
                !member.Span.IntersectsWith(context.Span))
            {
                MemberDeclarationsRefactoring.ComputeRefactoring(context, member);
            }

            switch (kind)
            {
            case SyntaxKind.NamespaceDeclaration:
            {
                var namespaceDeclaration = (NamespaceDeclarationSyntax)member;
                NamespaceDeclarationRefactoring.ComputeRefactorings(context, namespaceDeclaration);

                if (MemberDeclarationListSelection.TryCreate(namespaceDeclaration, context.Span, out MemberDeclarationListSelection selectedMembers))
                {
                    await SelectedMemberDeclarationsRefactoring.ComputeRefactoringAsync(context, selectedMembers).ConfigureAwait(false);
                }

                break;
            }

            case SyntaxKind.ClassDeclaration:
            {
                var classDeclaration = (ClassDeclarationSyntax)member;
                await ClassDeclarationRefactoring.ComputeRefactoringsAsync(context, classDeclaration).ConfigureAwait(false);

                if (MemberDeclarationListSelection.TryCreate(classDeclaration, context.Span, out MemberDeclarationListSelection selectedMembers))
                {
                    await SelectedMemberDeclarationsRefactoring.ComputeRefactoringAsync(context, selectedMembers).ConfigureAwait(false);
                }

                break;
            }

            case SyntaxKind.StructDeclaration:
            {
                var structDeclaration = (StructDeclarationSyntax)member;
                await StructDeclarationRefactoring.ComputeRefactoringsAsync(context, structDeclaration).ConfigureAwait(false);

                if (MemberDeclarationListSelection.TryCreate(structDeclaration, context.Span, out MemberDeclarationListSelection selectedMembers))
                {
                    await SelectedMemberDeclarationsRefactoring.ComputeRefactoringAsync(context, selectedMembers).ConfigureAwait(false);
                }

                break;
            }

            case SyntaxKind.InterfaceDeclaration:
            {
                var interfaceDeclaration = (InterfaceDeclarationSyntax)member;
                InterfaceDeclarationRefactoring.ComputeRefactorings(context, interfaceDeclaration);

                if (MemberDeclarationListSelection.TryCreate(interfaceDeclaration, context.Span, out MemberDeclarationListSelection selectedMembers))
                {
                    await SelectedMemberDeclarationsRefactoring.ComputeRefactoringAsync(context, selectedMembers).ConfigureAwait(false);
                }

                break;
            }

            case SyntaxKind.EnumDeclaration:
            {
                await EnumDeclarationRefactoring.ComputeRefactoringAsync(context, (EnumDeclarationSyntax)member).ConfigureAwait(false);

                break;
            }

            case SyntaxKind.EnumMemberDeclaration:
            {
                await EnumMemberDeclarationRefactoring.ComputeRefactoringAsync(context, (EnumMemberDeclarationSyntax)member).ConfigureAwait(false);

                break;
            }

            case SyntaxKind.DelegateDeclaration:
            {
                DelegateDeclarationRefactoring.ComputeRefactorings(context, (DelegateDeclarationSyntax)member);
                break;
            }

            case SyntaxKind.MethodDeclaration:
            {
                await MethodDeclarationRefactoring.ComputeRefactoringsAsync(context, (MethodDeclarationSyntax)member).ConfigureAwait(false);

                break;
            }

            case SyntaxKind.ConstructorDeclaration:
            {
                await ConstructorDeclarationRefactoring.ComputeRefactoringsAsync(context, (ConstructorDeclarationSyntax)member).ConfigureAwait(false);

                break;
            }

            case SyntaxKind.DestructorDeclaration:
            {
                DestructorDeclarationRefactoring.ComputeRefactorings(context, (DestructorDeclarationSyntax)member);
                break;
            }

            case SyntaxKind.IndexerDeclaration:
            {
                await IndexerDeclarationRefactoring.ComputeRefactoringsAsync(context, (IndexerDeclarationSyntax)member).ConfigureAwait(false);

                break;
            }

            case SyntaxKind.PropertyDeclaration:
            {
                await PropertyDeclarationRefactoring.ComputeRefactoringsAsync(context, (PropertyDeclarationSyntax)member).ConfigureAwait(false);

                break;
            }

            case SyntaxKind.OperatorDeclaration:
            {
                ComputeRefactorings(context, (OperatorDeclarationSyntax)member);
                break;
            }

            case SyntaxKind.ConversionOperatorDeclaration:
            {
                ComputeRefactorings(context, (ConversionOperatorDeclarationSyntax)member);
                break;
            }

            case SyntaxKind.FieldDeclaration:
            {
                await FieldDeclarationRefactoring.ComputeRefactoringsAsync(context, (FieldDeclarationSyntax)member).ConfigureAwait(false);

                break;
            }

            case SyntaxKind.EventDeclaration:
            {
                await EventDeclarationRefactoring.ComputeRefactoringsAsync(context, (EventDeclarationSyntax)member).ConfigureAwait(false);

                break;
            }

            case SyntaxKind.EventFieldDeclaration:
            {
                await EventFieldDeclarationRefactoring.ComputeRefactoringsAsync(context, (EventFieldDeclarationSyntax)member).ConfigureAwait(false);

                break;
            }
            }

            if (context.IsRefactoringEnabled(RefactoringIdentifiers.MoveUnsafeContextToContainingDeclaration))
            {
                MoveUnsafeContextToContainingDeclarationRefactoring.ComputeRefactoring(context, member);
            }
        }
Exemple #22
0
        public static async Task ComputeRefactoringAsync(RefactoringContext context, StatementListSelection selectedStatements)
        {
            if (context.IsRefactoringEnabled(RefactoringDescriptors.WrapStatementsInUsingStatement))
            {
                var refactoring = new WrapStatementsInUsingStatementRefactoring();
                await refactoring.ComputeRefactoringAsync(context, selectedStatements).ConfigureAwait(false);
            }

            if (context.IsRefactoringEnabled(RefactoringDescriptors.UseObjectInitializer))
            {
                await UseObjectInitializerRefactoring.ComputeRefactoringsAsync(context, selectedStatements).ConfigureAwait(false);
            }

            if (context.IsRefactoringEnabled(RefactoringDescriptors.MergeIfStatements))
            {
                MergeIfStatementsRefactoring.ComputeRefactorings(context, selectedStatements);
            }

            if (context.IsRefactoringEnabled(RefactoringDescriptors.ConvertStatementsToIfElse))
            {
                ConvertStatementsToIfElseRefactoring.ComputeRefactorings(context, selectedStatements);
            }

            if (context.IsAnyRefactoringEnabled(
                    RefactoringDescriptors.UseCoalesceExpressionInsteadOfIf,
                    RefactoringDescriptors.ConvertIfToConditionalExpression,
                    RefactoringDescriptors.SimplifyIf))
            {
                SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false);

                IfAnalysisOptions options = IfStatementRefactoring.GetIfAnalysisOptions(context);

                foreach (IfAnalysis analysis in IfAnalysis.Analyze(selectedStatements, options, semanticModel, context.CancellationToken))
                {
                    RefactoringDescriptor refactoring = IfStatementRefactoring.GetRefactoringDescriptor(analysis);

                    if (context.IsRefactoringEnabled(refactoring))
                    {
                        context.RegisterRefactoring(
                            analysis.Title,
                            ct => IfRefactoring.RefactorAsync(context.Document, analysis, ct),
                            refactoring);
                    }
                }
            }

            if (context.IsRefactoringEnabled(RefactoringDescriptors.MergeLocalDeclarations))
            {
                await MergeLocalDeclarationsRefactoring.ComputeRefactoringsAsync(context, selectedStatements).ConfigureAwait(false);
            }

            if (context.IsRefactoringEnabled(RefactoringDescriptors.RemoveUnnecessaryAssignment))
            {
                RemoveUnnecessaryAssignmentRefactoring.ComputeRefactorings(context, selectedStatements);
            }

            if (context.IsRefactoringEnabled(RefactoringDescriptors.CheckExpressionForNull))
            {
                await CheckExpressionForNullRefactoring.ComputeRefactoringAsync(context, selectedStatements).ConfigureAwait(false);
            }

            if (context.IsRefactoringEnabled(RefactoringDescriptors.ConvertWhileToFor))
            {
                await ConvertWhileToForRefactoring.ComputeRefactoringAsync(context, selectedStatements).ConfigureAwait(false);
            }

            if (context.IsRefactoringEnabled(RefactoringDescriptors.WrapStatementsInCondition))
            {
                context.RegisterRefactoring(
                    WrapInIfStatementRefactoring.Title,
                    ct => WrapInIfStatementRefactoring.Instance.RefactorAsync(context.Document, selectedStatements, ct),
                    RefactoringDescriptors.WrapStatementsInCondition);
            }

            if (context.IsRefactoringEnabled(RefactoringDescriptors.WrapLinesInTryCatch))
            {
                context.RegisterRefactoring(
                    WrapLinesInTryCatchRefactoring.Title,
                    ct => WrapLinesInTryCatchRefactoring.Instance.RefactorAsync(context.Document, selectedStatements, ct),
                    RefactoringDescriptors.WrapLinesInTryCatch);
            }
        }
        public static async Task ComputeRefactoringsAsync(RefactoringContext context, InvocationExpressionSyntax invocationExpression)
        {
            if (context.IsAnyRefactoringEnabled(
                    RefactoringIdentifiers.UseElementAccessInsteadOfEnumerableMethod,
                    RefactoringIdentifiers.ReplaceAnyWithAllOrAllWithAny,
                    RefactoringIdentifiers.CallExtensionMethodAsInstanceMethod,
                    RefactoringIdentifiers.ReplaceStringContainsWithStringIndexOf))
            {
                ExpressionSyntax expression = invocationExpression.Expression;

                if (expression != null &&
                    invocationExpression.ArgumentList != null)
                {
                    if (expression.IsKind(SyntaxKind.SimpleMemberAccessExpression) &&
                        ((MemberAccessExpressionSyntax)expression).Name?.Span.Contains(context.Span) == true)
                    {
                        if (context.IsRefactoringEnabled(RefactoringIdentifiers.UseElementAccessInsteadOfEnumerableMethod))
                        {
                            await UseElementAccessInsteadOfEnumerableMethodRefactoring.ComputeRefactoringsAsync(context, invocationExpression).ConfigureAwait(false);
                        }

                        if (context.IsRefactoringEnabled(RefactoringIdentifiers.ReplaceAnyWithAllOrAllWithAny))
                        {
                            await ReplaceAnyWithAllOrAllWithAnyRefactoring.ComputeRefactoringAsync(context, invocationExpression).ConfigureAwait(false);
                        }

                        if (context.IsRefactoringEnabled(RefactoringIdentifiers.ReplaceStringContainsWithStringIndexOf))
                        {
                            await ReplaceStringContainsWithStringIndexOfRefactoring.ComputeRefactoringAsync(context, invocationExpression).ConfigureAwait(false);
                        }
                    }

                    if (context.IsRefactoringEnabled(RefactoringIdentifiers.CallExtensionMethodAsInstanceMethod))
                    {
                        SyntaxNodeOrToken nodeOrToken = CallExtensionMethodAsInstanceMethodAnalysis.GetNodeOrToken(expression);

                        if (nodeOrToken.Span.Contains(context.Span))
                        {
                            SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false);

                            CallExtensionMethodAsInstanceMethodAnalysisResult analysis = CallExtensionMethodAsInstanceMethodAnalysis.Analyze(invocationExpression, semanticModel, allowAnyExpression: true, cancellationToken: context.CancellationToken);

                            if (analysis.Success)
                            {
                                context.RegisterRefactoring(
                                    CallExtensionMethodAsInstanceMethodRefactoring.Title,
                                    cancellationToken =>
                                {
                                    return(context.Document.ReplaceNodeAsync(
                                               analysis.InvocationExpression,
                                               analysis.NewInvocationExpression,
                                               cancellationToken));
                                });
                            }
                        }
                    }
                }
            }

            if (context.IsRefactoringEnabled(RefactoringIdentifiers.ReplaceStringFormatWithInterpolatedString) &&
                context.SupportsCSharp6)
            {
                await ReplaceStringFormatWithInterpolatedStringRefactoring.ComputeRefactoringsAsync(context, invocationExpression).ConfigureAwait(false);
            }

            if (context.IsRefactoringEnabled(RefactoringIdentifiers.UseBitwiseOperationInsteadOfCallingHasFlag))
            {
                SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false);

                if (UseBitwiseOperationInsteadOfCallingHasFlagAnalysis.IsFixable(invocationExpression, semanticModel, context.CancellationToken))
                {
                    context.RegisterRefactoring(
                        UseBitwiseOperationInsteadOfCallingHasFlagRefactoring.Title,
                        cancellationToken =>
                    {
                        return(UseBitwiseOperationInsteadOfCallingHasFlagRefactoring.RefactorAsync(
                                   context.Document,
                                   invocationExpression,
                                   cancellationToken));
                    });
                }
            }

            if (context.IsRefactoringEnabled(RefactoringIdentifiers.InlineMethod))
            {
                await InlineMethodRefactoring.ComputeRefactoringsAsync(context, invocationExpression).ConfigureAwait(false);
            }
        }
Exemple #24
0
        public static async Task ComputeRefactoringsAsync(RefactoringContext context, YieldStatementSyntax yieldStatement)
        {
            if (context.IsAnyRefactoringEnabled(
                    RefactoringIdentifiers.ChangeMemberTypeAccordingToYieldReturnExpression,
                    RefactoringIdentifiers.AddCastExpression,
                    RefactoringIdentifiers.CallToMethod) &&
                yieldStatement.IsYieldReturn() &&
                yieldStatement.Expression != null)
            {
                SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false);

                ISymbol memberSymbol = ReturnExpressionRefactoring.GetContainingMethodOrPropertySymbol(yieldStatement.Expression, semanticModel, context.CancellationToken);

                if (memberSymbol != null)
                {
                    SyntaxNode node = await memberSymbol
                                      .DeclaringSyntaxReferences[0]
                                      .GetSyntaxAsync(context.CancellationToken)
                                      .ConfigureAwait(false);

                    var containingMember = node as MemberDeclarationSyntax;

                    TypeSyntax memberType = ReturnExpressionRefactoring.GetMemberType(containingMember);

                    if (memberType != null)
                    {
                        ITypeSymbol memberTypeSymbol = semanticModel.GetTypeSymbol(memberType, context.CancellationToken);

                        if (memberTypeSymbol?.SpecialType != SpecialType.System_Collections_IEnumerable)
                        {
                            ITypeSymbol typeSymbol = semanticModel.GetTypeSymbol(yieldStatement.Expression, context.CancellationToken);

                            if (context.IsRefactoringEnabled(RefactoringIdentifiers.ChangeMemberTypeAccordingToYieldReturnExpression) &&
                                typeSymbol?.IsErrorType() == false &&
                                !typeSymbol.IsVoid() &&
                                !memberSymbol.IsOverride &&
                                (memberTypeSymbol == null ||
                                 memberTypeSymbol.IsErrorType() ||
                                 !memberTypeSymbol.IsConstructedFromIEnumerableOfT() ||
                                 !((INamedTypeSymbol)memberTypeSymbol).TypeArguments[0].Equals(typeSymbol)))
                            {
                                INamedTypeSymbol newTypeSymbol = semanticModel
                                                                 .Compilation
                                                                 .GetSpecialType(SpecialType.System_Collections_Generic_IEnumerable_T)
                                                                 .Construct(typeSymbol);

                                TypeSyntax newType = newTypeSymbol.ToMinimalTypeSyntax(semanticModel, memberType.SpanStart);

                                context.RegisterRefactoring(
                                    $"Change {ReturnExpressionRefactoring.GetText(containingMember)} type to '{SymbolDisplay.GetMinimalString(newTypeSymbol, semanticModel, memberType.SpanStart)}'",
                                    cancellationToken =>
                                {
                                    return(ChangeTypeRefactoring.ChangeTypeAsync(
                                               context.Document,
                                               memberType,
                                               newType,
                                               cancellationToken));
                                });
                            }

                            if (context.IsAnyRefactoringEnabled(RefactoringIdentifiers.AddCastExpression, RefactoringIdentifiers.CallToMethod) &&
                                yieldStatement.Expression.Span.Contains(context.Span) &&
                                memberTypeSymbol?.IsNamedType() == true)
                            {
                                var namedTypeSymbol = (INamedTypeSymbol)memberTypeSymbol;

                                if (namedTypeSymbol.IsConstructedFromIEnumerableOfT())
                                {
                                    ITypeSymbol argumentSymbol = namedTypeSymbol.TypeArguments[0];

                                    if (argumentSymbol != typeSymbol)
                                    {
                                        ModifyExpressionRefactoring.ComputeRefactoring(
                                            context,
                                            yieldStatement.Expression,
                                            argumentSymbol,
                                            semanticModel);
                                    }
                                }
                            }
                        }
                    }
                }
            }

            if (context.IsRefactoringEnabled(RefactoringIdentifiers.ReplaceStatementWithIfStatement) &&
                context.Span.IsBetweenSpans(yieldStatement))
            {
                var refactoring = new ReplaceYieldStatementWithIfStatementRefactoring();
                await refactoring.ComputeRefactoringAsync(context, yieldStatement).ConfigureAwait(false);
            }
        }
Exemple #25
0
        public static async Task ComputeRefactoringsAsync(RefactoringContext context, IfStatementSyntax ifStatement)
        {
            SyntaxToken ifKeyword = ifStatement.IfKeyword;

            bool isTopmostIf = ifStatement.IsTopmostIf();

            if (context.Span.IsEmptyAndContainedInSpan(ifKeyword) ||
                context.Span.IsBetweenSpans(ifStatement))
            {
                if (isTopmostIf &&
                    context.IsAnyRefactoringEnabled(
                        RefactoringIdentifiers.UseCoalesceExpressionInsteadOfIf,
                        RefactoringIdentifiers.ConvertIfToConditionalOperator,
                        RefactoringIdentifiers.SimplifyIf))
                {
                    SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false);

                    IfAnalysisOptions options = GetIfAnalysisOptions(context);

                    foreach (IfAnalysis analysis in IfAnalysis.Analyze(ifStatement, options, semanticModel, context.CancellationToken))
                    {
                        string refactoringId = GetRefactoringIdentifier(analysis);

                        if (context.IsRefactoringEnabled(refactoringId))
                        {
                            context.RegisterRefactoring(
                                analysis.Title,
                                ct => IfRefactoring.RefactorAsync(context.Document, analysis, ct),
                                refactoringId);
                        }
                    }
                }

                if (context.IsAnyRefactoringEnabled(RefactoringIdentifiers.InvertIf, RefactoringIdentifiers.InvertIfElse) &&
                    context.Span.IsEmptyAndContainedInSpan(ifKeyword))
                {
                    InvertIfRefactoring.ComputeRefactoring(context, ifStatement);
                }

                if (context.IsRefactoringEnabled(RefactoringIdentifiers.ConvertIfToSwitch) &&
                    isTopmostIf)
                {
                    SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false);

                    ConvertIfToSwitchRefactoring.ComputeRefactoring(context, ifStatement, semanticModel);
                }

                if (context.IsRefactoringEnabled(RefactoringIdentifiers.SplitIfStatement))
                {
                    SplitIfStatementRefactoring.ComputeRefactoring(context, ifStatement);
                }

                if (context.IsRefactoringEnabled(RefactoringIdentifiers.MergeIfWithParentIf) &&
                    isTopmostIf &&
                    context.Span.IsEmptyAndContainedInSpan(ifKeyword))
                {
                    MergeIfWithParentIfRefactoring.ComputeRefactoring(context, ifStatement);
                }
            }

            if (context.IsRefactoringEnabled(RefactoringIdentifiers.InvertIf) &&
                context.Span.IsEmptyAndContainedInSpan(ifKeyword))
            {
                SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false);

                ReduceIfNestingAnalysisResult analysis = ReduceIfNestingAnalysis.Analyze(
                    ifStatement,
                    semanticModel,
                    options: ReduceIfNestingOptions.AllowNestedFix
                    | ReduceIfNestingOptions.AllowIfInsideIfElse
                    | ReduceIfNestingOptions.AllowLoop
                    | ReduceIfNestingOptions.AllowSwitchSection,
                    cancellationToken: context.CancellationToken);

                if (analysis.Success)
                {
                    context.RegisterRefactoring(
                        "Invert if",
                        ct => ReduceIfNestingRefactoring.RefactorAsync(context.Document, ifStatement, analysis.JumpKind, false, ct),
                        RefactoringIdentifiers.InvertIf);

                    if (ReduceIfNestingAnalysis.IsFixableRecursively(ifStatement, analysis.JumpKind))
                    {
                        context.RegisterRefactoring(
                            "Invert if (recursively)",
                            ct => ReduceIfNestingRefactoring.RefactorAsync(context.Document, ifStatement, analysis.JumpKind, true, ct),
                            EquivalenceKey.Join(RefactoringIdentifiers.InvertIf, "Recursive"));
                    }
                }
            }

            if (context.IsRefactoringEnabled(RefactoringIdentifiers.SplitIfElse) &&
                context.Span.IsEmptyAndContainedInSpan(ifKeyword))
            {
                SplitIfElseRefactoring.ComputeRefactoring(context, ifStatement);
            }
        }
Exemple #26
0
        public static void ComputeRefactorings(RefactoringContext context, SwitchStatementSyntax switchStatement)
        {
            bool fRemoveStatements = context.IsRefactoringEnabled(RefactoringIdentifiers.RemoveStatementsFromSwitchSections);
            bool fAddBraces        = context.IsRefactoringEnabled(RefactoringIdentifiers.AddBracesToSwitchSections);
            bool fRemoveBraces     = context.IsRefactoringEnabled(RefactoringIdentifiers.RemoveBracesFromSwitchSections);

            if (fRemoveStatements || fAddBraces || fRemoveBraces)
            {
                SyntaxListSelection <SwitchSectionSyntax> selectedSections;
                if (SyntaxListSelection <SwitchSectionSyntax> .TryCreate(switchStatement.Sections, context.Span, out selectedSections))
                {
                    if (fAddBraces || fRemoveBraces)
                    {
                        var addBraces    = new List <SwitchSectionSyntax>();
                        var removeBraces = new List <SwitchSectionSyntax>();

                        foreach (SwitchSectionSyntax section in selectedSections)
                        {
                            if (addBraces.Count > 0 &&
                                removeBraces.Count > 0)
                            {
                                break;
                            }

                            switch (CSharpAnalysis.AnalyzeBraces(section))
                            {
                            case BracesAnalysisResult.AddBraces:
                            {
                                addBraces.Add(section);
                                break;
                            }

                            case BracesAnalysisResult.RemoveBraces:
                            {
                                removeBraces.Add(section);
                                break;
                            }
                            }
                        }

                        if (fAddBraces && addBraces.Count > 0)
                        {
                            string title = AddBracesToSwitchSectionRefactoring.Title;

                            if (addBraces.Count > 1)
                            {
                                title += "s";
                            }

                            context.RegisterRefactoring(
                                title,
                                cancellationToken =>
                            {
                                return(AddBracesToSwitchSectionsRefactoring.RefactorAsync(
                                           context.Document,
                                           switchStatement,
                                           addBraces.ToArray(),
                                           cancellationToken));
                            });
                        }

                        if (fRemoveBraces && removeBraces.Count > 0)
                        {
                            string title = RemoveBracesFromSwitchSectionRefactoring.Title;

                            if (removeBraces.Count > 1)
                            {
                                title += "s";
                            }

                            context.RegisterRefactoring(
                                title,
                                cancellationToken =>
                            {
                                return(RemoveBracesFromSwitchSectionsRefactoring.RefactorAsync(
                                           context.Document,
                                           switchStatement,
                                           removeBraces.ToArray(),
                                           cancellationToken));
                            });
                        }
                    }

                    if (fRemoveStatements)
                    {
                        string title = "Remove statements from section";

                        if (selectedSections.Count > 1)
                        {
                            title += "s";
                        }

                        context.RegisterRefactoring(
                            title,
                            cancellationToken =>
                        {
                            return(RemoveStatementsFromSwitchSectionsRefactoring.RefactorAsync(
                                       context.Document,
                                       switchStatement,
                                       selectedSections.ToImmutableArray(),
                                       cancellationToken));
                        });
                    }
                }
            }
        }
 public static bool IsAnyRefactoringEnabled(RefactoringContext context)
 {
     return(context.IsRefactoringEnabled(RefactoringIdentifiers.WrapInUsingStatement) ||
            context.IsRefactoringEnabled(RefactoringIdentifiers.CollapseToInitializer) ||
            context.IsRefactoringEnabled(RefactoringIdentifiers.MergeIfStatements) ||
            context.IsRefactoringEnabled(RefactoringIdentifiers.MergeLocalDeclarations) ||
            context.IsRefactoringEnabled(RefactoringIdentifiers.WrapInCondition) ||
            context.IsRefactoringEnabled(RefactoringIdentifiers.WrapInTryCatch) ||
            context.IsRefactoringEnabled(RefactoringIdentifiers.UseCoalesceExpressionInsteadOfIf) ||
            context.IsRefactoringEnabled(RefactoringIdentifiers.UseConditionalExpressionInsteadOfIf) ||
            context.IsRefactoringEnabled(RefactoringIdentifiers.SimplifyIf) ||
            context.IsRefactoringEnabled(RefactoringIdentifiers.CheckExpressionForNull) ||
            context.IsRefactoringEnabled(RefactoringIdentifiers.ReplaceWhileWithFor));
 }
Exemple #28
0
        public static void ComputeRefactorings(RefactoringContext context, LiteralExpressionSyntax literalExpression)
        {
            if (!literalExpression.Span.Contains(context.Span))
            {
                return;
            }

            if (context.IsRefactoringEnabled(RefactoringIdentifiers.InsertStringInterpolation) &&
                context.SupportsCSharp6 &&
                context.Span.End < literalExpression.Span.End)
            {
                int startIndex = GetStartIndex(context, literalExpression);

                if (startIndex != -1)
                {
                    context.RegisterRefactoring(
                        "Insert interpolation",
                        cancellationToken =>
                    {
                        return(ReplaceStringLiteralRefactoring.ReplaceWithInterpolatedStringAsync(
                                   context.Document,
                                   literalExpression,
                                   startIndex,
                                   context.Span.Length,
                                   cancellationToken));
                    });
                }
            }

            if (context.Span.IsBetweenSpans(literalExpression))
            {
                string text = SyntaxUtility.GetStringLiteralInnerText(literalExpression);

                if (literalExpression.IsVerbatimStringLiteral())
                {
                    if (text.Contains("\"\""))
                    {
                        if (context.IsRefactoringEnabled(RefactoringIdentifiers.ReplaceVerbatimStringLiteralWithRegularStringLiteral))
                        {
                            context.RegisterRefactoring(
                                "Replace verbatim string literal with regular string literal",
                                cancellationToken =>
                            {
                                return(ReplaceStringLiteralRefactoring.ReplaceWithRegularStringLiteralAsync(
                                           context.Document,
                                           literalExpression,
                                           cancellationToken));
                            });
                        }

                        if (context.IsRefactoringEnabled(RefactoringIdentifiers.ReplaceVerbatimStringLiteralWithRegularStringLiterals) &&
                            text.Contains("\n"))
                        {
                            context.RegisterRefactoring(
                                "Replace verbatim string literal with regular string literals",
                                cancellationToken =>
                            {
                                return(ReplaceStringLiteralRefactoring.ReplaceWithRegularStringLiteralsAsync(
                                           context.Document,
                                           literalExpression,
                                           cancellationToken));
                            });
                        }
                    }
                }
                else if (context.IsRefactoringEnabled(RefactoringIdentifiers.ReplaceRegularStringLiteralWithVerbatimStringLiteral) &&
                         text.Contains(@"\"))
                {
                    context.RegisterRefactoring(
                        "Replace regular string literal with verbatim string literal",
                        cancellationToken =>
                    {
                        return(ReplaceStringLiteralRefactoring.ReplaceWithVerbatimStringLiteralAsync(
                                   context.Document,
                                   literalExpression,
                                   cancellationToken));
                    });
                }
            }

            if (context.IsRefactoringEnabled(RefactoringIdentifiers.ReplaceEmptyStringLiteralWithStringEmpty) &&
                ReplaceStringLiteralRefactoring.CanReplaceWithStringEmpty(literalExpression))
            {
                context.RegisterRefactoring(
                    "Replace \"\" with 'string.Empty'",
                    cancellationToken =>
                {
                    return(ReplaceStringLiteralRefactoring.ReplaceWithStringEmptyAsync(
                               context.Document,
                               literalExpression,
                               cancellationToken));
                });
            }

            if (context.IsRefactoringEnabled(RefactoringIdentifiers.ReplaceStringLiteralWithCharacterLiteral) &&
                ReplaceStringLiteralRefactoring.CanReplaceWithCharacterLiteral(literalExpression))
            {
                context.RegisterRefactoring(
                    "Replace string literal with character literal",
                    cancellationToken =>
                {
                    return(ReplaceStringLiteralRefactoring.ReplaceWithCharacterLiteralAsync(
                               context.Document,
                               literalExpression,
                               cancellationToken));
                });
            }
        }
        public static async Task ComputeRefactoringsAsync(RefactoringContext context, ExpressionSyntax expression)
        {
            if (expression != null &&
                context.SupportsSemanticModel)
            {
                MemberDeclarationSyntax declaration = GetContainingMethodOrPropertyOrIndexer(expression);

                if (declaration != null)
                {
                    TypeSyntax memberType = GetMemberType(declaration);

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

                        ITypeSymbol memberTypeSymbol = semanticModel
                                                       .GetTypeInfo(memberType, context.CancellationToken)
                                                       .Type;

                        if (memberTypeSymbol != null)
                        {
                            ITypeSymbol expressionSymbol = semanticModel
                                                           .GetTypeInfo(expression, context.CancellationToken)
                                                           .Type;

                            if (expressionSymbol?.IsErrorType() == false)
                            {
                                if (context.IsRefactoringEnabled(RefactoringIdentifiers.AddBooleanComparison) &&
                                    memberTypeSymbol.IsBoolean() &&
                                    expressionSymbol.IsNamedType())
                                {
                                    var namedTypeSymbol = (INamedTypeSymbol)expressionSymbol;

                                    if (namedTypeSymbol?.IsNullableOf(SpecialType.System_Boolean) == true)
                                    {
                                        AddBooleanComparisonRefactoring.RegisterRefactoring(context, expression);
                                    }
                                }

                                ISymbol memberSymbol = semanticModel.GetDeclaredSymbol(declaration, context.CancellationToken);

                                if (context.IsRefactoringEnabled(RefactoringIdentifiers.ChangeMemberTypeAccordingToReturnExpression))
                                {
                                    ITypeSymbol newType = GetMemberNewType(memberSymbol, memberTypeSymbol, expression, expressionSymbol, semanticModel, context.CancellationToken);

                                    if (newType?.IsErrorType() == false &&
                                        !memberTypeSymbol.Equals(newType))
                                    {
                                        if (newType.IsNamedType() && memberTypeSymbol.IsNamedType())
                                        {
                                            var newNamedType = (INamedTypeSymbol)newType;

                                            INamedTypeSymbol orderedEnumerableSymbol = semanticModel.Compilation.GetTypeByMetadataName("System.Linq.IOrderedEnumerable`1");

                                            if (newNamedType.ConstructedFrom == orderedEnumerableSymbol)
                                            {
                                                INamedTypeSymbol enumerableSymbol = semanticModel.Compilation.GetTypeByMetadataName("System.Collections.Generic.IEnumerable`1");

                                                if (enumerableSymbol != null &&
                                                    ((INamedTypeSymbol)memberTypeSymbol).ConstructedFrom != enumerableSymbol)
                                                {
                                                    RegisterChangeType(context, declaration, memberType, enumerableSymbol.Construct(newNamedType.TypeArguments.ToArray()));
                                                }
                                            }
                                        }

                                        RegisterChangeType(context, declaration, memberType, newType);
                                    }
                                }

                                if (context.IsAnyRefactoringEnabled(RefactoringIdentifiers.AddCastExpression, RefactoringIdentifiers.CallToMethod) &&
                                    !memberTypeSymbol.IsErrorType())
                                {
                                    ITypeSymbol castTypeSymbol = GetCastTypeSymbol(memberSymbol, memberTypeSymbol, expressionSymbol, semanticModel);

                                    if (castTypeSymbol != null)
                                    {
                                        ModifyExpressionRefactoring.ComputeRefactoring(
                                            context,
                                            expression,
                                            castTypeSymbol,
                                            semanticModel);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
Exemple #30
0
        public static async Task ComputeRefactoringsAsync(RefactoringContext context, LiteralExpressionSyntax literalExpression)
        {
            StringLiteralExpressionInfo info = SyntaxInfo.StringLiteralExpressionInfo(literalExpression);

            Debug.Assert(info.Success);

            if (!info.Success)
            {
                return;
            }

            if (context.IsRefactoringEnabled(RefactoringIdentifiers.InsertStringInterpolation) &&
                context.SupportsCSharp6 &&
                context.Span.End < literalExpression.Span.End)
            {
                int startIndex = GetStartIndex(info, context.Span);

                if (startIndex != -1)
                {
                    context.RegisterRefactoring(
                        "Insert interpolation",
                        cancellationToken =>
                    {
                        return(ReplaceWithInterpolatedStringAsync(
                                   context.Document,
                                   literalExpression,
                                   startIndex,
                                   context.Span.Length,
                                   addNameOf: false,
                                   cancellationToken: cancellationToken));
                    });

                    if (!context.Span.IsEmpty)
                    {
                        SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false);

                        string name = StringLiteralParser.Parse(literalExpression.Token.Text, startIndex, context.Span.Length, info.IsVerbatim, isInterpolatedText: false);

                        foreach (ISymbol symbol in semanticModel.LookupSymbols(literalExpression.SpanStart))
                        {
                            if (string.Equals(name, symbol.MetadataName, StringComparison.Ordinal))
                            {
                                context.RegisterRefactoring(
                                    "Insert interpolation with nameof",
                                    cancellationToken =>
                                {
                                    return(ReplaceWithInterpolatedStringAsync(
                                               context.Document,
                                               literalExpression,
                                               startIndex,
                                               context.Span.Length,
                                               addNameOf: true,
                                               cancellationToken: cancellationToken));
                                });

                                break;
                            }
                        }
                    }
                }
            }

            if (context.Span.IsBetweenSpans(literalExpression))
            {
                if (info.IsVerbatim)
                {
                    if (info.ContainsEscapeSequence)
                    {
                        if (context.IsRefactoringEnabled(RefactoringIdentifiers.ReplaceVerbatimStringLiteralWithRegularStringLiteral))
                        {
                            context.RegisterRefactoring(
                                "Replace verbatim string literal with regular string literal",
                                ct => ReplaceWithRegularStringLiteralAsync(context.Document, literalExpression, ct));
                        }

                        if (context.IsRefactoringEnabled(RefactoringIdentifiers.ReplaceVerbatimStringLiteralWithRegularStringLiterals) &&
                            info.ContainsLinefeed)
                        {
                            context.RegisterRefactoring(
                                "Replace verbatim string literal with regular string literals",
                                ct => ReplaceWithRegularStringLiteralsAsync(context.Document, literalExpression, ct));
                        }
                    }
                }
                else if (context.IsRefactoringEnabled(RefactoringIdentifiers.ReplaceRegularStringLiteralWithVerbatimStringLiteral) &&
                         info.ContainsEscapeSequence)
                {
                    context.RegisterRefactoring(
                        "Replace regular string literal with verbatim string literal",
                        ct => ReplaceWithVerbatimStringLiteralAsync(context.Document, literalExpression, ct));
                }
            }

            if (context.IsRefactoringEnabled(RefactoringIdentifiers.UseStringEmptyInsteadOfEmptyStringLiteral) &&
                CanReplaceWithStringEmpty(literalExpression))
            {
                context.RegisterRefactoring(
                    "Replace \"\" with 'string.Empty'",
                    ct => ReplaceWithStringEmptyAsync(context.Document, literalExpression, ct));
            }
        }