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

Ruc on type analyzer part 1 #2330

Merged
merged 10 commits into from
Oct 29, 2021
Binary file not shown.
Binary file not shown.
10 changes: 10 additions & 0 deletions src/ILLink.RoslynAnalyzer/IOperationExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -242,5 +242,15 @@ public static bool IsAnyCompoundAssignment (this IOperation operation)
return false;
}
}

/*
public static IEventAssignmentOperation GetEventUsageInfo (this IOperation operation)
{
if (operation.Parent is IEventAssignmentOperation assignmentOperation) {
return assignmentOperation;
}
return null;
}
*/
}
}
14 changes: 6 additions & 8 deletions src/ILLink.RoslynAnalyzer/ISymbolExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -49,14 +49,6 @@ public static string GetDisplayName (this ISymbol symbol)
{
var sb = new StringBuilder ();
switch (symbol) {
case IFieldSymbol fieldSymbol:
sb.Append (fieldSymbol.Type);
sb.Append (" ");
sb.Append (fieldSymbol.ContainingSymbol.ToDisplayString ());
sb.Append ("::");
sb.Append (fieldSymbol.MetadataName);
break;

case IParameterSymbol parameterSymbol:
sb.Append (parameterSymbol.Name);
break;
Expand Down Expand Up @@ -93,5 +85,11 @@ public static bool IsSubclassOf (this ISymbol symbol, string ns, string type)

return false;
}

public static bool IsConstructor ([NotNullWhen (returnValue: true)] this ISymbol? symbol)
=> (symbol as IMethodSymbol)?.MethodKind == MethodKind.Constructor;

public static bool IsStaticConstructor ([NotNullWhen (returnValue: true)] this ISymbol? symbol)
=> (symbol as IMethodSymbol)?.MethodKind == MethodKind.StaticConstructor;
}
}
93 changes: 72 additions & 21 deletions src/ILLink.RoslynAnalyzer/RequiresAnalyzerBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,16 @@ public override void Initialize (AnalysisContext context)
}
}, OperationKind.ObjectCreation);

context.RegisterOperationAction (operationContext => {
var fieldReference = (IFieldReferenceOperation) operationContext.Operation;
if (fieldReference.Field.IsStatic &&
tlakollo marked this conversation as resolved.
Show resolved Hide resolved
fieldReference.Syntax.IsKind (SyntaxKind.SimpleMemberAccessExpression) &&
fieldReference.Field.ContainingType is INamedTypeSymbol fieldDeclaringType &&
fieldDeclaringType.TryGetAttribute (RequiresAttributeName, out var requiresAttribute)) {
ReportRequiresDiagnostic (operationContext, fieldReference.Field, requiresAttribute);
}
}, OperationKind.FieldReference);

