mirror of
https://github.com/ahwootech/BRUTAL.git
synced 2026-11-26 21:18:24 +01:00
SOURCE DUMP v2
This commit is contained in:
parent
fb20299e9d
commit
9083135f76
6 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);
|
||||
}
|
||||
}
|
||||
Loading…
Reference in a new issue