mirror of
https://github.com/ahwootech/BRUTAL.git
synced 2026-11-26 04:58:24 +01:00
SOURCE DUMP v2
This commit is contained in:
parent
fb20299e9d
commit
9083135f76
7 changed files with 175 additions and 2806 deletions
|
|
@ -1,188 +0,0 @@
|
|||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,37 +0,0 @@
|
|||
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";
|
||||
}
|
||||
|
|
@ -1,70 +0,0 @@
|
|||
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);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,17 +0,0 @@
|
|||
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);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,74 +0,0 @@
|
|||
using System.Collections.Immutable;
|
||||
using System.Composition;
|
||||
using Microsoft.CodeAnalysis;
|
||||
using Microsoft.CodeAnalysis.CodeActions;
|
||||
using Microsoft.CodeAnalysis.CodeFixes;
|
||||
using Microsoft.CodeAnalysis.CSharp;
|
||||
using Microsoft.CodeAnalysis.CSharp.Syntax;
|
||||
|
||||
namespace Brutal.Strings.Analyzers;
|
||||
|
||||
[ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(PreferString8OverloadFixProvider)), Shared]
|
||||
public class PreferString8OverloadFixProvider : CodeFixProvider
|
||||
{
|
||||
private static readonly string DiagnosticId = Resources.PreferU8OverloadBrutalCore0011.Id;
|
||||
private const string Suggestion = Resources.PreferU8OverloadBrutalCore0011Suggestion;
|
||||
|
||||
public sealed override ImmutableArray<string> FixableDiagnosticIds { get; } = [DiagnosticId];
|
||||
|
||||
public override FixAllProvider GetFixAllProvider() => WellKnownFixAllProviders.BatchFixer;
|
||||
|
||||
public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
|
||||
{
|
||||
// We link only one diagnostic and assume there is only one diagnostic in the context.
|
||||
var diagnostic = context.Diagnostics.Single();
|
||||
|
||||
// 'SourceSpan' of 'Location' is the highlighted area. We're going to use this area to find the 'SyntaxNode' to rename.
|
||||
var diagnosticSpan = diagnostic.Location.SourceSpan;
|
||||
|
||||
// Get the root of Syntax Tree that contains the highlighted diagnostic.
|
||||
var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);
|
||||
|
||||
// Find SyntaxNode corresponding to the diagnostic.
|
||||
var diagnosticNode = root?.FindNode(diagnosticSpan);
|
||||
|
||||
// We expect a string literal (argument or conversion)
|
||||
var literal = diagnosticNode switch
|
||||
{
|
||||
ArgumentSyntax { Expression: LiteralExpressionSyntax literalArg } => literalArg,
|
||||
LiteralExpressionSyntax literalConversion => literalConversion,
|
||||
_ => null,
|
||||
};
|
||||
if (literal == null)
|
||||
return;
|
||||
|
||||
// Register a code action that will invoke the fix.
|
||||
context.RegisterCodeFix(
|
||||
CodeAction.Create(
|
||||
title: Suggestion,
|
||||
createChangedSolution: c => FixAsync(context.Document, literal, c),
|
||||
equivalenceKey: nameof(DiagnosticId)
|
||||
),
|
||||
diagnostic
|
||||
);
|
||||
}
|
||||
|
||||
private static async Task<Solution> FixAsync(
|
||||
Document document,
|
||||
LiteralExpressionSyntax stringLiteral,
|
||||
CancellationToken cancellationToken
|
||||
)
|
||||
{
|
||||
var root = await document.GetSyntaxRootAsync(cancellationToken);
|
||||
if (root == null)
|
||||
return document.Project.Solution;
|
||||
|
||||
// change from "literal" to "literal"u8
|
||||
var token = stringLiteral.Token;
|
||||
var u8Token = SyntaxFactoryExtensions.Utf8Literal(token.Text + "u8", token.ValueText);
|
||||
var u8Literal = SyntaxFactory.LiteralExpression(SyntaxKind.Utf8StringLiteralExpression, u8Token);
|
||||
var newRoot = root.ReplaceNode(stringLiteral, u8Literal);
|
||||
var newDocument = document.WithSyntaxRoot(newRoot);
|
||||
return newDocument.Project.Solution;
|
||||
}
|
||||
}
|
||||
|
|
@ -1,67 +0,0 @@
|
|||
using System.Collections.Immutable;
|
||||
using System.Composition;
|
||||
using Microsoft.CodeAnalysis;
|
||||
using Microsoft.CodeAnalysis.CodeActions;
|
||||
using Microsoft.CodeAnalysis.CodeFixes;
|
||||
using Microsoft.CodeAnalysis.CSharp;
|
||||
|
||||
namespace Brutal.Strings.Analyzers;
|
||||
|
||||
[ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(SpanToStringFixProvider)), Shared]
|
||||
public class SpanToStringFixProvider : CodeFixProvider
|
||||
{
|
||||
// Specify the diagnostic IDs of analyzers that are expected to be linked.
|
||||
public sealed override ImmutableArray<string> FixableDiagnosticIds { get; } = [Resources.BrutalCore0001.Id];
|
||||
|
||||
// If you don't need the 'fix all' behaviour, return null.
|
||||
public override FixAllProvider? GetFixAllProvider() => null;
|
||||
|
||||
public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
|
||||
{
|
||||
// We link only one diagnostic and assume there is only one diagnostic in the context.
|
||||
var diagnostic = context.Diagnostics.Single();
|
||||
|
||||
// 'SourceSpan' of 'Location' is the highlighted area. We're going to use this area to find the 'SyntaxNode' to rename.
|
||||
var diagnosticSpan = diagnostic.Location.SourceSpan;
|
||||
|
||||
// Get the root of Syntax Tree that contains the highlighted diagnostic.
|
||||
var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);
|
||||
|
||||
// Find SyntaxNode corresponding to the diagnostic.
|
||||
var diagnosticNode = root?.FindNode(diagnosticSpan)!;
|
||||
|
||||
// Register a code action that will invoke the fix.
|
||||
context.RegisterCodeFix(
|
||||
CodeAction.Create(
|
||||
title: Resources.BrutalCore0001Suggestion,
|
||||
createChangedSolution: c => FixToStringAsync(context.Document, diagnosticNode, c),
|
||||
equivalenceKey: nameof(Resources.BrutalCore0001.Id)
|
||||
),
|
||||
diagnostic
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Executed on the quick fix action raised by the user.
|
||||
/// </summary>
|
||||
/// <param name="document">Affected source file.</param>
|
||||
/// <param name="methodName">The syntax node that we found in 'RegisterCodeFixesAsync'.</param>
|
||||
/// <param name="cancellationToken">Any fix is cancellable by the user, so we should support the cancellation token.</param>
|
||||
/// <returns>Clone of the solution with updates: renamed class.</returns>
|
||||
private static async Task<Solution> FixToStringAsync(
|
||||
Document document,
|
||||
SyntaxNode methodName,
|
||||
CancellationToken cancellationToken
|
||||
)
|
||||
{
|
||||
// change from "ReadOnlySpan<byte>.ToString()" to "ReadOnlySpan<byte>.ToString16()"
|
||||
var root = await document.GetSyntaxRootAsync(cancellationToken);
|
||||
if (root == null)
|
||||
return document.Project.Solution;
|
||||
|
||||
var newName = SyntaxFactory.IdentifierName("ToString16");
|
||||
var newRoot = root.ReplaceNode(methodName, newName);
|
||||
var newDocument = document.WithSyntaxRoot(newRoot);
|
||||
return newDocument.Project.Solution;
|
||||
}
|
||||
}
|
||||
|
|
@ -1,26 +0,0 @@
|
|||
using Microsoft.CodeAnalysis;
|
||||
using Microsoft.CodeAnalysis.CSharp;
|
||||
|
||||
namespace Brutal.Strings.Analyzers;
|
||||
|
||||
using static SyntaxFactory;
|
||||
|
||||
// TODO: move this to a shared package...
|
||||
public static class SyntaxFactoryExtensions
|
||||
{
|
||||
/// <inheritdoc cref="Utf8Literal(string,string)" />
|
||||
public static SyntaxToken Utf8Literal(string value)
|
||||
{
|
||||
return Utf8Literal(SymbolDisplay.FormatLiteral(value, quote: true) + "u8", value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a token with kind Utf8StringLiteralToken from the text and corresponding string value.
|
||||
/// </summary>
|
||||
/// <param name="text">The raw text of the literal, including quotes and escape sequences.</param>
|
||||
/// <param name="value">The string value to be represented by the returned token.</param>
|
||||
public static SyntaxToken Utf8Literal(string text, string value)
|
||||
{
|
||||
return Token(SyntaxTriviaList.Empty, SyntaxKind.Utf8StringLiteralToken, text, value, SyntaxTriviaList.Empty);
|
||||
}
|
||||
}
|
||||
Loading…
Reference in a new issue