public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
        {
            var diagnostic = context.Diagnostics.First();
            var serializedNamingStyle = diagnostic.Properties[nameof(NamingStyle)];
            var style = NamingStyle.FromXElement(XElement.Parse(serializedNamingStyle));

            var document = context.Document;
            var span = context.Span;

            var root = await document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);
            var node = root.FindNode(span);
            var model = await document.GetSemanticModelAsync(context.CancellationToken).ConfigureAwait(false);
            var symbol = model.GetDeclaredSymbol(node, context.CancellationToken);

            var fixedNames = style.MakeCompliant(symbol.Name);
            foreach (var fixedName in fixedNames)
            {
                var solution = context.Document.Project.Solution;
                context.RegisterCodeFix(
                    new FixNameCodeAction(
                        string.Format(FeaturesResources.FixNamingViolation, fixedName),
                        async c => await Renamer.RenameSymbolAsync(
                            solution,
                            symbol,
                            fixedName,
                            document.Options,
                            c).ConfigureAwait(false), 
                        nameof(AbstractNamingStyleCodeFixProvider)), 
                    diagnostic);
            }
        }
        public override Task RegisterCodeFixesAsync(CodeFixContext context)
        {
            context.RegisterCodeFix(
                new PreferFrameworkTypeCodeAction(
                    FeaturesResources.Use_framework_type,
                    c => CreateChangedDocumentAsync(context.Document, context.Span, c)),
                context.Diagnostics);

            return SpecializedTasks.EmptyTask;
        }
Esempio n. 3
0
 private void RegisterSuppressionFixes(CodeFixContext context, IEnumerable<CodeFix> suppressionFixes)
 {
     if (suppressionFixes != null)
     {
         foreach (var suppressionFix in suppressionFixes)
         {
             context.RegisterCodeFix(suppressionFix.Action, suppressionFix.Diagnostics);
         }
     }
 }
        public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
        {
            var document = context.Document;
            var span = context.Span;
            var diagnostics = context.Diagnostics;
            var cancellationToken = context.CancellationToken;

            var project = document.Project;
            var diagnostic = diagnostics.First();
            var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
            var node = root.FindToken(span.Start).GetAncestors<SyntaxNode>().First(n => n.Span.Contains(span));

            using (Logger.LogBlock(FunctionId.Refactoring_FullyQualify, cancellationToken))
            {
                // Has to be a simple identifier or generic name.
                if (node == null || !CanFullyQualify(diagnostic, ref node))
                {
                    return;
                }

                var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);

                var matchingTypes = await this.GetMatchingTypesAsync(project, semanticModel, node, cancellationToken).ConfigureAwait(false);
                var matchingNamespaces = await this.GetMatchingNamespacesAsync(project, semanticModel, node, cancellationToken).ConfigureAwait(false);

                if (matchingTypes.IsEmpty && matchingNamespaces.IsEmpty)
                {
                    return;
                }

                var matchingTypeContainers = FilterAndSort(GetContainers(matchingTypes, semanticModel.Compilation));
                var matchingNamespaceContainers = FilterAndSort(GetContainers(matchingNamespaces, semanticModel.Compilation));

                var proposedContainers =
                    matchingTypeContainers.Concat(matchingNamespaceContainers)
                                            .Distinct()
                                            .Take(MaxResults);

                var displayService = project.LanguageServices.GetService<ISymbolDisplayService>();
                var codeActions = CreateActions(context, document, diagnostic, node, semanticModel, proposedContainers, displayService).ToImmutableArray();

                if (codeActions.Length > 1)
                {
                    // Wrap the spell checking actions into a single top level suggestion
                    // so as to not clutter the list.
                    context.RegisterCodeFix(new GroupingCodeAction(
                        string.Format(FeaturesResources.Fully_qualify_0, GetNodeName(document, node)),
                        codeActions), context.Diagnostics);
                }
                else
                {
                    context.RegisterFixes(codeActions, context.Diagnostics);
                }
            }
        }
