Skip to content

Warn on RUC annotated attribute ctors (analyzer) #2201

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

Merged
merged 10 commits into from
Sep 16, 2021
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
104 changes: 85 additions & 19 deletions src/ILLink.RoslynAnalyzer/RequiresAnalyzerBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -43,26 +43,44 @@ public override void Initialize (AnalysisContext context)
context.RegisterSymbolAction (symbolAnalysisContext => {
var methodSymbol = (IMethodSymbol) symbolAnalysisContext.Symbol;
CheckMatchingAttributesInOverrides (symbolAnalysisContext, methodSymbol);
CheckAttributeInstantiation (symbolAnalysisContext, methodSymbol);
foreach (var typeParameter in methodSymbol.TypeParameters)
CheckAttributeInstantiation (symbolAnalysisContext, typeParameter);

}, SymbolKind.Method);

context.RegisterSymbolAction (symbolAnalysisContext => {
var typeSymbol = (INamedTypeSymbol) symbolAnalysisContext.Symbol;
CheckMatchingAttributesInInterfaces (symbolAnalysisContext, typeSymbol);
CheckAttributeInstantiation (symbolAnalysisContext, typeSymbol);
foreach (var typeParameter in typeSymbol.TypeParameters)
CheckAttributeInstantiation (symbolAnalysisContext, typeParameter);

}, SymbolKind.NamedType);

if (AnalyzerDiagnosticTargets.HasFlag (DiagnosticTargets.Property)) {
context.RegisterSymbolAction (symbolAnalysisContext => {
var propertySymbol = (IPropertySymbol) symbolAnalysisContext.Symbol;

context.RegisterSymbolAction (symbolAnalysisContext => {
var propertySymbol = (IPropertySymbol) symbolAnalysisContext.Symbol;
if (AnalyzerDiagnosticTargets.HasFlag (DiagnosticTargets.Property)) {
CheckMatchingAttributesInOverrides (symbolAnalysisContext, propertySymbol);
}, SymbolKind.Property);
}
}

CheckAttributeInstantiation (symbolAnalysisContext, propertySymbol);
}, SymbolKind.Property);

if (AnalyzerDiagnosticTargets.HasFlag (DiagnosticTargets.Event)) {
context.RegisterSymbolAction (symbolAnalysisContext => {
var eventSymbol = (IEventSymbol) symbolAnalysisContext.Symbol;
context.RegisterSymbolAction (symbolAnalysisContext => {
var eventSymbol = (IEventSymbol) symbolAnalysisContext.Symbol;
if (AnalyzerDiagnosticTargets.HasFlag (DiagnosticTargets.Event)) {
CheckMatchingAttributesInOverrides (symbolAnalysisContext, eventSymbol);
}, SymbolKind.Event);
}
}

CheckAttributeInstantiation (symbolAnalysisContext, eventSymbol);
}, SymbolKind.Event);

context.RegisterSymbolAction (symbolAnalysisContext => {
var fieldSymbol = (IFieldSymbol) symbolAnalysisContext.Symbol;
CheckAttributeInstantiation (symbolAnalysisContext, fieldSymbol);
}, SymbolKind.Field);

context.RegisterOperationAction (operationContext => {
var methodInvocation = (IInvocationOperation) operationContext.Operation;
Expand Down Expand Up @@ -99,12 +117,17 @@ public override void Initialize (AnalysisContext context)
CheckCalledMember (operationContext, prop, incompatibleMembers);
}, OperationKind.PropertyReference);

if (AnalyzerDiagnosticTargets.HasFlag (DiagnosticTargets.Event)) {
context.RegisterOperationAction (operationContext => {
var eventRef = (IEventReferenceOperation) operationContext.Operation;
CheckCalledMember (operationContext, eventRef.Member, incompatibleMembers);
}, OperationKind.EventReference);
}
context.RegisterOperationAction (operationContext => {
var eventRef = (IEventReferenceOperation) operationContext.Operation;
var eventSymbol = (IEventSymbol) eventRef.Member;
CheckCalledMember (operationContext, eventSymbol, incompatibleMembers);

if (eventSymbol.AddMethod is IMethodSymbol eventAddMethod)
CheckCalledMember (operationContext, eventAddMethod, incompatibleMembers);

if (eventSymbol.RemoveMethod is IMethodSymbol eventRemoveMethod)
CheckCalledMember (operationContext, eventRemoveMethod, incompatibleMembers);
}, OperationKind.EventReference);

context.RegisterOperationAction (operationContext => {
var delegateCreation = (IDelegateCreationOperation) operationContext.Operation;
Expand All @@ -115,6 +138,7 @@ public override void Initialize (AnalysisContext context)
methodSymbol = lambda.Symbol;
else
return;

CheckCalledMember (operationContext, methodSymbol, incompatibleMembers);
}, OperationKind.DelegateCreation);

