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

Include experimental attribute in API definition for properties #7232

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@ private sealed class Impl
private readonly ConcurrentDictionary<SyntaxTree, ImmutableArray<string>> _skippedNamespacesCache = new();
private readonly Lazy<IReadOnlyDictionary<string, ApiLine>> _apiMap;
private readonly AnalyzerOptions _analyzerOptions;
private readonly INamedTypeSymbol? _experimentalAttributeType;

internal Impl(Compilation compilation, ImmutableDictionary<AdditionalText, SourceText> additionalFiles, ApiData shippedData, ApiData unshippedData, bool isPublic, AnalyzerOptions analyzerOptions)
{
Expand All @@ -92,6 +93,9 @@ internal Impl(Compilation compilation, ImmutableDictionary<AdditionalText, Sourc
_isPublic = isPublic;
_analyzerOptions = analyzerOptions;

var typeProvider = WellKnownTypeProvider.GetOrCreate(compilation);
_experimentalAttributeType = typeProvider.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemDiagnosticsCodeAnalysisExperimentalAttribute);

static IReadOnlyDictionary<string, ApiLine> CreateApiMap(ApiData shippedData, ApiData unshippedData)
{
// Defer allocating/creating the apiMap until it's needed as there are many cases where it's never used
Expand Down Expand Up @@ -589,19 +593,40 @@ private static bool UsesOblivious(ISymbol symbol)

private ApiName GetApiName(ISymbol symbol)
{
var experimentName = getExperimentName(symbol);
var experimentName = getExperimentName(symbol, _experimentalAttributeType);

return new ApiName(
getApiString(_compilation, symbol, experimentName, s_publicApiFormat),
getApiString(_compilation, symbol, experimentName, s_publicApiFormatWithNullability));

static string? getExperimentName(ISymbol symbol)
static string? getExperimentName(ISymbol symbol, INamedTypeSymbol? experimentalAttribute)
{
if (experimentalAttribute is null)
{
return null;
}

for (var current = symbol; current is not null; current = current.ContainingSymbol)
{
foreach (var attribute in current.GetAttributes())
string? diagnosticId = GetDiagnosticIdFromExperimentalAttribute(current.GetAttributes(), experimentalAttribute);
if (diagnosticId is null && current is IMethodSymbol { AssociatedSymbol: IPropertySymbol property })
{
if (attribute.AttributeClass is { Name: "ExperimentalAttribute", ContainingSymbol: INamespaceSymbol { Name: nameof(System.Diagnostics.CodeAnalysis), ContainingNamespace: { Name: nameof(System.Diagnostics), ContainingNamespace: { Name: nameof(System), ContainingNamespace.IsGlobalNamespace: true } } } })
diagnosticId = GetDiagnosticIdFromExperimentalAttribute(property.GetAttributes(), experimentalAttribute);
}

if (diagnosticId is not null)
{
return diagnosticId;
}
}

return null;

static string? GetDiagnosticIdFromExperimentalAttribute(ImmutableArray<AttributeData> attributes, INamedTypeSymbol experimentalAttribute)
{
foreach (var attribute in attributes)
{
if (SymbolEqualityComparer.Default.Equals(attribute.AttributeClass, experimentalAttribute))
{
if (attribute.ConstructorArguments is not [{ Kind: TypedConstantKind.Primitive, Type.SpecialType: SpecialType.System_String, Value: string diagnosticId }])
return "???";
Expand All @@ -610,9 +635,9 @@ private ApiName GetApiName(ISymbol symbol)

}
}
}

return null;
return null;
}
}

static string getApiString(Compilation compilation, ISymbol symbol, string? experimentName, SymbolDisplayFormat format)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3295,6 +3295,106 @@ public async Task TestExperimentalApiWithInvalidArgumentAsync(string invalidArgu
await test.RunAsync();
}

[Fact]
[WorkItem(7195, "https://github.com/dotnet/roslyn-analyzers/issues/7195")]
public async Task TestExperimentalApiWithProperty()
{
var source = $$"""
using System.Diagnostics.CodeAnalysis;

{{EnabledModifierCSharp}} class C
{
[Experimental("RSEXPERIMENTAL001")]
{{EnabledModifierCSharp}} bool DisableNullableAnalysis { {|{{AddNewApiId}}:get|}; }
}
""";

const string shippedText = """
C
C.C() -> void
""";
const string fixedUnshippedText = """
[RSEXPERIMENTAL001]C.DisableNullableAnalysis.get -> bool
""";

var test = new CSharpCodeFixTest<DeclarePublicApiAnalyzer, DeclarePublicApiFix, XUnitVerifier>()
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net80,
CompilerDiagnostics = CompilerDiagnostics.None,
TestState =
{
Sources = { source },
AdditionalFiles =
{
(ShippedFileName, shippedText),
(UnshippedFileName, string.Empty),
},
},
FixedState =
{
AdditionalFiles =
{
(ShippedFileName, shippedText),
(UnshippedFileName, fixedUnshippedText),
},
},
};

test.DisabledDiagnostics.AddRange(DisabledDiagnostics);

await test.RunAsync();
}

[Fact]
[WorkItem(7195, "https://github.com/dotnet/roslyn-analyzers/issues/7195")]
public async Task TestExperimentalApiWithAbstractProperty()
{
var source = $$"""
using System.Diagnostics.CodeAnalysis;

{{EnabledModifierCSharp}} class C
{
[Experimental("RSEXPERIMENTAL001")]
{{EnabledModifierCSharp}} abstract bool DisableNullableAnalysis { {|{{AddNewApiId}}:get|}; }
}
""";

const string shippedText = """
C
C.C() -> void
""";
const string fixedUnshippedText = """
[RSEXPERIMENTAL001]abstract C.DisableNullableAnalysis.get -> bool
""";

var test = new CSharpCodeFixTest<DeclarePublicApiAnalyzer, DeclarePublicApiFix, XUnitVerifier>()
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net80,
CompilerDiagnostics = CompilerDiagnostics.None,
TestState =
{
Sources = { source },
AdditionalFiles =
{
(ShippedFileName, shippedText),
(UnshippedFileName, string.Empty),
},
},
FixedState =
{
AdditionalFiles =
{
(ShippedFileName, shippedText),
(UnshippedFileName, fixedUnshippedText),
},
},
};

test.DisabledDiagnostics.AddRange(DisabledDiagnostics);

await test.RunAsync();
}

#endregion
}
}
1 change: 1 addition & 0 deletions src/Utilities/Compiler/WellKnownTypeNames.cs
Original file line number Diff line number Diff line change
Expand Up @@ -214,6 +214,7 @@ internal static class WellKnownTypeNames
public const string SystemDecimal = "System.Decimal";
public const string SystemDiagnosticContractsContract = "System.Diagnostics.Contracts.Contract";
public const string SystemDiagnosticsCodeAnalysisConstantExpectedAttribute = "System.Diagnostics.CodeAnalysis.ConstantExpectedAttribute";
public const string SystemDiagnosticsCodeAnalysisExperimentalAttribute = "System.Diagnostics.CodeAnalysis.ExperimentalAttribute";
public const string SystemDiagnosticsCodeAnalysisNotNullAttribute = "System.Diagnostics.CodeAnalysis.NotNullAttribute";
public const string SystemDiagnosticsCodeAnalysisNotNullIfNotNullAttribute = "System.Diagnostics.CodeAnalysis.NotNullIfNotNullAttribute";
public const string SystemDiagnosticsCodeAnalysisStringSyntaxAttributeName = "System.Diagnostics.CodeAnalysis.StringSyntaxAttribute";
Expand Down