Beispiel #1
0
 internal static AnalysisResult InvokesPropertyChangedFor(ExpressionSyntax mutation, IPropertySymbol property, SemanticModel semanticModel, CancellationToken cancellationToken)
 {
     if (mutation.Parent is ArgumentSyntax {
         Parent : ArgumentListSyntax {
             Parent : InvocationExpressionSyntax invocation
         }
     } argument&&
         argument.RefOrOutKeyword.IsKind(SyntaxKind.RefKeyword) &&
         invocation.IsPotentialThisOrBase())
     {
         if (TrySet.IsMatch(invocation, semanticModel, cancellationToken) != AnalysisResult.No &&
             semanticModel.GetSymbolSafe(invocation, cancellationToken) is { } setAndRaiseMethod&&
             setAndRaiseMethod.Parameters.TryLast(x => x.Type == KnownSymbol.String, out var nameParameter))
         {
             if (invocation.TryFindArgument(nameParameter, out var nameArg))
             {
                 if (nameArg.TryGetStringValue(semanticModel, cancellationToken, out var name))
                 {
                     if (string.IsNullOrEmpty(name) ||
                         name == property.Name)
                     {
                         return(AnalysisResult.Yes);
                     }
                 }
             }
             else if (invocation.FirstAncestor <PropertyDeclarationSyntax>() is { } propertyDeclaration&&
                      propertyDeclaration.Identifier.ValueText == property.Name)
             {
                 return(AnalysisResult.Yes);
             }
         }
Beispiel #2
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 ExpressionStatementSyntax? onPropertyChangedStatement) &&
                    onPropertyChangedStatement.TryFirstAncestor(out AccessorDeclarationSyntax? setter) &&
                    setter.IsKind(SyntaxKind.SetAccessorDeclaration) &&
                    setter.Body is { } body)
                {
                    if (Setter.TryFindSingleAssignment(setter, out var assignment) &&
                        assignment.Parent is ExpressionStatementSyntax assignmentStatement &&
                        body.Statements.IndexOf(assignmentStatement) == 0)
                    {
                        if (semanticModel.TryGetSymbol(assignment.Left, CancellationToken.None, out var assignedSymbol) &&
                            assignedSymbol.Kind == SymbolKind.Field &&
                            semanticModel.TryGetSymbol(setter, context.CancellationToken, out IMethodSymbol? setterSymbol) &&
                            TrySet.TryFind(setterSymbol.ContainingType, semanticModel, context.CancellationToken, out var trySetMethod) &&
                            TrySet.CanCreateInvocation(trySetMethod, out _) &&
                            setter.TryFirstAncestor(out PropertyDeclarationSyntax? property))
                        {
                            if (setter.Body.Statements.Count == 2)
                            {
                                context.RegisterCodeFix(
                                    trySetMethod.DisplaySignature(),
                                    async(editor, cancellationToken) =>
                                {
                                    var trySet = await editor.TrySetInvocationAsync(trySetMethod, assignment.Left, assignment.Right, property, cancellationToken)
                                                 .ConfigureAwait(false);
                                    _ = editor.ReplaceNode(
                                        setter,
                                        x => x.AsExpressionBody(trySet));
                                },
                                    trySetMethod.MetadataName,
                                    diagnostic);
                            }
                        }

                        context.RegisterCodeFix(
                            "Check that value is different before notifying.",
                            (editor, cancellationToken) => editor.InsertBefore(
                                assignmentStatement,
                                InpcFactory.IfReturn(
                                    InpcFactory.Equals(
                                        assignment.Right,
                                        assignment.Left,
                                        editor.SemanticModel,
                                        cancellationToken))),
                            nameof(CheckIfDifferentBeforeNotifyFix),
                            diagnostic);
                    }
Beispiel #3
0
        internal static bool TryFindSingleTrySet(AccessorDeclarationSyntax setter, SemanticModel semanticModel, CancellationToken cancellationToken, [NotNullWhen(true)] out InvocationExpressionSyntax?invocation)
        {
            invocation = null;
            if (setter == null)
            {
                return(false);
            }

            using var walker = InvocationWalker.Borrow(setter);
            return(walker.Invocations.TrySingle <InvocationExpressionSyntax>(x => TrySet.IsMatch(x, semanticModel, cancellationToken) != AnalysisResult.No, out invocation));
        }
        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 } })
Beispiel #5
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);
                            }
                        }
Beispiel #6
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;