Expand All @@ -125,6 +149,35 @@ public override void Initialize (AnalysisContext context)
foreach (var extraSyntaxNodeAction in ExtraSyntaxNodeActions)
context.RegisterSyntaxNodeAction (extraSyntaxNodeAction.Action, extraSyntaxNodeAction.SyntaxKind);

void CheckAttributeInstantiation (
SymbolAnalysisContext symbolAnalysisContext,
ISymbol symbol)
{
if (symbol.HasAttribute (RequiresAttributeName))
return;

foreach (var attr in symbol.GetAttributes ()) {
if (TryGetRequiresAttribute (attr.AttributeConstructor, out var requiresAttribute)) {
symbolAnalysisContext.ReportDiagnostic (Diagnostic.Create (RequiresDiagnosticRule,
symbol.Locations[0], attr.AttributeConstructor!.Name, GetMessageFromAttribute (requiresAttribute), GetUrlFromAttribute (requiresAttribute)));
}

foreach (var namedArgument in attr.NamedArguments) {
var propertyOnArgument = attr.AttributeClass!.GetMembers ()
.Where (m => m.Kind == SymbolKind.Property && m.Name == namedArgument.Key)
.FirstOrDefault ();

if (propertyOnArgument is not IPropertySymbol setProperty)
continue;

if (setProperty.SetMethod is IMethodSymbol setter && setter.TryGetAttribute (RequiresAttributeFullyQualifiedName, out var requiresAttributeOnProperty)) {
symbolAnalysisContext.ReportDiagnostic (Diagnostic.Create (RequiresDiagnosticRule,
symbol.Locations[0], attr.AttributeConstructor!.Name, GetMessageFromAttribute (requiresAttributeOnProperty), GetUrlFromAttribute (requiresAttributeOnProperty)));
}
}
}
}