context.RegisterOperationAction (operationContext => {
var propAccess = (IPropertyReferenceOperation) operationContext.Operation;
var prop = propAccess.Property;
Expand All @@ -111,13 +121,19 @@ public override void Initialize (AnalysisContext context)
context.RegisterOperationAction (operationContext => {
var eventRef = (IEventReferenceOperation) operationContext.Operation;
var eventSymbol = (IEventSymbol) eventRef.Member;
CheckCalledMember (operationContext, eventSymbol, incompatibleMembers);
var assignmentOperation = eventRef.Parent as IEventAssignmentOperation;

if (eventSymbol.AddMethod is IMethodSymbol eventAddMethod)
if (assignmentOperation != null && assignmentOperation.Adds && eventSymbol.AddMethod is IMethodSymbol eventAddMethod)
CheckCalledMember (operationContext, eventAddMethod, incompatibleMembers);

if (eventSymbol.RemoveMethod is IMethodSymbol eventRemoveMethod)
if (assignmentOperation != null && !assignmentOperation.Adds && eventSymbol.RemoveMethod is IMethodSymbol eventRemoveMethod)
CheckCalledMember (operationContext, eventRemoveMethod, incompatibleMembers);

if (eventSymbol.RaiseMethod is IMethodSymbol eventRaiseMethod)
tlakollo marked this conversation as resolved.
Show resolved Hide resolved
CheckCalledMember (operationContext, eventRaiseMethod, incompatibleMembers);

if (AnalyzerDiagnosticTargets.HasFlag (DiagnosticTargets.Event))
CheckCalledMember (operationContext, eventSymbol, incompatibleMembers);
}, OperationKind.EventReference);

context.RegisterOperationAction (operationContext => {
Expand Down Expand Up @@ -163,34 +179,28 @@ void CheckCalledMember (
ISymbol containingSymbol = FindContainingSymbol (operationContext, AnalyzerDiagnosticTargets);

// 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 (IsMemberInRequiresScope (containingSymbol))
return;

if (ReportSpecialIncompatibleMembersDiagnostic (operationContext, incompatibleMembers, member))
return;

if (!member.HasAttribute (RequiresAttributeName))
return;

// Warn on the most derived base method taking into account covariant returns
while (member is IMethodSymbol method && method.OverriddenMethod != null && SymbolEqualityComparer.Default.Equals (method.ReturnType, method.OverriddenMethod.ReturnType))
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;
}
if (!TargetHasRequiresAttribute (member, out var requiresAttribute))
return;

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

@tlakollo tlakollo Oct 28, 2021

Choose a reason for hiding this comment

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

After fixing the event test that wasn't exercising calling the annotated add and remove event I realized that the linker warns on the event always (I think wrongfully) and on the caller if it's using an event accessor so I think it's better if I delete this logic and just let the analyzer warn on the caller when tries to use the event accesor.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

End up deleting this logic

}

ReportRequiresDiagnostic (operationContext, member, requiresAttribute);
}

void CheckMatchingAttributesInOverrides (
Expand Down Expand Up @@ -228,7 +238,8 @@ protected enum DiagnosticTargets
Property = 0x0002,
Field = 0x0004,
Event = 0x0008,
All = MethodOrConstructor | Property | Field | Event
Class = 0x0010,
All = MethodOrConstructor | Property | Field | Event | Class
}

/// <summary>
Expand Down Expand Up @@ -293,6 +304,46 @@ private void ReportMismatchInAttributesDiagnostic (SymbolAnalysisContext symbolA

private bool HasMismatchingAttributes (ISymbol member1, ISymbol member2) => member1.HasAttribute (RequiresAttributeName) ^ member2.HasAttribute (RequiresAttributeName);

// TODO: Consider sharing method with linker
tlakollo marked this conversation as resolved.
Show resolved Hide resolved
/// <summary>
/// True if the source of a call is considered to be annotated with the Requires... attribute
/// </summary>
protected bool IsMemberInRequiresScope (ISymbol containingSymbol)
{
if (containingSymbol.HasAttribute (RequiresAttributeName) ||
containingSymbol.ContainingType.HasAttribute (RequiresAttributeName)) {
return true;
}

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

return false;
}

// TODO: Consider sharing method with linker
/// <summary>
/// True if the target of a call is considered to be annotated with the Requires... attribute
/// </summary>
protected bool TargetHasRequiresAttribute (ISymbol member, [NotNullWhen (returnValue: true)] out AttributeData? requiresAttribute)
{
requiresAttribute = null;
if (member.IsStaticConstructor ()) {
return false;
}

if (TryGetRequiresAttribute (member, out requiresAttribute)) {
return true;
}

// Also check the containing type
if (member.IsStatic || member.IsConstructor ()) {
return TryGetRequiresAttribute (member.ContainingType, out requiresAttribute);
}
return false;
}

protected abstract string GetMessageFromAttribute (AttributeData requiresAttribute);

public static string GetUrlFromAttribute (AttributeData? requiresAttribute)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ public sealed class RequiresUnreferencedCodeAnalyzer : RequiresAnalyzerBase

private protected override string RequiresAttributeFullyQualifiedName => FullyQualifiedRequiresUnreferencedCodeAttribute;

private protected override DiagnosticTargets AnalyzerDiagnosticTargets => DiagnosticTargets.MethodOrConstructor;
private protected override DiagnosticTargets AnalyzerDiagnosticTargets => DiagnosticTargets.MethodOrConstructor | DiagnosticTargets.Class;

private protected override DiagnosticDescriptor RequiresDiagnosticRule => s_requiresUnreferencedCodeRule;

Expand Down
14 changes: 14 additions & 0 deletions src/linker/Linker/MethodReferenceExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,20 @@ public static string GetDisplayName (this MethodReference method)
return sb.ToString ();
}

if (methodDefinition != null && methodDefinition.IsEventMethod ()) {
// Append event name
string name = methodDefinition.SemanticsAttributes switch {
MethodSemanticsAttributes.AddOn => string.Concat (methodDefinition.Name.AsSpan (4), ".add"),
MethodSemanticsAttributes.RemoveOn => string.Concat (methodDefinition.Name.AsSpan (7), ".remove"),
MethodSemanticsAttributes.Fire => string.Concat (methodDefinition.Name.AsSpan (6), ".raise"),
Copy link
Contributor Author

Choose a reason for hiding this comment

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

I'm not 100% sure if the AsSpan should be 6 (for raise) or 5 (for fire) but seems like documentation mentions more raise than fire

_ => throw new NotSupportedException (),
};
sb.Append (name);
// Insert declaring type name and namespace
sb.Insert (0, '.').Insert (0, method.DeclaringType.GetDisplayName ());
return sb.ToString ();
}

// Append parameters
sb.Append ("(");
if (method.HasParameters) {
Expand Down
Loading