Add API Analyzer Assembly (#906)

* Start on API analyzers

* Finish GuildAccessAnalyzer

* Update build script (will this do?)

* Correct slashes

* Extrapolate DerivesFromModuleBase() to an extension method

* Quick refactoring

* Add doc file
This commit is contained in:
Joe4evr
2018-01-14 04:54:47 +01:00
committed by Christopher F
parent 87124d3e39
commit f69ef2a8ca
14 changed files with 1074 additions and 1 deletions

View File

@@ -0,0 +1,15 @@
<Project Sdk="Microsoft.NET.Sdk">
<Import Project="../../Discord.Net.targets" />
<PropertyGroup>
<AssemblyName>Discord.Net.Analyzers</AssemblyName>
<RootNamespace>Discord.Analyzers</RootNamespace>
<Description>A Discord.Net extension adding support for design-time analysis of the API usage.</Description>
<TargetFramework>netstandard1.3</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.CodeAnalysis" Version="2.6.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Discord.Net.Commands\Discord.Net.Commands.csproj" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,70 @@
using System;
using System.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using Discord.Commands;
namespace Discord.Analyzers
{
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public sealed class GuildAccessAnalyzer : DiagnosticAnalyzer
{
private const string DiagnosticId = "DNET0001";
private const string Title = "Limit command to Guild contexts.";
private const string MessageFormat = "Command method '{0}' is accessing 'Context.Guild' but is not restricted to Guild contexts.";
private const string Description = "Accessing 'Context.Guild' in a command without limiting the command to run only in guilds.";
private const string Category = "API Usage";
private static DiagnosticDescriptor Rule = new DiagnosticDescriptor(DiagnosticId, Title, MessageFormat, Category, DiagnosticSeverity.Warning, isEnabledByDefault: true, description: Description);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule);
public override void Initialize(AnalysisContext context)
{
context.RegisterSyntaxNodeAction(AnalyzeMemberAccess, SyntaxKind.SimpleMemberAccessExpression);
}
private static void AnalyzeMemberAccess(SyntaxNodeAnalysisContext context)
{
// Bail out if the accessed member isn't named 'Guild'
var memberAccessSymbol = context.SemanticModel.GetSymbolInfo(context.Node).Symbol;
if (memberAccessSymbol.Name != "Guild")
return;
// Bail out if it happens to be 'ContextType.Guild' in the '[RequireContext]' argument
if (context.Node.Parent is AttributeArgumentSyntax)
return;
// Bail out if the containing class doesn't derive from 'ModuleBase<T>'
var typeNode = context.Node.FirstAncestorOrSelf<TypeDeclarationSyntax>();
var typeSymbol = context.SemanticModel.GetDeclaredSymbol(typeNode);
if (!typeSymbol.DerivesFromModuleBase())
return;
// Bail out if the containing method isn't marked with '[Command]'
var methodNode = context.Node.FirstAncestorOrSelf<MethodDeclarationSyntax>();
var methodSymbol = context.SemanticModel.GetDeclaredSymbol(methodNode);
var methodAttributes = methodSymbol.GetAttributes();
if (!methodAttributes.Any(a => a.AttributeClass.Name == nameof(CommandAttribute)))
return;
// Is the '[RequireContext]' attribute not applied to either the
// method or the class, or its argument isn't 'ContextType.Guild'?
var ctxAttribute = methodAttributes.SingleOrDefault(_attributeDataPredicate)
?? typeSymbol.GetAttributes().SingleOrDefault(_attributeDataPredicate);
if (ctxAttribute == null || ctxAttribute.ConstructorArguments.Any(arg => !arg.Value.Equals((int)ContextType.Guild)))
{
// Report the diagnostic
var diagnostic = Diagnostic.Create(Rule, context.Node.GetLocation(), methodSymbol.Name);
context.ReportDiagnostic(diagnostic);
}
}
private static readonly Func<AttributeData, bool> _attributeDataPredicate =
(a => a.AttributeClass.Name == nameof(RequireContextAttribute));
}
}

View File

@@ -0,0 +1,21 @@
using System;
using Microsoft.CodeAnalysis;
using Discord.Commands;
namespace Discord.Analyzers
{
internal static class SymbolExtensions
{
private static readonly string _moduleBaseName = typeof(ModuleBase<>).Name;
public static bool DerivesFromModuleBase(this ITypeSymbol symbol)
{
for (var bType = symbol.BaseType; bType != null; bType = bType.BaseType)
{
if (bType.MetadataName == _moduleBaseName)
return true;
}
return false;
}
}
}

View File

@@ -0,0 +1,30 @@
# DNET0001
<table>
<tr>
<td>TypeName</td>
<td>GuildAccessAnalyzer</td>
</tr>
<tr>
<td>CheckId</td>
<td>DNET0001</td>
</tr>
<tr>
<td>Category</td>
<td>API Usage</td>
</tr>
</table>
## Cause
A method identified as a command is accessing `Context.Guild` without the requisite precondition.
## Rule description
The value of `Context.Guild` is `null` if a command is invoked in a DM channel. Attempting to access
guild properties in such a case will result in a `NullReferenceException` at runtime.
This exception is entirely avoidable by using the library's provided preconditions.
## How to fix violations
Add the precondition `[RequireContext(ContextType.Guild)]` to the command or module class.