Esempio n. 5
0
 public async override Task RegisterCodeFixesAsync(CodeFixContext context)
 {
     var diagnostics = context.Diagnostics.WhereAsArray(_suppressionFixProvider.CanBeSuppressedOrUnsuppressed);
     var suppressionFixes = await _suppressionFixProvider.GetSuppressionsAsync(context.Document, context.Span, diagnostics, context.CancellationToken).ConfigureAwait(false);
     if (suppressionFixes != null)
     {
         foreach (var suppressionFix in suppressionFixes)
         {
             context.RegisterCodeFix(suppressionFix.Action, suppressionFix.Diagnostics);
         }
     }
 }
        public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
        {
            var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);
            if (!TryGetNode(root, context.Span, out var node))
            {
                return;
            }

            var diagnostic = context.Diagnostics.FirstOrDefault();

            var codeAction = await GetCodeFixAsync(root, node, context.Document, diagnostic, context.CancellationToken).ConfigureAwait(false);

            if (codeAction != null)
            {
                context.RegisterCodeFix(codeAction, diagnostic);
            }
        }
        public sealed override Task RegisterCodeFixesAsync(CodeFixContext context)
        {
            var project = context.Document.Project;
            var publicSurfaceAreaDocument = PublicApiFixHelpers.GetUnshippedDocument(project);

            foreach (Diagnostic diagnostic in context.Diagnostics)
            {
                string minimalSymbolName           = diagnostic.Properties[DeclarePublicApiAnalyzer.MinimalNamePropertyBagKey];
                string publicSurfaceAreaSymbolName = diagnostic.Properties[DeclarePublicApiAnalyzer.PublicApiNamePropertyBagKey];
                ImmutableHashSet <string> siblingSymbolNamesToRemove = diagnostic.Properties[DeclarePublicApiAnalyzer.PublicApiNamesOfSiblingsToRemovePropertyBagKey]
                                                                       .Split(DeclarePublicApiAnalyzer.PublicApiNamesOfSiblingsToRemovePropertyBagValueSeparator.ToCharArray())
                                                                       .ToImmutableHashSet();

                context.RegisterCodeFix(
                    new AdditionalDocumentChangeAction(
                        $"Add {minimalSymbolName} to public API",
                        c => GetFixAsync(publicSurfaceAreaDocument, project, publicSurfaceAreaSymbolName, siblingSymbolNamesToRemove, c)),
                    diagnostic);
            }

            return(Task.CompletedTask);
        }
        public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
        {
            SyntaxNode root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);

            Diagnostic diagnostic     = context.Diagnostics.First();
            TextSpan   diagnosticSpan = diagnostic.Location.SourceSpan;

            // find the node which is the "TestContext" type identifier
            // the parent of the parent is the declaration we want to remove
            if (root != null)
            {
                SyntaxNode node = root.FindToken(diagnosticSpan.Start).Parent;

                // Register a code action that will invoke the fix.
                context.RegisterCodeFix(
                    CodeAction.Create(
                        title: Title,
                        createChangedDocument: c => TestContextFix(context.Document, node, c),
                        equivalenceKey: Title),
                    diagnostic);
            }
        }
        public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
        {
            var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);

            var diagnostic     = context.Diagnostics.First();
            var diagnosticSpan = diagnostic.Location.SourceSpan;

            var classDecl = root.FindToken(diagnosticSpan.Start).Parent.AncestorsAndSelf().OfType <ClassDeclarationSyntax>().FirstOrDefault();

            if (classDecl == null)
            {
                return;
            }

            // Register a code action that will invoke the fix.
            context.RegisterCodeFix(
                CodeAction.Create(
                    title: Title,
                    createChangedDocument: c => AddAttributeAsync(context.Document, classDecl, c),
                    equivalenceKey: Title),
                diagnostic);
        }
Esempio n. 10
0
        public override async Task RegisterCodeFixesAsync(CodeFixContext context)
        {
            SemanticModel model = await context.Document.GetSemanticModelAsync(context.CancellationToken).ConfigureAwait(false);

            INamedTypeSymbol?flagsAttributeType = model.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemFlagsAttribute);

            if (flagsAttributeType == null)
            {
                return;
            }

            foreach (var diagnostic in context.Diagnostics)
            {
                string fixTitle = diagnostic.Id == EnumWithFlagsAttributeAnalyzer.RuleIdMarkEnumsWithFlags ?
                                  MicrosoftCodeQualityAnalyzersResources.MarkEnumsWithFlagsCodeFix :
                                  MicrosoftCodeQualityAnalyzersResources.DoNotMarkEnumsWithFlagsCodeFix;
                context.RegisterCodeFix(new MyCodeAction(fixTitle,
                                                         async ct => await AddOrRemoveFlagsAttribute(context.Document, context.Span, diagnostic.Id, flagsAttributeType, ct).ConfigureAwait(false),
                                                         equivalenceKey: fixTitle),
                                        diagnostic);
            }
        }
        public override async Task RegisterCodeFixesAsync(CodeFixContext context)
        {
            SemanticModel model = await context.Document.GetSemanticModelAsync(context.CancellationToken).ConfigureAwait(false);

            INamedTypeSymbol flagsAttributeType = WellKnownTypes.FlagsAttribute(model.Compilation);

            if (flagsAttributeType == null)
            {
                return;
            }

            // We cannot have multiple overlapping diagnostics of this id.
            Diagnostic diagnostic = context.Diagnostics.Single();
            string     fixTitle   = diagnostic.Id == EnumWithFlagsAttributeAnalyzer.RuleIdMarkEnumsWithFlags ?
                                    MicrosoftApiDesignGuidelinesAnalyzersResources.MarkEnumsWithFlagsCodeFix :
                                    MicrosoftApiDesignGuidelinesAnalyzersResources.DoNotMarkEnumsWithFlagsCodeFix;

            context.RegisterCodeFix(new MyCodeAction(fixTitle,
                                                     async ct => await AddOrRemoveFlagsAttribute(context.Document, context.Span, diagnostic.Id, flagsAttributeType, ct).ConfigureAwait(false),
                                                     equivalenceKey: fixTitle),
                                    diagnostic);
        }
        public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
        {
            SyntaxNode root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);

            StatementSyntax statement = root
                                        .FindNode(context.Span, getInnermostNodeForTie: true)?
                                        .FirstAncestorOrSelf <StatementSyntax>();

            Debug.Assert(statement != null, $"{nameof(statement)} is null");

            if (statement == null)
            {
                return;
            }

            CodeAction codeAction = CodeAction.Create(
                "Remove unreachable code",
                cancellationToken => Remover.RemoveStatementAsync(context.Document, statement, cancellationToken),
                DiagnosticIdentifiers.RemoveUnreachableCode + EquivalenceKeySuffix);

            context.RegisterCodeFix(codeAction, context.Diagnostics);
        }
        protected sealed override async Task RegisterCodeFixesAsync(SyntaxNode root, CodeFixContext context)
        {
            var diagnostic     = context.Diagnostics.First();
            var diagnosticSpan = diagnostic.Location.SourceSpan;
            var invocation     = root.FindNode(diagnosticSpan, getInnermostNodeForTie: true) as InvocationExpressionSyntax;
            var memberAccess   = invocation?.Expression as MemberAccessExpressionSyntax;

            if (memberAccess == null)
            {
                return;
            }

            context.RegisterCodeFix(
                CodeAction.Create(
                    Title,
                    c =>
            {
                var newRoot = root.ReplaceNode(invocation, memberAccess.Expression.WithTriviaFrom(invocation));
                return(Task.FromResult(context.Document.WithSyntaxRoot(newRoot)));
            }),
                context.Diagnostics);
        }
