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 analyzer for RequiresAssemblyFilesAttribute #1722

Merged
merged 9 commits into from
Jan 20, 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
33 changes: 33 additions & 0 deletions src/ILLink.RoslynAnalyzer/INamedTypeSymbolExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
// 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 Microsoft.CodeAnalysis;

namespace ILLink.RoslynAnalyzer
{
static class INamedTypeSymbolExtensions
{
/// <summary>
/// Returns true if <see paramref="type" /> has the same name as <see paramref="typename" />
/// </summary>
internal static bool HasName (this INamedTypeSymbol type, string typeName)
{
var roSpan = typeName.AsSpan ();
INamespaceOrTypeSymbol? currentType = type;
while (roSpan.Length > 0) {
var dot = roSpan.LastIndexOf ('.');
var currentName = dot < 0 ? roSpan : roSpan.Slice (dot + 1);
if (currentType is null ||
!currentName.Equals (currentType.Name.AsSpan (), StringComparison.Ordinal)) {
return false;
}
currentType = (INamespaceOrTypeSymbol?) currentType.ContainingType ?? currentType.ContainingNamespace;
roSpan = roSpan.Slice (0, dot > 0 ? dot : 0);
}

return true;
}
}
}
53 changes: 53 additions & 0 deletions src/ILLink.RoslynAnalyzer/ISymbolExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
// 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 Microsoft.CodeAnalysis;

namespace ILLink.RoslynAnalyzer
{
static class ISymbolExtensions
{
/// <summary>
/// Returns true if symbol <see paramref="symbol"/> has an attribute with name <see paramref="attributeName"/>.
/// </summary>
internal static bool HasAttribute (this ISymbol symbol, string attributeName)
{
foreach (var attr in symbol.GetAttributes ())
if (attr.AttributeClass?.Name == attributeName)
return true;

return false;
}

internal static bool TryGetRequiresAssemblyFileAttribute (this ISymbol symbol, out AttributeData? attribute)
{
attribute = null;
foreach (var _attribute in symbol.GetAttributes ()) {
if (_attribute.AttributeClass is var attrClass && attrClass != null &&
attrClass.HasName (RequiresAssemblyFilesAnalyzer.FullyQualifiedRequiresAssemblyFilesAttribute) &&
_attribute.ConstructorArguments.Length == 0) {
attribute = _attribute;
return true;
}
}

return false;
}

internal static bool TryGetAttributeWithMessageOnCtor (this ISymbol symbol, string qualifiedAttributeName, out AttributeData? attribute)
{
attribute = null;
foreach (var _attribute in symbol.GetAttributes ()) {
if (_attribute.AttributeClass is var attrClass && attrClass != null &&
attrClass.HasName (qualifiedAttributeName) && _attribute.ConstructorArguments.Length >= 1 &&
_attribute.ConstructorArguments[0] is { Type: { SpecialType: SpecialType.System_String } } ctorArg) {
attribute = _attribute;
return true;
}
}

return false;
}
}
}
97 changes: 97 additions & 0 deletions src/ILLink.RoslynAnalyzer/RequiresAssemblyFilesAnalyzer.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
// 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.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Operations;