void CheckStaticConstructors (OperationAnalysisContext operationContext,
ImmutableArray<IMethodSymbol> staticConstructors)
{
Expand All @@ -144,10 +197,11 @@ void CheckCalledMember (
// Do not emit any diagnostic if caller is annotated with the attribute too.
if (containingSymbol.HasAttribute (RequiresAttributeName))
return;

// Check also for RequiresAttribute in the associated symbol
if (containingSymbol is IMethodSymbol methodSymbol && methodSymbol.AssociatedSymbol is not null && methodSymbol.AssociatedSymbol!.HasAttribute (RequiresAttributeName)) {
if (containingSymbol is IMethodSymbol methodSymbol && methodSymbol.AssociatedSymbol is not null && methodSymbol.AssociatedSymbol!.HasAttribute (RequiresAttributeName))
return;
}

// If calling an instance constructor, check first for any static constructor since it will be called implicitly
if (member.ContainingType is { } containingType && operationContext.Operation is IObjectCreationOperation)
CheckStaticConstructors (operationContext, containingType.StaticConstructors);
Expand All @@ -163,6 +217,14 @@ void CheckCalledMember (
member = method.OverriddenMethod;

if (TryGetRequiresAttribute (member, out var requiresAttribute)) {
if (member is IMethodSymbol eventAccessorMethod && eventAccessorMethod.AssociatedSymbol is IEventSymbol eventSymbol) {
// If the annotated member is an event accessor, we warn on the event to match the linker behavior.
member = eventAccessorMethod.ContainingSymbol;
operationContext.ReportDiagnostic (Diagnostic.Create (RequiresDiagnosticRule,
eventSymbol.Locations[0], member.Name, GetMessageFromAttribute (requiresAttribute), GetUrlFromAttribute (requiresAttribute)));
return;
}

ReportRequiresDiagnostic (operationContext, member, requiresAttribute);
}
}
Expand Down Expand Up @@ -281,9 +343,12 @@ public static string GetUrlFromAttribute (AttributeData? requiresAttribute)
/// <param name="member">Symbol of the member to search attribute.</param>
/// <param name="requiresAttribute">Output variable in case of matching Requires attribute.</param>
/// <returns>True if the member contains a Requires attribute; otherwise, returns false.</returns>
private bool TryGetRequiresAttribute (ISymbol member, [NotNullWhen (returnValue: true)] out AttributeData? requiresAttribute)
private bool TryGetRequiresAttribute (ISymbol? member, [NotNullWhen (returnValue: true)] out AttributeData? requiresAttribute)
{
requiresAttribute = null;
if (member == null)
return false;

foreach (var _attribute in member.GetAttributes ()) {
if (_attribute.AttributeClass is { } attrClass &&
attrClass.HasName (RequiresAttributeFullyQualifiedName) &&
Expand All @@ -292,6 +357,7 @@ private bool TryGetRequiresAttribute (ISymbol member, [NotNullWhen (returnValue:
return true;
}
}

return false;
}

Expand Down
14 changes: 7 additions & 7 deletions test/ILLink.RoslynAnalyzer.Tests/LinkerTestCases.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,14 +15,14 @@ public class LinkerTestCases : TestCaseUtils
{
[Theory]
[MemberData (nameof (TestCaseUtils.GetTestData), parameters: nameof (RequiresCapability))]
public void RequiresCapability (MethodDeclarationSyntax m, List<AttributeSyntax> attrs)
public void RequiresCapability (MemberDeclarationSyntax m, List<AttributeSyntax> attrs)
{
switch (m.Identifier.ValueText) {
// There is a discrepancy between the way linker and the analyzer represent the location of the error,
// linker will point to the method caller and the analyzer will point to a line of code.
// The TestTypeIsBeforeFieldInit scenario is supported by the analyzer, just the diagnostic message is different
// We verify the analyzer generating the right diagnostic in RequiresUnreferencedCodeAnalyzerTests.cs
case "TestTypeIsBeforeFieldInit":
if (m is MethodDeclarationSyntax method &&
method.Identifier.ValueText == "TestTypeIsBeforeFieldInit") {
// There is a discrepancy between the way linker and the analyzer represent the location of the error,
// linker will point to the method caller and the analyzer will point to a line of code.
// The TestTypeIsBeforeFieldInit scenario is supported by the analyzer, just the diagnostic message is different
// We verify the analyzer generating the right diagnostic in RequiresUnreferencedCodeAnalyzerTests.cs
return;
}

Expand Down
26 changes: 22 additions & 4 deletions test/ILLink.RoslynAnalyzer.Tests/TestCaseUtils.cs
Original file line number Diff line number Diff line change
Expand Up @@ -57,8 +57,6 @@ static bool IsWellKnown (AttributeSyntax attr)
case "ExpectedWarning":
case "LogContains":
case "LogDoesNotContain":
return attr.Ancestors ().OfType<MemberDeclarationSyntax> ().First ().IsKind (SyntaxKind.MethodDeclaration);

case "UnrecognizedReflectionAccessPattern":
return true;
}
Expand All @@ -71,8 +69,13 @@ static bool IsWellKnown (AttributeSyntax attr)
public static void RunTest<TAnalyzer> (MemberDeclarationSyntax m, List<AttributeSyntax> attrs, params (string, string)[] MSBuildProperties)
where TAnalyzer : DiagnosticAnalyzer, new()
{
var testSyntaxTree = m.SyntaxTree.GetRoot ().SyntaxTree;
var testDependenciesSource = GetTestDependencies (testSyntaxTree)
.Select (testDependency => CSharpSyntaxTree.ParseText (File.ReadAllText (testDependency)));

var test = new TestChecker (m, CSharpAnalyzerVerifier<TAnalyzer>
.CreateCompilation (m.SyntaxTree.GetRoot ().SyntaxTree, MSBuildProperties).Result);
.CreateCompilation (testSyntaxTree, MSBuildProperties, additionalSources: testDependenciesSource).Result);

test.ValidateAttributes (attrs);
}

Expand Down Expand Up @@ -171,7 +174,6 @@ public static Dictionary<string, ExpressionSyntax> GetAttributeArguments (Attrib
public static IEnumerable<string> GetTestFiles ()
{
GetDirectoryPaths (out var rootSourceDir, out _);

foreach (var subDir in Directory.EnumerateDirectories (rootSourceDir, "*", SearchOption.AllDirectories)) {
var subDirName = Path.GetFileName (subDir);
switch (subDirName) {
Expand Down Expand Up @@ -200,5 +202,21 @@ public static string GetRepoRoot ()

string ThisFile ([CallerFilePath] string path = "") => path;
}

public static IEnumerable<string> GetTestDependencies (SyntaxTree testSyntaxTree)
{
GetDirectoryPaths (out var rootSourceDir, out _);
foreach (var attribute in testSyntaxTree.GetRoot ().DescendantNodes ().OfType<AttributeSyntax> ()) {
if (attribute.Name.ToString () != "SetupCompileBefore")
continue;

var testNamespace = testSyntaxTree.GetRoot ().DescendantNodes ().OfType<NamespaceDeclarationSyntax> ().Single ().Name.ToString ();
var testSuiteName = testNamespace.Substring (testNamespace.LastIndexOf ('.') + 1);
var args = GetAttributeArguments (attribute);
string outputName = GetStringFromExpression (args["#0"]);
foreach (var sourceFile in ((ImplicitArrayCreationExpressionSyntax) args["#1"]).DescendantNodes ().OfType<LiteralExpressionSyntax> ())
yield return Path.Combine (rootSourceDir, testSuiteName, GetStringFromExpression (sourceFile));
}
}
}
}
6 changes: 4 additions & 2 deletions test/ILLink.RoslynAnalyzer.Tests/TestChecker.cs
Original file line number Diff line number Diff line change
Expand Up @@ -64,8 +64,10 @@ private void ValidateExpectedWarningAttribute (AttributeSyntax attribute)
if (!expectedWarningCode.StartsWith ("IL"))
return;

if (args.TryGetValue ("GlobalAnalysisOnly", out var globalAnalysisOnly) &&
globalAnalysisOnly is LiteralExpressionSyntax { Token: { Value: true } })
if (args.TryGetValue ("ProducedBy", out var producedBy) &&
producedBy is MemberAccessExpressionSyntax memberAccessExpression &&
memberAccessExpression.Name is IdentifierNameSyntax identifierNameSyntax &&
identifierNameSyntax.Identifier.ValueText == "Trimmer")
return;

List<string> expectedMessages = args
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,22 +37,26 @@ public static DiagnosticResult Diagnostic (DiagnosticDescriptor descriptor)
public static Task<(CompilationWithAnalyzers Compilation, SemanticModel SemanticModel)> CreateCompilation (
string src,
(string, string)[]? globalAnalyzerOptions = null,
IEnumerable<MetadataReference>? additionalReferences = null)
=> CreateCompilation (CSharpSyntaxTree.ParseText (src), globalAnalyzerOptions, additionalReferences);
IEnumerable<MetadataReference>? additionalReferences = null,
IEnumerable<SyntaxTree>? additionalSources = null)
=> CreateCompilation (CSharpSyntaxTree.ParseText (src), globalAnalyzerOptions, additionalReferences, additionalSources);

public static async Task<Compilation> GetCompilation (string source, IEnumerable<MetadataReference>? additionalReferences = null)
public static async Task<Compilation> GetCompilation (string source, IEnumerable<MetadataReference>? additionalReferences = null, IEnumerable<SyntaxTree>? additionalSources = null)
=> (await CSharpAnalyzerVerifier<RequiresAssemblyFilesAnalyzer>.CreateCompilation (source, additionalReferences: additionalReferences ?? Array.Empty<MetadataReference> ())).Compilation.Compilation;

public static async Task<(CompilationWithAnalyzers Compilation, SemanticModel SemanticModel)> CreateCompilation (
SyntaxTree src,
(string, string)[]? globalAnalyzerOptions = null,
IEnumerable<MetadataReference>? additionalReferences = null)
IEnumerable<MetadataReference>? additionalReferences = null,
IEnumerable<SyntaxTree>? additionalSources = null)
{
var mdRef = MetadataReference.CreateFromFile (typeof (Mono.Linker.Tests.Cases.Expectations.Metadata.BaseMetadataAttribute).Assembly.Location);
additionalReferences ??= Array.Empty<MetadataReference> ();
var sources = new List<SyntaxTree> () { src };
sources.AddRange (additionalSources ?? Array.Empty<SyntaxTree> ());
var comp = CSharpCompilation.Create (
assemblyName: Guid.NewGuid ().ToString ("N"),
syntaxTrees: new SyntaxTree[] { src },
syntaxTrees: sources,
references: (await TestCaseUtils.GetNet6References ()).Add (mdRef).AddRange (additionalReferences),
new CSharpCompilationOptions (OutputKind.DynamicallyLinkedLibrary));

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,11 @@ public ExpectedWarningAttribute (string warningCode, params string[] messageCont
public int SourceLine { get; set; }
public int SourceColumn { get; set; }

// Set to true if the warning only applies to global analysis (ILLinker, as opposed to Roslyn Analyzer)
public bool GlobalAnalysisOnly { get; set; }
/// <summary>
/// Property used by the result checkers of trimmer and analyzers to determine whether
/// the tool should have produced the specified warning on the annotated member.
/// </summary>
public ProducedBy ProducedBy { get; set; } = ProducedBy.TrimmerAndAnalyzer;

public bool CompilerGeneratedCode { get; set; }
}
Expand Down
16 changes: 16 additions & 0 deletions test/Mono.Linker.Tests.Cases.Expectations/Assertions/ProducedBy.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;

namespace Mono.Linker.Tests.Cases.Expectations.Assertions
{
[Flags]
public enum ProducedBy
{
Trimmer = 1,
Analyzer = 2,
TrimmerAndAnalyzer = Trimmer | Analyzer
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using System.Diagnostics.CodeAnalysis;

namespace Mono.Linker.Tests.Cases.RequiresCapability.Dependencies
{
public class RequiresUnreferencedCodeOnAttributeCtorAttribute : Attribute
{
[RequiresUnreferencedCode ("Message from attribute's ctor.")]
public RequiresUnreferencedCodeOnAttributeCtorAttribute ()
{
}
}
}
Loading