/// <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 (syntaxRoot.TryFindNode(diagnostic, out ArgumentSyntax? argument) && argument.Expression is LiteralExpressionSyntax literal && semanticModel.LookupSymbols(argument.SpanStart, name: literal.Token.ValueText).TryFirst(out var member)) { context.RegisterCodeFix( "Use nameof", async(editor, cancellationToken) => { var replacement = await editor.SymbolAccessAsync(member, literal, cancellationToken) .ConfigureAwait(false); _ = editor.ReplaceNode( literal, x => InpcFactory.Nameof(replacement).WithTriviaFrom(x)); }, nameof(UseNameofFix), diagnostic); } } }
/// <inheritdoc/> protected override async Task RegisterCodeFixesAsync(DocumentEditorCodeFixContext context) { var syntaxRoot = await context.Document.GetSyntaxRootAsync(context.CancellationToken) .ConfigureAwait(false); foreach (var diagnostic in context.Diagnostics) { if (syntaxRoot.TryFindNode(diagnostic, out AssignmentExpressionSyntax? assignment) && diagnostic.AdditionalLocations.TrySingle(out var additionalLocation) && syntaxRoot.FindNode(additionalLocation.SourceSpan) is ExpressionSyntax fieldAccess) { context.RegisterCodeFix( "Set backing field.", (e, cancellationToken) => e.ReplaceNode( assignment.Left, (x, _) => Qualify(fieldAccess).WithTriviaFrom(x)), nameof(SetBackingFieldFix), diagnostic); ExpressionSyntax Qualify(ExpressionSyntax expression) { if (expression is IdentifierNameSyntax identifierName && (Scope.HasParameter(assignment, identifierName.Identifier.ValueText) || Scope.HasLocal(assignment, identifierName.Identifier.ValueText))) { return(InpcFactory.SymbolAccess(identifierName.Identifier.ValueText, CodeStyleResult.Yes)); } return(expression); } } } }
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); }
internal static async Task <ExpressionSyntax> AddBackingFieldAsync(this DocumentEditor editor, PropertyDeclarationSyntax property, CancellationToken cancellationToken) { var backingField = editor.AddBackingField(property); var qualifyFieldAccessAsync = property.Modifiers.Any(SyntaxKind.StaticKeyword) ? CodeStyleResult.No : await editor.QualifyFieldAccessAsync(cancellationToken) .ConfigureAwait(false); return(InpcFactory.SymbolAccess(backingField.Name(), qualifyFieldAccessAsync)); }
internal static async Task <ExpressionStatementSyntax> OnPropertyChangedInvocationStatementAsync(this DocumentEditor editor, IMethodSymbol invoker, string propertyName, CancellationToken cancellationToken) { var qualifyMethodAccess = await editor.QualifyMethodAccessAsync(cancellationToken) .ConfigureAwait(false); var qualifyPropertyAccess = await editor.QualifyPropertyAccessAsync(cancellationToken) .ConfigureAwait(false); return(InpcFactory.OnPropertyChangedInvocationStatement( InpcFactory.SymbolAccess(invoker.Name, qualifyMethodAccess), InpcFactory.Nameof(InpcFactory.SymbolAccess(propertyName, qualifyPropertyAccess)))); }
private static ParameterSyntax AsCallerMemberName(ParameterSyntax parameter, bool nullabilityAnnotationsEnabled) { parameter = parameter.AddAttributeLists(InpcFactory.CallerMemberNameAttributeList) .WithDefault(SyntaxFactory.EqualsValueClause(SyntaxFactory.LiteralExpression(SyntaxKind.NullLiteralExpression))); if (nullabilityAnnotationsEnabled) { parameter = parameter.WithType(InpcFactory.WithNullability(parameter.Type, nullable: true)); } return(parameter); }
internal static async Task AddOnPropertyChangedMethodAsync(this DocumentEditor editor, ClassDeclarationSyntax classDeclaration, bool nullabilityAnnotationsEnabled, CancellationToken cancellationToken) { var qualifyAccess = classDeclaration.Modifiers.Any(SyntaxKind.StaticKeyword) ? CodeStyleResult.No : await editor.QualifyEventAccessAsync(cancellationToken) .ConfigureAwait(false); _ = editor.AddMethod( classDeclaration, InpcFactory.OnPropertyChangedDeclaration( qualifyAccess, classDeclaration.Modifiers.Any(SyntaxKind.SealedKeyword), classDeclaration.Modifiers.Any(SyntaxKind.StaticKeyword), CallerMemberNameAttribute.IsAvailable(editor.SemanticModel), nullabilityAnnotationsEnabled)); }
internal static async Task <ExpressionStatementSyntax> OnPropertyChangedInvocationStatementAsync(this DocumentEditor editor, IMethodSymbol invoker, PropertyDeclarationSyntax containingProperty, CancellationToken cancellationToken) { if (invoker.Parameters.TrySingle(out var parameter)) { var qualifyMethodAccess = await editor.QualifyMethodAccessAsync(cancellationToken) .ConfigureAwait(false); var nameExpression = await editor.NameOfContainingAsync(containingProperty, parameter, cancellationToken) .ConfigureAwait(false); return(InpcFactory.OnPropertyChangedInvocationStatement( InpcFactory.SymbolAccess(invoker.Name, qualifyMethodAccess), nameExpression)); } throw new InvalidOperationException("Could not find name parameter."); }
internal static async Task <InvocationExpressionSyntax> TrySetInvocationAsync(this DocumentEditor editor, IMethodSymbol trySet, ExpressionSyntax field, ExpressionSyntax value, PropertyDeclarationSyntax containingProperty, CancellationToken cancellationToken) { if (trySet.TryFindParameter(KnownSymbol.String, out var nameParameter)) { var qualifyMethodAccess = await editor.QualifyMethodAccessAsync(cancellationToken) .ConfigureAwait(false); var nameExpression = await editor.NameOfContainingAsync(containingProperty, nameParameter, cancellationToken) .ConfigureAwait(false); return(InpcFactory.TrySetInvocation( qualifyMethodAccess, trySet, field, value, nameExpression)); } throw new InvalidOperationException("Could not find name parameter."); }
protected override async Task RegisterCodeFixesAsync(DocumentEditorCodeFixContext context) { var syntaxRoot = await context.Document.GetSyntaxRootAsync(context.CancellationToken) .ConfigureAwait(false); foreach (var diagnostic in context.Diagnostics) { if (syntaxRoot.TryFindNode(diagnostic, out InvocationExpressionSyntax? invocation) && invocation.ArgumentList is { } argumentList&& TryGetMethodName(out var name)) { if (argumentList.Arguments.Count == 2) { context.RegisterCodeFix( $"Use {name}", editor => editor.ReplaceNode( invocation.Expression, x => SyntaxFactory.IdentifierName(name).WithTriviaFrom(x)), nameof(EqualityFix), diagnostic); } else if (argumentList.Arguments.TrySingle(out var argument) && invocation.Expression is MemberAccessExpressionSyntax { Expression: { } expression }) { context.RegisterCodeFix( $"Use {name}", editor => editor.ReplaceNode( invocation, x => InpcFactory.Equals(null, name, expression, argument.Expression).WithTriviaFrom(x)), nameof(EqualityFix), diagnostic); } } if (syntaxRoot.TryFindNode(diagnostic, out BinaryExpressionSyntax? binary) && TryGetMethodName(out name)) { switch (binary.Kind()) { case SyntaxKind.EqualsExpression: context.RegisterCodeFix( $"Use {name}", editor => editor.ReplaceNode( binary, x => InpcFactory.Equals(null, name, x.Left.WithoutTrivia(), x.Right.WithoutTrivia()).WithTriviaFrom(x)), nameof(EqualityFix), diagnostic); break; case SyntaxKind.NotEqualsExpression: context.RegisterCodeFix( $"Use !{name}", editor => editor.ReplaceNode( binary, x => SyntaxFactory.PrefixUnaryExpression( SyntaxKind.LogicalNotExpression, InpcFactory.Equals( null, name, x.Left.WithoutTrivia(), x.Right.WithoutTrivia())) .WithTriviaFrom(x)), nameof(EqualityFix), diagnostic); break; } } bool TryGetMethodName(out string result) { if (diagnostic.Id == Descriptors.INPC006UseReferenceEqualsForReferenceTypes.Id) { result = nameof(ReferenceEquals); return(true); } if (diagnostic.Id == Descriptors.INPC006UseObjectEqualsForReferenceTypes.Id) { result = nameof(Equals); return(true); } result = null !; return(false); } }
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); } }
/// <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;