Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for converting an auto-prop to a field-backed property. #76900

Merged
merged 11 commits into from
Jan 24, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Shared.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Shared.Extensions;
Expand Down Expand Up @@ -41,23 +42,9 @@ protected override bool SupportsReadOnlyProperties(Compilation compilation)
protected override bool SupportsPropertyInitializer(Compilation compilation)
=> compilation.LanguageVersion() >= LanguageVersion.CSharp6;

protected override bool SupportsFieldExpression(Compilation compilation)
=> compilation.LanguageVersion() >= LanguageVersion.Preview;
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

moved to SyntaxFacts, where we have our other checks.


protected override ExpressionSyntax? GetFieldInitializer(VariableDeclaratorSyntax variable, CancellationToken cancellationToken)
=> variable.Initializer?.Value;

protected override bool ContainsFieldExpression(PropertyDeclarationSyntax propertyDeclaration, CancellationToken cancellationToken)
{
foreach (var node in propertyDeclaration.DescendantNodes())
{
if (node.IsKind(SyntaxKind.FieldExpression))
return true;
}

return false;
}

protected override void RecordIneligibleFieldLocations(
HashSet<string> fieldNames,
ConcurrentDictionary<IFieldSymbol, ConcurrentSet<SyntaxNode>> ineligibleFieldUsageIfOutsideProperty,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Shared.Extensions;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
Expand All @@ -14,7 +15,7 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseAutoProperty;
public sealed partial class UseAutoPropertyTests
{
private static readonly ParseOptions CSharp13 = CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp13);
private static readonly ParseOptions CSharp14 = CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.Preview);
private static readonly ParseOptions CSharp14 = CSharpParseOptions.Default.WithLanguageVersion(LanguageVersionExtensions.CSharpNext);

[Fact]
public async Task TestNotInCSharp13()
Expand Down Expand Up @@ -1601,4 +1602,111 @@ void M()
}
""", new TestParameters(parseOptions: CSharp14));
}

[Fact, WorkItem("https://github.com/dotnet/roslyn/issues/76901")]
public async Task TestReadAndWrite()
{
await TestInRegularAndScript1Async(
"""
class C
{
private int [|_g|];

public int CustomGetter
{
get => _g < 0 ? 0 : _g; // Synthesized return value
set => _g = value;
}
}
""",
"""
class C
{
public int CustomGetter
{
get => field < 0 ? 0 : field; // Synthesized return value
set;
}
}
""", new TestParameters(parseOptions: CSharp14));
}

[Fact, WorkItem("https://github.com/dotnet/roslyn/issues/76901")]
public async Task TestContractCall()
{
await TestInRegularAndScript1Async(
"""
class C
{
private int [|_s|];

public int CustomSetter
{
get => _s;
set
{
Assumes.True(value >= 0); // Validation
_s = value;
}
}
}
""",
"""
class C
{
public int CustomSetter
{
get;
set
{
Assumes.True(value >= 0); // Validation
field = value;
}
}
}
""", new TestParameters(parseOptions: CSharp14));
}

[Fact, WorkItem("https://github.com/dotnet/roslyn/issues/76901")]
public async Task TestDelegateInvoke()
{
await TestInRegularAndScript1Async(
"""
using System;

class C
{
private int [|_s|];
public event Action<string> OnChanged;

public int ObservableProp
{
get => _s;
set
{
_s = value;
OnChanged.Invoke(nameof(ObservableProp));
}
}
}
""",
"""
using System;

