mirror of
https://github.com/ahwootech/BRUTAL.git
synced 2026-11-25 20:48:24 +01:00
SOURCE DUMP v2
This commit is contained in:
parent
fb20299e9d
commit
9083135f76
25 changed files with 175 additions and 2806 deletions
File diff suppressed because it is too large
Load diff
|
|
@ -1,54 +0,0 @@
|
|||
using System.Collections.Immutable;
|
||||
using Microsoft.CodeAnalysis;
|
||||
using Microsoft.CodeAnalysis.CSharp;
|
||||
using Microsoft.CodeAnalysis.CSharp.Syntax;
|
||||
using Microsoft.CodeAnalysis.Diagnostics;
|
||||
|
||||
namespace Brutal.Core.Analyzers;
|
||||
|
||||
[DiagnosticAnalyzer(LanguageNames.CSharp)]
|
||||
public class OperatingSystemAnalyzer : DiagnosticAnalyzer
|
||||
{
|
||||
// Keep in mind: you have to list your rules here.
|
||||
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } =
|
||||
ImmutableArray.Create(Resources.BrutalCore0003);
|
||||
|
||||
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 the Syntax Node with the appropriate 'SyntaxKind' (ClassDeclaration) action.
|
||||
// To figure out which Syntax Nodes you should choose, consider installing the Roslyn syntax tree viewer plugin Rossynt: https://plugins.jetbrains.com/plugin/16902-rossynt/
|
||||
context.RegisterSyntaxNodeAction(AnalyzeSyntax, SyntaxKind.InvocationExpression);
|
||||
}
|
||||
|
||||
private static void AnalyzeSyntax(SyntaxNodeAnalysisContext context)
|
||||
{
|
||||
if (context.Node is not InvocationExpressionSyntax invocation)
|
||||
return;
|
||||
|
||||
var memberAccess = invocation.Expression as MemberAccessExpressionSyntax;
|
||||
if (memberAccess == null)
|
||||
return;
|
||||
|
||||
var symbolInfo = context.SemanticModel.GetSymbolInfo(memberAccess.Expression);
|
||||
if (symbolInfo.Symbol == null)
|
||||
return;
|
||||
|
||||
var systemOperatingSystem = context.SemanticModel.Compilation.GetTypeByMetadataName("System.OperatingSystem");
|
||||
|
||||
if (!SymbolEqualityComparer.Default.Equals(symbolInfo.Symbol, systemOperatingSystem))
|
||||
return;
|
||||
|
||||
// check if member name is "IsWindows", "IsLinux", "IsMacOS"
|
||||
if (memberAccess.Name.Identifier.Text is not ("IsWindows" or "IsLinux" or "IsMacOS"))
|
||||
return;
|
||||
|
||||
var diagnostic = Diagnostic.Create(Resources.BrutalCore0003, invocation.GetLocation());
|
||||
context.ReportDiagnostic(diagnostic);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,66 +0,0 @@
|
|||
using Microsoft.CodeAnalysis;
|
||||
|
||||
namespace Brutal.Core.Analyzers;
|
||||
|
||||
public static class Resources
|
||||
{
|
||||
public static readonly DiagnosticDescriptor BrutalCore0003 = new(
|
||||
"BRUTALCORE0003",
|
||||
"Prefer Brutal.Platform instead of System.OperatingSystem",
|
||||
"Brutal.Platform provides a simpler API to check the current platform",
|
||||
"Obsolete",
|
||||
DiagnosticSeverity.Info,
|
||||
isEnabledByDefault: true,
|
||||
description: "Use Brutal.Platform instead of System.OperatingSystem."
|
||||
);
|
||||
public const string BrutalCore0003Suggestion = "Use Brutal.Platform";
|
||||
|
||||
// From framework analyser BRUTAL4003 var fixes
|
||||
public static readonly DiagnosticDescriptor VarBrutalCore0007 = new(
|
||||
"BRUTALCORE0007",
|
||||
"Prefer var over explicit type",
|
||||
"Use var for terseness and ease of refactoring",
|
||||
"Usage",
|
||||
DiagnosticSeverity.Info,
|
||||
isEnabledByDefault: true,
|
||||
description: "Use var instead of explicit types."
|
||||
);
|
||||
|
||||
// From framework analyser BRUTAL4003 var fixes for default initialisation
|
||||
public static readonly DiagnosticDescriptor VarDefaultBrutalCore0008 = new(
|
||||
"BRUTALCORE0008",
|
||||
"Prefer var default literal over explicit with default",
|
||||
"Use var with default(type) for terseness and consistency",
|
||||
"Usage",
|
||||
DiagnosticSeverity.Info,
|
||||
isEnabledByDefault: true,
|
||||
description: "Use var instead of explicit types."
|
||||
);
|
||||
|
||||
public static readonly DiagnosticDescriptor ExpectsFixedBrutalCore0009 = new(
|
||||
"BRUTALCORE0009",
|
||||
"This should be a fixed value",
|
||||
"Potential unsafe call to {0}. Ensure the argument for '{1}' comes from a fixed source.",
|
||||
"Usage",
|
||||
DiagnosticSeverity.Error,
|
||||
isEnabledByDefault: true
|
||||
);
|
||||
|
||||
public static readonly DiagnosticDescriptor ExpectsFixedBrutalCore0010 = new(
|
||||
"BRUTALCORE0010",
|
||||
"This should be a fixed value",
|
||||
"Potential unsafe implicit conversion from {0} to {1}. Ensure cast comes from a fixed source.",
|
||||
"Usage",
|
||||
DiagnosticSeverity.Error,
|
||||
isEnabledByDefault: true
|
||||
);
|
||||
|
||||
public static readonly DiagnosticDescriptor LosesFixedBrutalCore0012 = new(
|
||||
"BRUTALCORE0012",
|
||||
"Delegate conversion loses [Fixed]",
|
||||
"Converting {0} to '{1}' erases the [Fixed] requirement on parameter '{2}'. Calls through the delegate are not checked; use a delegate type that marks the parameter [Fixed].",
|
||||
"Usage",
|
||||
DiagnosticSeverity.Warning,
|
||||
isEnabledByDefault: true
|
||||
);
|
||||
}
|
||||
|
|
@ -1,180 +0,0 @@
|
|||
using System.Collections.Immutable;
|
||||
using Microsoft.CodeAnalysis;
|
||||
using Microsoft.CodeAnalysis.CSharp;
|
||||
using Microsoft.CodeAnalysis.CSharp.Syntax;
|
||||
using Microsoft.CodeAnalysis.Diagnostics;
|
||||
|
||||
namespace Brutal.Core.Analyzers;
|
||||
|
||||
/// <summary>
|
||||
/// Analyzer that flags explicit type declarations that can be replaced with 'var'.
|
||||
/// </summary>
|
||||
[DiagnosticAnalyzer(LanguageNames.CSharp)]
|
||||
public class VarAnalyzer : DiagnosticAnalyzer
|
||||
{
|
||||
// Keep in mind: you have to list your rules here.
|
||||
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } =
|
||||
ImmutableArray.Create(Resources.VarBrutalCore0007, Resources.VarDefaultBrutalCore0008);
|
||||
|
||||
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();
|
||||
|
||||
// Analyze variable declarations like `float x = 1f` or `MyType obj = new()`
|
||||
context.RegisterSyntaxNodeAction(AnalyzeVariableDeclaration, SyntaxKind.VariableDeclaration);
|
||||
|
||||
// Check other 'context.Register...' methods that might be helpful for your purposes.
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Analyzes explicit variable declarations to suggest 'var' where applicable.
|
||||
/// </summary>
|
||||
/// <param name="context">Operation context.</param>
|
||||
private void AnalyzeVariableDeclaration(SyntaxNodeAnalysisContext context)
|
||||
{
|
||||
var variableDeclaration = (VariableDeclarationSyntax)context.Node;
|
||||
|
||||
if (
|
||||
variableDeclaration.Type.IsVar
|
||||
|| variableDeclaration.Parent is not LocalDeclarationStatementSyntax localDecl
|
||||
|| IsConst(localDecl)
|
||||
)
|
||||
return;
|
||||
|
||||
foreach (var variable in variableDeclaration.Variables)
|
||||
{
|
||||
if (variable.Initializer == null)
|
||||
continue;
|
||||
|
||||
var declaredType = context.SemanticModel.GetTypeInfo(variableDeclaration.Type).Type;
|
||||
var initializerType = context.SemanticModel.GetTypeInfo(variable.Initializer.Value).Type;
|
||||
|
||||
if (declaredType == null || initializerType == null)
|
||||
continue;
|
||||
|
||||
// SomeType me = default -> var me default(SomeType);
|
||||
if (variable.Initializer.Value.IsKind(SyntaxKind.DefaultLiteralExpression))
|
||||
{
|
||||
ReportVarDefaultDiagnostic(context, variableDeclaration);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!WouldVarDeclarationProduceSameType(variable, context.SemanticModel))
|
||||
continue;
|
||||
|
||||
// Report diagnostic on the explicit type
|
||||
context.ReportDiagnostic(
|
||||
Diagnostic.Create(
|
||||
Resources.VarBrutalCore0007,
|
||||
variableDeclaration.Type.GetLocation(),
|
||||
declaredType.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat)
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private static void ReportVarDefaultDiagnostic(
|
||||
SyntaxNodeAnalysisContext context,
|
||||
VariableDeclarationSyntax variableDeclaration
|
||||
)
|
||||
{
|
||||
context.ReportDiagnostic(
|
||||
Diagnostic.Create(
|
||||
Resources.VarDefaultBrutalCore0008,
|
||||
variableDeclaration.Type.GetLocation(),
|
||||
variableDeclaration.Type.ToString()
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// This function returns whether, if the variable declaration was made into a 'var' declaration,
|
||||
/// that the same final type would be the same as what it originally was. e.g.
|
||||
///
|
||||
/// Given:
|
||||
/// Span <byte> data = stackalloc byte[1024];
|
||||
/// If we test
|
||||
/// var data = stackalloc byte[1024];
|
||||
///
|
||||
/// Is the resulting type of the symbol 'data' the same in both cases.
|
||||
/// </summary>
|
||||
/// <param name="declarator"></param>
|
||||
/// <param name="semanticModel"></param>
|
||||
/// <param name="ct"></param>
|
||||
/// <returns></returns>
|
||||
public static bool WouldVarDeclarationProduceSameType(
|
||||
VariableDeclaratorSyntax declarator,
|
||||
SemanticModel semanticModel,
|
||||
CancellationToken ct = default
|
||||
)
|
||||
{
|
||||
// Must have an initializer to use 'var'
|
||||
if (declarator.Initializer is null)
|
||||
return false;
|
||||
|
||||
var declaration = (VariableDeclarationSyntax)declarator.Parent!;
|
||||
var originalLocal = (ILocalSymbol?)semanticModel.GetDeclaredSymbol(declarator, ct);
|
||||
if (originalLocal is null)
|
||||
return false;
|
||||
|
||||
if (declaration.Parent is not LocalDeclarationStatementSyntax localStmt)
|
||||
return false;
|
||||
|
||||
var synthesisedVarDeclaration = SynthesisedVarDeclaration(declarator, declaration);
|
||||
|
||||
if (!TryGetSynthesisedSymbol(semanticModel, localStmt, synthesisedVarDeclaration, out var specLocal, ct))
|
||||
return false;
|
||||
|
||||
return specLocal?.Type is not null
|
||||
&& specLocal.Type.Kind != SymbolKind.ErrorType
|
||||
&& SymbolEqualityComparer.Default.Equals(originalLocal.Type, specLocal.Type);
|
||||
}
|
||||
|
||||
private static bool TryGetSynthesisedSymbol(
|
||||
SemanticModel semanticModel,
|
||||
LocalDeclarationStatementSyntax localStmt,
|
||||
VariableDeclarationSyntax synthesisedVarDeclaration,
|
||||
out ILocalSymbol? specLocal,
|
||||
CancellationToken ct
|
||||
)
|
||||
{
|
||||
var newLocalStmt = localStmt.WithDeclaration(synthesisedVarDeclaration);
|
||||
if (!semanticModel.TryGetSpeculativeSemanticModel(localStmt.SpanStart, newLocalStmt, out var specModel))
|
||||
{
|
||||
specLocal = null;
|
||||
return false;
|
||||
}
|
||||
|
||||
var specRoot = specModel.SyntaxTree.GetRoot(ct);
|
||||
var specDeclarator = specRoot.FindNode(synthesisedVarDeclaration.Variables[0].Span); // <VariableDeclaratorSyntax>(node => node == varDeclaration.Variables[0]);
|
||||
|
||||
specLocal = (ILocalSymbol?)specModel.GetDeclaredSymbol(specDeclarator, ct);
|
||||
return true;
|
||||
}
|
||||
|
||||
private static VariableDeclarationSyntax SynthesisedVarDeclaration(
|
||||
VariableDeclaratorSyntax declarator,
|
||||
VariableDeclarationSyntax declaration
|
||||
)
|
||||
{
|
||||
var varType = SyntaxFactory.IdentifierName("var").WithTriviaFrom(declaration.Type);
|
||||
|
||||
var varDecl = declaration.WithType(varType);
|
||||
return varDecl;
|
||||
}
|
||||
|
||||
private static bool IsConst(LocalDeclarationStatementSyntax localDecl)
|
||||
{
|
||||
for (var i = 0; i < localDecl.Modifiers.Count; i++)
|
||||
{
|
||||
if (localDecl.Modifiers[i].IsKind(SyntaxKind.ConstKeyword))
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
|
@ -1,76 +0,0 @@
|
|||
using System.Collections.Immutable;
|
||||
using System.Composition;
|
||||
using Brutal.Core.Analyzers;
|
||||
using Microsoft.CodeAnalysis;
|
||||
using Microsoft.CodeAnalysis.CodeActions;
|
||||
using Microsoft.CodeAnalysis.CodeFixes;
|
||||
using Microsoft.CodeAnalysis.CSharp;
|
||||
using Microsoft.CodeAnalysis.CSharp.Syntax;
|
||||
|
||||
namespace Brutal.Core.Analyzers;
|
||||
|
||||
[ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(OperatingSystemFixProvider)), Shared]
|
||||
public class OperatingSystemFixProvider : CodeFixProvider
|
||||
{
|
||||
// Specify the diagnostic IDs of analyzers that are expected to be linked.
|
||||
public sealed override ImmutableArray<string> FixableDiagnosticIds { get; } = [Resources.BrutalCore0003.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);
|
||||
|
||||
// To get the required metadata, we should match the Node to the specific type: 'ClassDeclarationSyntax'.
|
||||
if (diagnosticNode is not InvocationExpressionSyntax declaration)
|
||||
return;
|
||||
|
||||
// Register a code action that will invoke the fix.
|
||||
context.RegisterCodeFix(
|
||||
CodeAction.Create(
|
||||
title: Resources.BrutalCore0003Suggestion,
|
||||
createChangedSolution: c => FixToBrutalPlatformAsync(context.Document, declaration, c),
|
||||
equivalenceKey: nameof(Resources.BrutalCore0003.Id)
|
||||
),
|
||||
diagnostic
|
||||
);
|
||||
}
|
||||
|
||||
private static async Task<Solution> FixToBrutalPlatformAsync(
|
||||
Document document,
|
||||
InvocationExpressionSyntax invocationExpression,
|
||||
CancellationToken cancellationToken
|
||||
)
|
||||
{
|
||||
// Change from OperatingSystem.XYZ() to Platform.XYZ
|
||||
// Platform.XYZ is a property, not a method, so we just change the expression part.
|
||||
var memberAccess = invocationExpression.Expression as MemberAccessExpressionSyntax;
|
||||
if (memberAccess == null)
|
||||
return document.Project.Solution;
|
||||
|
||||
var root = await document.GetSyntaxRootAsync(cancellationToken);
|
||||
if (root == null)
|
||||
return document.Project.Solution;
|
||||
|
||||
var newMemberAccess = SyntaxFactory.MemberAccessExpression(
|
||||
SyntaxKind.SimpleMemberAccessExpression,
|
||||
SyntaxFactory.IdentifierName("Platform"),
|
||||
memberAccess.Name
|
||||
);
|
||||
|
||||
var newRoot = root.ReplaceNode(invocationExpression, newMemberAccess);
|
||||
var newDocument = document.WithSyntaxRoot(newRoot);
|
||||
return newDocument.Project.Solution;
|
||||
}
|
||||
}
|
||||
|
|
@ -1,192 +0,0 @@
|
|||
using System.Collections.Immutable;
|
||||
using System.Composition;
|
||||
using Brutal.Core.Analyzers;
|
||||
using Microsoft.CodeAnalysis;
|
||||
using Microsoft.CodeAnalysis.CodeActions;
|
||||
using Microsoft.CodeAnalysis.CodeFixes;
|
||||
using Microsoft.CodeAnalysis.CSharp;
|
||||
using Microsoft.CodeAnalysis.CSharp.Syntax;
|
||||
|
||||
namespace Brutal.Core.Analyzers;
|
||||
|
||||
/// <summary>
|
||||
/// A code fix provider that replaces explicit types with 'var' and expands 'new()' to 'new TypeName()'.
|
||||
/// All code fixes must be linked to specific analyzers.
|
||||
/// </summary>
|
||||
[ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(VarFixProvider)), Shared]
|
||||
public class VarFixProvider : CodeFixProvider
|
||||
{
|
||||
// Specify the diagnostic IDs of analyzers that are expected to be linked.
|
||||
public sealed override ImmutableArray<string> FixableDiagnosticIds { get; } =
|
||||
[Resources.VarBrutalCore0007.Id, Resources.VarDefaultBrutalCore0008.Id];
|
||||
|
||||
// If you don't need the 'fix all' behavior, return null.
|
||||
public override FixAllProvider? GetFixAllProvider() => null; //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.
|
||||
if (context.Diagnostics.Length != 1)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var diagnostic = context.Diagnostics[0];
|
||||
|
||||
// 'SourceSpan' of 'Location' is the highlighted area.
|
||||
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 the TypeSyntax node to replace (eg., 'float' in 'float x = 1f')
|
||||
if (root?.FindNode(diagnosticSpan) is not TypeSyntax typeSyntax)
|
||||
return;
|
||||
|
||||
var declaration = typeSyntax.FirstAncestorOrSelf<VariableDeclarationSyntax>();
|
||||
if (declaration is not null && TryRegisterDefault(declaration, context, diagnostic, root))
|
||||
return;
|
||||
|
||||
// Register a code action that will invoke the fix.
|
||||
context.RegisterCodeFix(
|
||||
CodeAction.Create(
|
||||
title: string.Format(Resources.VarBrutalCore0007.Id),
|
||||
createChangedDocument: c => ReplaceWithVarAsync(context.Document, typeSyntax, c),
|
||||
equivalenceKey: nameof(Resources.VarBrutalCore0007.Id)
|
||||
),
|
||||
diagnostic
|
||||
);
|
||||
}
|
||||
|
||||
private bool TryRegisterDefault(
|
||||
VariableDeclarationSyntax declaration,
|
||||
CodeFixContext context,
|
||||
Diagnostic diagnostic,
|
||||
SyntaxNode root
|
||||
)
|
||||
{
|
||||
var variable = declaration.Variables.FirstOrDefault();
|
||||
if (variable?.Initializer is null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
// e.g. int bob = default. Here, default is a DefaultLiteralExpression
|
||||
// int bob = default(3). Here, default is a DefaultExpression
|
||||
if (!variable.Initializer.Value.IsKind(SyntaxKind.DefaultLiteralExpression))
|
||||
return false;
|
||||
|
||||
context.RegisterCodeFix(
|
||||
CodeAction.Create(
|
||||
Resources.VarDefaultBrutalCore0008.Title.ToString(),
|
||||
c => UseVarAndExplicitDefaultAsync(context.Document, declaration, variable, c, root),
|
||||
nameof(VarFixProvider)
|
||||
),
|
||||
diagnostic
|
||||
);
|
||||
return true;
|
||||
}
|
||||
|
||||
private Task<Document> UseVarAndExplicitDefaultAsync(
|
||||
Document document,
|
||||
VariableDeclarationSyntax declaration,
|
||||
VariableDeclaratorSyntax variable,
|
||||
CancellationToken cancellationToken,
|
||||
SyntaxNode root
|
||||
)
|
||||
{
|
||||
var varType = SyntaxFactory
|
||||
.IdentifierName("var")
|
||||
.WithLeadingTrivia(declaration.Type.GetLeadingTrivia())
|
||||
.WithTrailingTrivia(declaration.Type.GetTrailingTrivia());
|
||||
|
||||
var explicitDefault = SyntaxFactory.DefaultExpression(declaration.Type.WithoutTrivia());
|
||||
|
||||
var newVariable = variable.WithInitializer(
|
||||
SyntaxFactory.EqualsValueClause(explicitDefault).WithEqualsToken(variable.Initializer!.EqualsToken)
|
||||
);
|
||||
|
||||
var newDeclaration = declaration
|
||||
.WithType(varType)
|
||||
.WithVariables(SyntaxFactory.SingletonSeparatedList(newVariable));
|
||||
|
||||
// var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
|
||||
var newRoot = root.ReplaceNode(declaration, newDeclaration);
|
||||
|
||||
return Task.FromResult(document.WithSyntaxRoot(newRoot));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Executed on the quick fix action raised by the user.
|
||||
/// </summary>
|
||||
/// <param name="document">Affected source file.</param>
|
||||
/// <param name="explicitType">The explicit type syntax node to replace.</param>
|
||||
/// <param name="cancellationToken">Any fix is cancellable by the user, so we should support the cancellation token.</param>
|
||||
/// <returns>A new document with the explicit type replaced by 'var'.</returns>
|
||||
private async Task<Document> ReplaceWithVarAsync(
|
||||
Document document,
|
||||
TypeSyntax explicitType,
|
||||
CancellationToken cancellationToken
|
||||
)
|
||||
{
|
||||
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (root == null)
|
||||
return document;
|
||||
|
||||
var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (semanticModel == null)
|
||||
return document;
|
||||
|
||||
// Get the VariableDeclarationSyntax node (e.g., 'myObject obj = new();')
|
||||
if (explicitType.Parent is not VariableDeclarationSyntax declaration || declaration.Variables.Count == 0)
|
||||
return document;
|
||||
|
||||
var variable = declaration.Variables[0];
|
||||
|
||||
// Create 'var' keyword with preserved trivia
|
||||
var varType = SyntaxFactory
|
||||
.IdentifierName("var")
|
||||
.WithLeadingTrivia(explicitType.GetLeadingTrivia())
|
||||
.WithTrailingTrivia(explicitType.GetTrailingTrivia());
|
||||
|
||||
ExpressionSyntax? newInitializerExpr = variable.Initializer?.Value;
|
||||
|
||||
// Replace 'new()' with 'new myObject()' if necessary
|
||||
if (variable.Initializer?.Value is ImplicitObjectCreationExpressionSyntax implicitNew)
|
||||
{
|
||||
newInitializerExpr = SyntaxFactory
|
||||
.ObjectCreationExpression(explicitType.WithoutTrivia())
|
||||
.WithArgumentList(implicitNew.ArgumentList ?? SyntaxFactory.ArgumentList())
|
||||
.WithTrailingTrivia(implicitNew.GetTrailingTrivia())
|
||||
.WithLeadingTrivia(implicitNew.GetLeadingTrivia());
|
||||
}
|
||||
|
||||
if (variable.Initializer?.Value is DefaultExpressionSyntax defaultExpression)
|
||||
{
|
||||
newInitializerExpr = SyntaxFactory
|
||||
.DefaultExpression(explicitType.WithoutTrivia())
|
||||
.WithType(explicitType.NormalizeWhitespace());
|
||||
}
|
||||
|
||||
// Reconstruct initializer
|
||||
var newInitializer = variable.Initializer?.WithValue(newInitializerExpr!);
|
||||
|
||||
// Reconstruct the variable
|
||||
var newVariable = variable
|
||||
.WithInitializer(newInitializer)
|
||||
.WithLeadingTrivia(variable.GetLeadingTrivia())
|
||||
.WithTrailingTrivia(variable.GetTrailingTrivia());
|
||||
|
||||
// Replace the declaration node
|
||||
var newDeclaration = declaration
|
||||
.WithType(varType)
|
||||
.WithVariables(SyntaxFactory.SingletonSeparatedList(newVariable))
|
||||
.WithLeadingTrivia(declaration.GetLeadingTrivia())
|
||||
.WithTrailingTrivia(declaration.GetTrailingTrivia());
|
||||
|
||||
// Replace the old node with the new one in the tree
|
||||
var newRoot = root.ReplaceNode(declaration, newDeclaration);
|
||||
|
||||
return document.WithSyntaxRoot(newRoot);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,41 +0,0 @@
|
|||
# Finds FreeType from the RocketWerkz.Brutal.FreeType NuGet package, for consumers building native
|
||||
# code against freetype. Shipped inside the package (build/natives/cmake/); a consumer puts this dir
|
||||
# on CMAKE_MODULE_PATH and calls find_package(Freetype). FREETYPE_NUGET_DIR is injected by the
|
||||
# package's auto-imported .targets.
|
||||
|
||||
# Normalise path separators (MSBuild may produce backslashes on Windows).
|
||||
file(TO_CMAKE_PATH "${FREETYPE_NUGET_DIR}" FREETYPE_NUGET_DIR)
|
||||
|
||||
# Point at the shared lib (and Windows import lib) inside the NuGet package.
|
||||
if(WIN32)
|
||||
set(freetype_shared "${FREETYPE_NUGET_DIR}/runtimes/win-x64/native/freetype.dll")
|
||||
set(freetype_implib "${FREETYPE_NUGET_DIR}/build/natives/lib/win-x64/freetype.lib")
|
||||
elseif(APPLE)
|
||||
set(freetype_shared "${FREETYPE_NUGET_DIR}/runtimes/osx-arm64/native/libfreetype.dylib")
|
||||
else()
|
||||
set(freetype_shared "${FREETYPE_NUGET_DIR}/runtimes/linux-x64/native/libfreetype.so")
|
||||
endif()
|
||||
|
||||
# Hand find_package the results it expects.
|
||||
set(FREETYPE_FOUND TRUE)
|
||||
set(FREETYPE_INCLUDE_DIRS "${FREETYPE_NUGET_DIR}/build/natives/include")
|
||||
set(FREETYPE_LIBRARIES "${freetype_shared}")
|
||||
|
||||
# Expose the standard Freetype::Freetype target so consumers can link it.
|
||||
if(NOT TARGET Freetype::Freetype)
|
||||
add_library(Freetype::Freetype SHARED IMPORTED GLOBAL)
|
||||
set_target_properties(Freetype::Freetype PROPERTIES
|
||||
IMPORTED_LOCATION "${freetype_shared}"
|
||||
INTERFACE_INCLUDE_DIRECTORIES "${FREETYPE_NUGET_DIR}/build/natives/include"
|
||||
)
|
||||
# Match the soname/implib the linker expects per platform.
|
||||
if(WIN32)
|
||||
set_property(TARGET Freetype::Freetype PROPERTY IMPORTED_IMPLIB "${freetype_implib}")
|
||||
elseif(APPLE)
|
||||
set_property(TARGET Freetype::Freetype PROPERTY IMPORTED_SONAME "@rpath/libfreetype.6.dylib")
|
||||
else()
|
||||
set_property(TARGET Freetype::Freetype PROPERTY IMPORTED_SONAME "libfreetype.so.6")
|
||||
endif()
|
||||
endif()
|
||||
|
||||
mark_as_advanced(FREETYPE_FOUND FREETYPE_INCLUDE_DIRS FREETYPE_LIBRARIES)
|
||||
|
|
@ -1,10 +0,0 @@
|
|||
<Project>
|
||||
<!-- Injects the package root into cmake for any project building native code against FreeType. -->
|
||||
<PropertyGroup>
|
||||
<FreeTypeNuGetDir>$([MSBuild]::NormalizePath('$(MSBuildThisFileDirectory)', '..').Replace('\', '/'))</FreeTypeNuGetDir>
|
||||
<CMakeBuildArgs Condition="'$(CMakeBuildArgs)' != ''"
|
||||
>$(CMakeBuildArgs) -DFREETYPE_NUGET_DIR=$(FreeTypeNuGetDir)</CMakeBuildArgs
|
||||
>
|
||||
<CMakeBuildArgs Condition="'$(CMakeBuildArgs)' == ''">-DFREETYPE_NUGET_DIR=$(FreeTypeNuGetDir)</CMakeBuildArgs>
|
||||
</PropertyGroup>
|
||||
</Project>
|
||||
175
brutal.imgui/LICENSES/BRUTAL-IMGUI-THIRD-PARTY-NOTICES.txt
Normal file
175
brutal.imgui/LICENSES/BRUTAL-IMGUI-THIRD-PARTY-NOTICES.txt
Normal file
|
|
@ -0,0 +1,175 @@
|
|||
THIRD-PARTY LICENSE NOTICES
|
||||
The Brutal.ImGui packages
|
||||
|
||||
This file ships in all eight packages named below. They redistribute the third-party
|
||||
components listed here, each reproduced with the license that governs it.
|
||||
|
||||
One file serves all eight packages, so this table says which components apply to
|
||||
the package you are holding:
|
||||
|
||||
RocketWerkz.Brutal.ImGui Dear ImGui, and the three stb libraries
|
||||
compiled into it
|
||||
RocketWerkz.Brutal.ImGui.Backends Dear ImGui's platform and renderer
|
||||
backends, translated to C#
|
||||
RocketWerkz.Brutal.ImGui.DemoWindow Dear ImGui's demo sources, translated
|
||||
to C#
|
||||
RocketWerkz.Brutal.ImGui.FreeType Dear ImGui's FreeType font adapter
|
||||
RocketWerkz.Brutal.ImPlot ImPlot
|
||||
RocketWerkz.Brutal.ImPlot.DemoWindow ImPlot's demo sources, translated to C#
|
||||
RocketWerkz.Brutal.ImGui.Abstractions no third-party code
|
||||
RocketWerkz.Brutal.ImGui.Extensions no third-party code
|
||||
|
||||
Where a package ships native libraries, it ships them for every runtime identifier
|
||||
it supports (win-x64, linux-x64, osx-arm64):
|
||||
|
||||
Dear ImGui 1.92.2 imgui.dll / libimgui.so / libimgui.dylib
|
||||
imgui_freetype.dll / libimgui_freetype.so / libimgui_freetype.dylib
|
||||
ImPlot 0.17 implot.dll / libimplot.so / libimplot.dylib
|
||||
|
||||
Dear ImGui vendors three of Sean Barrett's stb libraries, and all three are
|
||||
compiled into the Dear ImGui binaries shipped here. They have their own section
|
||||
below.
|
||||
|
||||
The managed assemblies are in scope as well as the native libraries. Type names,
|
||||
enumerant values and entry-point signatures are generated from the corresponding
|
||||
upstream headers, and the backend and demo assemblies are C# translations of
|
||||
upstream sources.
|
||||
|
||||
RocketWerkz.Brutal.ImGui.FreeType binds Dear ImGui's FreeType font adapter, which
|
||||
is Dear ImGui code and is covered by the Dear ImGui section below. FreeType itself
|
||||
is in none of these eight packages; it is supplied by RocketWerkz.Brutal.FreeType,
|
||||
whose own notices reproduce the FreeType License in full.
|
||||
|
||||
|
||||
==============================================================================
|
||||
Dear ImGui
|
||||
==============================================================================
|
||||
|
||||
Name Dear ImGui
|
||||
Version 1.92.2, docking branch
|
||||
Upstream https://github.com/ocornut/imgui
|
||||
SPDX MIT
|
||||
|
||||
Built from a RocketWerkz fork of the docking branch. The modifications are ours
|
||||
and do not alter the terms below, which are reproduced from the copy these
|
||||
packages were built from.
|
||||
|
||||
This component covers the imgui and imgui_freetype native libraries, the managed
|
||||
bindings generated from Dear ImGui's headers, and the C# translations of Dear
|
||||
ImGui's backend and demo sources.
|
||||
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2014-2025 Omar Cornut
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
|
||||
|
||||
==============================================================================
|
||||
stb
|
||||
==============================================================================
|
||||
|
||||
Name stb_rect_pack, stb_textedit, stb_truetype
|
||||
Version 1.01, 1.14, 1.26 respectively
|
||||
Upstream https://github.com/nothings/stb
|
||||
SPDX MIT OR Unlicense
|
||||
|
||||
Vendored by Dear ImGui as imstb_rectpack.h, imstb_textedit.h and
|
||||
imstb_truetype.h, and compiled into the Dear ImGui native libraries shipped
|
||||
here. All three carry the same dual license, which offers a choice between
|
||||
the MIT License and release into the public domain. It is reproduced once
|
||||
below, from the copy these packages were built from.
|
||||
|
||||
This software is available under 2 licenses -- choose whichever you prefer.
|
||||
------------------------------------------------------------------------------
|
||||
ALTERNATIVE A - MIT License
|
||||
Copyright (c) 2017 Sean Barrett
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of
|
||||
this software and associated documentation files (the "Software"), to deal in
|
||||
the Software without restriction, including without limitation the rights to
|
||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
||||
of the Software, and to permit persons to whom the Software is furnished to do
|
||||
so, subject to the following conditions:
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
------------------------------------------------------------------------------
|
||||
ALTERNATIVE B - Public Domain (www.unlicense.org)
|
||||
This is free and unencumbered software released into the public domain.
|
||||
Anyone is free to copy, modify, publish, use, compile, sell, or distribute this
|
||||
software, either in source code form or as a compiled binary, for any purpose,
|
||||
commercial or non-commercial, and by any means.
|
||||
In jurisdictions that recognize copyright laws, the author or authors of this
|
||||
software dedicate any and all copyright interest in the software to the public
|
||||
domain. We make this dedication for the benefit of the public at large and to
|
||||
the detriment of our heirs and successors. We intend this dedication to be an
|
||||
overt act of relinquishment in perpetuity of all present and future rights to
|
||||
this software under copyright law.
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
|
||||
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
------------------------------------------------------------------------------
|
||||
|
||||
|
||||
==============================================================================
|
||||
ImPlot
|
||||
==============================================================================
|
||||
|
||||
Name ImPlot
|
||||
Version 0.17, upstream commit 3da8bd3 (26 commits after tag v0.16)
|
||||
Upstream https://github.com/epezent/implot
|
||||
SPDX MIT
|
||||
|
||||
ImPlot is a plotting extension for Dear ImGui. Its version is the one ImPlot
|
||||
reports for itself; the commit is given because upstream had not tagged 0.17 when
|
||||
these packages were built.
|
||||
|
||||
This component covers the implot native library, the managed bindings generated
|
||||
from ImPlot's headers, and the C# translation of ImPlot's demo sources.
|
||||
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2020 Evan Pezent
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
|
|
@ -1,58 +0,0 @@
|
|||
using System.Text;
|
||||
using Microsoft.CodeAnalysis;
|
||||
using Microsoft.CodeAnalysis.CSharp.Syntax;
|
||||
using Microsoft.CodeAnalysis.Text;
|
||||
|
||||
namespace Brutal.Interop.SourceGenerators;
|
||||
|
||||
[Generator]
|
||||
public class InteropHandleGenerator : IIncrementalGenerator
|
||||
{
|
||||
public void Initialize(IncrementalGeneratorInitializationContext context)
|
||||
{
|
||||
var pipeline = context.SyntaxProvider.ForAttributeWithMetadataName(
|
||||
fullyQualifiedMetadataName: "Brutal.Interop.InteropHandleAttribute",
|
||||
predicate: static (node, _) => node is StructDeclarationSyntax,
|
||||
transform: static (ctx, _) => new Model(ctx)
|
||||
);
|
||||
|
||||
context.RegisterSourceOutput(pipeline, static (ctx, model) => model.Generate(ctx));
|
||||
}
|
||||
|
||||
private readonly record struct Model
|
||||
{
|
||||
private readonly string? _namespace;
|
||||
private readonly string _typeName;
|
||||
|
||||
public Model(GeneratorAttributeSyntaxContext context)
|
||||
{
|
||||
var symbol = (INamedTypeSymbol)context.TargetSymbol;
|
||||
_namespace = symbol.ContainingNamespace is { IsGlobalNamespace: false } ns
|
||||
? ns.ToDisplayString()
|
||||
: null;
|
||||
_typeName = symbol.Name;
|
||||
}
|
||||
|
||||
public void Generate(SourceProductionContext context)
|
||||
{
|
||||
var nsDecl = _namespace is not null ? $"namespace {_namespace};\n\n" : "";
|
||||
|
||||
var source = $$"""
|
||||
#nullable enable
|
||||
using System.Runtime.InteropServices.Marshalling;
|
||||
using Brutal.Interop;
|
||||
|
||||
{{nsDecl}}[NativeMarshalling(typeof(InteropHandleMarshaller<{{_typeName}}, {{_typeName}}.Handle>))]
|
||||
public readonly unsafe partial struct {{_typeName}} : IInteropHandle<{{_typeName}}.Handle, {{_typeName}}>
|
||||
{
|
||||
public record struct Handle(nint Value);
|
||||
public required Handle Pointer { get; init; }
|
||||
public bool IsNull() => Pointer.Value == 0;
|
||||
public static implicit operator {{_typeName}}(void* ptr) => new() { Pointer = new Handle((nint)ptr) };
|
||||
}
|
||||
""";
|
||||
|
||||
context.AddSource($"{_typeName}.g.cs", SourceText.From(source, Encoding.UTF8));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,29 +0,0 @@
|
|||
<Project>
|
||||
<!-- NuGet extraction does not preserve executable permissions for the NativeAOT watchdog. -->
|
||||
<Target
|
||||
Name="MakeMonitorBuildExecutable"
|
||||
AfterTargets="CopyFilesToOutputDirectory"
|
||||
Condition="!$([MSBuild]::IsOSPlatform('Windows')) and '$(TargetDir)' != ''"
|
||||
>
|
||||
<ItemGroup>
|
||||
<_MonitorBuildExecutable Include="$(TargetDir)Brutal.Monitor.Subprocess;$(TargetDir)runtimes/*/native/Brutal.Monitor.Subprocess" />
|
||||
</ItemGroup>
|
||||
<Exec
|
||||
Command="chmod +x "%(_MonitorBuildExecutable.Identity)""
|
||||
Condition="Exists('%(_MonitorBuildExecutable.Identity)')"
|
||||
/>
|
||||
</Target>
|
||||
<Target
|
||||
Name="MakeMonitorPublishExecutable"
|
||||
AfterTargets="Publish"
|
||||
Condition="!$([MSBuild]::IsOSPlatform('Windows')) and '$(PublishDir)' != ''"
|
||||
>
|
||||
<ItemGroup>
|
||||
<_MonitorPublishExecutable Include="$(PublishDir)Brutal.Monitor.Subprocess;$(PublishDir)runtimes/*/native/Brutal.Monitor.Subprocess" />
|
||||
</ItemGroup>
|
||||
<Exec
|
||||
Command="chmod +x "%(_MonitorPublishExecutable.Identity)""
|
||||
Condition="Exists('%(_MonitorPublishExecutable.Identity)')"
|
||||
/>
|
||||
</Target>
|
||||
</Project>
|
||||
|
|
@ -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."
|
||||
);
|
||||
}
|
||||
|
|
@ -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;
|
||||
}
|
||||
}
|
||||
|
|
@ -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())
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
@ -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())
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
@ -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;
|
||||
}
|
||||
}
|
||||
|
|
@ -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);
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue