SOURCE DUMP v2

This commit is contained in:
Rian Drake 2026-10-15 14:29:37 +13:00
commit 9083135f76
5 changed files with 175 additions and 2806 deletions

View file

@ -1,39 +0,0 @@
using Microsoft.CodeAnalysis;
namespace Brutal.Numerics.Analyzers;
public static class Resources
{
// From framework analyser BRUTAL3001 Usage of System.Drawing
public static readonly DiagnosticDescriptor SystemDrawingBrutalCore0004 = new(
"BRUTALCORE0004",
"Prefer Brutal.Numerics instead of System.Drawing.Color",
"Brutal.Numerics has colour constant types",
"Obsolete",
DiagnosticSeverity.Warning,
isEnabledByDefault: true,
description: "Use Brutal.Numerics instead of System.Drawing.Color."
);
// From framework analyser BRUTAL3002 Usage of System.Numerics
public static readonly DiagnosticDescriptor SystemNumericsBrutalCore0005 = new(
"BRUTALCORE0005",
"Prefer Brutal.Numerics instead of System.Numerics",
"Brutal.Numerics provides optimised numeric functions",
"Obsolete",
DiagnosticSeverity.Info,
isEnabledByDefault: true,
description: "Brutal.Numerics instead of System.Numerics."
);
// From framework analyser BRUTAL4002 Usage of float3.Rgb(...) to create grayscale colors
public static readonly DiagnosticDescriptor RgbToGreyBrutalCore0006 = new(
"BRUTALCORE0006",
"Prefer Brutal.Numerics.Color.Gray instead of specifying explicit color channel values",
"Brutal.Numerics provides a set of predefined colors",
"Usage",
DiagnosticSeverity.Info,
isEnabledByDefault: true,
description: "Brutal.Numerics instead of System.Numerics."
);
}

View file

@ -1,143 +0,0 @@
using System.Collections.Immutable;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Operations;
namespace Brutal.Numerics.Analyzers;
/// <summary>
/// Analyzer that flags usage of Brutal color types such as `float3.Rgb(...)` and suggests replacing it with
/// `float3.Grayscale()`.
/// </summary>
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class RgbToGrayAnalyzer : DiagnosticAnalyzer
{
// Keep in mind: you have to list your rules here.
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } =
ImmutableArray.Create(Resources.RgbToGreyBrutalCore0006);
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();
// Only interested in invocation operations, like `float3.Rgb(...)`
context.RegisterOperationAction(AnalyzeInvocation, OperationKind.Invocation);
// Check other 'context.Register...' methods that might be helpful for your purposes.
}
/// <summary>
/// Called for each invocation expression in the code.
/// </summary>
/// <param name="context">Operation context.</param>
private void AnalyzeInvocation(OperationAnalysisContext context)
{
if (context.Operation is not IInvocationOperation invocation)
return;
var methodSymbol = invocation.TargetMethod;
// Must be in Brutal namespace
if (methodSymbol.ContainingNamespace.ToDisplayString() != "Brutal.Numerics")
return;
// Color type must match allowed set
var typeName = methodSymbol.ContainingType.Name;
switch (typeName)
{
case "float3":
case "float4":
case "byte3":
case "byte4":
case "ushort3":
case "ushort4":
break;
default:
return;
}
// Only check methods named Rgb or Rgba
var methodName = methodSymbol.Name;
if (methodName != "Rgb" && methodName != "Rgba")
return;
// Check argument count and argument equality
var args = invocation.Arguments;
if (methodName == "Rgb")
{
if (args.Length != 3)
return;
if (!ArgsAreEqual(args[0], args[1], args[2]))
return;
}
else if (methodName == "Rgba")
{
if (args.Length != 4)
return;
if (!ArgsAreEqual(args[0], args[1], args[2]))
return;
var alphaLiteral = args[3].Syntax.ToString();
switch (typeName)
{
case "float4":
if (alphaLiteral != "1")
return;
break;
case "byte4":
if (alphaLiteral != "0xFF")
return;
break;
case "ushort4":
if (alphaLiteral != "0xFFFF")
return;
break;
default:
return;
}
}
else
return;
var location = invocation.Syntax.GetLocation();
if (invocation.Syntax is InvocationExpressionSyntax invocationExpression)
{
ExpressionSyntax expr = invocationExpression;
// Get location of method name
var methodNameToken = expr switch
{
IdentifierNameSyntax id => id.Identifier, // Simple method call like Foo()
MemberAccessExpressionSyntax memberAccess => memberAccess.Name.Identifier, // Call like obj.Method()
// Handle cases like Console.WriteLine(...)
InvocationExpressionSyntax nestedInvocation => nestedInvocation.Expression switch
{
MemberAccessExpressionSyntax nestedMemberAccess => nestedMemberAccess.Name.Identifier, // Nested like Console.WriteLine(...)
IdentifierNameSyntax nestedId => nestedId.Identifier, // Nested like Foo.Bar()
_ => default,
},
_ => default,
};
location = methodNameToken.GetLocation();
}
// Emit a diagnostic at the location of the entire invocation
context.ReportDiagnostic(Diagnostic.Create(Resources.RgbToGreyBrutalCore0006, location));
}
private static bool ArgsAreEqual(IArgumentOperation a, IArgumentOperation b, IArgumentOperation c)
{
var t0 = a.Syntax.ToString();
var t1 = b.Syntax.ToString();
var t2 = c.Syntax.ToString();
return t0 == t1 && t0 == t2;
}
}

View file

@ -1,73 +0,0 @@
using System.Collections.Immutable;
using Brutal.Numerics.Analyzers;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Operations;
namespace Brutal.Numerics.Analyzers;
/// <summary>
/// Analyzer that flags usage of System.Drawing.Color.
/// </summary>
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class SystemDrawingAnalyzer : DiagnosticAnalyzer
{
// Keep in mind: you have to list your rules here.
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } =
ImmutableArray.Create(Resources.SystemDrawingBrutalCore0004);
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();
// Subscribe to semantic (compile time) action invocation, e.g. method invocation.
context.RegisterOperationAction(
AnalyzeOperation,
OperationKind.FieldReference,
OperationKind.PropertyReference
);
}
/// <summary>
/// Executed on the completion of the semantic analysis associated with the Invocation operation.
/// </summary>
/// <param name="context">Operation context.</param>
private void AnalyzeOperation(OperationAnalysisContext context)
{
// Check if the current operation is a reference to a member (field or property), such as accessing Color.Red.
// If not, exit early as this analyzer only targets member references.
if (context.Operation is not IMemberReferenceOperation memberRef)
return;
// Get the type that contains the referenced member, e.g., System.Drawing.Color.
var containingType = memberRef.Member.ContainingType;
if (containingType == null)
return;
// Get the namespace of the containing type (e.g. "System.Drawing").
var namespaceName = containingType.ContainingNamespace?.ToDisplayString();
// Validate the namespace and type name. If the namespace is null or empty, ignore the operation. If the
// namespace does not start with "System.Drawing" or if the type is not specifically "Color", ignore it.
// Together, this ensures we only target usages like System.Drawing.Color.Red.
if (
namespaceName != null
&& (
string.IsNullOrEmpty(namespaceName)
|| !namespaceName.StartsWith("System.Drawing", StringComparison.Ordinal)
|| containingType.Name != "Color"
)
)
return;
// At this point, we've confirmed a usage of System.Drawing.Color.<member>. Create and report a diagnostic at
// the location where the member is used.
context.ReportDiagnostic(
Diagnostic.Create(Resources.SystemDrawingBrutalCore0004, memberRef.Syntax.GetLocation())
);
}
}

View file

