mirror of
https://github.com/ahwootech/BRUTAL.git
synced 2026-11-26 13:08:24 +01:00
SOURCE DUMP v1
This commit is contained in:
parent
bd62d51ec9
commit
fb20299e9d
4 changed files with 768360 additions and 0 deletions
1032
brutal.core/Brutal.Core.Analyzers/FixedAnalyzer.cs
Normal file
1032
brutal.core/Brutal.Core.Analyzers/FixedAnalyzer.cs
Normal file
File diff suppressed because it is too large
Load diff
54
brutal.core/Brutal.Core.Analyzers/OperatingSystemAnalyzer.cs
Normal file
54
brutal.core/Brutal.Core.Analyzers/OperatingSystemAnalyzer.cs
Normal file
|
|
@ -0,0 +1,54 @@
|
|||
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);
|
||||
}
|
||||
}
|
||||
66
brutal.core/Brutal.Core.Analyzers/Resources.cs
Normal file
66
brutal.core/Brutal.Core.Analyzers/Resources.cs
Normal file
|
|
@ -0,0 +1,66 @@
|
|||
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
|
||||
);
|
||||
}
|
||||
180
brutal.core/Brutal.Core.Analyzers/VarAnalyzer.cs
Normal file
180
brutal.core/Brutal.Core.Analyzers/VarAnalyzer.cs
Normal file
|
|
@ -0,0 +1,180 @@
|
|||
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;
|
||||
}
|
||||
}
|
||||
Loading…
Reference in a new issue