Esempio n. 14
0
        protected sealed override async Task RegisterCodeFixesAsync(SyntaxNode root, CodeFixContext context)
        {
            var diagnostic     = context.Diagnostics.First();
            var diagnosticSpan = diagnostic.Location.SourceSpan;

            var member = root.FindNode(diagnosticSpan) as MemberDeclarationSyntax;

            if (member == null)
            {
                return;
            }

            context.RegisterCodeFix(
                CodeAction.Create(
                    Title,
                    c =>
            {
                var newRoot = root.RemoveNode(member, SyntaxRemoveOptions.KeepNoTrivia);
                return(Task.FromResult(context.Document.WithSyntaxRoot(newRoot)));
            }),
                context.Diagnostics);
        }
Esempio n. 15
0
        /// <inheritdoc />
        public override async Task RegisterCodeFixesAsync(CodeFixContext context)
        {
            var diagnostic = context.Diagnostics.First();
            var root       = await context.Document.GetSyntaxRootAsync(context.CancellationToken);

            var        node            = root.FindNode(diagnostic.Location.SourceSpan, getInnermostNodeForTie: true);
            SyntaxNode presentArgument = node is VariableDeclaratorSyntax declaratorSyntax?SyntaxFactory.IdentifierName(declaratorSyntax.Identifier)
                                             : node.Parent is InvocationExpressionSyntax ? null // direct GetService result invocation
                : node is NameSyntax ? node
                : node is MemberAccessExpressionSyntax ? node
                : null;

            if (presentArgument != null)
            {
                context.RegisterCodeFix(
                    CodeAction.Create(
                        "Add Assumes.Present after assignment",
                        ct => AppendAfterAssignmentAsync(context, node.FirstAncestorOrSelf <StatementSyntax>(), presentArgument, ct),
                        "After"),
                    diagnostic);
            }
        }
    public override async Task RegisterCodeFixesAsync(CodeFixContext context)
    {
        var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);

        if (root?.FindNode(context.Span, getInnermostNodeForTie: true) is not InvocationExpressionSyntax nodeToFix)
        {
            return;
        }

        if (nodeToFix.Expression is not MemberAccessExpressionSyntax)
        {
            return;
        }

        var title      = "Use StringComparer.Ordinal";
        var codeAction = CodeAction.Create(
            title,
            ct => AddStringComparison(context.Document, nodeToFix, ct),
            equivalenceKey: title);

        context.RegisterCodeFix(codeAction, context.Diagnostics);
    }
Esempio n. 17
0
        public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
        {
            SyntaxNode root = await context.GetSyntaxRootAsync().ConfigureAwait(false);

            if (!TryFindFirstAncestorOrSelf(
                    root,
                    context.Span,
                    out SyntaxNode node,
                    predicate: f => f.IsKind(SyntaxKind.EqualsExpression, SyntaxKind.NotEqualsExpression, SyntaxKind.IsPatternExpression)))
            {
                return;
            }

            Diagnostic diagnostic = context.Diagnostics[0];

            CodeAction codeAction = CodeAction.Create(
                "Use 'is' operator",
                cancellationToken => UseIsOperatorInsteadOfAsOperatorRefactoring.RefactorAsync(context.Document, node, cancellationToken),
                GetEquivalenceKey(diagnostic));

            context.RegisterCodeFix(codeAction, diagnostic);
        }