namespace ILLink.RoslynAnalyzer
{
[DiagnosticAnalyzer (LanguageNames.CSharp)]
public sealed class RequiresAssemblyFilesAnalyzer : DiagnosticAnalyzer
{
public const string IL3002 = nameof (IL3002);
internal const string RequiresAssemblyFilesAttribute = nameof (RequiresAssemblyFilesAttribute);
internal const string FullyQualifiedRequiresAssemblyFilesAttribute = "System.Diagnostics.CodeAnalysis." + RequiresAssemblyFilesAttribute;

static readonly DiagnosticDescriptor s_requiresAssemblyFilesRule = new DiagnosticDescriptor (
IL3002,
new LocalizableResourceString (nameof (Resources.RequiresAssemblyFilesTitle),
Resources.ResourceManager, typeof (Resources)),
new LocalizableResourceString (nameof (Resources.RequiresAssemblyFilesMessage),
Resources.ResourceManager, typeof (Resources)),
DiagnosticCategory.SingleFile,
DiagnosticSeverity.Warning,
isEnabledByDefault: true);

public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create (s_requiresAssemblyFilesRule);

public override void Initialize (AnalysisContext context)
{
context.EnableConcurrentExecution ();
context.ConfigureGeneratedCodeAnalysis (GeneratedCodeAnalysisFlags.ReportDiagnostics);

context.RegisterCompilationStartAction (context => {
var compilation = context.Compilation;

var isSingleFilePublish = context.Options.GetMSBuildPropertyValue (MSBuildPropertyOptionNames.PublishSingleFile, compilation);
if (!string.Equals (isSingleFilePublish?.Trim (), "true", StringComparison.OrdinalIgnoreCase))
return;

var includesAllContent = context.Options.GetMSBuildPropertyValue (MSBuildPropertyOptionNames.IncludeAllContentForSelfExtract, compilation);
if (string.Equals (includesAllContent?.Trim (), "true", StringComparison.OrdinalIgnoreCase))
return;

context.RegisterOperationAction (operationContext => {
var methodInvocation = (IInvocationOperation) operationContext.Operation;
CheckCalledMember (operationContext, methodInvocation.TargetMethod);
}, OperationKind.Invocation);

context.RegisterOperationAction (operationContext => {
var objectCreation = (IObjectCreationOperation) operationContext.Operation;
CheckCalledMember (operationContext, objectCreation.Constructor);
}, OperationKind.ObjectCreation);

context.RegisterOperationAction (operationContext => {
var propAccess = (IPropertyReferenceOperation) operationContext.Operation;
var prop = propAccess.Property;
var usageInfo = propAccess.GetValueUsageInfo (prop);
if (usageInfo.HasFlag (ValueUsageInfo.Read) && prop.GetMethod != null)
CheckCalledMember (operationContext, prop.GetMethod);

if (usageInfo.HasFlag (ValueUsageInfo.Write) && prop.SetMethod != null)
CheckCalledMember (operationContext, prop.SetMethod);

CheckCalledMember (operationContext, prop);
}, OperationKind.PropertyReference);

context.RegisterOperationAction (operationContext => {
var eventRef = (IEventReferenceOperation) operationContext.Operation;
CheckCalledMember (operationContext, eventRef.Member);
}, OperationKind.EventReference);

static void CheckCalledMember (
OperationAnalysisContext operationContext,
ISymbol member)
{
// Do not emit any diagnostic if caller is annotated with the attribute too.
if (operationContext.ContainingSymbol.HasAttribute (RequiresAssemblyFilesAttribute))
return;

if (member.TryGetRequiresAssemblyFileAttribute (out AttributeData? requiresAssemblyFilesAttribute)) {
operationContext.ReportDiagnostic (Diagnostic.Create (
s_requiresAssemblyFilesRule,
operationContext.Operation.Syntax.GetLocation (),
member.OriginalDefinition.ToString (),
requiresAssemblyFilesAttribute?.NamedArguments.FirstOrDefault (na => na.Key == "Message").Value.Value?.ToString (),
requiresAssemblyFilesAttribute?.NamedArguments.FirstOrDefault (na => na.Key == "Url").Value.Value?.ToString ()));
}
}
});
}
}
}
84 changes: 21 additions & 63 deletions src/ILLink.RoslynAnalyzer/RequiresUnreferencedCodeAnalyzer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,10 @@ namespace ILLink.RoslynAnalyzer
public class RequiresUnreferencedCodeAnalyzer : DiagnosticAnalyzer
{
public const string DiagnosticId = "IL2026";
const string RequiresUnreferencedCodeAttribute = nameof (RequiresUnreferencedCodeAttribute);
const string FullyQualifiedRequiresUnreferencedCodeAttribute = "System.Diagnostics.CodeAnalysis." + RequiresUnreferencedCodeAttribute;

private static readonly DiagnosticDescriptor s_rule = new DiagnosticDescriptor (
static readonly DiagnosticDescriptor s_requiresUnreferencedCodeRule = new DiagnosticDescriptor (
DiagnosticId,
new LocalizableResourceString (nameof (Resources.RequiresUnreferencedCodeAnalyzerTitle),
Resources.ResourceManager, typeof (Resources)),
Expand All @@ -26,7 +28,7 @@ public class RequiresUnreferencedCodeAnalyzer : DiagnosticAnalyzer
DiagnosticSeverity.Warning,
isEnabledByDefault: true);

public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create (s_rule);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create (s_requiresUnreferencedCodeRule);

public override void Initialize (AnalysisContext context)
{
Expand All @@ -46,91 +48,47 @@ public override void Initialize (AnalysisContext context)
if (call.IsVirtual && call.TargetMethod.OverriddenMethod != null)
return;

CheckMethodOrCtorCall (operationContext, call.TargetMethod, call.Syntax.GetLocation ());
CheckMethodOrCtorCall (operationContext, call.TargetMethod);
}, OperationKind.Invocation);

context.RegisterOperationAction (operationContext => {
var call = (IObjectCreationOperation) operationContext.Operation;
CheckMethodOrCtorCall (operationContext, call.Constructor, call.Syntax.GetLocation ());
CheckMethodOrCtorCall (operationContext, call.Constructor);
}, OperationKind.ObjectCreation);

context.RegisterOperationAction (operationContext => {
var propAccess = (IPropertyReferenceOperation) operationContext.Operation;
var prop = propAccess.Property;
var usageInfo = propAccess.GetValueUsageInfo (prop);
if (usageInfo.HasFlag (ValueUsageInfo.Read) && prop.GetMethod != null) {
CheckMethodOrCtorCall (
operationContext,
prop.GetMethod,
propAccess.Syntax.GetLocation ());
}
if (usageInfo.HasFlag (ValueUsageInfo.Write) && prop.SetMethod != null) {
CheckMethodOrCtorCall (
operationContext,
prop.SetMethod,
propAccess.Syntax.GetLocation ());
}
if (usageInfo.HasFlag (ValueUsageInfo.Read) && prop.GetMethod != null)
CheckMethodOrCtorCall (operationContext, prop.GetMethod);

if (usageInfo.HasFlag (ValueUsageInfo.Write) && prop.SetMethod != null)
CheckMethodOrCtorCall (operationContext, prop.SetMethod);
}, OperationKind.PropertyReference);

void CheckMethodOrCtorCall (
static void CheckMethodOrCtorCall (
OperationAnalysisContext operationContext,
IMethodSymbol method,
Location location)
IMethodSymbol method)
{
AttributeData? requiresUnreferencedCode;
// If parent method contains RequiresUnreferencedCodeAttribute then we shouldn't report diagnostics for this method
if (operationContext.ContainingSymbol is IMethodSymbol &&
TryGetRequiresUnreferencedCodeAttribute (operationContext.ContainingSymbol.GetAttributes (), out requiresUnreferencedCode))
operationContext.ContainingSymbol.HasAttribute (RequiresUnreferencedCodeAttribute))
return;

if (!method.HasAttribute (RequiresUnreferencedCodeAttribute))
return;
if (TryGetRequiresUnreferencedCodeAttribute (method.GetAttributes (), out requiresUnreferencedCode)) {

if (method.TryGetAttributeWithMessageOnCtor (FullyQualifiedRequiresUnreferencedCodeAttribute, out AttributeData? requiresUnreferencedCode)) {
operationContext.ReportDiagnostic (Diagnostic.Create (
s_rule,
location,
s_requiresUnreferencedCodeRule,
operationContext.Operation.Syntax.GetLocation (),
method.OriginalDefinition.ToString (),
(string) requiresUnreferencedCode!.ConstructorArguments[0].Value!,
requiresUnreferencedCode!.NamedArguments.FirstOrDefault (na => na.Key == "Url").Value.Value?.ToString ()));
}
}
});
}