@ -1,68 +0,0 @@
using System;
using System.Collections.Immutable;
using Brutal.Numerics.Analyzers;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Operations;
namespace Brutal.Numerics.Analyzers;
/// <summary>
/// Analyzer that reports invalid usage of System.Numerics.
/// </summary>
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class SystemNumericsAnalyzer : DiagnosticAnalyzer
{
// Keep in mind: you have to list your rules here.
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } =
ImmutableArray.Create(Resources.SystemNumericsBrutalCore0005);
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();
// Subscribe to semantic (compile time) action invocation, e.g. method invocation.
context.RegisterOperationAction(AnalyzeOperation, OperationKind.ObjectCreation);
}
/// <summary>
/// Executed on the completion of the semantic analysis associated with the Invocation operation.
/// </summary>
/// <param name="context">Operation context.</param>
private void AnalyzeOperation(OperationAnalysisContext context)
{
// Check if the operation is an object creation (ie., 'new TypeName(...)'). Specifically targeting cases like
// 'new Vector2(...)'.
if (context.Operation is not IObjectCreationOperation objectCreation)
return;
// Retrieve the type being instantiated
var containingType = objectCreation.Type;
if (containingType == null)
return;
// Get the namespace of the type (e.g. "System.Numerics").
var namespaceName = containingType.ContainingNamespace?.ToDisplayString();
// Ensure the namespace is valid and starts with "System.Numerics". If null or empty, the type is not from a
// relevant namespace. If the namespace doesn't match, ignore the operation.
if (
namespaceName != null
&& (
string.IsNullOrEmpty(namespaceName)
|| !namespaceName.StartsWith("System.Numerics", StringComparison.Ordinal)
)
)
return;
// At this point, we've identified an instantiation of a System.Numerics type. Create and report a diagnostic
// at the source location of the 'new' expression.git
context.ReportDiagnostic(
Diagnostic.Create(Resources.SystemNumericsBrutalCore0005, context.Operation.Syntax.GetLocation())
);
}
}

View file