Esempio n. 18
0
        public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
        {
            var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);

            var diagnostic  = context.Diagnostics.First();
            var name        = diagnostic.Properties[Constants.DiagnosticName];
            var description = diagnostic.Properties[Constants.DiagnosticDescription];

            var param    = root.FindNode(diagnostic.Location.SourceSpan, true) as XmlElementSyntax;
            var newParam = param.WithContent(
                SyntaxFactory.SingletonList <XmlNodeSyntax>(
                    SyntaxFactory.XmlText().WithTextTokens(
                        SyntaxFactory.TokenList(
                            SyntaxFactory.XmlTextLiteral(SyntaxFactory.TriviaList(), description, description, SyntaxFactory.TriviaList())
                            ))));

            context.RegisterCodeFix(
                CodeAction.Create($"Update '{name}' description",
                                  token => Task.FromResult(context.Document.WithSyntaxRoot(root.ReplaceNode(param, newParam))),
                                  string.Concat(diagnostic.Id, name)),
                diagnostic);
        }
        public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
        {
            SyntaxNode root = await context.Document
                              .GetSyntaxRootAsync(context.CancellationToken)
                              .ConfigureAwait(false);

            NamespaceDeclarationSyntax declaration = root
                                                     .FindNode(context.Span, getInnermostNodeForTie: true)?
                                                     .FirstAncestorOrSelf <NamespaceDeclarationSyntax>();

            if (declaration == null)
            {
                return;
            }

            CodeAction codeAction = CodeAction.Create(
                "Remove empty namespace declaration",
                cancellationToken => RemoveEmptyNamespaceDeclarationAsync(context.Document, declaration, cancellationToken),
                DiagnosticIdentifiers.RemoveEmptyNamespaceDeclaration + EquivalenceKeySuffix);

            context.RegisterCodeFix(codeAction, context.Diagnostics);
        }
Esempio n. 20
0
        protected override Task RegisterCodeFixesAsync(SyntaxNode root, CodeFixContext context)
        {
            var diagnostic     = context.Diagnostics.First();
            var diagnosticSpan = diagnostic.Location.SourceSpan;

            if (!(root.FindNode(diagnosticSpan) is CaseSwitchLabelSyntax syntaxNode))
            {
                return(TaskHelper.CompletedTask);
            }

            context.RegisterCodeFix(
                CodeAction.Create(
                    Title,
                    c =>
            {
                var newRoot = root.RemoveNode(syntaxNode, SyntaxRemoveOptions.KeepNoTrivia);
                return(Task.FromResult(context.Document.WithSyntaxRoot(newRoot)));
            }),
                context.Diagnostics);

            return(TaskHelper.CompletedTask);
        }
        public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
        {
            SyntaxNode root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);

            IfStatementSyntax ifStatement = root
                                            .FindNode(context.Span, getInnermostNodeForTie: true)?
                                            .FirstAncestorOrSelf <IfStatementSyntax>();

            if (ifStatement == null)
            {
                return;
            }

            ifStatement = IfElseChain.GetTopmostIf(ifStatement);

            CodeAction codeAction = CodeAction.Create(
                "Add braces to if-else",
                cancellationToken => AddBracesToIfElseRefactoring.RefactorAsync(context.Document, ifStatement, cancellationToken),
                DiagnosticIdentifiers.AddBracesToIfElse + EquivalenceKeySuffix);

            context.RegisterCodeFix(codeAction, context.Diagnostics);
        }
Esempio n. 22
0
        public override async Task RegisterCodeFixesAsync(CodeFixContext context)
        {
            SyntaxNode root = await context.GetSyntaxRootAsync().ConfigureAwait(false);

            if (!TryFindFirstAncestorOrSelf(root, context.Span, out EndRegionDirectiveTriviaSyntax endRegionDirective, findInsideTrivia: true))
            {
                return;
            }

            RegionDirectiveTriviaSyntax regionDirective = endRegionDirective.GetRegionDirective();

            SyntaxTrivia trivia = regionDirective.GetPreprocessingMessageTrivia();

            CodeAction codeAction = CodeAction.Create(
                (trivia.IsKind(SyntaxKind.PreprocessingMessageTrivia))
                    ? "Add region name to #endregion"
                    : "Remove region name from #endregion",
                cancellationToken => AddOrRemoveRegionNameRefactoring.RefactorAsync(context.Document, endRegionDirective, trivia, cancellationToken),
                GetEquivalenceKey(DiagnosticIdentifiers.AddOrRemoveRegionName));

            context.RegisterCodeFix(codeAction, context.Diagnostics);
        }
        public static void Register(
            CodeFixContext context,
            Diagnostic diagnostic,
            InvocationExpressionSyntax invocation)
        {
            string propertyName = diagnostic.Properties["PropertyName"];
            string sign         = (invocation.Parent?.IsKind(SyntaxKind.LogicalNotExpression) == true) ? "==" : ">";

            CodeAction codeAction = CodeAction.Create(
                $"Replace 'Any' with '{propertyName} {sign} 0'",
                cancellationToken =>
            {
                return(RefactorAsync(
                           context.Document,
                           invocation,
                           propertyName,
                           cancellationToken));
            },
                diagnostic.Id + BaseCodeFixProvider.EquivalenceKeySuffix);

            context.RegisterCodeFix(codeAction, diagnostic);
        }