class C
{
public event Action<string> OnChanged;

public int ObservableProp
{
get;
set
{
field = value;
OnChanged.Invoke(nameof(ObservableProp));
}
}
}
""", new TestParameters(parseOptions: CSharp14));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Shared.Extensions;
using Microsoft.CodeAnalysis.CSharp.UseImplicitlyTypedLambdaExpression;
using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions;
using Microsoft.CodeAnalysis.Test.Utilities;
Expand All @@ -18,7 +19,7 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseImplicitlyTypedLambd
[Trait(Traits.Feature, Traits.Features.CodeActionsUseImplicitObjectCreation)]
public sealed class UseImplicitlyTypedLambdaExpressionTests
{
private static readonly LanguageVersion CSharp14 = LanguageVersion.Preview;
private static readonly LanguageVersion CSharp14 = LanguageVersionExtensions.CSharpNext;
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we use CSharpNext as there's a process where we look for this when adding the actual CSharp14 LangVersion before shpping that release.


[Fact]
public async Task TestAssignedToObject()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -82,9 +82,6 @@ public override DiagnosticAnalyzerCategory GetAnalyzerCategory()

protected abstract bool SupportsReadOnlyProperties(Compilation compilation);
protected abstract bool SupportsPropertyInitializer(Compilation compilation);
protected abstract bool SupportsFieldExpression(Compilation compilation);

protected abstract bool ContainsFieldExpression(TPropertyDeclaration propertyDeclaration, CancellationToken cancellationToken);

protected abstract TExpression? GetFieldInitializer(TVariableDeclarator variable, CancellationToken cancellationToken);
protected abstract TExpression? GetGetterExpression(IMethodSymbol getMethod, CancellationToken cancellationToken);
Expand Down Expand Up @@ -265,7 +262,7 @@ private AccessedFields GetGetterFields(
if (trivialFieldExpression != null)
return new(CheckFieldAccessExpression(semanticModel, trivialFieldExpression, fieldNames, cancellationToken));

if (!this.SupportsFieldExpression(semanticModel.Compilation))
if (!this.SyntaxFacts.SupportsFieldExpression(semanticModel.SyntaxTree.Options))
return AccessedFields.Empty;

using var _ = PooledHashSet<IFieldSymbol>.GetInstance(out var set);
Expand All @@ -281,7 +278,7 @@ private AccessedFields GetSetterFields(
if (trivialFieldExpression != null)
return new(CheckFieldAccessExpression(semanticModel, trivialFieldExpression, fieldNames, cancellationToken));

if (!this.SupportsFieldExpression(semanticModel.Compilation))
if (!this.SyntaxFacts.SupportsFieldExpression(semanticModel.SyntaxTree.Options))
return AccessedFields.Empty;

using var _ = PooledHashSet<IFieldSymbol>.GetInstance(out var set);
Expand Down Expand Up @@ -381,8 +378,11 @@ private void AnalyzePropertyDeclaration(
return;

// If the property already contains a `field` expression, then we can't do anything more here.
if (SupportsFieldExpression(compilation) && ContainsFieldExpression(propertyDeclaration, cancellationToken))
if (this.SyntaxFacts.SupportsFieldExpression(propertyDeclaration.SyntaxTree.Options) &&
propertyDeclaration.DescendantNodes().Any(this.SyntaxFacts.IsFieldExpression))
{
return;
}

var getterFields = GetGetterFields(semanticModel, property.GetMethod, fieldNames, cancellationToken);
getterFields = getterFields.Where(
Expand Down Expand Up @@ -550,7 +550,7 @@ private void Process(

// All the usages were inside the property. This is ok if we support the `field` keyword as those
// usages will be updated to that form.
if (!this.SupportsFieldExpression(context.Compilation))
if (!this.SyntaxFacts.SupportsFieldExpression(result.PropertyDeclaration.SyntaxTree.Options))
continue;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,18 +34,9 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.UseAutoProperty
Return DirectCast(compilation, VisualBasicCompilation).LanguageVersion >= LanguageVersion.VisualBasic10
End Function

Protected Overrides Function SupportsFieldExpression(compilation As Compilation) As Boolean
' 'field' keyword not supported in VB.
Return False
End Function

Protected Overrides ReadOnly Property CanExplicitInterfaceImplementationsBeFixed As Boolean = True
Protected Overrides ReadOnly Property SupportsFieldAttributesOnProperties As Boolean = False

Protected Overrides Function ContainsFieldExpression(propertyDeclaration As PropertyBlockSyntax, cancellationToken As CancellationToken) As Boolean
Return False
End Function

Protected Overrides Sub RecordIneligibleFieldLocations(
fieldNames As HashSet(Of String),
ineligibleFieldUsageIfOutsideProperty As ConcurrentDictionary(Of IFieldSymbol, ConcurrentSet(Of SyntaxNode)),
Expand Down
Loading
Loading