@ -1,215 +0,0 @@
using System.Collections.Immutable;
using System.Composition;
using Brutal.Numerics.Analyzers;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Document = Microsoft.CodeAnalysis.Document;
namespace Brutal.Numerics.Analyzers;
/// <summary>
/// A code fix provider that replaces calls to float3.Rgb(...) with float3.Grayscale().
/// All code fixes must be linked to specific analyzers.
/// </summary>
[ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(RgbToGrayFixProvider)), Shared]
public class RgbToGrayFixProvider : CodeFixProvider
{
public sealed override ImmutableArray<string> FixableDiagnosticIds { get; } =
[Resources.RgbToGreyBrutalCore0006.Id];
// If you don't need the 'fix all' behavior, 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.
if (context.Diagnostics.Length != 1)
{
return;
}
var diagnostic = context.Diagnostics[0];
var diagnosticSpan = diagnostic.Location.SourceSpan;
var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);
var diagnosticNode = root?.FindNode(diagnosticSpan);
var invocation = diagnosticNode?.FirstAncestorOrSelf<InvocationExpressionSyntax>();
if (invocation is null)
return;
context.RegisterCodeFix(
CodeAction.Create(
title: string.Format(Resources.RgbToGreyBrutalCore0006.Id),
createChangedDocument: c => ReplaceWithGrayscaleAsync(context.Document, invocation, c),
equivalenceKey: nameof(Resources.RgbToGreyBrutalCore0006.Id)
),
diagnostic
);
}
/// <summary>
/// Executed on the quick fix action raised by the user.
/// </summary>
/// <param name="document">Affected source file.</param>
/// <param name="invocation">The original method invocation node.</param>
/// <param name="cancellationToken">Any fix is cancellable by the user, so we should support the cancellation token.</param>
/// <returns>A modified version of the solution with the method call replaced.</returns>
private async Task<Document> ReplaceWithGrayscaleAsync(
Document document,
InvocationExpressionSyntax invocation,
CancellationToken cancellationToken
)
{
if (invocation.Expression is not MemberAccessExpressionSyntax memberAccess)
return document;
var method = await TryGetReplaceableMethod(memberAccess, document, cancellationToken);
if (
method == null
|| !IsMethodOfReplaceableType(method, out var typeName)
|| !IsMethodParametersReplaceableByGrayscale(invocation, method.Name, typeName, out var replacementArgExpr)
)
return document;
var newInvocation = CreateFunctionCallToGrayscale(invocation, memberAccess, replacementArgExpr!);
var newRoot = await ReplaceNode(document, invocation, cancellationToken, newInvocation);
return document.WithSyntaxRoot(newRoot);
}
private static bool IsMethodOfReplaceableType(IMethodSymbol methodSymbol, out string typeName)
{
typeName = methodSymbol.ContainingType.Name;
switch (typeName)
{
case "float3" or "float4" or "byte3" or "byte4" or "ushort3" or "ushort4":
var methodName = methodSymbol.Name;
return methodName is "Rgb" or "Rgba";
default:
return false;
}
}
private static async Task<IMethodSymbol?> TryGetReplaceableMethod(
MemberAccessExpressionSyntax memberAccess,
Document document,
CancellationToken cancellationToken
)
{
var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var symbolInfo = semanticModel.GetSymbolInfo(memberAccess, cancellationToken);
if (
symbolInfo.Symbol is not IMethodSymbol methodSymbol
|| methodSymbol.ContainingNamespace.ToDisplayString() != "Brutal.Numerics"
)
return null;
return methodSymbol;
}
private static bool IsMethodParametersReplaceableByGrayscale(
InvocationExpressionSyntax invocation,
string methodName,
string typeName,
out ExpressionSyntax? replacementArgExpr
)
{
var args = invocation.ArgumentList.Arguments;
switch (methodName)
{
case "Rgb" when args.Count != 3 || !ArgsAreEqual(args[0], args[1], args[2]):
replacementArgExpr = null;
return false;
case "Rgb":
replacementArgExpr = args[0].Expression;
break;
case "Rgba" when args.Count != 4 || !ArgsAreEqual(args[0], args[1], args[2]):
replacementArgExpr = null;
return false;
case "Rgba":
{
var alphaLiteral = args[3].Expression.ToString();
switch (typeName)
{
case "float4":
if (alphaLiteral != "1")
{
replacementArgExpr = null;
return false;
}
break;
case "byte4":
if (alphaLiteral != "0xFF")
{
replacementArgExpr = null;
return false;
}
break;
case "ushort4":
if (alphaLiteral != "0xFFFF")
{
replacementArgExpr = null;
return false;
}
break;
default:
replacementArgExpr = null;
return false;
}
replacementArgExpr = args[0].Expression;
break;
}
default:
replacementArgExpr = null;
return false;
}
return true;
}
private static InvocationExpressionSyntax CreateFunctionCallToGrayscale(
InvocationExpressionSyntax invocation,
MemberAccessExpressionSyntax memberAccess,
ExpressionSyntax replacementArgExpr
)
{
var newMemberAccess = memberAccess.WithName(SyntaxFactory.IdentifierName("Grayscale"));
var newInvocation = invocation
.WithExpression(newMemberAccess)
.WithArgumentList(
SyntaxFactory.ArgumentList(
SyntaxFactory.SingletonSeparatedList(SyntaxFactory.Argument(replacementArgExpr))
)
);
return newInvocation;
}
private static async Task<SyntaxNode> ReplaceNode(
Document document,
InvocationExpressionSyntax invocation,
CancellationToken cancellationToken,
InvocationExpressionSyntax newInvocation
)
{
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var newRoot = root!.ReplaceNode(invocation, newInvocation);
return newRoot;
}
private static bool ArgsAreEqual(ArgumentSyntax a, ArgumentSyntax b, ArgumentSyntax c)
{
var t0 = a.ToString();
var t1 = b.ToString();
var t2 = c.ToString();
return t0 == t1 && t0 == t2;
}
}