/// <summary>
/// Returns true if <see paramref="type" /> has the same name as <see paramref="typename" />
/// </summary>
internal static bool IsNamedType (INamedTypeSymbol type, string typeName)
{
var roSpan = typeName.AsSpan ();
INamespaceOrTypeSymbol? currentType = type;
while (roSpan.Length > 0) {
var dot = roSpan.LastIndexOf ('.');
var currentName = dot < 0 ? roSpan : roSpan.Slice (dot + 1);
if (currentType is null ||
!currentName.Equals (currentType.Name.AsSpan (), StringComparison.Ordinal)) {
return false;
}
currentType = (INamespaceOrTypeSymbol?) currentType.ContainingType ?? currentType.ContainingNamespace;
roSpan = roSpan.Slice (0, dot > 0 ? dot : 0);
}

return true;
}

/// <summary>
/// Returns a RequiresUnreferencedCodeAttribute if found
/// </summary>
static bool TryGetRequiresUnreferencedCodeAttribute (ImmutableArray<AttributeData> attributes, out AttributeData? requiresUnreferencedCode)
{
requiresUnreferencedCode = null;
foreach (var attr in attributes) {
if (attr.AttributeClass is { } attrClass &&
IsNamedType (attrClass, "System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute") &&
attr.ConstructorArguments.Length == 1 &&
attr.ConstructorArguments[0] is { Type: { SpecialType: SpecialType.System_String } } ctorArg) {
requiresUnreferencedCode = attr;
return true;
}
}
return false;
}
}
}
6 changes: 6 additions & 0 deletions src/ILLink.RoslynAnalyzer/Resources.resx
Original file line number Diff line number Diff line change
Expand Up @@ -135,4 +135,10 @@
<data name="AvoidAssemblyGetFilesInSingleFileMessage" xml:space="preserve">
<value>'{0}' will throw for assemblies embedded in a single-file app</value>
</data>
<data name="RequiresAssemblyFilesMessage" xml:space="preserve">
<value />
</data>
<data name="RequiresAssemblyFilesTitle" xml:space="preserve">
<value />
</data>
</root>
10 changes: 5 additions & 5 deletions src/ILLink.RoslynAnalyzer/SingleFileAnalyzer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ public sealed class AvoidAssemblyLocationInSingleFile : DiagnosticAnalyzer
public const string IL3000 = nameof (IL3000);
public const string IL3001 = nameof (IL3001);

