-
Notifications
You must be signed in to change notification settings - Fork 128
Add DynamicallyAccessedMembers analyzer #2184
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
mateoatr
merged 26 commits into
dotnet:feature/damAnalyzer
from
mateoatr:dynamicallyAccessedMembersAnalyzer
Sep 16, 2021
Merged
Changes from all commits
Commits
Show all changes
26 commits
Select commit
Hold shift + click to select a range
24e13e8
Add DiagnosticId enum
30beedd
Check that the diagnostic id is in the range of the supported linker …
4e0ef04
Lint
ee71998
Share DiagnosticString
84d4db0
Noisy whitespace
abf96d9
Warnings go up to 6000 inclusive
d448d37
PR feedback
fb34464
Get diagnostic string
844d3a7
Lint
a7a6dff
Tests
2b37d4a
Add warnings
df8dc26
Display members using the linker's format
7ad9664
Remove unused Xunit theory
5455141
Check for PublicParameterlessCtor
64c61e9
Refactor analyzer
7454a87
Merge
3ebd0d0
Delete SemanticModelExtensions
5a958f9
Update DiagnosticString
0de625b
Lint
12a2caf
Rename methods
8738b88
Don't warn when the method is RUC annotated
0ca4e6c
Merge branch 'main' into dynamicallyAccessedMembersAnalyzer
mateoatr 6dae3cb
Add comments, add source/targetIsMethodReturnType parameters
f7f1619
Match with NamedType for consistency
ef23bc4
Merge branch 'feature/damAnalyzer' into dynamicallyAccessedMembersAna…
mateoatr c2dc202
Remove GetMembersTypesString
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
95 changes: 95 additions & 0 deletions
95
src/ILLink.RoslynAnalyzer/DynamicallyAccessedMemberTypes.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,95 @@ | ||
// Licensed to the .NET Foundation under one or more agreements. | ||
// The .NET Foundation licenses this file to you under the MIT license. | ||
|
||
namespace System.Diagnostics.CodeAnalysis | ||
{ | ||
/// <summary> | ||
/// Specifies the types of members that are dynamically accessed. | ||
/// | ||
/// This enumeration has a <see cref="FlagsAttribute"/> attribute that allows a | ||
/// bitwise combination of its member values. | ||
/// </summary> | ||
[Flags] | ||
internal enum DynamicallyAccessedMemberTypes | ||
{ | ||
/// <summary> | ||
/// Specifies no members. | ||
/// </summary> | ||
None = 0, | ||
|
||
/// <summary> | ||
/// Specifies the default, parameterless public constructor. | ||
/// </summary> | ||
PublicParameterlessConstructor = 0x0001, | ||
|
||
/// <summary> | ||
/// Specifies all public constructors. | ||
/// </summary> | ||
PublicConstructors = 0x0002 | PublicParameterlessConstructor, | ||
|
||
/// <summary> | ||
/// Specifies all non-public constructors. | ||
/// </summary> | ||
NonPublicConstructors = 0x0004, | ||
|
||
/// <summary> | ||
/// Specifies all public methods. | ||
/// </summary> | ||
PublicMethods = 0x0008, | ||
|
||
/// <summary> | ||
/// Specifies all non-public methods. | ||
/// </summary> | ||
NonPublicMethods = 0x0010, | ||
|
||
/// <summary> | ||
/// Specifies all public fields. | ||
/// </summary> | ||
PublicFields = 0x0020, | ||
|
||
/// <summary> | ||
/// Specifies all non-public fields. | ||
/// </summary> | ||
NonPublicFields = 0x0040, | ||
|
||
/// <summary> | ||
/// Specifies all public nested types. | ||
/// </summary> | ||
PublicNestedTypes = 0x0080, | ||
|
||
/// <summary> | ||
/// Specifies all non-public nested types. | ||
/// </summary> | ||
NonPublicNestedTypes = 0x0100, | ||
|
||
/// <summary> | ||
/// Specifies all public properties. | ||
/// </summary> | ||
PublicProperties = 0x0200, | ||
|
||
/// <summary> | ||
/// Specifies all non-public properties. | ||
/// </summary> | ||
NonPublicProperties = 0x0400, | ||
|
||
/// <summary> | ||
/// Specifies all public events. | ||
/// </summary> | ||
PublicEvents = 0x0800, | ||
|
||
/// <summary> | ||
/// Specifies all non-public events. | ||
/// </summary> | ||
NonPublicEvents = 0x1000, | ||
|
||
/// <summary> | ||
/// Specifies all interfaces implemented by the type. | ||
/// </summary> | ||
Interfaces = 0x2000, | ||
|
||
/// <summary> | ||
/// Specifies all members. | ||
/// </summary> | ||
All = ~None | ||
} | ||
} |
243 changes: 243 additions & 0 deletions
243
src/ILLink.RoslynAnalyzer/DynamicallyAccessedMembersAnalyzer.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,243 @@ | ||
// 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.Collections.Generic; | ||
using System.Collections.Immutable; | ||
using ILLink.Shared; | ||
using Microsoft.CodeAnalysis; | ||
using Microsoft.CodeAnalysis.Diagnostics; | ||
using Microsoft.CodeAnalysis.Operations; | ||
|
||
namespace ILLink.RoslynAnalyzer | ||
{ | ||
[DiagnosticAnalyzer (LanguageNames.CSharp)] | ||
public class DynamicallyAccessedMembersAnalyzer : DiagnosticAnalyzer | ||
{ | ||
internal const string DynamicallyAccessedMembers = nameof (DynamicallyAccessedMembers); | ||
internal const string DynamicallyAccessedMembersAttribute = nameof (DynamicallyAccessedMembersAttribute); | ||
|
||
static ImmutableArray<DiagnosticDescriptor> GetSupportedDiagnostics () | ||
{ | ||
var diagDescriptorsArrayBuilder = ImmutableArray.CreateBuilder<DiagnosticDescriptor> (23); | ||
for (int i = (int) DiagnosticId.DynamicallyAccessedMembersMismatchParameterTargetsParameter; | ||
i <= (int) DiagnosticId.DynamicallyAccessedMembersMismatchTypeArgumentTargetsGenericParameter; i++) { | ||
diagDescriptorsArrayBuilder.Add (DiagnosticDescriptors.GetDiagnosticDescriptor ((DiagnosticId) i)); | ||
} | ||
|
||
return diagDescriptorsArrayBuilder.ToImmutable (); | ||
} | ||
|
||
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => GetSupportedDiagnostics (); | ||
|
||
public override void Initialize (AnalysisContext context) | ||
{ | ||
context.EnableConcurrentExecution (); | ||
context.ConfigureGeneratedCodeAnalysis (GeneratedCodeAnalysisFlags.ReportDiagnostics); | ||
context.RegisterOperationAction (operationAnalysisContext => { | ||
var assignmentOperation = (IAssignmentOperation) operationAnalysisContext.Operation; | ||
ProcessAssignmentOperation (operationAnalysisContext, assignmentOperation); | ||
}, OperationKind.SimpleAssignment); | ||
|
||
context.RegisterOperationAction (operationAnalysisContext => { | ||
var invocationOperation = (IInvocationOperation) operationAnalysisContext.Operation; | ||
ProcessInvocationOperation (operationAnalysisContext, invocationOperation); | ||
}, OperationKind.Invocation); | ||
|
||
context.RegisterOperationAction (operationAnalysisContext => { | ||
var returnOperation = (IReturnOperation) operationAnalysisContext.Operation; | ||
ProcessReturnOperation (operationAnalysisContext, returnOperation); | ||
}, OperationKind.Return); | ||
} | ||
|
||
static void ProcessAssignmentOperation (OperationAnalysisContext context, IAssignmentOperation assignmentOperation) | ||
{ | ||
if (context.ContainingSymbol.HasAttribute (RequiresUnreferencedCodeAnalyzer.FullyQualifiedRequiresUnreferencedCodeAttribute)) | ||
return; | ||
|
||
if (TryGetSymbolFromOperation (assignmentOperation.Target) is not ISymbol target || | ||
TryGetSymbolFromOperation (assignmentOperation.Value) is not ISymbol source) | ||
return; | ||
|
||
if (!target.TryGetDynamicallyAccessedMemberTypes (out var damtOnTarget)) | ||
return; | ||
|
||
source.TryGetDynamicallyAccessedMemberTypes (out var damtOnSource); | ||
if (Annotations.SourceHasRequiredAnnotations (damtOnSource, damtOnTarget, out var missingAnnotations)) | ||
return; | ||
|
||
var diag = GetDiagnosticId (source.Kind, target.Kind); | ||
var diagArgs = GetDiagnosticArguments (source.Kind == SymbolKind.NamedType ? context.ContainingSymbol : source, target, missingAnnotations); | ||
context.ReportDiagnostic (Diagnostic.Create (DiagnosticDescriptors.GetDiagnosticDescriptor (diag), assignmentOperation.Syntax.GetLocation (), diagArgs)); | ||
} | ||
|
||
static void ProcessInvocationOperation (OperationAnalysisContext context, IInvocationOperation invocationOperation) | ||
{ | ||
if (context.ContainingSymbol.HasAttribute (RequiresUnreferencedCodeAnalyzer.FullyQualifiedRequiresUnreferencedCodeAttribute)) | ||
return; | ||
|
||
ProcessTypeArguments (context, invocationOperation); | ||
ProcessArguments (context, invocationOperation); | ||
if (!invocationOperation.TargetMethod.TryGetDynamicallyAccessedMemberTypes (out var damtOnCalledMethod)) | ||
return; | ||
|
||
if (TryGetSymbolFromOperation (invocationOperation.Instance) is ISymbol instance && | ||
!instance.HasAttribute (RequiresUnreferencedCodeAnalyzer.FullyQualifiedRequiresUnreferencedCodeAttribute)) { | ||
instance!.TryGetDynamicallyAccessedMemberTypes (out var damtOnCaller); | ||
if (Annotations.SourceHasRequiredAnnotations (damtOnCaller, damtOnCalledMethod, out var missingAnnotations)) | ||
return; | ||
|
||
var diag = GetDiagnosticId (instance!.Kind, invocationOperation.TargetMethod.Kind); | ||
var diagArgs = GetDiagnosticArguments (instance.Kind == SymbolKind.NamedType ? context.ContainingSymbol : instance, invocationOperation.TargetMethod, missingAnnotations); | ||
context.ReportDiagnostic (Diagnostic.Create (DiagnosticDescriptors.GetDiagnosticDescriptor (diag), invocationOperation.Syntax.GetLocation (), diagArgs)); | ||
} | ||
} | ||
|
||
static void ProcessReturnOperation (OperationAnalysisContext context, IReturnOperation returnOperation) | ||
{ | ||
if (!context.ContainingSymbol.TryGetDynamicallyAccessedMemberTypesOnReturnType (out var damtOnReturnType) || | ||
context.ContainingSymbol.HasAttribute (RequiresUnreferencedCodeAnalyzer.FullyQualifiedRequiresUnreferencedCodeAttribute)) | ||
return; | ||
|
||
if (TryGetSymbolFromOperation (returnOperation) is not ISymbol returnedSymbol) | ||
return; | ||
|
||
returnedSymbol.TryGetDynamicallyAccessedMemberTypes (out var damtOnReturnedValue); | ||
if (Annotations.SourceHasRequiredAnnotations (damtOnReturnedValue, damtOnReturnType, out var missingAnnotations)) | ||
return; | ||
|
||
var diag = GetDiagnosticId (returnedSymbol.Kind, context.ContainingSymbol.Kind, true); | ||
var diagArgs = GetDiagnosticArguments (returnedSymbol.Kind == SymbolKind.NamedType ? context.ContainingSymbol : returnedSymbol, context.ContainingSymbol, missingAnnotations); | ||
context.ReportDiagnostic (Diagnostic.Create (DiagnosticDescriptors.GetDiagnosticDescriptor (diag), returnOperation.Syntax.GetLocation (), diagArgs)); | ||
mateoatr marked this conversation as resolved.
Show resolved
Hide resolved
|
||
} | ||
|
||
static void ProcessArguments (OperationAnalysisContext context, IInvocationOperation invocationOperation) | ||
{ | ||
if (context.ContainingSymbol.HasAttribute (RequiresUnreferencedCodeAnalyzer.FullyQualifiedRequiresUnreferencedCodeAttribute)) | ||
return; | ||
|
||
foreach (var argument in invocationOperation.Arguments) { | ||
var targetParameter = argument.Parameter; | ||
if (targetParameter is null || !targetParameter.TryGetDynamicallyAccessedMemberTypes (out var damtOnParameter)) | ||
return; | ||
|
||
bool sourceIsMethodReturnType = argument.Value.Kind != OperationKind.Conversion; | ||
ISymbol sourceArgument = sourceIsMethodReturnType ? TryGetSymbolFromOperation (argument.Value)! : context.ContainingSymbol; | ||
if (sourceArgument is null) | ||
return; | ||
|
||
sourceArgument.TryGetDynamicallyAccessedMemberTypes (out var damtOnArgument); | ||
if (Annotations.SourceHasRequiredAnnotations (damtOnArgument, damtOnParameter, out var missingAnnotations)) | ||
return; | ||
|
||
IMethodSymbol? callerMethod = null; | ||
// This can only happen within methods of System.Type and derived types. | ||
if (sourceArgument.Kind == SymbolKind.Method && !sourceIsMethodReturnType) { | ||
callerMethod = (IMethodSymbol?) sourceArgument; | ||
sourceArgument = sourceArgument.ContainingType; | ||
} | ||
|
||
var diag = GetDiagnosticId (sourceArgument.Kind, targetParameter.Kind); | ||
var diagArgs = GetDiagnosticArguments (callerMethod ?? sourceArgument, targetParameter, missingAnnotations); | ||
context.ReportDiagnostic (Diagnostic.Create (DiagnosticDescriptors.GetDiagnosticDescriptor (diag), argument.Syntax.GetLocation (), diagArgs)); | ||
} | ||
} | ||
|
||
static void ProcessTypeArguments (OperationAnalysisContext context, IInvocationOperation invocationOperation) | ||
{ | ||
var targetMethod = invocationOperation.TargetMethod; | ||
if (targetMethod.HasAttribute (RequiresUnreferencedCodeAnalyzer.FullyQualifiedRequiresUnreferencedCodeAttribute)) | ||
return; | ||
|
||
for (int i = 0; i < targetMethod.TypeParameters.Length; i++) { | ||
var arg = targetMethod.TypeArguments[i]; | ||
var param = targetMethod.TypeParameters[i]; | ||
if (!param.TryGetDynamicallyAccessedMemberTypes (out var damtOnTypeParameter)) | ||
continue; | ||
|
||
arg.TryGetDynamicallyAccessedMemberTypes (out var damtOnTypeArgument); | ||
if (Annotations.SourceHasRequiredAnnotations (damtOnTypeArgument, damtOnTypeParameter, out var missingAnnotations)) | ||
continue; | ||
|
||
var diag = GetDiagnosticId (arg.Kind, param.Kind); | ||
var diagArgs = GetDiagnosticArguments (arg, param, missingAnnotations); | ||
context.ReportDiagnostic (Diagnostic.Create (DiagnosticDescriptors.GetDiagnosticDescriptor (diag), invocationOperation.Syntax.GetLocation (), diagArgs)); | ||
} | ||
} | ||
|
||
static DiagnosticId GetDiagnosticId (SymbolKind source, SymbolKind target, bool targetIsMethodReturnType = false) | ||
=> (source, target) switch { | ||
(SymbolKind.Parameter, SymbolKind.Field) => DiagnosticId.DynamicallyAccessedMembersMismatchParameterTargetsField, | ||
(SymbolKind.Parameter, SymbolKind.Method) => targetIsMethodReturnType ? | ||
DiagnosticId.DynamicallyAccessedMembersMismatchParameterTargetsMethodReturnType : | ||
DiagnosticId.DynamicallyAccessedMembersMismatchParameterTargetsThisParameter, | ||
(SymbolKind.Parameter, SymbolKind.Parameter) => DiagnosticId.DynamicallyAccessedMembersMismatchParameterTargetsParameter, | ||
(SymbolKind.Field, SymbolKind.Parameter) => DiagnosticId.DynamicallyAccessedMembersMismatchFieldTargetsParameter, | ||
(SymbolKind.Field, SymbolKind.Field) => DiagnosticId.DynamicallyAccessedMembersMismatchFieldTargetsField, | ||
(SymbolKind.Field, SymbolKind.Method) => targetIsMethodReturnType ? | ||
DiagnosticId.DynamicallyAccessedMembersMismatchFieldTargetsMethodReturnType : | ||
DiagnosticId.DynamicallyAccessedMembersMismatchFieldTargetsThisParameter, | ||
(SymbolKind.Field, SymbolKind.TypeParameter) => DiagnosticId.DynamicallyAccessedMembersMismatchFieldTargetsGenericParameter, | ||
(SymbolKind.NamedType, SymbolKind.Method) => targetIsMethodReturnType ? | ||
DiagnosticId.DynamicallyAccessedMembersMismatchThisParameterTargetsMethodReturnType : | ||
DiagnosticId.DynamicallyAccessedMembersMismatchThisParameterTargetsThisParameter, | ||
(SymbolKind.Method, SymbolKind.Field) => DiagnosticId.DynamicallyAccessedMembersMismatchMethodReturnTypeTargetsField, | ||
(SymbolKind.Method, SymbolKind.Method) => targetIsMethodReturnType ? | ||
DiagnosticId.DynamicallyAccessedMembersMismatchMethodReturnTypeTargetsMethodReturnType : | ||
DiagnosticId.DynamicallyAccessedMembersMismatchMethodReturnTypeTargetsThisParameter, | ||
// Source here will always be a method's return type. | ||
(SymbolKind.Method, SymbolKind.Parameter) => DiagnosticId.DynamicallyAccessedMembersMismatchMethodReturnTypeTargetsParameter, | ||
(SymbolKind.NamedType, SymbolKind.Field) => DiagnosticId.DynamicallyAccessedMembersMismatchThisParameterTargetsField, | ||
(SymbolKind.NamedType, SymbolKind.Parameter) => DiagnosticId.DynamicallyAccessedMembersMismatchThisParameterTargetsParameter, | ||
(SymbolKind.TypeParameter, SymbolKind.Field) => DiagnosticId.DynamicallyAccessedMembersMismatchTypeArgumentTargetsField, | ||
(SymbolKind.TypeParameter, SymbolKind.Method) => DiagnosticId.DynamicallyAccessedMembersMismatchTypeArgumentTargetsMethodReturnType, | ||
(SymbolKind.TypeParameter, SymbolKind.Parameter) => DiagnosticId.DynamicallyAccessedMembersMismatchTypeArgumentTargetsParameter, | ||
(SymbolKind.TypeParameter, SymbolKind.TypeParameter) => DiagnosticId.DynamicallyAccessedMembersMismatchTypeArgumentTargetsGenericParameter, | ||
_ => throw new NotImplementedException () | ||
}; | ||
|
||
static string[] GetDiagnosticArguments (ISymbol source, ISymbol target, string missingAnnotations) | ||
{ | ||
var args = new List<string> (); | ||
args.AddRange (GetDiagnosticArguments (target)); | ||
args.AddRange (GetDiagnosticArguments (source)); | ||
args.Add (missingAnnotations); | ||
return args.ToArray (); | ||
} | ||
|
||
static IEnumerable<string> GetDiagnosticArguments (ISymbol symbol) | ||
{ | ||
var args = new List<string> (); | ||
args.AddRange (symbol.Kind switch { | ||
SymbolKind.Parameter => new string[] { symbol.GetDisplayName (), symbol.ContainingSymbol.GetDisplayName () }, | ||
SymbolKind.NamedType => new string[] { symbol.GetDisplayName () }, | ||
SymbolKind.Field => new string[] { symbol.GetDisplayName () }, | ||
SymbolKind.Method => new string[] { symbol.GetDisplayName () }, | ||
SymbolKind.TypeParameter => new string[] { symbol.GetDisplayName (), symbol.ContainingSymbol.GetDisplayName () }, | ||
_ => throw new NotImplementedException ($"Unsupported source or target symbol {symbol}.") | ||
}); | ||
|
||
return args; | ||
} | ||
|
||
static ISymbol? TryGetSymbolFromOperation (IOperation? operation) => | ||
operation switch { | ||
IArgumentOperation argument => TryGetSymbolFromOperation (argument.Value), | ||
IAssignmentOperation assignment => TryGetSymbolFromOperation (assignment.Value), | ||
IConversionOperation conversion => TryGetSymbolFromOperation (conversion.Operand), | ||
// Represents an implicit/explicit reference to an instance. We grab the result type of this operation. | ||
// In cases where this is an implicit reference, this will result in returning the actual type of the | ||
// instance that 'this' represents. | ||
IInstanceReferenceOperation instanceReference => instanceReference.Type, | ||
mateoatr marked this conversation as resolved.
Show resolved
Hide resolved
|
||
// The target method of an invocation represents the called method. If this invocation is found within | ||
// a return operation, this representes the returned value, which might be annotated. | ||
IInvocationOperation invocation => invocation.TargetMethod, | ||
mateoatr marked this conversation as resolved.
Show resolved
Hide resolved
|
||
IMemberReferenceOperation memberReference => memberReference.Member, | ||
IParameterReferenceOperation parameterReference => parameterReference.Parameter, | ||
IReturnOperation returnOp => TryGetSymbolFromOperation (returnOp.ReturnedValue), | ||
ITypeOfOperation typeOf => typeOf.TypeOperand, | ||
sbomer marked this conversation as resolved.
Show resolved
Hide resolved
|
||
_ => null | ||
}; | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.