Esempio n. 24
0
        public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
        {
            var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);

            var diagnostic     = context.Diagnostics.First();
            var diagnosticSpan = diagnostic.Location.SourceSpan;

            Debug.Assert(root != null);
            var parent = root.FindToken(diagnosticSpan.Start).Parent;

            if (parent != null)
            {
                // Find the type declaration identified by the diagnostic.
                var variableDeclaration = parent.FirstAncestorOrSelf <VariableDeclarationSyntax>();

                // Register a code action that will invoke the fix.
                context.RegisterCodeFix(
                    new AsyncLambdaVariableCodeAction("Async lambdas should not be stored in void-returning delegates",
                                                      c => ChangeToFunc(context.Document, variableDeclaration, c)),
                    diagnostic);
            }
        }
Esempio n. 25
0
        protected sealed override Task RegisterCodeFixesAsync(SyntaxNode root, CodeFixContext context)
        {
            var diagnostic     = context.Diagnostics.First();
            var diagnosticSpan = diagnostic.Location.SourceSpan;
            var unary          = root.FindNode(diagnosticSpan, getInnermostNodeForTie: true) as UnaryExpressionSyntax;

            var isExpression = unary?.Operand as BinaryExpressionSyntax;

            if (isExpression == null ||
                !isExpression.IsKind(SyntaxKind.IsExpression))
            {
                return(TaskHelper.CompletedTask);
            }

            context.RegisterCodeFix(
                CodeAction.Create(
                    Title,
                    c => ChangeToIsNotAsync(context.Document, unary, isExpression, c)),
                context.Diagnostics);

            return(TaskHelper.CompletedTask);
        }
        public override async Task RegisterCodeFixesAsync(CodeFixContext context)
        {
            var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken);

            foreach (var diagnostic in context.Diagnostics)
            {
                var span      = diagnostic.Location.SourceSpan;
                var classDecl = root.FindToken(span.Start).Parent.AncestorsAndSelf().OfType <ClassDeclarationSyntax>().First();

                if (!diagnostic.Properties.TryGetValue("requiredAttributes", out var requiredAttributes))
                {
                    return;
                }

                context.RegisterCodeFix(
                    CodeAction.Create(
                        Title,
                        c => FixAsync(context.Document, classDecl, requiredAttributes, c),
                        Title),
                    diagnostic);
            }
        }
Esempio n. 27
0
        public override async Task RegisterCodeFixesAsync(CodeFixContext context)
        {
            Diagnostic diagnostic = context.Diagnostics[0];

            if (!Settings.IsEnabled(diagnostic.Id, CodeFixIdentifiers.SynchronizeAccessibility))
            {
                return;
            }

            SyntaxNode root = await context.GetSyntaxRootAsync().ConfigureAwait(false);

            if (!TryFindFirstAncestorOrSelf(root, context.Span, out MemberDeclarationSyntax memberDeclaration))
            {
                return;
            }

            SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false);

            var symbol = (INamedTypeSymbol)semanticModel.GetDeclaredSymbol(memberDeclaration, context.CancellationToken);

            ImmutableArray <MemberDeclarationSyntax> memberDeclarations = ImmutableArray.CreateRange(
                symbol.DeclaringSyntaxReferences,
                f => (MemberDeclarationSyntax)f.GetSyntax(context.CancellationToken));

            foreach (Accessibility accessibility in memberDeclarations
                     .Select(f => SyntaxAccessibility.GetExplicitAccessibility(f))
                     .Where(f => f != Accessibility.NotApplicable))
            {
                if (SyntaxAccessibility.IsValidAccessibility(memberDeclaration, accessibility))
                {
                    CodeAction codeAction = CodeAction.Create(
                        $"Change accessibility to '{SyntaxFacts.GetText(accessibility)}'",
                        cancellationToken => ChangeAccessibilityRefactoring.RefactorAsync(context.Solution(), memberDeclarations, accessibility, cancellationToken),
                        GetEquivalenceKey(CompilerDiagnosticIdentifiers.PartialDeclarationsHaveConflictingAccessibilityModifiers, accessibility.ToString()));

                    context.RegisterCodeFix(codeAction, diagnostic);
                }
            }
        }
Esempio n. 28
0
        public async override Task RegisterCodeFixesAsync(CodeFixContext context)
        {
            var document          = context.Document;
            var cancellationToken = context.CancellationToken;
            var span        = context.Span;
            var diagnostics = context.Diagnostics;
            var root        = await document.GetSyntaxRootAsync(cancellationToken);

            var diagnostic = diagnostics.First();
            var node       = root.FindNode(context.Span) as InitializerExpressionSyntax;

            //if (!node.IsKind(SyntaxKind.BaseList))
            //	continue;
            if (node == null)
            {
                return;
            }

            var elementCount = node.Expressions.Count;

            if (elementCount > node.Expressions.GetSeparators().Count())
            {
                return;
            }

            var redundantComma      = node.Expressions.GetSeparator(elementCount - 1);
            var newSeparatedExpList = new List <SyntaxNodeOrToken>(node.Expressions.GetWithSeparators().Where(t => t != redundantComma));
            var lastExp             = newSeparatedExpList.Last();

            newSeparatedExpList.RemoveAt(newSeparatedExpList.Count - 1);
            newSeparatedExpList.Add(lastExp.WithTrailingTrivia(redundantComma.TrailingTrivia));

            var newRoot = root.ReplaceNode(
                node,
                node
                .WithExpressions(SyntaxFactory.SeparatedList <ExpressionSyntax>(SyntaxFactory.NodeOrTokenList(newSeparatedExpList))));

            context.RegisterCodeFix(CodeActionFactory.Create(node.Span, diagnostic.Severity, "Remove ','", document.WithSyntaxRoot(newRoot)), diagnostic);
        }
