From bc66ce0adfdffe45a953a7cfcdf4503ffdd062b5 Mon Sep 17 00:00:00 2001 From: earloc Date: Sat, 26 Oct 2024 14:53:30 +0200 Subject: [PATCH] chore: code-rub --- .editorconfig | 82 +++++++++++- src/Playground.Common/Greeter.cs | 6 +- .../IStringLocalizerExtensions.cs | 3 +- src/TypealizR.CLI/Abstractions/FileStorage.cs | 5 +- src/TypealizR.CLI/App.cs | 8 +- .../Commands/CodeFirst/ExportCommand.cs | 73 +++++------ .../Extensions/ExpressionSyntaxExtensions.cs | 3 +- .../CLI.Tests/ExportCommand.Tests.cs | 4 +- .../CodeFirstSourceGenerator.Tests/.Tests.cs | 20 +-- .../DiagnosticsFactory.Tests.cs | 4 +- src/TypealizR.Tests/ModuleInitializer.cs | 5 +- src/TypealizR.Tests/RessourceFile.Tests.cs | 12 +- .../Snapshots/GeneratorTester.cs | 2 +- .../Snapshots/GeneratorTesterBuilder.cs | 3 +- .../GeneratorTesterOptionsProvider.cs | 5 +- src/TypealizR.Tests/Snapshots/ResxFile.cs | 5 +- .../.Tests.cs | 10 +- .../.Tests.cs | 123 ++++-------------- .../_.Tests.cs | 30 +---- .../CodeFirstMethodModel.cs | 2 +- .../CodeFirstParameterBuilder.cs | 2 +- .../CodeFirstParameterModel.cs | 8 +- .../CodeFirstPropertyBuilder.cs | 5 +- .../CodeFirstPropertyModel.cs | 2 +- .../CodeFirstSourceGenerator.cs | 4 +- src/TypealizR/Core/CommentModel.cs | 3 +- src/TypealizR/Core/GeneratorOptions.cs | 13 +- src/TypealizR/Core/MemberName.cs | 1 + src/TypealizR/Core/ParameterBuilder.cs | 12 +- src/TypealizR/Core/ParameterModel.cs | 9 +- .../Core/ResxFileSourceGeneratorBase.cs | 10 +- src/TypealizR/Core/Visibility.cs | 9 +- src/TypealizR/Diagnostics/DiagnosticsEntry.cs | 2 +- .../Diagnostics/DiagnosticsFactory.cs | 22 +--- src/TypealizR/Extensions/CharExtensions.cs | 35 +++-- src/TypealizR/Extensions/StringExtensions.cs | 34 ++--- src/TypealizR/Extensions/TypeExtensions.cs | 2 +- .../StringFormatterClassBuilder.cs | 29 ++--- .../ExtensionClassBuilder.cs | 2 +- .../ExtensionMethodBuilder.cs | 2 +- .../ExtensionMethodModel.cs | 9 +- ...tringLocalizerExtensionsSourceGenerator.cs | 2 +- .../InstanceMemberModel.cs | 2 +- .../TypealizedClassSourceGenerator.cs | 2 +- .../TypealizeRCodeFixProvider.cs | 13 +- .../UseIndexerAnalyzer.cs | 9 +- 46 files changed, 266 insertions(+), 382 deletions(-) diff --git a/.editorconfig b/.editorconfig index 18c57550..1de43103 100644 --- a/.editorconfig +++ b/.editorconfig @@ -13,4 +13,84 @@ dotnet_diagnostic.CA1707.severity = none dotnet_diagnostic.CA2007.severity = none # CA1852: Type 'Program' can be sealed because it has no subtypes in its containing assembly and is not externally visible -dotnet_diagnostic.CA1852.severity = none +dotnet_diagnostic.CA1852.severity = none +csharp_indent_labels = one_less_than_current +csharp_using_directive_placement = outside_namespace:silent +csharp_prefer_simple_using_statement = true:warning +csharp_prefer_braces = true:warning +csharp_style_namespace_declarations = file_scoped:warning +csharp_style_prefer_method_group_conversion = true:warning +csharp_style_prefer_top_level_statements = true:silent +csharp_style_prefer_primary_constructors = true:suggestion +csharp_style_expression_bodied_methods = true:silent +csharp_style_expression_bodied_constructors = true:silent +csharp_style_expression_bodied_operators = true:silent +csharp_style_expression_bodied_properties = true:silent +csharp_style_expression_bodied_indexers = true:silent +csharp_style_expression_bodied_accessors = true:silent +csharp_style_expression_bodied_lambdas = true:silent +csharp_style_expression_bodied_local_functions = true:silent +csharp_style_inlined_variable_declaration = true:suggestion +csharp_style_deconstructed_variable_declaration = true:suggestion +csharp_style_var_for_built_in_types = true:silent +csharp_style_var_when_type_is_apparent = true:silent +csharp_style_var_elsewhere = true:silent +csharp_space_around_binary_operators = before_and_after + +[*.{cs,vb}] +#### Naming styles #### + +# Naming rules + +dotnet_naming_rule.interface_should_be_begins_with_i.severity = suggestion +dotnet_naming_rule.interface_should_be_begins_with_i.symbols = interface +dotnet_naming_rule.interface_should_be_begins_with_i.style = begins_with_i + +dotnet_naming_rule.types_should_be_pascal_case.severity = suggestion +dotnet_naming_rule.types_should_be_pascal_case.symbols = types +dotnet_naming_rule.types_should_be_pascal_case.style = pascal_case + +dotnet_naming_rule.non_field_members_should_be_pascal_case.severity = suggestion +dotnet_naming_rule.non_field_members_should_be_pascal_case.symbols = non_field_members +dotnet_naming_rule.non_field_members_should_be_pascal_case.style = pascal_case + +# Symbol specifications + +dotnet_naming_symbols.interface.applicable_kinds = interface +dotnet_naming_symbols.interface.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected +dotnet_naming_symbols.interface.required_modifiers = + +dotnet_naming_symbols.types.applicable_kinds = class, struct, interface, enum +dotnet_naming_symbols.types.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected +dotnet_naming_symbols.types.required_modifiers = + +dotnet_naming_symbols.non_field_members.applicable_kinds = property, event, method +dotnet_naming_symbols.non_field_members.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected +dotnet_naming_symbols.non_field_members.required_modifiers = + +# Naming styles + +dotnet_naming_style.begins_with_i.required_prefix = I +dotnet_naming_style.begins_with_i.required_suffix = +dotnet_naming_style.begins_with_i.word_separator = +dotnet_naming_style.begins_with_i.capitalization = pascal_case + +dotnet_naming_style.pascal_case.required_prefix = +dotnet_naming_style.pascal_case.required_suffix = +dotnet_naming_style.pascal_case.word_separator = +dotnet_naming_style.pascal_case.capitalization = pascal_case + +dotnet_naming_style.pascal_case.required_prefix = +dotnet_naming_style.pascal_case.required_suffix = +dotnet_naming_style.pascal_case.word_separator = +dotnet_naming_style.pascal_case.capitalization = pascal_case +dotnet_style_operator_placement_when_wrapping = beginning_of_line +dotnet_style_coalesce_expression = true:suggestion +dotnet_style_null_propagation = true:suggestion +dotnet_style_prefer_is_null_check_over_reference_equality_method = true:warning +dotnet_style_prefer_auto_properties = true:silent +dotnet_style_object_initializer = true:suggestion +dotnet_style_collection_initializer = true:suggestion +dotnet_style_prefer_simplified_boolean_expressions = true:suggestion +dotnet_style_prefer_conditional_expression_over_assignment = true:silent +dotnet_style_prefer_conditional_expression_over_return = true:silent diff --git a/src/Playground.Common/Greeter.cs b/src/Playground.Common/Greeter.cs index e8e7d016..b27309f9 100644 --- a/src/Playground.Common/Greeter.cs +++ b/src/Playground.Common/Greeter.cs @@ -15,11 +15,9 @@ public Greeter(IStringLocalizer localize, IStringLocalizer Console.WriteLine(localize.Hello__name(name)); - + public void SayHello(string name) => Console.WriteLine(localize.Hello__name(name)); + public void SayHelloPublic(string name) => Console.WriteLine(publicDuplicate.Hello__name(name)); - public void GoodMorning(string name) => Console.WriteLine(duplicates.GoodMorning__name(name)); - } diff --git a/src/Playground.Console/IStringLocalizerExtensions.cs b/src/Playground.Console/IStringLocalizerExtensions.cs index c6cc7d09..7a3cf73a 100644 --- a/src/Playground.Console/IStringLocalizerExtensions.cs +++ b/src/Playground.Console/IStringLocalizerExtensions.cs @@ -4,11 +4,12 @@ namespace Playground.Console; internal static class IStringLocalizerExtensions { public static LocalizedString Bar(this IStringLocalizer that) => that["Bar"]; + public static LocalizedString Bar(this IStringLocalizer that, string value) => that["Bar", value]; public static LocalizedString Foo(this IStringLocalizer that, string value) => that["Foo {bar}", value]; + public static LocalizedString FooBar(this IStringLocalizer that, string value) => that["FooBar {0}", value]; public static LocalizedString Bars(this IStringLocalizer that, string v1, int v2) => that["Bar {0} {1}", v1, v2]; - } \ No newline at end of file diff --git a/src/TypealizR.CLI/Abstractions/FileStorage.cs b/src/TypealizR.CLI/Abstractions/FileStorage.cs index 5c028ad1..34678806 100644 --- a/src/TypealizR.CLI/Abstractions/FileStorage.cs +++ b/src/TypealizR.CLI/Abstractions/FileStorage.cs @@ -1,8 +1,5 @@ namespace TypealizR.CLI.Abstractions; internal class FileStorage : IStorage { - public async Task AddAsync(string fileName, string content) - { - await File.WriteAllTextAsync(fileName, content); - } + public async Task AddAsync(string fileName, string content) => await File.WriteAllTextAsync(fileName, content); } diff --git a/src/TypealizR.CLI/App.cs b/src/TypealizR.CLI/App.cs index 1c2092aa..d92f8255 100644 --- a/src/TypealizR.CLI/App.cs +++ b/src/TypealizR.CLI/App.cs @@ -30,10 +30,10 @@ public App(Action? configureServices = null, params string[] codeFirstCommand.AddAlias("cf"); - var rootCommand = new RootCommand() - { + RootCommand rootCommand = + [ codeFirstCommand - }; + ]; runner = new CommandLineBuilder(rootCommand) .UseDefaults() @@ -57,5 +57,5 @@ private void ConfigureServices(IServiceCollection services) services.TryAddSingleton(); } - public Task RunAsync() => runner.InvokeAsync(args); + public Task RunAsync() => runner.InvokeAsync(args); } diff --git a/src/TypealizR.CLI/Commands/CodeFirst/ExportCommand.cs b/src/TypealizR.CLI/Commands/CodeFirst/ExportCommand.cs index 228f7a0b..c36bd20c 100644 --- a/src/TypealizR.CLI/Commands/CodeFirst/ExportCommand.cs +++ b/src/TypealizR.CLI/Commands/CodeFirst/ExportCommand.cs @@ -29,10 +29,7 @@ public Implementation(IConsole console, IStorage storage) this.storage = storage; } - public int Invoke(InvocationContext context) - { - throw new NotImplementedException(); - } + public int Invoke(InvocationContext context) => throw new NotImplementedException(); public async Task InvokeAsync(InvocationContext context) { @@ -130,25 +127,23 @@ private static async Task ExportAsync(IConsole console, string baseDirectory, IE } } - private static IEnumerable FindNamespaces(Compilation compilation, CancellationToken cancellationToken) - => compilation.SyntaxTrees - .Where(x => x.GetRoot() is CompilationUnitSyntax) - .Select(x => (CompilationUnitSyntax)x.GetRoot(cancellationToken)) - .SelectMany(x => x.Members.OfType()) - ; - - private static IEnumerable FindInterfaces(Compilation compilation, IEnumerable allNamespaces, CancellationToken cancellationToken) - => allNamespaces - .SelectMany(x => x.Members.OfType()) - .Select(x => new { Declaration = x, Model = compilation.GetSemanticModel(x.SyntaxTree) }) - .Select(x => new { x.Declaration, Symbol = x.Model.GetDeclaredSymbol(x.Declaration, cancellationToken) }) - .Where(x => x.Symbol is not null) - .Select(x => new InterfaceInfo(x.Declaration, x.Symbol!)) - .Where(x => x.Symbol - .GetAttributes() - .Any(x => x.AttributeClass is not null && x.AttributeClass!.Name.StartsWith(MarkerAttributeName, StringComparison.Ordinal)) - ) - ; + private static IEnumerable FindNamespaces(Compilation compilation, CancellationToken cancellationToken) => compilation.SyntaxTrees + .Where(x => x.GetRoot() is CompilationUnitSyntax) + .Select(x => (CompilationUnitSyntax)x.GetRoot(cancellationToken)) + .SelectMany(x => x.Members.OfType()) + ; + + private static IEnumerable FindInterfaces(Compilation compilation, IEnumerable allNamespaces, CancellationToken cancellationToken) => allNamespaces + .SelectMany(x => x.Members.OfType()) + .Select(x => new { Declaration = x, Model = compilation.GetSemanticModel(x.SyntaxTree) }) + .Select(x => new { x.Declaration, Symbol = x.Model.GetDeclaredSymbol(x.Declaration, cancellationToken) }) + .Where(x => x.Symbol is not null) + .Select(x => new InterfaceInfo(x.Declaration, x.Symbol!)) + .Where(x => x.Symbol + .GetAttributes() + .Any(x => x.AttributeClass is not null && x.AttributeClass!.Name.StartsWith(MarkerAttributeName, StringComparison.Ordinal)) + ) + ; private static IEnumerable FindClasses(Compilation compilation, IEnumerable allNamespaces, IEnumerable markedInterfacesIdentifier, CancellationToken cancellationToken) { @@ -172,23 +167,21 @@ private static IEnumerable FindClasses(Compilation compilation, IEnume ; } - private static VariableDeclaratorSyntax? FindKeyOf(TypeInfo type, PropertyDeclarationSyntax propertySyntax) - => type.Declaration.Members - .OfType() - .Where(x => x.Modifiers.Any(y => y.Text == "const")) - .Select(x => x.Declaration.Variables.SingleOrDefault()) - .Where(x => x is not null).Select(x => x!) - .FirstOrDefault(x => x.Identifier.Text == $"{propertySyntax.Identifier.Text}{TypealizR._.FallBackKeySuffix}") - ; - - private static VariableDeclaratorSyntax? FindKeyOf(TypeInfo type, MethodDeclarationSyntax methodSyntax) - => type.Declaration.Members - .OfType() - .Where(x => x.Modifiers.Any(y => y.Text == "const")) - .Select(x => x.Declaration.Variables.SingleOrDefault()) - .Where(x => x is not null).Select(x => x!) - .FirstOrDefault(x => x.Identifier.Text == $"{methodSyntax.Identifier.Text}{TypealizR._.FallBackKeySuffix}") - ; + private static VariableDeclaratorSyntax? FindKeyOf(TypeInfo type, PropertyDeclarationSyntax propertySyntax) => type.Declaration.Members + .OfType() + .Where(x => x.Modifiers.Any(y => y.Text == "const")) + .Select(x => x.Declaration.Variables.SingleOrDefault()) + .Where(x => x is not null).Select(x => x!) + .FirstOrDefault(x => x.Identifier.Text == $"{propertySyntax.Identifier.Text}{TypealizR._.FallBackKeySuffix}") + ; + + private static VariableDeclaratorSyntax? FindKeyOf(TypeInfo type, MethodDeclarationSyntax methodSyntax) => type.Declaration.Members + .OfType() + .Where(x => x.Modifiers.Any(y => y.Text == "const")) + .Select(x => x.Declaration.Variables.SingleOrDefault()) + .Where(x => x is not null).Select(x => x!) + .FirstOrDefault(x => x.Identifier.Text == $"{methodSyntax.Identifier.Text}{TypealizR._.FallBackKeySuffix}") + ; private static void AddProperty(IConsole console, TypeInfo type, ResxBuilder builder, PropertyDeclarationSyntax property) { diff --git a/src/TypealizR.CLI/Extensions/ExpressionSyntaxExtensions.cs b/src/TypealizR.CLI/Extensions/ExpressionSyntaxExtensions.cs index fb83cbd8..05e31e4e 100644 --- a/src/TypealizR.CLI/Extensions/ExpressionSyntaxExtensions.cs +++ b/src/TypealizR.CLI/Extensions/ExpressionSyntaxExtensions.cs @@ -1,6 +1,5 @@ namespace Microsoft.CodeAnalysis.CSharp.Syntax; internal static class ExpressionSyntaxExtensions { - public static string ToResourceKey(this ExpressionSyntax that) - => that.ToString().Trim('@', '$', '"'); + public static string ToResourceKey(this ExpressionSyntax that) => that.ToString().Trim('@', '$', '"'); } diff --git a/src/TypealizR.Tests/CLI.Tests/ExportCommand.Tests.cs b/src/TypealizR.Tests/CLI.Tests/ExportCommand.Tests.cs index 19efad71..594af402 100644 --- a/src/TypealizR.Tests/CLI.Tests/ExportCommand.Tests.cs +++ b/src/TypealizR.Tests/CLI.Tests/ExportCommand.Tests.cs @@ -6,8 +6,8 @@ namespace TypealizR.Tests.CLI.Tests; public class ExportCommand_Tests { - private static string ProjectFile(string x) => $"../../../../{x}/{x}.csproj"; - + private static string ProjectFile(string x) => $"../../../../{x}/{x}.csproj"; + [Fact] public async Task Export_Generates_ResxFiles() { diff --git a/src/TypealizR.Tests/CodeFirstSourceGenerator.Tests/.Tests.cs b/src/TypealizR.Tests/CodeFirstSourceGenerator.Tests/.Tests.cs index 01bae342..ef006b8c 100644 --- a/src/TypealizR.Tests/CodeFirstSourceGenerator.Tests/.Tests.cs +++ b/src/TypealizR.Tests/CodeFirstSourceGenerator.Tests/.Tests.cs @@ -7,47 +7,35 @@ public class CodeFirstSourceGenerator_Tests private const string BaseDirectory = "../../../CodeFirstSourceGenerator.Tests"; [Fact] - public async Task Does_Not_Care_About_NonMarked_Interfaces() - { - await GeneratorTesterBuilder + public async Task Does_Not_Care_About_NonMarked_Interfaces() => await GeneratorTesterBuilder .Create(BaseDirectory, null) .WithSourceFile("ISomeInterface.cs") .Build() .Verify() ; - } [Fact] - public async Task Uses_Default_Values_From_Member_Names() - { - await GeneratorTesterBuilder + public async Task Uses_Default_Values_From_Member_Names() => await GeneratorTesterBuilder .Create(BaseDirectory, null) .WithSourceFile("ITranslatables.cs") .Build() .Verify() ; - } [Fact] - public async Task Honors_Members_With_Simple_Xml_Comment() - { - await GeneratorTesterBuilder + public async Task Honors_Members_With_Simple_Xml_Comment() => await GeneratorTesterBuilder .Create(BaseDirectory, null) .WithSourceFile("IMembersWithSimpleXmlComment.cs") .Build() .Verify() ; - } [Fact] - public async Task Honors_Methods_With_Parameters_In_Xml_Comment() - { - await GeneratorTesterBuilder + public async Task Honors_Methods_With_Parameters_In_Xml_Comment() => await GeneratorTesterBuilder .Create(BaseDirectory, null) .WithSourceFile("IMethodsWithXmlCommentParameters.cs") .Build() .Verify() ; - } } diff --git a/src/TypealizR.Tests/DiagnosticsFactory.Tests.cs b/src/TypealizR.Tests/DiagnosticsFactory.Tests.cs index 5b4362a8..551a689f 100644 --- a/src/TypealizR.Tests/DiagnosticsFactory.Tests.cs +++ b/src/TypealizR.Tests/DiagnosticsFactory.Tests.cs @@ -7,9 +7,7 @@ namespace TypealizR.Tests; public class DiagnosticsFactory_Tests { - private static DiagnosticsFactory CreateSut(DiagnosticsEntry entryid, DiagnosticSeverity severity) - => new("someFile.resx", "someKey", 42, new Dictionary() { { entryid.Id.ToString(), severity } }); - + private static DiagnosticsFactory CreateSut(DiagnosticsEntry entryid, DiagnosticSeverity severity) => new("someFile.resx", "someKey", 42, new Dictionary() { { entryid.Id.ToString(), severity } }); [Theory] [InlineData(DiagnosticSeverity.Error)] diff --git a/src/TypealizR.Tests/ModuleInitializer.cs b/src/TypealizR.Tests/ModuleInitializer.cs index 2a72af81..a0d7cbe7 100644 --- a/src/TypealizR.Tests/ModuleInitializer.cs +++ b/src/TypealizR.Tests/ModuleInitializer.cs @@ -5,8 +5,5 @@ namespace TypealizR.Tests; public static class ModuleInitializer { [ModuleInitializer] - public static void Init() - { - VerifySourceGenerators.Initialize(); - } + public static void Init() => VerifySourceGenerators.Initialize(); } \ No newline at end of file diff --git a/src/TypealizR.Tests/RessourceFile.Tests.cs b/src/TypealizR.Tests/RessourceFile.Tests.cs index 19c1617d..9b08c70b 100644 --- a/src/TypealizR.Tests/RessourceFile.Tests.cs +++ b/src/TypealizR.Tests/RessourceFile.Tests.cs @@ -13,22 +13,16 @@ internal sealed class EmptyFile : AdditionalText public override string Path { get; } - public EmptyFile(string path) - { - Path = path; - } + public EmptyFile(string path) => Path = path; - public override SourceText GetText(CancellationToken cancellationToken = new CancellationToken()) - { - return SourceText.From(text); - } + public override SourceText GetText(CancellationToken cancellationToken = new CancellationToken()) => SourceText.From(text); } public class RessourceFile_Tests { private sealed record LineInfo(int LineNumber = 42, int LinePosition = 1337, bool HasLineInfo = true) : IXmlLineInfo { - bool IXmlLineInfo.HasLineInfo() => HasLineInfo; + bool IXmlLineInfo.HasLineInfo() => HasLineInfo; } [Theory] diff --git a/src/TypealizR.Tests/Snapshots/GeneratorTester.cs b/src/TypealizR.Tests/Snapshots/GeneratorTester.cs index 71d6ef7f..17f56499 100644 --- a/src/TypealizR.Tests/Snapshots/GeneratorTester.cs +++ b/src/TypealizR.Tests/Snapshots/GeneratorTester.cs @@ -19,5 +19,5 @@ public Task Verify([CallerMemberName] string caller = "") => Verifier .ScrubEmptyLines() .UseFileName(caller) .UseDirectory(snapshotDirectory) - ; + ; } diff --git a/src/TypealizR.Tests/Snapshots/GeneratorTesterBuilder.cs b/src/TypealizR.Tests/Snapshots/GeneratorTesterBuilder.cs index ef8c4923..58ac619e 100644 --- a/src/TypealizR.Tests/Snapshots/GeneratorTesterBuilder.cs +++ b/src/TypealizR.Tests/Snapshots/GeneratorTesterBuilder.cs @@ -128,8 +128,7 @@ public IVerifiable Build() private readonly Dictionary severityConfig = []; - internal GeneratorTesterBuilder WithSeverityConfig(DiagnosticsId id, DiagnosticSeverity severity) - => WithSeverityConfig(id, severity.ToString()); + internal GeneratorTesterBuilder WithSeverityConfig(DiagnosticsId id, DiagnosticSeverity severity) => WithSeverityConfig(id, severity.ToString()); internal GeneratorTesterBuilder WithSeverityConfig(DiagnosticsId id, string severity) { diff --git a/src/TypealizR.Tests/Snapshots/GeneratorTesterOptionsProvider.cs b/src/TypealizR.Tests/Snapshots/GeneratorTesterOptionsProvider.cs index 379cb054..480cab1b 100644 --- a/src/TypealizR.Tests/Snapshots/GeneratorTesterOptionsProvider.cs +++ b/src/TypealizR.Tests/Snapshots/GeneratorTesterOptionsProvider.cs @@ -29,10 +29,7 @@ public GeneratorTesterOptionsProvider( public override AnalyzerConfigOptions GlobalOptions => globalOptions; - public override AnalyzerConfigOptions GetOptions(SyntaxTree tree) - { - throw new NotImplementedException(); - } + public override AnalyzerConfigOptions GetOptions(SyntaxTree tree) => throw new NotImplementedException(); public override AnalyzerConfigOptions GetOptions(AdditionalText textFile) { diff --git a/src/TypealizR.Tests/Snapshots/ResxFile.cs b/src/TypealizR.Tests/Snapshots/ResxFile.cs index 9b9d467b..0f1ae1ae 100644 --- a/src/TypealizR.Tests/Snapshots/ResxFile.cs +++ b/src/TypealizR.Tests/Snapshots/ResxFile.cs @@ -14,8 +14,5 @@ public ResxFile(string path) text = File.ReadAllText(path); } - public override SourceText GetText(CancellationToken cancellationToken = new CancellationToken()) - { - return SourceText.From(text); - } + public override SourceText GetText(CancellationToken cancellationToken = new CancellationToken()) => SourceText.From(text); } diff --git a/src/TypealizR.Tests/StringFormatterSourceGenerator.Tests/.Tests.cs b/src/TypealizR.Tests/StringFormatterSourceGenerator.Tests/.Tests.cs index 7d15fbeb..0e356b9c 100644 --- a/src/TypealizR.Tests/StringFormatterSourceGenerator.Tests/.Tests.cs +++ b/src/TypealizR.Tests/StringFormatterSourceGenerator.Tests/.Tests.cs @@ -8,23 +8,17 @@ public class StringFormatterSourceGenerator_Tests private const string RootNamespace = "Some.Root.Namespace"; [Fact] - public async Task Generates_StringFormatter_With_Default_Implementation() - { - await GeneratorTesterBuilder + public async Task Generates_StringFormatter_With_Default_Implementation() => await GeneratorTesterBuilder .Create(BaseDirectory, RootNamespace) .Build() .Verify() ; - } [Fact] - public async Task Generates_StringFormatter_Stub_Only_When_UserImplementation_Is_Provided() - { - await GeneratorTesterBuilder + public async Task Generates_StringFormatter_Stub_Only_When_UserImplementation_Is_Provided() => await GeneratorTesterBuilder .Create(BaseDirectory, RootNamespace) .WithSourceFile("StringFormatter.cs") .Build() .Verify() ; - } } diff --git a/src/TypealizR.Tests/StringLocalizerExtensionsSourceGenerator.Tests/.Tests.cs b/src/TypealizR.Tests/StringLocalizerExtensionsSourceGenerator.Tests/.Tests.cs index 940bb8b6..daf5b342 100644 --- a/src/TypealizR.Tests/StringLocalizerExtensionsSourceGenerator.Tests/.Tests.cs +++ b/src/TypealizR.Tests/StringLocalizerExtensionsSourceGenerator.Tests/.Tests.cs @@ -12,50 +12,39 @@ public class StringLocalizerExtensionsSourceGenerator_Tests [Fact] - public async Task Throws_When_RootNamespace_Is_Missing() - { - await GeneratorTesterBuilder + public async Task Throws_When_RootNamespace_Is_Missing() => await GeneratorTesterBuilder .Create(BaseDirectory, null) .WithResxFile("Empty_NoCode.resx") .Build() .Verify() ; - } [Fact] - public async Task Throws_For_Invalid_SeverityConfig() - { - await this.Invoking(async (x) => - await GeneratorTesterBuilder - .Create(BaseDirectory, null) - .WithSeverityConfig(DiagnosticsId.TR0001, "invalid") - .WithResxFile("Empty_NoCode.resx") - .Build() - .Verify() + public async Task Throws_For_Invalid_SeverityConfig() => await this.Invoking(async (x) => + await GeneratorTesterBuilder + .Create(BaseDirectory, null) + .WithSeverityConfig(DiagnosticsId.TR0001, "invalid") + .WithResxFile("Empty_NoCode.resx") + .Build() + .Verify() ) .Should() .ThrowAsync() .WithMessage("'dotnet_diagnostic_tr0001_severity' has invalid value 'invalid'") ; - } [Fact] - public async Task Emits_Error_TR0001() - { - await GeneratorTesterBuilder + public async Task Emits_Error_TR0001() => await GeneratorTesterBuilder .Create(BaseDirectory, RootNamespace) .WithoutMsBuildProjectDirectory() .WithResxFile("Empty_NoCode.resx") .Build() .Verify() ; - } [Fact] - public async Task DoesNot_Emit_Warning_TR0001_When_Using_ProjectDir() - { - await GeneratorTesterBuilder + public async Task DoesNot_Emit_Warning_TR0001_When_Using_ProjectDir() => await GeneratorTesterBuilder .Create(BaseDirectory, RootNamespace) .WithoutMsBuildProjectDirectory(butWithProjectDir: BaseDirectory) .WithResxFile("Empty_NoCode.resx") @@ -63,8 +52,6 @@ await GeneratorTesterBuilder .Verify() ; - } - [Fact] public async Task Emits_Error_TR0001_Localized() { @@ -83,208 +70,154 @@ await GeneratorTesterBuilder } [Fact] - public async Task Emits_Warning_TR0002() - { - await GeneratorTesterBuilder + public async Task Emits_Warning_TR0002() => await GeneratorTesterBuilder .Create(BaseDirectory, RootNamespace) .WithResxFile("TR0002_NoCode.resx") .Build() .Verify() ; - } [Fact] - public async Task Emits_Error_TR0002() - { - await GeneratorTesterBuilder + public async Task Emits_Error_TR0002() => await GeneratorTesterBuilder .Create(BaseDirectory, RootNamespace) .WithSeverityConfig(DiagnosticsId.TR0002, DiagnosticSeverity.Error) .WithResxFile("TR0002_NoCode.resx") .Build() .Verify() ; - } [Fact] - public async Task Emits_Warning_TR0003() - { - await GeneratorTesterBuilder + public async Task Emits_Warning_TR0003() => await GeneratorTesterBuilder .Create(BaseDirectory, RootNamespace) .WithResxFile("TR0003_NoCode.resx") .Build() .Verify() ; - } [Fact] - public async Task Emits_Error_TR0003() - { - await GeneratorTesterBuilder + public async Task Emits_Error_TR0003() => await GeneratorTesterBuilder .Create(BaseDirectory, RootNamespace) .WithSeverityConfig(DiagnosticsId.TR0003, DiagnosticSeverity.Error) .WithResxFile("TR0003_NoCode.resx") .Build() .Verify() ; - } [Fact] - public async Task Emits_Warning_TR0004() - { - await GeneratorTesterBuilder + public async Task Emits_Warning_TR0004() => await GeneratorTesterBuilder .Create(BaseDirectory, RootNamespace) .WithResxFile("TR0004_NoCode.resx") .Build() .Verify() ; - } [Fact] - public async Task Emits_Error_TR0004() - { - await GeneratorTesterBuilder + public async Task Emits_Error_TR0004() => await GeneratorTesterBuilder .Create(BaseDirectory, RootNamespace) .WithSeverityConfig(DiagnosticsId.TR0004, DiagnosticSeverity.Error) .WithResxFile("TR0004_NoCode.resx") .Build() .Verify() ; - } [Fact] - public async Task Emits_Warning_TR0005() - { - await GeneratorTesterBuilder + public async Task Emits_Warning_TR0005() => await GeneratorTesterBuilder .Create(BaseDirectory, RootNamespace) .WithResxFile("TR0005_NoCode.resx", useParamNamesInMethodNames: "false") .Build() .Verify() ; - } [Fact] - public async Task Emits_Error_TR0005() - { - await GeneratorTesterBuilder + public async Task Emits_Error_TR0005() => await GeneratorTesterBuilder .Create(BaseDirectory, RootNamespace) .WithSeverityConfig(DiagnosticsId.TR0005, DiagnosticSeverity.Error) .WithResxFile("TR0005_NoCode.resx", useParamNamesInMethodNames: "false") .Build() .Verify() ; - } [Fact] - public async Task NoCode_Resx() - { - await GeneratorTesterBuilder + public async Task NoCode_Resx() => await GeneratorTesterBuilder .Create(BaseDirectory, RootNamespace) .WithResxFile("NoWarnings_NoCode.resx") .Build() .Verify() ; - } [Fact] - public async Task NoCode_Resx_Honors_CustomToolNamespace() - { - await GeneratorTesterBuilder + public async Task NoCode_Resx_Honors_CustomToolNamespace() => await GeneratorTesterBuilder .Create(BaseDirectory, RootNamespace) .WithResxFile("NoWarnings_NoCode.resx", andCustomToolNamespace: "Some.Special.Custom.Namespace") .Build() .Verify() ; - } [Fact] - public async Task NoCode_Resx_Ignores_Empty_CustomToolNamespace() - { - await GeneratorTesterBuilder + public async Task NoCode_Resx_Ignores_Empty_CustomToolNamespace() => await GeneratorTesterBuilder .Create(BaseDirectory, RootNamespace) .WithResxFile("NoWarnings_NoCode.resx", andCustomToolNamespace: "") .Build() .Verify() ; - } [Fact] - public async Task NoCode_Resx_Honors_Internal_MarkerType() - { - await GeneratorTesterBuilder + public async Task NoCode_Resx_Honors_Internal_MarkerType() => await GeneratorTesterBuilder .Create(BaseDirectory, RootNamespace) .WithSourceFile($"NoWarnings_NoCode_Internal.cs") .WithResxFile($"NoWarnings_NoCode.resx") .Build() .Verify() ; - } [Fact] - public async Task NoCode_Resx_Honors_Public_MarkerType() - { - await GeneratorTesterBuilder + public async Task NoCode_Resx_Honors_Public_MarkerType() => await GeneratorTesterBuilder .Create(BaseDirectory, RootNamespace) .WithSourceFile($"NoWarnings_NoCode_Public.cs") .WithResxFile($"NoWarnings_NoCode.resx") .Build() .Verify() ; - } [Fact] - public async Task NoCode_Resx_MarkerType_Fallback() - { - await GeneratorTesterBuilder + public async Task NoCode_Resx_MarkerType_Fallback() => await GeneratorTesterBuilder .Create(BaseDirectory, RootNamespace) .WithSourceFile($"NoWarnings_NoCode_NamespaceMismatch.cs") .WithResxFile($"NoWarnings_NoCode.resx") .Build() .Verify() ; - } [Fact] - public async Task NoCode_Resx_Groups_Are_Honored_In_Generated_Code() - { - await GeneratorTesterBuilder + public async Task NoCode_Resx_Groups_Are_Honored_In_Generated_Code() => await GeneratorTesterBuilder .Create(BaseDirectory, RootNamespace) .WithResxFile($"Groupings_NoCode.resx") .Build() .Verify() ; - } [Theory] [InlineData("wtf")] - public async Task NoCode_Ignores_Invalid_Setting_UseParamNamesInMethodNames(string useParamNamesInMethodNames) - { - await GeneratorTesterBuilder + public async Task NoCode_Ignores_Invalid_Setting_UseParamNamesInMethodNames(string useParamNamesInMethodNames) => await GeneratorTesterBuilder .Create(BaseDirectory, RootNamespace) .WithResxFile("NoWarnings_NoCode.resx", useParamNamesInMethodNames: useParamNamesInMethodNames) .Build() .Verify() ; - } [Fact] - public async Task NoCode_Honors_Setting_UseParamNamesInMethodNames_BuildProperty() - { - await GeneratorTesterBuilder + public async Task NoCode_Honors_Setting_UseParamNamesInMethodNames_BuildProperty() => await GeneratorTesterBuilder .Create(BaseDirectory, RootNamespace, useParamNamesInMethodNames: "false") .WithResxFile("NoWarnings_NoCode.resx") .Build() .Verify() ; - } [Fact] - public async Task NoCode_Honors_Setting_UseParamNamesInMethodNames_ItemMetadata() - { - await GeneratorTesterBuilder + public async Task NoCode_Honors_Setting_UseParamNamesInMethodNames_ItemMetadata() => await GeneratorTesterBuilder .Create(BaseDirectory, RootNamespace) .WithResxFile("NoWarnings_NoCode.resx", useParamNamesInMethodNames: "false") .Build() .Verify() ; - } } diff --git a/src/TypealizR.Tests/TypealizedClassSourceGenerator.Tests/_.Tests.cs b/src/TypealizR.Tests/TypealizedClassSourceGenerator.Tests/_.Tests.cs index 1174306d..60926916 100644 --- a/src/TypealizR.Tests/TypealizedClassSourceGenerator.Tests/_.Tests.cs +++ b/src/TypealizR.Tests/TypealizedClassSourceGenerator.Tests/_.Tests.cs @@ -10,70 +10,52 @@ public class TypealizedClassSourceGenerator_Tests private const string RootNamespace = "Some.Root.Namespace"; [Fact] - public async Task NoCode_Resx_Groups_Are_Honored_In_Generated_Code() - { - await GeneratorTesterBuilder + public async Task NoCode_Resx_Groups_Are_Honored_In_Generated_Code() => await GeneratorTesterBuilder .Create(BaseDirectory, RootNamespace) .WithResxFile($"Groupings_NoCode.resx") .Build() .Verify() ; - } [Fact] - public async Task NoCode_Resx_Groups_Honors_Setting_UseParamNamesInMethodNames_BuildProperty() - { - await GeneratorTesterBuilder + public async Task NoCode_Resx_Groups_Honors_Setting_UseParamNamesInMethodNames_BuildProperty() => await GeneratorTesterBuilder .Create(BaseDirectory, RootNamespace, useParamNamesInMethodNames: "false") .WithResxFile($"Groupings_NoCode.resx") .Build() .Verify() ; - } [Fact] - public async Task NoCode_Resx_Groups_Honors_Setting_UseParamNamesInMethodNames_ItemMetadata() - { - await GeneratorTesterBuilder + public async Task NoCode_Resx_Groups_Honors_Setting_UseParamNamesInMethodNames_ItemMetadata() => await GeneratorTesterBuilder .Create(BaseDirectory, RootNamespace) .WithResxFile($"Groupings_NoCode.resx", useParamNamesInMethodNames: "false") .Build() .Verify() ; - } [Fact] - public async Task NoCode_Resx_Groups_Handles_Duplicates() - { - await GeneratorTesterBuilder + public async Task NoCode_Resx_Groups_Handles_Duplicates() => await GeneratorTesterBuilder .Create(BaseDirectory, RootNamespace) .WithResxFile($"Groupings_NoCode_WithDuplicates.resx") .Build() .Verify() ; - } [Fact] - public async Task Emits_Warning_TR0005() - { - await GeneratorTesterBuilder + public async Task Emits_Warning_TR0005() => await GeneratorTesterBuilder .Create(BaseDirectory, RootNamespace) .WithResxFile("TR0005_NoCode.resx", useParamNamesInMethodNames: "false") .Build() .Verify() ; - } [Fact] - public async Task Emits_Error_TR0005() - { - await GeneratorTesterBuilder + public async Task Emits_Error_TR0005() => await GeneratorTesterBuilder .Create(BaseDirectory, RootNamespace) .WithSeverityConfig(DiagnosticsId.TR0005, DiagnosticSeverity.Error) .WithResxFile("TR0005_NoCode.resx", useParamNamesInMethodNames: "false") .Build() .Verify() ; - } } diff --git a/src/TypealizR/CodeFirstSourceGenerator/CodeFirstMethodModel.cs b/src/TypealizR/CodeFirstSourceGenerator/CodeFirstMethodModel.cs index a5c86429..21fb3fa1 100644 --- a/src/TypealizR/CodeFirstSourceGenerator/CodeFirstMethodModel.cs +++ b/src/TypealizR/CodeFirstSourceGenerator/CodeFirstMethodModel.cs @@ -28,5 +28,5 @@ internal string ToCSharp() => $$""" private const string {{FallbackKeyName}} = @"{{fallbackKey}}"; public {{returnType}} {{RawName}} => localizer[{{KeyName}}].Or(localizer[{{FallbackKeyName}}]); public {{returnType}} {{key}} ({{parameters.ToCharpDeclaration()}}) => localizer[{{KeyName}}, {{parameters.ToCSharpInvocation()}}].Or(localizer[{{FallbackKeyName}}, {{parameters.ToCSharpInvocation()}}]); - """; + """; } diff --git a/src/TypealizR/CodeFirstSourceGenerator/CodeFirstParameterBuilder.cs b/src/TypealizR/CodeFirstSourceGenerator/CodeFirstParameterBuilder.cs index 6b742d4a..24ce68bc 100644 --- a/src/TypealizR/CodeFirstSourceGenerator/CodeFirstParameterBuilder.cs +++ b/src/TypealizR/CodeFirstSourceGenerator/CodeFirstParameterBuilder.cs @@ -11,5 +11,5 @@ public CodeFirstParameterBuilder(string name, string type) this.type = type; } - internal CodeFirstParameterModel Build() => new(name, type); + internal CodeFirstParameterModel Build() => new(name, type); } diff --git a/src/TypealizR/CodeFirstSourceGenerator/CodeFirstParameterModel.cs b/src/TypealizR/CodeFirstSourceGenerator/CodeFirstParameterModel.cs index 2b9d170f..fd055579 100644 --- a/src/TypealizR/CodeFirstSourceGenerator/CodeFirstParameterModel.cs +++ b/src/TypealizR/CodeFirstSourceGenerator/CodeFirstParameterModel.cs @@ -19,9 +19,7 @@ public CodeFirstParameterModel(string name, string type) internal static class CodeFirstParameterModelExtensions { - public static string ToCharpDeclaration(this IEnumerable that) - => that.Select(x => $"{x.Type} {x.Name}").ToCommaDelimited(); - - public static string ToCSharpInvocation(this IEnumerable that) - => that.Select(x => x.Name).ToCommaDelimited(); + public static string ToCharpDeclaration(this IEnumerable that) => that.Select(x => $"{x.Type} {x.Name}").ToCommaDelimited(); + + public static string ToCSharpInvocation(this IEnumerable that) => that.Select(x => x.Name).ToCommaDelimited(); } diff --git a/src/TypealizR/CodeFirstSourceGenerator/CodeFirstPropertyBuilder.cs b/src/TypealizR/CodeFirstSourceGenerator/CodeFirstPropertyBuilder.cs index 15f8bcdc..efa15dd8 100644 --- a/src/TypealizR/CodeFirstSourceGenerator/CodeFirstPropertyBuilder.cs +++ b/src/TypealizR/CodeFirstSourceGenerator/CodeFirstPropertyBuilder.cs @@ -11,8 +11,5 @@ public CodeFirstPropertyBuilder(string name, string? defaultValue) this.defaultValue = defaultValue ?? name; } - internal CodeFirstPropertyModel Build() - { - return new CodeFirstPropertyModel(name, "LocalizedString", defaultValue); - } + internal CodeFirstPropertyModel Build() => new CodeFirstPropertyModel(name, "LocalizedString", defaultValue); } diff --git a/src/TypealizR/CodeFirstSourceGenerator/CodeFirstPropertyModel.cs b/src/TypealizR/CodeFirstSourceGenerator/CodeFirstPropertyModel.cs index 55692881..f2aaa3cc 100644 --- a/src/TypealizR/CodeFirstSourceGenerator/CodeFirstPropertyModel.cs +++ b/src/TypealizR/CodeFirstSourceGenerator/CodeFirstPropertyModel.cs @@ -20,5 +20,5 @@ internal string ToCSharp() => $$""" private const string {{KeyName}} = @"{{key}}"; private const string {{FallbackKeyName}} = @"{{fallbackKey}}"; public {{returnType}} {{key}} => localizer[{{KeyName}}].Or(localizer[{{FallbackKeyName}}]); - """; + """; } diff --git a/src/TypealizR/CodeFirstSourceGenerator/CodeFirstSourceGenerator.cs b/src/TypealizR/CodeFirstSourceGenerator/CodeFirstSourceGenerator.cs index dfd10d54..764b7d8e 100644 --- a/src/TypealizR/CodeFirstSourceGenerator/CodeFirstSourceGenerator.cs +++ b/src/TypealizR/CodeFirstSourceGenerator/CodeFirstSourceGenerator.cs @@ -52,7 +52,7 @@ public void Initialize(IncrementalGeneratorInitializationContext context) typealizedInterface.Declaration.Identifier.Text )); - var diagnostics = new List(); + List diagnostics = []; TryAddMethods(builder, diagnostics, members, options, ctxt.CancellationToken); TryAddProperties(builder, diagnostics, members, options, ctxt.CancellationToken); @@ -141,7 +141,7 @@ private static void TryAddProperties(CodeFirstClassBuilder builder, List x is XmlTextSyntax || x is XmlEmptyElementSyntax).ToArray(); + var xmlComments = comment.Content.Where(x => x is XmlTextSyntax or XmlEmptyElementSyntax).ToArray(); var builder = new StringBuilder(); diff --git a/src/TypealizR/Core/CommentModel.cs b/src/TypealizR/Core/CommentModel.cs index 59b66bd5..9a950a81 100644 --- a/src/TypealizR/Core/CommentModel.cs +++ b/src/TypealizR/Core/CommentModel.cs @@ -1 +1,2 @@ -namespace TypealizR.Core; internal class CommentModel { private readonly string rawResourceName; private readonly string defaultValue; public CommentModel(string rawResourceName, string defaultValue) { this.rawResourceName = rawResourceName; this.defaultValue = defaultValue; } public string ToCSharp() => $""" /// /// Looks up a localized string similar to '{rawResourceName}' /// /// /// A localized version of the current default value of '{defaultValue}' /// """; } \ No newline at end of file +namespace TypealizR.Core; internal class CommentModel { private readonly string rawResourceName; private readonly string defaultValue; public CommentModel(string rawResourceName, string defaultValue) { this.rawResourceName = rawResourceName; this.defaultValue = defaultValue; } public string ToCSharp() => $""" /// /// Looks up a localized string similar to '{rawResourceName}' /// /// /// A localized version of the current default value of '{defaultValue}' /// """; +} \ No newline at end of file diff --git a/src/TypealizR/Core/GeneratorOptions.cs b/src/TypealizR/Core/GeneratorOptions.cs index 479a6fbd..7fbd9055 100644 --- a/src/TypealizR/Core/GeneratorOptions.cs +++ b/src/TypealizR/Core/GeneratorOptions.cs @@ -55,7 +55,7 @@ public static GeneratorOptions From(AnalyzerConfigOptions options) [SuppressMessage("Globalization", "CA1308:Normalize strings to uppercase", Justification = "uppercase would not be valid")] private static Dictionary ReadSeverityConfig(AnalyzerConfigOptions options) { - var severityConfig = new Dictionary(); + Dictionary severityConfig = []; var availableDiagnostics = Enum.GetValues(typeof(DiagnosticsId)) .OfType() @@ -68,14 +68,9 @@ private static Dictionary ReadSeverityConfig(Analyze if (options.TryGetValue(key, out var rawValue)) { - if (Enum.TryParse(rawValue, true, out var severity)) - { - severityConfig[diagnostic] = severity; - } - else - { - throw new InvalidOperationException($"'{key}' has invalid value '{rawValue}'"); - } + severityConfig[diagnostic] = Enum.TryParse(rawValue, true, out var severity) + ? severity + : throw new InvalidOperationException($"'{key}' has invalid value '{rawValue}'"); } } diff --git a/src/TypealizR/Core/MemberName.cs b/src/TypealizR/Core/MemberName.cs index f421cae3..533736f4 100644 --- a/src/TypealizR/Core/MemberName.cs +++ b/src/TypealizR/Core/MemberName.cs @@ -38,6 +38,7 @@ public MemberName(string raw) } public static implicit operator string(MemberName that) => that.nameOverride ?? that.name; + public override string ToString() => nameOverride ?? name; internal bool IsValidMethodName() diff --git a/src/TypealizR/Core/ParameterBuilder.cs b/src/TypealizR/Core/ParameterBuilder.cs index d4503cb9..91593e1e 100644 --- a/src/TypealizR/Core/ParameterBuilder.cs +++ b/src/TypealizR/Core/ParameterBuilder.cs @@ -8,10 +8,7 @@ namespace TypealizR.Core; internal class ParameterBuilder { - public ParameterBuilder(string rawKeyValue) - { - this.rawKeyValue = rawKeyValue; - } + public ParameterBuilder(string rawKeyValue) => this.rawKeyValue = rawKeyValue; private readonly List models = []; private readonly string rawKeyValue; @@ -60,12 +57,7 @@ private static (string, string) TryDeriveTypeFrom(string expression) } var type = SanitizeType(expression); - if (type is not null) - { - return (type, ""); - } - - return ("object", expression); + return type is not null ? ((string, string))(type, "") : ((string, string))("object", expression); } private static string? SanitizeType(string type) => type switch diff --git a/src/TypealizR/Core/ParameterModel.cs b/src/TypealizR/Core/ParameterModel.cs index 018f6c71..0390a2a9 100644 --- a/src/TypealizR/Core/ParameterModel.cs +++ b/src/TypealizR/Core/ParameterModel.cs @@ -30,12 +30,7 @@ private static string SanitizeName(string rawParameterName) .ToArray() ); - if (!parameterName.First().IsValidInIdentifier()) - { - return $"_{rawParameterName}"; - } - - return parameterName; + return !parameterName.First().IsValidInIdentifier() ? $"_{rawParameterName}" : parameterName; } } @@ -43,5 +38,5 @@ internal static class ParameterModelExtensions { internal static string ToDeclarationCSharp(this IEnumerable that) => that .Select(x => $"{x.Type} {x.DisplayName}") - .ToCommaDelimited(); + .ToCommaDelimited(); } diff --git a/src/TypealizR/Core/ResxFileSourceGeneratorBase.cs b/src/TypealizR/Core/ResxFileSourceGeneratorBase.cs index a32bd6ff..fd475043 100644 --- a/src/TypealizR/Core/ResxFileSourceGeneratorBase.cs +++ b/src/TypealizR/Core/ResxFileSourceGeneratorBase.cs @@ -106,13 +106,9 @@ private static (string, Accessibility) FindNameSpaceAndAccessabilityOf(Compilati var matchingMarkerType = Array.Find(possibleMarkerTypeSymbols, x => x.ContainingNamespace.OriginalDefinition.ToDisplayString() == nameSpace); - if (matchingMarkerType is null) - { - return (nameSpace.Trim('.', ' '), Accessibility.Internal); - } - - return (matchingMarkerType.ContainingNamespace.OriginalDefinition.ToDisplayString(), matchingMarkerType.DeclaredAccessibility); - + return matchingMarkerType is null + ? ((string, Accessibility))(nameSpace.Trim('.', ' '), Accessibility.Internal) + : ((string, Accessibility))(matchingMarkerType.ContainingNamespace.OriginalDefinition.ToDisplayString(), matchingMarkerType.DeclaredAccessibility); } protected abstract GeneratedSourceFile GenerateSourceFileFor( diff --git a/src/TypealizR/Core/Visibility.cs b/src/TypealizR/Core/Visibility.cs index ebde1c3b..a254b48b 100644 --- a/src/TypealizR/Core/Visibility.cs +++ b/src/TypealizR/Core/Visibility.cs @@ -11,10 +11,9 @@ internal enum Visibility internal static class AccessibilityExtensions { - public static Visibility ToVisibilty(this Accessibility that) => that switch - { - Accessibility.Public => Visibility.Public, - _ => Visibility.Internal + public static Visibility ToVisibilty(this Accessibility that) => that switch + { + Accessibility.Public => Visibility.Public, + _ => Visibility.Internal }; - } diff --git a/src/TypealizR/Diagnostics/DiagnosticsEntry.cs b/src/TypealizR/Diagnostics/DiagnosticsEntry.cs index 5b7add1e..4a4e844a 100644 --- a/src/TypealizR/Diagnostics/DiagnosticsEntry.cs +++ b/src/TypealizR/Diagnostics/DiagnosticsEntry.cs @@ -10,5 +10,5 @@ public DiagnosticsEntry(DiagnosticsId id, string title) public DiagnosticsId Id { get; } public string Title { get; } - internal static string LinkToDocs(DiagnosticsEntry that) => $"https://github.com/earloc/TypealizR/blob/main/docs/reference/{that.Id}_{that.Title}.md"; + internal static string LinkToDocs(DiagnosticsEntry that) => $"https://github.com/earloc/TypealizR/blob/main/docs/reference/{that.Id}_{that.Title}.md"; } diff --git a/src/TypealizR/Diagnostics/DiagnosticsFactory.cs b/src/TypealizR/Diagnostics/DiagnosticsFactory.cs index 112face5..5a00dc7d 100644 --- a/src/TypealizR/Diagnostics/DiagnosticsFactory.cs +++ b/src/TypealizR/Diagnostics/DiagnosticsFactory.cs @@ -9,10 +9,7 @@ internal class DiagnosticsCollector { private readonly DiagnosticsFactory factory; - public DiagnosticsCollector(string filePath, string rawRessourceKey, int lineNumber, IDictionary? severityConfig = null) - { - this.factory = new(filePath, rawRessourceKey, lineNumber, severityConfig); - } + public DiagnosticsCollector(string filePath, string rawRessourceKey, int lineNumber, IDictionary? severityConfig = null) => this.factory = new(filePath, rawRessourceKey, lineNumber, severityConfig); private readonly List diagnostics = []; @@ -38,11 +35,10 @@ public DiagnosticsFactory(string filePath, string rawRessourceKey, int lineNumbe this.severityConfig = severityConfig ?? new Dictionary(); } - private DiagnosticSeverity? SeverityFor(id id) => severityConfig.TryGetValue(id.ToString(), out DiagnosticSeverity value) ? value : null; + private DiagnosticSeverity? SeverityFor(id id) => severityConfig.TryGetValue(id.ToString(), out var value) ? value : null; internal static readonly DiagnosticsEntry TR0001 = new(id.TR0001, "TargetProjectRootDirectoryNotFound"); - internal static Diagnostic TargetProjectRootDirectoryNotFound_0001() => - Diagnostic.Create( + internal static Diagnostic TargetProjectRootDirectoryNotFound_0001() => Diagnostic.Create( new(id: TR0001.Id.ToString(), title: TR0001.Title, messageFormat: Strings.TR0001_MessageFormat, @@ -57,8 +53,7 @@ internal static Diagnostic TargetProjectRootDirectoryNotFound_0001() => ); internal static readonly DiagnosticsEntry TR0002 = new(id.TR0002, "AmbigiousRessourceKey"); - internal Diagnostic AmbigiousRessourceKey_0002(string fallback) => - Diagnostic.Create( + internal Diagnostic AmbigiousRessourceKey_0002(string fallback) => Diagnostic.Create( new(id: TR0002.Id.ToString(), title: TR0002.Title, messageFormat: Strings.TR0002_MessageFormat, @@ -79,8 +74,7 @@ internal Diagnostic AmbigiousRessourceKey_0002(string fallback) => ); internal static readonly DiagnosticsEntry TR0003 = new(id.TR0003, "UnnamedGenericParameter"); - internal Diagnostic UnnamedGenericParameter_0003(string parameterName) => - Diagnostic.Create( + internal Diagnostic UnnamedGenericParameter_0003(string parameterName) => Diagnostic.Create( new(id: TR0003.Id.ToString(), title: TR0003.Title, messageFormat: Strings.TR0003_MessageFormat, @@ -102,8 +96,7 @@ internal Diagnostic UnnamedGenericParameter_0003(string parameterName) => internal static readonly DiagnosticsEntry TR0004 = new(id.TR0004, "UnrecognizedParameterType"); - internal Diagnostic UnrecognizedParameterType_0004(string parameterTypeAnnotation) => - Diagnostic.Create( + internal Diagnostic UnrecognizedParameterType_0004(string parameterTypeAnnotation) => Diagnostic.Create( new(id: TR0004.Id.ToString(), title: TR0004.Title, messageFormat: Strings.TR0004_MessageFormat, @@ -125,8 +118,7 @@ internal Diagnostic UnrecognizedParameterType_0004(string parameterTypeAnnotatio internal static readonly DiagnosticsEntry TR0005 = new(id.TR0005, "InvalidMemberName"); - internal Diagnostic InvalidMemberName_0005(string source, string replacement) => - Diagnostic.Create( + internal Diagnostic InvalidMemberName_0005(string source, string replacement) => Diagnostic.Create( new(id: TR0005.Id.ToString(), title: TR0005.Title, messageFormat: Strings.TR0005_MessageFormat, diff --git a/src/TypealizR/Extensions/CharExtensions.cs b/src/TypealizR/Extensions/CharExtensions.cs index 881e7d96..008c3cff 100644 --- a/src/TypealizR/Extensions/CharExtensions.cs +++ b/src/TypealizR/Extensions/CharExtensions.cs @@ -4,23 +4,20 @@ namespace TypealizR.Extensions; internal static class CharExtensions { //thx https://stackoverflow.com/a/60820647/4136104 - internal static bool IsValidInIdentifier(this char c, bool firstChar = true) - { - return char.GetUnicodeCategory(c) switch - { - UnicodeCategory.UppercaseLetter or - UnicodeCategory.LowercaseLetter or - UnicodeCategory.TitlecaseLetter or - UnicodeCategory.ModifierLetter or - UnicodeCategory.OtherLetter => true,// Always allowed in C# identifiers - - UnicodeCategory.LetterNumber or - UnicodeCategory.NonSpacingMark or - UnicodeCategory.SpacingCombiningMark or - UnicodeCategory.DecimalDigitNumber or - UnicodeCategory.ConnectorPunctuation or - UnicodeCategory.Format => !firstChar,// Only allowed after first char - _ => false, - }; - } + internal static bool IsValidInIdentifier(this char c, bool firstChar = true) => char.GetUnicodeCategory(c) switch + { + UnicodeCategory.UppercaseLetter or + UnicodeCategory.LowercaseLetter or + UnicodeCategory.TitlecaseLetter or + UnicodeCategory.ModifierLetter or + UnicodeCategory.OtherLetter => true,// Always allowed in C# identifiers + + UnicodeCategory.LetterNumber or + UnicodeCategory.NonSpacingMark or + UnicodeCategory.SpacingCombiningMark or + UnicodeCategory.DecimalDigitNumber or + UnicodeCategory.ConnectorPunctuation or + UnicodeCategory.Format => !firstChar,// Only allowed after first char + _ => false, + }; } diff --git a/src/TypealizR/Extensions/StringExtensions.cs b/src/TypealizR/Extensions/StringExtensions.cs index f7b0859e..22fcc333 100644 --- a/src/TypealizR/Extensions/StringExtensions.cs +++ b/src/TypealizR/Extensions/StringExtensions.cs @@ -10,7 +10,7 @@ public static string ToMultiline(this IEnumerable that, string prependLi { var builder = new StringBuilder(); - int i = 0; + var i = 0; foreach (var line in that) { if (i++ > 0) @@ -27,25 +27,15 @@ public static string ToMultiline(this IEnumerable that, string prependLi return builder.ToString(); } - public static string ToCommaDelimited(this IEnumerable that) - => that.Join(", ") - ; - - public static string ToSpaceDelimited(this IEnumerable that) - => that.Join(" ") - ; - - public static string Join(this IEnumerable that, string seperator = "") - => string.Join(seperator, that) - ; - - public static string RemoveAndReplaceDuplicatesOf(this string s, string seperator, string join) - => string.Join(join, s.Split(new[] { seperator }, StringSplitOptions.RemoveEmptyEntries)) - ; - - public static string ReplaceInvalidForMemberNameWith(this string that, char replacement) - => new(that.Select(x => x.IsValidInIdentifier(false) ? x : replacement).ToArray()) - ; - - public static string Escape(this string that) => that.Replace("\"", "\"\""); + public static string ToCommaDelimited(this IEnumerable that) => that.Join(", "); + + public static string ToSpaceDelimited(this IEnumerable that) => that.Join(" "); + + public static string Join(this IEnumerable that, string seperator = "") => string.Join(seperator, that); + + public static string RemoveAndReplaceDuplicatesOf(this string s, string seperator, string join) => string.Join(join, s.Split(new[] { seperator }, StringSplitOptions.RemoveEmptyEntries)); + + public static string ReplaceInvalidForMemberNameWith(this string that, char replacement) => new(that.Select(x => x.IsValidInIdentifier(false) ? x : replacement).ToArray()); + + public static string Escape(this string that) => that.Replace("\"", "\"\""); } diff --git a/src/TypealizR/Extensions/TypeExtensions.cs b/src/TypealizR/Extensions/TypeExtensions.cs index 8f41c872..5c962687 100644 --- a/src/TypealizR/Extensions/TypeExtensions.cs +++ b/src/TypealizR/Extensions/TypeExtensions.cs @@ -3,5 +3,5 @@ namespace TypealizR.Extensions; internal static class TypeExtensions { - internal static string GeneratedCodeAttribute(this Type that) => $@"[GeneratedCode(""{that.FullName}"", ""{that.Assembly.GetName().Version}"")]"; + internal static string GeneratedCodeAttribute(this Type that) => $@"[GeneratedCode(""{that.FullName}"", ""{that.Assembly.GetName().Version}"")]"; } diff --git a/src/TypealizR/StringFormatterSourceGenerator/StringFormatterClassBuilder.cs b/src/TypealizR/StringFormatterSourceGenerator/StringFormatterClassBuilder.cs index 733b7901..131a7cbb 100644 --- a/src/TypealizR/StringFormatterSourceGenerator/StringFormatterClassBuilder.cs +++ b/src/TypealizR/StringFormatterSourceGenerator/StringFormatterClassBuilder.cs @@ -9,19 +9,16 @@ internal class StringFormatterClassBuilder private readonly string rootNamespace; - public StringFormatterClassBuilder(string rootNamespace) - { - this.rootNamespace = rootNamespace; - } + public StringFormatterClassBuilder(string rootNamespace) => this.rootNamespace = rootNamespace; private bool isUserModeImplementationProvided; - internal void UserModeImplementationIsProvided() => isUserModeImplementationProvided = true; - + internal void UserModeImplementationIsProvided() => isUserModeImplementationProvided = true; + internal string Build(Type generatorType) { - string stringFormatterStub = GenerateStub(generatorType); + var stringFormatterStub = GenerateStub(generatorType); - var defaultImplementation = default(string?); + string? defaultImplementation = default; if (isUserModeImplementationProvided) { defaultImplementation = GenerateDefaultImplementation(); @@ -52,10 +49,10 @@ private static string GenerateUsings() => $""" using System.CodeDom.Compiler; using Microsoft.Extensions.Localization; - """; - - private static string OpenNamespace(string rootNamespace) => $@"namespace {rootNamespace} {{"; - + """; + + private static string OpenNamespace(string rootNamespace) => $@"namespace {rootNamespace} {{"; + private static string GenerateStub(Type generatorType) => $$""" {{generatorType.GeneratedCodeAttribute()}} internal static partial class {{TypeName}} @@ -69,16 +66,16 @@ internal static LocalizedString Or(this LocalizedString that, LocalizedString fa internal static partial string Format(string s, object[] args); } - """; - + """; + private static string GenerateDefaultImplementation() => $$""" internal static partial class {{TypeName}} { [DebuggerStepThrough] internal static partial string Format(string s, object[] args) => string.Format(System.Globalization.CultureInfo.CurrentCulture, s, args); } - """; - + """; + private const string CloseNamespace = "}"; } diff --git a/src/TypealizR/StringLocalizerExtensionsSourceGenerator/ExtensionClassBuilder.cs b/src/TypealizR/StringLocalizerExtensionsSourceGenerator/ExtensionClassBuilder.cs index deb2fdd9..c5a687b1 100644 --- a/src/TypealizR/StringLocalizerExtensionsSourceGenerator/ExtensionClassBuilder.cs +++ b/src/TypealizR/StringLocalizerExtensionsSourceGenerator/ExtensionClassBuilder.cs @@ -1 +1 @@ -using TypealizR.Core; using TypealizR.Diagnostics; namespace TypealizR; internal partial class ExtensionClassBuilder { private readonly TypeModel markerType; private readonly string rootNamespace; private readonly bool useParametersInMethodNames; public ExtensionClassBuilder(TypeModel markerType, string rootNamespace, bool useParametersInMethodNames) { this.markerType = markerType; this.rootNamespace = rootNamespace; this.useParametersInMethodNames = useParametersInMethodNames; } private readonly DeduplicatingCollection methods = new(); public ExtensionClassBuilder WithExtensionMethod(string key, string value, DiagnosticsCollector diagnostics) { var builder = new ExtensionMethodBuilder(useParametersInMethodNames, markerType, key, value, diagnostics); var model = builder.Build(); methods.Add(model, diagnostics); return this; } public ExtensionClassModel Build() { return new(markerType, rootNamespace, methods.Items); } } \ No newline at end of file +using TypealizR.Core; using TypealizR.Diagnostics; namespace TypealizR; internal partial class ExtensionClassBuilder { private readonly TypeModel markerType; private readonly string rootNamespace; private readonly bool useParametersInMethodNames; public ExtensionClassBuilder(TypeModel markerType, string rootNamespace, bool useParametersInMethodNames) { this.markerType = markerType; this.rootNamespace = rootNamespace; this.useParametersInMethodNames = useParametersInMethodNames; } private readonly DeduplicatingCollection methods = new(); public ExtensionClassBuilder WithExtensionMethod(string key, string value, DiagnosticsCollector diagnostics) { var builder = new ExtensionMethodBuilder(useParametersInMethodNames, markerType, key, value, diagnostics); var model = builder.Build(); methods.Add(model, diagnostics); return this; } public ExtensionClassModel Build() => new(markerType, rootNamespace, methods.Items); } \ No newline at end of file diff --git a/src/TypealizR/StringLocalizerExtensionsSourceGenerator/ExtensionMethodBuilder.cs b/src/TypealizR/StringLocalizerExtensionsSourceGenerator/ExtensionMethodBuilder.cs index e09981ff..8db359e6 100644 --- a/src/TypealizR/StringLocalizerExtensionsSourceGenerator/ExtensionMethodBuilder.cs +++ b/src/TypealizR/StringLocalizerExtensionsSourceGenerator/ExtensionMethodBuilder.cs @@ -24,7 +24,7 @@ public ExtensionMethodBuilder(bool useParametersInMethodNames, TypeModel markerT public ExtensionMethodModel Build() { var parameters = parameterBuilder.Build(diagnostics); - string sanitizedMethodName = key; + var sanitizedMethodName = key; foreach (var parameter in parameters) { diff --git a/src/TypealizR/StringLocalizerExtensionsSourceGenerator/ExtensionMethodModel.cs b/src/TypealizR/StringLocalizerExtensionsSourceGenerator/ExtensionMethodModel.cs index a79ee640..52540429 100644 --- a/src/TypealizR/StringLocalizerExtensionsSourceGenerator/ExtensionMethodModel.cs +++ b/src/TypealizR/StringLocalizerExtensionsSourceGenerator/ExtensionMethodModel.cs @@ -5,10 +5,7 @@ using TypealizR.Core; namespace TypealizR; internal class ExtensionMethodModel : IMemberModel { - public void DeduplicateWith(int discriminator) - { - Name = new MemberName($"{Name}{discriminator}"); - } + public void DeduplicateWith(int discriminator) => Name = new MemberName($"{Name}{discriminator}"); public TypeModel ExtendedType { get; } public string RawRessourceName { get; } @@ -28,8 +25,8 @@ public ExtensionMethodModel(TypeModel extendedType, string rawRessourceName, str public string ToCSharp() { - static string ThisParameterFor(TypeModel T) => $"this IStringLocalizer<{T.GlobalFullName}> that"; - + static string ThisParameterFor(TypeModel T) => $"this IStringLocalizer<{T.GlobalFullName}> that"; + var signature = $"({ThisParameterFor(ExtendedType)})"; var body = $@"that[""{RawRessourceName}""]"; diff --git a/src/TypealizR/StringLocalizerExtensionsSourceGenerator/StringLocalizerExtensionsSourceGenerator.cs b/src/TypealizR/StringLocalizerExtensionsSourceGenerator/StringLocalizerExtensionsSourceGenerator.cs index e8a30a0f..259b52a7 100644 --- a/src/TypealizR/StringLocalizerExtensionsSourceGenerator/StringLocalizerExtensionsSourceGenerator.cs +++ b/src/TypealizR/StringLocalizerExtensionsSourceGenerator/StringLocalizerExtensionsSourceGenerator.cs @@ -22,7 +22,7 @@ CancellationToken cancellationToken { var builder = new ExtensionClassBuilder(markerType, rootNamespace, file.UseParamNamesInMethodNames); - var diagnostics = new List(); + List diagnostics = []; foreach (var entry in file.Entries) { diff --git a/src/TypealizR/TypealizedClassSourceGenerator/InstanceMemberModel.cs b/src/TypealizR/TypealizedClassSourceGenerator/InstanceMemberModel.cs index b31b81f0..7ddc3d95 100644 --- a/src/TypealizR/TypealizedClassSourceGenerator/InstanceMemberModel.cs +++ b/src/TypealizR/TypealizedClassSourceGenerator/InstanceMemberModel.cs @@ -1 +1 @@ -using System; using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis; using TypealizR.Core; namespace TypealizR; internal class InstanceMemberModel : IMemberModel { public void DeduplicateWith(int discriminator) { Name = new MemberName($"{Name}{discriminator}"); } private readonly string rawRessourceName; private readonly string ressourceDefaultValue; private readonly IEnumerable parameters; public InstanceMemberModel(string rawRessourceName, string ressourceDefaultValue, MemberName name, IEnumerable parameters) { this.rawRessourceName = rawRessourceName; this.ressourceDefaultValue = ressourceDefaultValue.Replace("\r\n", " ").Replace("\n", " "); this.Name = name; this.parameters = parameters; } public MemberName Name { get; private set; } public string ToCSharp() { var signature = ""; var body = $@"localizer[""{rawRessourceName}""]"; if (parameters.Any()) { var additionalParameterDeclarations = string.Join(", ", parameters.Select(x => $"{x.Type} {x.DisplayName}")); signature = $"({additionalParameterDeclarations})"; var parameterCollection = parameters.Select(x => x.DisplayName).ToCommaDelimited(); body = $@"localizer[""{rawRessourceName}""].Format({parameterCollection})"; } var comment = new CommentModel(rawRessourceName, ressourceDefaultValue); return $""" {comment.ToCSharp()} public LocalizedString {Name}{signature} => {body}; """; } } \ No newline at end of file +using System; using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis; using TypealizR.Core; namespace TypealizR; internal class InstanceMemberModel : IMemberModel { public void DeduplicateWith(int discriminator) => Name = new MemberName($"{Name}{discriminator}"); private readonly string rawRessourceName; private readonly string ressourceDefaultValue; private readonly IEnumerable parameters; public InstanceMemberModel(string rawRessourceName, string ressourceDefaultValue, MemberName name, IEnumerable parameters) { this.rawRessourceName = rawRessourceName; this.ressourceDefaultValue = ressourceDefaultValue.Replace("\r\n", " ").Replace("\n", " "); this.Name = name; this.parameters = parameters; } public MemberName Name { get; private set; } public string ToCSharp() { var signature = ""; var body = $@"localizer[""{rawRessourceName}""]"; if (parameters.Any()) { var additionalParameterDeclarations = string.Join(", ", parameters.Select(x => $"{x.Type} {x.DisplayName}")); signature = $"({additionalParameterDeclarations})"; var parameterCollection = parameters.Select(x => x.DisplayName).ToCommaDelimited(); body = $@"localizer[""{rawRessourceName}""].Format({parameterCollection})"; } var comment = new CommentModel(rawRessourceName, ressourceDefaultValue); return $""" {comment.ToCSharp()} public LocalizedString {Name}{signature} => {body}; """; } } \ No newline at end of file diff --git a/src/TypealizR/TypealizedClassSourceGenerator/TypealizedClassSourceGenerator.cs b/src/TypealizR/TypealizedClassSourceGenerator/TypealizedClassSourceGenerator.cs index b97fcd5e..dc10d303 100644 --- a/src/TypealizR/TypealizedClassSourceGenerator/TypealizedClassSourceGenerator.cs +++ b/src/TypealizR/TypealizedClassSourceGenerator/TypealizedClassSourceGenerator.cs @@ -23,7 +23,7 @@ CancellationToken cancellationToken { var builder = new TypealizedClassBuilder(file.UseParamNamesInMethodNames, markerType, $"Typealized{markerType.Name}", rootNamespace, severityConfig); - var diagnostics = new List(); + List diagnostics = []; foreach (var entry in file.Entries) { diff --git a/src/TypealizeR.Analyzers.CodeFixes/TypealizeRCodeFixProvider.cs b/src/TypealizeR.Analyzers.CodeFixes/TypealizeRCodeFixProvider.cs index 33b22585..52d86ac3 100644 --- a/src/TypealizeR.Analyzers.CodeFixes/TypealizeRCodeFixProvider.cs +++ b/src/TypealizeR.Analyzers.CodeFixes/TypealizeRCodeFixProvider.cs @@ -20,16 +20,11 @@ public class TypealizeRCodeFixProvider : CodeFixProvider { UseIndexerAnalyzer.DiagnosticId, (root, diagnostics) => new UseIndexerCodeFixer(root, diagnostics) } }; - public sealed override ImmutableArray FixableDiagnosticIds - { - get { return [UseIndexerAnalyzer.DiagnosticId]; } - } + public sealed override ImmutableArray FixableDiagnosticIds => [UseIndexerAnalyzer.DiagnosticId]; - public sealed override FixAllProvider GetFixAllProvider() - { + public sealed override FixAllProvider GetFixAllProvider() => // See https://github.com/dotnet/roslyn/blob/main/docs/analyzers/FixAllProvider.md for more information on Fix All Providers - return WellKnownFixAllProviders.BatchFixer; - } + WellKnownFixAllProviders.BatchFixer; public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) { @@ -41,7 +36,7 @@ public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) return; } - if (!codeFixers.TryGetValue(diagnostic.Id, out CodeFixerFactory createCodeFixer)) + if (!codeFixers.TryGetValue(diagnostic.Id, out var createCodeFixer)) { return; } diff --git a/src/TypealizeR.Analyzers/UseIndexerAnalyzer.cs b/src/TypealizeR.Analyzers/UseIndexerAnalyzer.cs index 2f0a0dbf..bc681d44 100644 --- a/src/TypealizeR.Analyzers/UseIndexerAnalyzer.cs +++ b/src/TypealizeR.Analyzers/UseIndexerAnalyzer.cs @@ -21,7 +21,7 @@ public class UseIndexerAnalyzer : DiagnosticAnalyzer private static readonly DiagnosticDescriptor Rule = new(DiagnosticId, Title, MessageFormat, Category, DiagnosticSeverity.Hidden, isEnabledByDefault: true, description: Description); - public override ImmutableArray SupportedDiagnostics { get { return [Rule]; } } + public override ImmutableArray SupportedDiagnostics => [Rule]; public override void Initialize(AnalysisContext context) { @@ -85,12 +85,7 @@ private static void AnalyzeSyntaxNode(SyntaxNodeAnalysisContext context) var nonGenericDisplayName = displayName.Trim('?').Split('<')[0]; - if (nonGenericDisplayName != wantedTypeFullName) - { - return null; - } - - return symbolInfo.Symbol.Name; + return nonGenericDisplayName != wantedTypeFullName ? null : symbolInfo.Symbol.Name; } }