mirror of
https://github.com/ahwootech/BRUTAL.git
synced 2026-11-26 13:08:24 +01:00
SOURCE DUMP v1
This commit is contained in:
parent
bd62d51ec9
commit
fb20299e9d
4 changed files with 768360 additions and 0 deletions
|
|
@ -0,0 +1,188 @@
|
|||
using System.Collections.Immutable;
|
||||
using Microsoft.CodeAnalysis;
|
||||
using Microsoft.CodeAnalysis.CSharp.Syntax;
|
||||
using Microsoft.CodeAnalysis.Diagnostics;
|
||||
using Microsoft.CodeAnalysis.Operations;
|
||||
|
||||
namespace Brutal.Strings.Analyzers;
|
||||
|
||||
[DiagnosticAnalyzer(LanguageNames.CSharp)]
|
||||
public class PreferString8OverloadAnalyzer : DiagnosticAnalyzer
|
||||
{
|
||||
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } =
|
||||
[Resources.PreferU8OverloadBrutalCore0011];
|
||||
|
||||
public override void Initialize(AnalysisContext context)
|
||||
{
|
||||
context.EnableConcurrentExecution();
|
||||
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
|
||||
|
||||
context.RegisterCompilationStartAction(startContext =>
|
||||
{
|
||||
// Early-exit if ReadOnlySpan<T> is unavailable (e.g. netstandard2.0 without System.Memory)
|
||||
var readOnlySpan = startContext.Compilation.GetTypeByMetadataName("System.ReadOnlySpan`1");
|
||||
if (readOnlySpan is null)
|
||||
return;
|
||||
|
||||
var analyzer = new PreferString8OverloadCompilationAnalyzer(startContext.Compilation, readOnlySpan);
|
||||
startContext.RegisterOperationAction(analyzer.Analyze, OperationKind.Argument, OperationKind.Conversion);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* Follow the guidelines frmo RS1008 (https://dotnetrules.com):
|
||||
* Avoid storing per-compilation data into the fields of a diagnostic analyzer
|
||||
* Instance of a diagnostic analyzer might outlive the lifetime of compilation.
|
||||
* Hence, storing per-compilation data, such as symbols, into the fields of a diagnostic analyzer might cause stale compilations to stay alive and cause memory leaks.
|
||||
* Instead, you should store this data on a separate type instantiated in a compilation start action, registered using 'AnalysisContext.RegisterCompilationStartAction' API.
|
||||
* An instance of this type will be created per-compilation and it won't outlive compilation's lifetime, hence avoiding memory leaks.
|
||||
*/
|
||||
class PreferString8OverloadCompilationAnalyzer(Compilation compilation, INamedTypeSymbol readOnlySpan)
|
||||
{
|
||||
private readonly INamedTypeSymbol _readOnlySpanByte = readOnlySpan.Construct(
|
||||
compilation.GetSpecialType(SpecialType.System_Byte)
|
||||
);
|
||||
|
||||
private bool IsString8(ITypeSymbol type) => compilation.HasImplicitConversion(_readOnlySpanByte, type);
|
||||
|
||||
private static bool IsString16(ITypeSymbol type) => type.SpecialType == SpecialType.System_String;
|
||||
|
||||
/// Is method <paramref name="overload"/> a compatible replacement for <paramref name="method"/>?
|
||||
private bool IsCompatible(OperationAnalysisContext context, IMethodSymbol method, IMethodSymbol overload)
|
||||
{
|
||||
/*
|
||||
* We want to err on the side of caution: only suggest using an overload if it is _strictly_ identical:
|
||||
* - same kind/generic-ness etc.
|
||||
* - same type parameters (same constraints etc.)
|
||||
* - same parameters (except for string/String8 of course)
|
||||
*
|
||||
* We won't suggest overloads with (type) parameters that _could_ be compatible through conversion, type constraints etc.
|
||||
*/
|
||||
|
||||
if (method.MethodKind != overload.MethodKind)
|
||||
return false;
|
||||
|
||||
var isGeneric = method.IsGenericMethod;
|
||||
if (isGeneric != overload.IsGenericMethod)
|
||||
return false;
|
||||
|
||||
// ignore self
|
||||
if (SymbolEqualityComparer.IncludeNullability.Equals(isGeneric ? method.OriginalDefinition : method, overload))
|
||||
return false;
|
||||
|
||||
// is the overload accessible from the call site?
|
||||
if (!compilation.IsSymbolAccessibleWithin(overload, context.ContainingSymbol.ContainingType))
|
||||
return false;
|
||||
|
||||
if (isGeneric)
|
||||
{
|
||||
// compare type parameters
|
||||
if (!method.TypeParameters.SequenceEqual(overload.TypeParameters, IsCompatible))
|
||||
return false;
|
||||
}
|
||||
|
||||
// compare parameters
|
||||
if (!method.Parameters.SequenceEqual(overload.Parameters, (a, b) => IsCompatible(a.Type, b.Type)))
|
||||
return false;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/// Is type <paramref name="overloadParamType"/> a compatible replacement for <paramref name="methodParamType"/>?
|
||||
private bool IsCompatible(ITypeSymbol methodParamType, ITypeSymbol overloadParamType)
|
||||
{
|
||||
if (SymbolEqualityComparer.IncludeNullability.Equals(methodParamType, overloadParamType))
|
||||
return true;
|
||||
|
||||
if (IsString16(methodParamType) && IsString8(overloadParamType))
|
||||
return true;
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/// Are type parameters a and b compatible?
|
||||
private static bool IsCompatible(ITypeParameterSymbol a, ITypeParameterSymbol b)
|
||||
{
|
||||
return a.AllowsRefLikeType == b.AllowsRefLikeType
|
||||
&& a.HasConstructorConstraint == b.HasConstructorConstraint
|
||||
&& a.HasNotNullConstraint == b.HasNotNullConstraint
|
||||
&& a.HasReferenceTypeConstraint == b.HasReferenceTypeConstraint
|
||||
&& a.HasUnmanagedTypeConstraint == b.HasUnmanagedTypeConstraint
|
||||
&& a.HasValueTypeConstraint == b.HasValueTypeConstraint
|
||||
&& a.Variance == b.Variance
|
||||
&& Utility.SequenceEqual(a.ConstraintTypes, b.ConstraintTypes, SymbolEqualityComparer.IncludeNullability);
|
||||
}
|
||||
|
||||
public void Analyze(OperationAnalysisContext context)
|
||||
{
|
||||
switch (context.Operation)
|
||||
{
|
||||
case IArgumentOperation argumentOp:
|
||||
{
|
||||
var parameter = argumentOp.Parameter;
|
||||
if (parameter == null)
|
||||
break;
|
||||
|
||||
// is the current argument a string literal?
|
||||
if (!IsString16(parameter.Type) || argumentOp.Value.Syntax is not LiteralExpressionSyntax)
|
||||
break;
|
||||
|
||||
if (argumentOp.Parent is not IInvocationOperation parent)
|
||||
break;
|
||||
|
||||
// does the method have an overload that takes a UTF8 string instead?
|
||||
var method = parent.TargetMethod;
|
||||
var overloads = method.ContainingType.GetMembers(method.Name).OfType<IMethodSymbol>();
|
||||
var overload = overloads.FirstOrDefault(o => IsCompatible(context, method, o));
|
||||
|
||||
if (overload == null)
|
||||
break;
|
||||
|
||||
// suggest using a UTF8 literal instead of a string
|
||||
var message = overload.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat);
|
||||
ReportDiagnostic(message);
|
||||
break;
|
||||
}
|
||||
|
||||
case IConversionOperation conversionOp:
|
||||
{
|
||||
if (conversionOp.OperatorMethod == null)
|
||||
break;
|
||||
|
||||
// are we converting from a string literal?
|
||||
if (conversionOp.Operand is not ILiteralOperation { Type.SpecialType: SpecialType.System_String })
|
||||
break;
|
||||
|
||||
// is the target type assignable from UTF8?
|
||||
var targetType = conversionOp.Type;
|
||||
if (targetType == null || !IsString8(targetType))
|
||||
break;
|
||||
|
||||
// find the actual conversion method - only for displaying to the user / debugging
|
||||
var conversions = targetType
|
||||
.GetMembers()
|
||||
.OfType<IMethodSymbol>()
|
||||
.Where(m => m.MethodKind == MethodKind.Conversion);
|
||||
var overload = conversions.FirstOrDefault(m => IsString8(m.Parameters[0].Type));
|
||||
var message =
|
||||
overload?.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat)
|
||||
?? $"{targetType.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat)} implicit conversion from UTF8";
|
||||
|
||||
// suggest using a UTF8 literal instead of a string
|
||||
ReportDiagnostic(message);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
void ReportDiagnostic(string message)
|
||||
{
|
||||
var diagnostic = Diagnostic.Create(
|
||||
Resources.PreferU8OverloadBrutalCore0011,
|
||||
context.Operation.Syntax.GetLocation(),
|
||||
message
|
||||
);
|
||||
context.ReportDiagnostic(diagnostic);
|
||||
}
|
||||
}
|
||||
}
|
||||
37
brutal.strings/Brutal.Strings.Analyzers/Resources.cs
Normal file
37
brutal.strings/Brutal.Strings.Analyzers/Resources.cs
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
using Microsoft.CodeAnalysis;
|
||||
|
||||
namespace Brutal.Strings.Analyzers;
|
||||
|
||||
public static class Resources
|
||||
{
|
||||
public static readonly DiagnosticDescriptor BrutalCore0001 = new(
|
||||
"BRUTALCORE0001",
|
||||
"Avoid calling ToString on (ReadOnly)Span<byte>",
|
||||
"ToString() on a span does not convert the contents to a string, did you mean to use ToString16?",
|
||||
"Intent",
|
||||
DiagnosticSeverity.Warning,
|
||||
isEnabledByDefault: true,
|
||||
description: "Span<byte>.ToString() does not decode the bytes to a string."
|
||||
);
|
||||
public const string BrutalCore0001Suggestion = "Use .ToString16()";
|
||||
|
||||
public static readonly DiagnosticDescriptor BrutalCore0002 = new(
|
||||
"BRUTALCORE0002",
|
||||
"Avoid calling ToString on (ReadOnly)Span<T> where T is not string or byte",
|
||||
"ToString() on a span does not convert the contents to a string, did you mean to use a different method?",
|
||||
"Intent",
|
||||
DiagnosticSeverity.Warning,
|
||||
isEnabledByDefault: true,
|
||||
description: "Span<T>.ToString() does not decode the content to a string."
|
||||
);
|
||||
|
||||
public static readonly DiagnosticDescriptor PreferU8OverloadBrutalCore0011 = new(
|
||||
"BRUTALCORE0011",
|
||||
"Prefer using a UTF8 string",
|
||||
"Prefer using a UTF8 string: {0}",
|
||||
"Usage",
|
||||
DiagnosticSeverity.Warning,
|
||||
isEnabledByDefault: true
|
||||
);
|
||||
public const string PreferU8OverloadBrutalCore0011Suggestion = "Append u8 to the string literal";
|
||||
}
|
||||
|
|
@ -0,0 +1,70 @@
|
|||
using System.Collections.Immutable;
|
||||
using Microsoft.CodeAnalysis;
|
||||
using Microsoft.CodeAnalysis.CSharp.Syntax;
|
||||
using Microsoft.CodeAnalysis.Diagnostics;
|
||||
using Microsoft.CodeAnalysis.Operations;
|
||||
|
||||
namespace Brutal.Strings.Analyzers;
|
||||
|
||||
[DiagnosticAnalyzer(LanguageNames.CSharp)]
|
||||
public class SpanToStringAnalyzer : DiagnosticAnalyzer
|
||||
{
|
||||
// Keep in mind: you have to list your rules here.
|
||||
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } =
|
||||
[Resources.BrutalCore0001, Resources.BrutalCore0002];
|
||||
|
||||
public override void Initialize(AnalysisContext context)
|
||||
{
|
||||
// You must call this method to avoid analyzing generated code.
|
||||
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
|
||||
|
||||
// You must call this method to enable the Concurrent Execution.
|
||||
context.EnableConcurrentExecution();
|
||||
|
||||
// Monitor (method) invocations
|
||||
context.RegisterOperationAction(AnalyzeInvocation, OperationKind.Invocation);
|
||||
}
|
||||
|
||||
private static void AnalyzeInvocation(OperationAnalysisContext context)
|
||||
{
|
||||
var invocation = (IInvocationOperation)context.Operation;
|
||||
var method = invocation.TargetMethod;
|
||||
|
||||
if (method.Name != "ToString")
|
||||
return;
|
||||
|
||||
var type = method.ContainingType;
|
||||
if (type.TypeArguments.Length != 1)
|
||||
return;
|
||||
|
||||
var compilation = context.Compilation;
|
||||
var spanType = compilation.GetTypeByMetadataName("System.Span`1");
|
||||
var readOnlySpanType = compilation.GetTypeByMetadataName("System.ReadOnlySpan`1");
|
||||
|
||||
// no need for IncludeNullability as all types we're testing are value types, and spans can't be nullable
|
||||
var comparer = SymbolEqualityComparer.Default;
|
||||
|
||||
if (
|
||||
!comparer.Equals(type.OriginalDefinition, spanType)
|
||||
&& !comparer.Equals(type.OriginalDefinition, readOnlySpanType)
|
||||
)
|
||||
return;
|
||||
|
||||
var typeArg = type.TypeArguments[0];
|
||||
var charType = compilation.GetTypeByMetadataName("System.Char");
|
||||
var byteType = compilation.GetTypeByMetadataName("System.Byte");
|
||||
|
||||
// Span<char>.ToString() is ok
|
||||
if (comparer.Equals(typeArg, charType))
|
||||
return;
|
||||
|
||||
var rule = comparer.Equals(typeArg, byteType) ? Resources.BrutalCore0001 : Resources.BrutalCore0002;
|
||||
|
||||
var invocationSyntax = (InvocationExpressionSyntax)invocation.Syntax;
|
||||
var memberAccess = (MemberAccessExpressionSyntax)invocationSyntax.Expression;
|
||||
var methodSyntax = memberAccess.Name;
|
||||
|
||||
var diagnostic = Diagnostic.Create(rule, methodSyntax.GetLocation());
|
||||
context.ReportDiagnostic(diagnostic);
|
||||
}
|
||||
}
|
||||
17
brutal.strings/Brutal.Strings.Analyzers/Utility.cs
Normal file
17
brutal.strings/Brutal.Strings.Analyzers/Utility.cs
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
using System.Collections.Immutable;
|
||||
using Microsoft.CodeAnalysis;
|
||||
|
||||
public static class Utility
|
||||
{
|
||||
public static bool SequenceEqual<TSymbol>(
|
||||
ImmutableArray<TSymbol> a,
|
||||
ImmutableArray<TSymbol> b,
|
||||
SymbolEqualityComparer comparer
|
||||
)
|
||||
where TSymbol : class, ISymbol
|
||||
{
|
||||
var aUp = ImmutableArray<ISymbol>.CastUp(a);
|
||||
var bUp = ImmutableArray<ISymbol>.CastUp(b);
|
||||
return aUp.SequenceEqual(bUp, comparer);
|
||||
}
|
||||
}
|
||||
Loading…
Reference in a new issue