private static readonly DiagnosticDescriptor LocationRule = new DiagnosticDescriptor (
static readonly DiagnosticDescriptor s_locationRule = new DiagnosticDescriptor (
IL3000,
new LocalizableResourceString (nameof (Resources.AvoidAssemblyLocationInSingleFileTitle),
Resources.ResourceManager, typeof (Resources)),
Expand All @@ -30,7 +30,7 @@ public sealed class AvoidAssemblyLocationInSingleFile : DiagnosticAnalyzer
DiagnosticSeverity.Warning,
isEnabledByDefault: true);

private static readonly DiagnosticDescriptor GetFilesRule = new DiagnosticDescriptor (
static readonly DiagnosticDescriptor s_getFilesRule = new DiagnosticDescriptor (
IL3001,
new LocalizableResourceString (nameof (Resources.AvoidAssemblyGetFilesInSingleFileTitle),
Resources.ResourceManager, typeof (Resources)),
Expand All @@ -40,7 +40,7 @@ public sealed class AvoidAssemblyLocationInSingleFile : DiagnosticAnalyzer
DiagnosticSeverity.Warning,
isEnabledByDefault: true);

public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create (LocationRule, GetFilesRule);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create (s_locationRule, s_getFilesRule);

public override void Initialize (AnalysisContext context)
{
Expand Down Expand Up @@ -88,7 +88,7 @@ public override void Initialize (AnalysisContext context)
return;
}

operationContext.ReportDiagnostic (Diagnostic.Create (LocationRule, access.Syntax.GetLocation (), property));
operationContext.ReportDiagnostic (Diagnostic.Create (s_locationRule, access.Syntax.GetLocation (), property));
}, OperationKind.PropertyReference);

context.RegisterOperationAction (operationContext => {
Expand All @@ -98,7 +98,7 @@ public override void Initialize (AnalysisContext context)
return;
}

operationContext.ReportDiagnostic (Diagnostic.Create (GetFilesRule, invocation.Syntax.GetLocation (), targetMethod));
operationContext.ReportDiagnostic (Diagnostic.Create (s_getFilesRule, invocation.Syntax.GetLocation (), targetMethod));
}, OperationKind.Invocation);

return;
Expand Down
Loading