Esempio n. 29
0
        public async override Task RegisterCodeFixesAsync(CodeFixContext context)
        {
            var document          = context.Document;
            var cancellationToken = context.CancellationToken;
            var span          = context.Span;
            var diagnostics   = context.Diagnostics;
            var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);

            var root       = semanticModel.SyntaxTree.GetRoot(cancellationToken);
            var diagnostic = diagnostics.First();
            var node       = root.FindNode(context.Span);

            if (node == null)
            {
                return;
            }
            var typeInfo = semanticModel.GetSymbolInfo(node.Parent);
            var newType  = typeInfo.Symbol.ContainingType.ToMinimalDisplayString(semanticModel, node.SpanStart);
            var newRoot  = root.ReplaceNode((SyntaxNode)node, SyntaxFactory.ParseTypeName(newType).WithLeadingTrivia(node.GetLeadingTrivia()));

            context.RegisterCodeFix(CodeActionFactory.Create(node.Span, diagnostic.Severity, string.Format("Use base qualifier '{0}'", newType), document.WithSyntaxRoot(newRoot)), diagnostic);
        }
Esempio n. 30
0
        public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
        {
            SyntaxNode root = await context.GetSyntaxRootAsync().ConfigureAwait(false);

            if (!TryFindFirstAncestorOrSelf(root, context.Span, out CaseSwitchLabelSyntax label))
            {
                return;
            }

            CodeAction codeAction = CodeAction.Create(
                "Remove unnecessary case label",
                cancellationToken =>
            {
                return(RemoveUnnecessaryCaseLabelRefactoring.RefactorAsync(
                           context.Document,
                           label,
                           cancellationToken));
            },
                GetEquivalenceKey(DiagnosticIdentifiers.RemoveUnnecessaryCaseLabel));

            context.RegisterCodeFix(codeAction, context.Diagnostics);
        }
        /// <inheritdoc/>
        public override async Task RegisterCodeFixesAsync(CodeFixContext context)
        {
            var document   = context.Document;
            var syntaxRoot = await document.GetSyntaxRootAsync(context.CancellationToken)
                             .ConfigureAwait(false);

            var semanticModel = await document.GetSemanticModelAsync(context.CancellationToken).ConfigureAwait(false);

            foreach (var diagnostic in context.Diagnostics)
            {
                var token = syntaxRoot.FindToken(diagnostic.Location.SourceSpan.Start);
                if (string.IsNullOrEmpty(token.ValueText))
                {
                    continue;
                }

                var node = syntaxRoot.FindNode(diagnostic.Location.SourceSpan);
                if (node == null || node.IsMissing)
                {
                    continue;
                }

                var property = semanticModel.SemanticModelFor(node)
                               .GetDeclaredSymbol(node, context.CancellationToken) as IPropertySymbol;
                if (ClrProperty.TryGetRegisteredName(
                        property,
                        semanticModel,
                        context.CancellationToken,
                        out string registeredName))
                {
                    context.RegisterCodeFix(
                        CodeAction.Create(
                            $"Rename to: {registeredName}.",
                            _ => ApplyFixAsync(context, token, registeredName),
                            this.GetType().FullName),
                        diagnostic);
                }
            }
        }
        public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
        {
            SyntaxNode root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);

            UsingDirectiveSyntax usingDirective = root
                                                  .FindNode(context.Span, getInnermostNodeForTie: true)?
                                                  .FirstAncestorOrSelf <UsingDirectiveSyntax>();

            if (usingDirective == null)
            {
                return;
            }

            string name = usingDirective.Alias.Name.Identifier.ValueText;

            CodeAction codeAction = CodeAction.Create(
                "Inline alias expression",
                cancellationToken => RemoveUsingAliasDirectiveRefactoring.RefactorAsync(context.Document, usingDirective, cancellationToken),
                DiagnosticIdentifiers.AvoidUsageOfUsingAliasDirective + EquivalenceKeySuffix);

            context.RegisterCodeFix(codeAction, context.Diagnostics);
        }
