private static void Handle(SyntaxNodeAnalysisContext context)
        {
            if (!context.IsExcludedFromAnalysis() &&
                context.ContainingSymbol is IMethodSymbol method &&
                context.Node is MethodDeclarationSyntax methodDeclaration)
            {
                if (OnPropertyChanged.IsMatch(method, context.SemanticModel, context.CancellationToken, out var parameter) == AnalysisResult.Yes)
                {
                    if (ShouldBeCallerMemberName(parameter, out var parameterSyntax))
                    {
                        context.ReportDiagnostic(Diagnostic.Create(Descriptors.INPC004UseCallerMemberName, parameterSyntax !.GetLocation()));
                    }

                    if (ShouldBeProtected() is { } location)
                    {
                        context.ReportDiagnostic(
                            Diagnostic.Create(
                                Descriptors.INPC018InvokerShouldBeProtected,
                                location));
                    }
                }
                else if (TrySet.IsMatch(method, context.SemanticModel, context.CancellationToken, out _, out _, out parameter) == AnalysisResult.Yes)
                {
                    if (ShouldBeCallerMemberName(parameter, out var parameterSyntax))
                    {
                        context.ReportDiagnostic(Diagnostic.Create(Descriptors.INPC004UseCallerMemberName, parameterSyntax !.GetLocation()));
                    }

                    if (ShouldBeProtected() is { } location)
                    {
                        context.ReportDiagnostic(
                            Diagnostic.Create(
                                Descriptors.INPC018InvokerShouldBeProtected,
                                location));
                    }
                }
            }

            bool ShouldBeCallerMemberName(IParameterSymbol candidate, out ParameterSyntax?parameterSyntax)
            {
                parameterSyntax = null;
                return(!candidate.IsCallerMemberName() &&
                       candidate.Type == KnownSymbol.String &&
                       methodDeclaration.TryFindParameter(candidate.Name, out parameterSyntax) &&
                       CallerMemberNameAttribute.IsAvailable(context.SemanticModel));
            }

            Location?ShouldBeProtected()
            {
                if (method is { DeclaredAccessibility : Accessibility.Private, ContainingType : { IsSealed : false, IsStatic : false } })
        private static void Handle(SyntaxNodeAnalysisContext context)
        {
            if (!context.IsExcludedFromAnalysis() &&
                context.Node is ArgumentSyntax {
                Parent : ArgumentListSyntax argumentList
            } argument)
            {
                if (argument.TryGetStringValue(context.SemanticModel, context.CancellationToken, out var text))
                {
                    if (text == ContainingSymbolName(context.ContainingSymbol) &&
                        context.SemanticModel.GetSymbolSafe(argumentList.Parent, context.CancellationToken) is IMethodSymbol method &&
                        method.TryFindParameter(argument, out var parameter))
                    {
                        if (parameter.IsCallerMemberName())
                        {
                            context.ReportDiagnostic(Diagnostic.Create(Descriptors.INPC004UseCallerMemberName, argument.GetLocation()));
                        }
                        else if (parameter.TrySingleDeclaration <SyntaxNode>(context.CancellationToken, out _) &&
                                 OnPropertyChanged.IsMatch(method, context.SemanticModel, context.CancellationToken) == AnalysisResult.Yes)
                        {
                            context.ReportDiagnostic(Diagnostic.Create(Descriptors.INPC004UseCallerMemberName, argument.GetLocation()));
                        }
                    }

                    if (SyntaxFacts.IsValidIdentifier(text))
                    {
                        if (argumentList.Parent is InvocationExpressionSyntax onPropertyChangedCandidate &&
                            OnPropertyChanged.IsMatch(onPropertyChangedCandidate, context.SemanticModel, context.CancellationToken) != AnalysisResult.No &&
                            !context.ContainingSymbol.ContainingType.TryFindPropertyRecursive(text, out _))
                        {
                            context.ReportDiagnostic(Diagnostic.Create(Descriptors.INPC009DoNotRaiseChangeForMissingProperty, argument.GetLocation()));
                        }

                        if (argumentList.Parent is ObjectCreationExpressionSyntax {
                            Parent : ArgumentSyntax parentArg
                        } objectCreation&&
                            parentArg.FirstAncestor <InvocationExpressionSyntax>() is { } parentInvocation&&
                            context.SemanticModel.TryGetSymbol(objectCreation, KnownSymbol.PropertyChangedEventArgs, context.CancellationToken, out _))
                        {
                            if ((OnPropertyChanged.IsMatch(parentInvocation, context.SemanticModel, context.CancellationToken) != AnalysisResult.No ||
                                 PropertyChangedEvent.IsInvoke(parentInvocation, context.SemanticModel, context.CancellationToken)) &&
                                !context.ContainingSymbol.ContainingType.TryFindPropertyRecursive(text, out _))
                            {
                                context.ReportDiagnostic(Diagnostic.Create(Descriptors.INPC009DoNotRaiseChangeForMissingProperty, argument.GetLocation()));
                            }
                        }

                        if (argument.Expression is LiteralExpressionSyntax literal &&
                            literal.IsKind(SyntaxKind.StringLiteralExpression))
                        {
                            if (context.ContainingSymbol is IMethodSymbol containingMethod &&
                                containingMethod.Parameters.TrySingle(x => x.Name == literal.Token.ValueText, out _))
                            {
                                context.ReportDiagnostic(Diagnostic.Create(Descriptors.INPC013UseNameof, argument.GetLocation()));
                            }

                            if (context.ContainingSymbol.ContainingType.TryFindPropertyRecursive(literal.Token.ValueText, out _))
                            {
                                context.ReportDiagnostic(Diagnostic.Create(Descriptors.INPC013UseNameof, argument.GetLocation()));
                            }
                        }
                    }
                }

                if (argument is { Expression : AnonymousFunctionExpressionSyntax lambda } &&
Ejemplo n.º 3
0
        protected override async Task RegisterCodeFixesAsync(DocumentEditorCodeFixContext context)
        {
            var syntaxRoot = await context.Document.GetSyntaxRootAsync(context.CancellationToken)
                             .ConfigureAwait(false);

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

            foreach (var diagnostic in context.Diagnostics)
            {
                if (syntaxRoot.TryFindNodeOrAncestor(diagnostic, out PropertyDeclarationSyntax? propertyDeclaration) &&
                    propertyDeclaration.Parent is ClassDeclarationSyntax classDeclarationSyntax &&
                    semanticModel.TryGetSymbol(classDeclarationSyntax, context.CancellationToken, out var type))
                {
                    if (TrySet.TryFind(type, semanticModel, context.CancellationToken, out var trySetMethod) &&
                        TrySet.CanCreateInvocation(trySetMethod, out _))
                    {
                        if (Property.IsMutableAutoProperty(propertyDeclaration, out var getter, out var setter))
                        {
                            context.RegisterCodeFix(
                                trySetMethod.DisplaySignature(),
                                (editor, cancellationToken) => TrySet(editor, cancellationToken),
                                trySetMethod.MetadataName,
                                diagnostic);

                            async Task TrySet(DocumentEditor editor, CancellationToken cancellationToken)
                            {
                                var fieldAccess = await editor.AddBackingFieldAsync(propertyDeclaration, cancellationToken)
                                                  .ConfigureAwait(false);

                                var trySet = await editor.TrySetInvocationAsync(trySetMethod, fieldAccess, InpcFactory.Value, propertyDeclaration, cancellationToken)
                                             .ConfigureAwait(false);

                                _ = editor.ReplaceNode(
                                    getter,
                                    x => x.AsExpressionBody(fieldAccess))
                                    .ReplaceNode(
                                    setter,
                                    x => x.AsExpressionBody(trySet));

                                if (propertyDeclaration.Initializer != null)
                                {
                                    editor.ReplaceNode(
                                        propertyDeclaration,
                                        (node, g) => ((PropertyDeclarationSyntax)node).WithoutInitializer());
                                }

                                _ = editor.FormatNode(propertyDeclaration);
                            }
                        }
                        else if (IsSimpleAssignmentOnly(propertyDeclaration, out _, out var assignment))
                        {
                            context.RegisterCodeFix(
                                trySetMethod.DisplaySignature(),
                                async(editor, cancellationToken) =>
                            {
                                var trySet = await editor.TrySetInvocationAsync(trySetMethod, assignment.Left, assignment.Right, propertyDeclaration, cancellationToken)
                                             .ConfigureAwait(false);
                                _ = editor.ReplaceNode(
                                    assignment,
                                    x => trySet);
                            },
                                trySetMethod.MetadataName,
                                diagnostic);
                        }
                    }

                    if (OnPropertyChanged.TryFind(type, semanticModel, context.CancellationToken, out var invoker) &&
                        invoker.Parameters.TrySingle(out var parameter) &&
                        parameter.Type.IsEither(KnownSymbol.String, KnownSymbol.PropertyChangedEventArgs))
                    {
                        if (Property.IsMutableAutoProperty(propertyDeclaration, out var getter, out var setter) &&
                            semanticModel.TryGetSymbol(propertyDeclaration, context.CancellationToken, out var property))
                        {
                            context.RegisterCodeFix(
                                NotifyWhenValueChanges,
                                (editor, cancellationToken) =>
                                NotifyWhenValueChangesAsync(editor, cancellationToken),
                                nameof(NotifyWhenValueChangesAsync),
                                diagnostic);

                            async Task NotifyWhenValueChangesAsync(DocumentEditor editor, CancellationToken cancellationToken)
                            {
                                var backingField = await editor.AddBackingFieldAsync(propertyDeclaration, cancellationToken)
                                                   .ConfigureAwait(false);

                                var onPropertyChanged = await editor.OnPropertyChangedInvocationStatementAsync(invoker, propertyDeclaration, cancellationToken)
                                                        .ConfigureAwait(false);

                                _ = editor.ReplaceNode(
                                    getter,
                                    x => x.AsExpressionBody(backingField)
                                    .WithTrailingLineFeed());
                                _ = editor.ReplaceNode(
                                    setter,
                                    x => x.AsBlockBody(
                                        InpcFactory.IfReturn(
                                            InpcFactory.Equals(property.Type, InpcFactory.Value, backingField, editor.SemanticModel)),
                                        SyntaxFactory.ExpressionStatement(SyntaxFactory.AssignmentExpression(SyntaxKind.SimpleAssignmentExpression, backingField, InpcFactory.Value)),
                                        onPropertyChanged));
                                if (propertyDeclaration.Initializer != null)
                                {
                                    _ = editor.ReplaceNode(
                                        propertyDeclaration,
                                        x => x.WithoutInitializer());
                                }

                                _ = editor.FormatNode(propertyDeclaration);
                            }
                        }
Ejemplo n.º 4
0
        /// <inheritdoc/>
        protected override async Task RegisterCodeFixesAsync(DocumentEditorCodeFixContext context)
        {
            var syntaxRoot = await context.Document.GetSyntaxRootAsync(context.CancellationToken)
                             .ConfigureAwait(false);

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

            foreach (var diagnostic in context.Diagnostics)
            {
                if (diagnostic.Properties.TryGetValue(MutationAnalyzer.PropertyNameKey, out var propertyName))
                {
                    if (syntaxRoot.TryFindNodeOrAncestor(diagnostic, out ExpressionSyntax? expression) &&
                        expression.TryFirstAncestor(out ClassDeclarationSyntax? classDeclaration) &&
                        semanticModel.TryGetNamedType(classDeclaration, context.CancellationToken, out var type) &&
                        OnPropertyChanged.TryFind(type, semanticModel, context.CancellationToken, out var onPropertyChangedMethod) &&
                        onPropertyChangedMethod.Parameters.TrySingle(out var parameter) &&
                        parameter.Type.IsEither(KnownSymbol.String, KnownSymbol.PropertyChangedEventArgs))
                    {
                        if (expression is InvocationExpressionSyntax trySet &&
                            semanticModel.TryGetSymbol(trySet, context.CancellationToken, out var trySetMethod) &&
                            TrySet.IsMatch(trySetMethod, semanticModel, context.CancellationToken) != AnalysisResult.No)
                        {
                            switch (trySet.Parent)
                            {
                            case ExpressionStatementSyntax expressionStatement:
                                context.RegisterCodeFix(
                                    $"Notify that property {propertyName} changes.",
                                    async(editor, cancellationToken) =>
                                {
                                    var onPropertyChangedStatement = await editor.OnPropertyChangedInvocationStatementAsync(onPropertyChangedMethod, propertyName, cancellationToken)
                                                                     .ConfigureAwait(false);
                                    editor.ReplaceNode(
                                        expressionStatement,
                                        InpcFactory.IfStatement(
                                            trySet,
                                            onPropertyChangedStatement));
                                    if (expressionStatement.TryFirstAncestor(out AccessorDeclarationSyntax? setter))
                                    {
                                        _ = editor.FormatNode(setter);
                                    }
                                },
                                    nameof(NotifyForDependentPropertyFix),
                                    diagnostic);
                                break;

                            case ArrowExpressionClauseSyntax {
                                    Parent: AccessorDeclarationSyntax setter
                            } :
                                context.RegisterCodeFix(
                                    $"Notify that property {propertyName} changes.",
                                    async(editor, cancellationToken) =>
                                {
                                    var onPropertyChangedStatement = await editor.OnPropertyChangedInvocationStatementAsync(onPropertyChangedMethod, propertyName, cancellationToken)
                                                                     .ConfigureAwait(false);
                                    _ = editor.ReplaceNode(
                                        setter,
                                        x => x.AsBlockBody(
                                            InpcFactory.IfStatement(
                                                trySet,
                                                onPropertyChangedStatement)));
                                },
                                    nameof(NotifyForDependentPropertyFix),
                                    diagnostic);
                                break;