Esempio n. 33
0
        public override Task RegisterCodeFixesAsync(CodeFixContext context)
        {
            context.RegisterCodeFix(
                new MyCodeAction(
                    c =>
                    FixAllWithEditorAsync(
                        context.Document,
                        e =>
                        FixInCurrentMemberAsync(
                            context.Document,
                            e,
                            context.Diagnostics[0],
                            c
                            ),
                        c
                        )
                    ),
                context.Diagnostics
                );

            return(Task.CompletedTask);
        }
        public async override Task RegisterCodeFixesAsync(CodeFixContext context)
        {
            foreach (var diagnostic in context.Diagnostics)
            {
                var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);

                var token = root.FindToken(diagnostic.Location.SourceSpan.Start);
                if (!IsCatchDeclarationIdentifier(token))
                {
                    var ancestor = token.GetAncestor <TLocalDeclarationStatement>();

                    if (ancestor == null)
                    {
                        return;
                    }
                }
            }

            context.RegisterCodeFix(
                new MyCodeAction(c => FixAsync(context.Document, context.Diagnostics.First(), c)),
                context.Diagnostics);
        }
        public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
        {
            SyntaxNode root = await context.GetSyntaxRootAsync().ConfigureAwait(false);

            if (!TryFindFirstAncestorOrSelf(root, context.Span, out MemberAccessExpressionSyntax memberAccess))
            {
                return;
            }

            CodeAction codeAction = CodeAction.Create(
                $"Use \"\" instead of '{memberAccess}'",
                cancellationToken =>
            {
                return(UseEmptyStringLiteralInsteadOfStringEmptyRefactoring.RefactorAsync(
                           context.Document,
                           memberAccess,
                           cancellationToken));
            },
                GetEquivalenceKey(DiagnosticIdentifiers.UseEmptyStringLiteralInsteadOfStringEmpty));

            context.RegisterCodeFix(codeAction, context.Diagnostics);
        }
        public override async Task RegisterCodeFixesAsync(CodeFixContext context)
        {
            var syntaxRoot = await context.Document.GetSyntaxRootAsync(context.CancellationToken)
                             .ConfigureAwait(false);

            foreach (var diagnostic in context.Diagnostics)
            {
                if (syntaxRoot?.FindNode(diagnostic.Location.SourceSpan) is LiteralExpressionSyntax literal)
                {
                    context.RegisterCodeFix(
                        CodeAction.Create(
                            "Prefix with $",
                            _ => Task.FromResult(
                                context.Document.WithSyntaxRoot(
                                    syntaxRoot.ReplaceNode(
                                        literal,
                                        CreateInterpolatedStringExpression(literal)))),
                            "Prefix with $"),
                        diagnostic);
                }
            }
        }
        public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
        {
            var document = context.Document;
            var span = context.Span;
            var diagnostics = context.Diagnostics;
            var cancellationToken = context.CancellationToken;

            var project = document.Project;
            var diagnostic = diagnostics.First();
            var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
            var node = root.FindToken(span.Start).GetAncestors<SyntaxNode>().First(n => n.Span.Contains(span));

            using (Logger.LogBlock(FunctionId.Refactoring_FullyQualify, cancellationToken))
            {
                // Has to be a simple identifier or generic name.
                if (node != null && CanFullyQualify(diagnostic, ref node))
                {
                    var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);

                    var matchingTypes = await this.GetMatchingTypesAsync(project, semanticModel, node, cancellationToken).ConfigureAwait(false);
                    var matchingNamespaces = await this.GetMatchingNamespacesAsync(project, semanticModel, node, cancellationToken).ConfigureAwait(false);

                    if (matchingTypes != null || matchingNamespaces != null)
                    {
                        matchingTypes = matchingTypes ?? SpecializedCollections.EmptyEnumerable<ISymbol>();
                        matchingNamespaces = matchingNamespaces ?? SpecializedCollections.EmptyEnumerable<ISymbol>();

                        var matchingTypeContainers = FilterAndSort(GetContainers(matchingTypes, semanticModel.Compilation));
                        var matchingNamespaceContainers = FilterAndSort(GetContainers(matchingNamespaces, semanticModel.Compilation));

                        var proposedContainers =
                            matchingTypeContainers.Concat(matchingNamespaceContainers)
                                              .Distinct()
                                              .Take(MaxResults);

                        var displayService = project.LanguageServices.GetService<ISymbolDisplayService>();

                        foreach (var container in proposedContainers)
                        {
                            var containerName = displayService.ToMinimalDisplayString(semanticModel, node.SpanStart, container);

                            var syntaxFacts = document.Project.LanguageServices.GetService<ISyntaxFactsService>();
                            string name;
                            int arity;
                            syntaxFacts.GetNameAndArityOfSimpleName(node, out name, out arity);

                            // Actual member name might differ by case.
                            string memberName;
                            if (this.IgnoreCase)
                            {
                                var member = container.GetMembers(name).FirstOrDefault();
                                memberName = member != null ? member.Name : name;
                            }
                            else
                            {
                                memberName = name;
                            }

                            var codeAction = new MyCodeAction(
                                $"{containerName}.{memberName}",
                                c => ProcessNode(document, node, containerName, c));

                            context.RegisterCodeFix(codeAction, diagnostic);
                        }
                    }
                }
            }
        }
        public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
        {
            var document = context.Document;
            var span = context.Span;
            var diagnostics = context.Diagnostics;
            var cancellationToken = context.CancellationToken;

            var project = document.Project;
            var diagnostic = diagnostics.First();
            var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
            var ancestors = root.FindToken(span.Start, findInsideTrivia: true).GetAncestors<SyntaxNode>();
            if (!ancestors.Any())
            {
                return;
            }

            var node = ancestors.FirstOrDefault(n => n.Span.Contains(span) && n != root);
            if (node == null)
            {
                return;
            }

            var placeSystemNamespaceFirst = document.Project.Solution.Workspace.Options.GetOption(Microsoft.CodeAnalysis.Shared.Options.OrganizerOptions.PlaceSystemNamespaceFirst, document.Project.Language);

            using (Logger.LogBlock(FunctionId.Refactoring_AddImport, cancellationToken))
            {
                if (!cancellationToken.IsCancellationRequested)
                {
                    if (this.CanAddImport(node, cancellationToken))
                    {
                        var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
                        var containingType = semanticModel.GetEnclosingNamedType(node.SpanStart, cancellationToken);
                        var containingTypeOrAssembly = containingType ?? (ISymbol)semanticModel.Compilation.Assembly;
                        var namespacesInScope = this.GetNamespacesInScope(semanticModel, node, cancellationToken);
                        var syntaxFacts = document.Project.LanguageServices.GetService<ISyntaxFactsService>();

                        var matchingTypesNamespaces = await this.GetNamespacesForMatchingTypesAsync(project, diagnostic, node, semanticModel, namespacesInScope, syntaxFacts, cancellationToken).ConfigureAwait(false);
                        var matchingTypes = await this.GetMatchingTypesAsync(project, diagnostic, node, semanticModel, namespacesInScope, syntaxFacts, cancellationToken).ConfigureAwait(false);
                        var matchingNamespaces = await this.GetNamespacesForMatchingNamespacesAsync(project, diagnostic, node, semanticModel, namespacesInScope, syntaxFacts, cancellationToken).ConfigureAwait(false);
                        var matchingExtensionMethodsNamespaces = await this.GetNamespacesForMatchingExtensionMethodsAsync(project, diagnostic, node, semanticModel, namespacesInScope, syntaxFacts, cancellationToken).ConfigureAwait(false);
                        var matchingFieldsAndPropertiesAsync = await this.GetNamespacesForMatchingFieldsAndPropertiesAsync(project, diagnostic, node, semanticModel, namespacesInScope, syntaxFacts, cancellationToken).ConfigureAwait(false);
                        var queryPatternsNamespaces = await this.GetNamespacesForQueryPatternsAsync(project, diagnostic, node, semanticModel, namespacesInScope, cancellationToken).ConfigureAwait(false);

                        if (matchingTypesNamespaces != null || matchingNamespaces != null || matchingExtensionMethodsNamespaces != null || matchingFieldsAndPropertiesAsync != null || queryPatternsNamespaces != null || matchingTypes != null)
                        {
                            matchingTypesNamespaces = matchingTypesNamespaces ?? SpecializedCollections.EmptyList<INamespaceSymbol>();
                            matchingNamespaces = matchingNamespaces ?? SpecializedCollections.EmptyList<INamespaceSymbol>();
                            matchingExtensionMethodsNamespaces = matchingExtensionMethodsNamespaces ?? SpecializedCollections.EmptyList<INamespaceSymbol>();
                            matchingFieldsAndPropertiesAsync = matchingFieldsAndPropertiesAsync ?? SpecializedCollections.EmptyList<INamespaceSymbol>();
                            queryPatternsNamespaces = queryPatternsNamespaces ?? SpecializedCollections.EmptyList<INamespaceSymbol>();
                            matchingTypes = matchingTypes ?? SpecializedCollections.EmptyList<ITypeSymbol>();

                            var proposedImports =
                                matchingTypesNamespaces.Cast<INamespaceOrTypeSymbol>()
                                           .Concat(matchingNamespaces.Cast<INamespaceOrTypeSymbol>())
                                           .Concat(matchingExtensionMethodsNamespaces.Cast<INamespaceOrTypeSymbol>())
                                           .Concat(matchingFieldsAndPropertiesAsync.Cast<INamespaceOrTypeSymbol>())
                                           .Concat(queryPatternsNamespaces.Cast<INamespaceOrTypeSymbol>())
                                           .Concat(matchingTypes.Cast<INamespaceOrTypeSymbol>())
                                           .Distinct()
                                           .Where(NotNull)
                                           .Where(NotGlobalNamespace)
                                           .OrderBy(INamespaceOrTypeSymbolExtensions.CompareNamespaceOrTypeSymbols)
                                           .Take(8)
                                           .ToList();

                            if (proposedImports.Count > 0)
                            {
                                cancellationToken.ThrowIfCancellationRequested();

                                foreach (var import in proposedImports)
                                {
                                    var action = new MyCodeAction(this.GetDescription(import, semanticModel, node), (c) =>
                                        this.AddImportAsync(node, import, document, placeSystemNamespaceFirst, cancellationToken));

                                    context.RegisterCodeFix(action, diagnostic);
                                }
                            }
                        }
                    }
                }
            }
        }