diff --git a/src/Analyzers/CSharp/Tests/CSharpAnalyzers.UnitTests.projitems b/src/Analyzers/CSharp/Tests/CSharpAnalyzers.UnitTests.projitems index 7e673de61d11aabdc9e189b0edd93595d5b9c961..bed6bbd0b9d09f7d2c26db53a0c5d9bc04bde6a2 100644 --- a/src/Analyzers/CSharp/Tests/CSharpAnalyzers.UnitTests.projitems +++ b/src/Analyzers/CSharp/Tests/CSharpAnalyzers.UnitTests.projitems @@ -73,8 +73,10 @@ + + diff --git a/src/EditorFeatures/CSharpTest/UseSystemHashCode/UseSystemHashCodeTests.cs b/src/Analyzers/CSharp/Tests/UseSystemHashCode/UseSystemHashCodeTests.cs similarity index 99% rename from src/EditorFeatures/CSharpTest/UseSystemHashCode/UseSystemHashCodeTests.cs rename to src/Analyzers/CSharp/Tests/UseSystemHashCode/UseSystemHashCodeTests.cs index 82d875f37bacc47c3b448fe24ff30e5e584ed408..e02cdbfdf1e767485783c3d9afed39b6a259cf75 100644 --- a/src/EditorFeatures/CSharpTest/UseSystemHashCode/UseSystemHashCodeTests.cs +++ b/src/Analyzers/CSharp/Tests/UseSystemHashCode/UseSystemHashCodeTests.cs @@ -1209,7 +1209,7 @@ public override int GetHashCode() hash.Add(i); return hash.ToHashCode(); } -}", options: this.PreferImplicitTypeWithInfo()); +}", options: UseVarTestExtensions.PreferImplicitTypeWithInfo(this)); } [WorkItem(39916, "https://github.com/dotnet/roslyn/issues/39916")] diff --git a/src/EditorFeatures/CSharpTest/CodeActions/UseVarTestExtensions.cs b/src/Analyzers/CSharp/Tests/UseVarTestExtensions.cs similarity index 97% rename from src/EditorFeatures/CSharpTest/CodeActions/UseVarTestExtensions.cs rename to src/Analyzers/CSharp/Tests/UseVarTestExtensions.cs index e9bc24c53f40993e3dafd58ffa3487e8af4edd37..70c924ca2c82d70466acee41850db99f3b4bb8d0 100644 --- a/src/EditorFeatures/CSharpTest/CodeActions/UseVarTestExtensions.cs +++ b/src/Analyzers/CSharp/Tests/UseVarTestExtensions.cs @@ -5,7 +5,12 @@ using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; + +#if CODE_STYLE +using AbstractCodeActionOrUserDiagnosticTest = Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest; +#else using static Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions.AbstractCodeActionOrUserDiagnosticTest; +#endif namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeActions { diff --git a/src/Analyzers/Core/Analyzers/Analyzers.projitems b/src/Analyzers/Core/Analyzers/Analyzers.projitems index a2de9de87a2f8dc43356ad33752d1e70a17757bf..c198a0748106ceebe795db8e273b70dee61b01a0 100644 --- a/src/Analyzers/Core/Analyzers/Analyzers.projitems +++ b/src/Analyzers/Core/Analyzers/Analyzers.projitems @@ -67,6 +67,9 @@ + + + diff --git a/src/Analyzers/Core/Analyzers/AnalyzersResources.resx b/src/Analyzers/Core/Analyzers/AnalyzersResources.resx index 4ca9ae9cdfd9efd907f430f12128c9e918d5ee42..92bc8c7b5634a66aaf0269723684c17fb5685bb4 100644 --- a/src/Analyzers/Core/Analyzers/AnalyzersResources.resx +++ b/src/Analyzers/Core/Analyzers/AnalyzersResources.resx @@ -265,6 +265,12 @@ Use explicitly provided tuple name + + Use 'System.HashCode' + + + 'GetHashCode' implementation can be simplified + Use compound assignment diff --git a/src/Features/Core/Portable/UseSystemHashCode/Analyzer.OperationDeconstructor.cs b/src/Analyzers/Core/Analyzers/UseSystemHashCode/Analyzer.OperationDeconstructor.cs similarity index 100% rename from src/Features/Core/Portable/UseSystemHashCode/Analyzer.OperationDeconstructor.cs rename to src/Analyzers/Core/Analyzers/UseSystemHashCode/Analyzer.OperationDeconstructor.cs diff --git a/src/Features/Core/Portable/UseSystemHashCode/Analyzer.cs b/src/Analyzers/Core/Analyzers/UseSystemHashCode/Analyzer.cs similarity index 99% rename from src/Features/Core/Portable/UseSystemHashCode/Analyzer.cs rename to src/Analyzers/Core/Analyzers/UseSystemHashCode/Analyzer.cs index a21d4ebee1c7f3346937a4bfe50a44c4819c0e4d..664007f961077a1033775faecaf09fdcf6cef4eb 100644 --- a/src/Features/Core/Portable/UseSystemHashCode/Analyzer.cs +++ b/src/Analyzers/Core/Analyzers/UseSystemHashCode/Analyzer.cs @@ -14,7 +14,7 @@ namespace Microsoft.CodeAnalysis.UseSystemHashCode { /// - /// Helper code to support both and + /// Helper code to support both "UseSystemHashCodeCodeFixProvider" and /// . /// internal partial struct Analyzer diff --git a/src/Features/Core/Portable/UseSystemHashCode/UseSystemHashCodeDiagnosticAnalyzer.cs b/src/Analyzers/Core/Analyzers/UseSystemHashCode/UseSystemHashCodeDiagnosticAnalyzer.cs similarity index 88% rename from src/Features/Core/Portable/UseSystemHashCode/UseSystemHashCodeDiagnosticAnalyzer.cs rename to src/Analyzers/Core/Analyzers/UseSystemHashCode/UseSystemHashCodeDiagnosticAnalyzer.cs index bb6ebb5cfd037c6b344f1a586ad2e849e2a7b912..954d4be6f54284ea3625f605852b75ed6ba0b3da 100644 --- a/src/Features/Core/Portable/UseSystemHashCode/UseSystemHashCodeDiagnosticAnalyzer.cs +++ b/src/Analyzers/Core/Analyzers/UseSystemHashCode/UseSystemHashCodeDiagnosticAnalyzer.cs @@ -16,8 +16,8 @@ internal class UseSystemHashCodeDiagnosticAnalyzer : AbstractBuiltInCodeStyleDia public UseSystemHashCodeDiagnosticAnalyzer() : base(IDEDiagnosticIds.UseSystemHashCode, CodeStyleOptions2.PreferSystemHashCode, - new LocalizableResourceString(nameof(FeaturesResources.Use_System_HashCode), FeaturesResources.ResourceManager, typeof(FeaturesResources)), - new LocalizableResourceString(nameof(FeaturesResources.GetHashCode_implementation_can_be_simplified), FeaturesResources.ResourceManager, typeof(FeaturesResources))) + new LocalizableResourceString(nameof(AnalyzersResources.Use_System_HashCode), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)), + new LocalizableResourceString(nameof(AnalyzersResources.GetHashCode_implementation_can_be_simplified), AnalyzersResources.ResourceManager, typeof(AnalyzersResources))) { } diff --git a/src/Analyzers/Core/Analyzers/xlf/AnalyzersResources.cs.xlf b/src/Analyzers/Core/Analyzers/xlf/AnalyzersResources.cs.xlf index 68f4fa72559ea1846f300e3aa847491c43433091..0602b871aaa9e6ccc893440751a757079b9f2c9e 100644 --- a/src/Analyzers/Core/Analyzers/xlf/AnalyzersResources.cs.xlf +++ b/src/Analyzers/Core/Analyzers/xlf/AnalyzersResources.cs.xlf @@ -77,6 +77,11 @@ Format string contains invalid placeholder + + 'GetHashCode' implementation can be simplified + 'GetHashCode' implementation can be simplified + + Invalid format string Invalid format string @@ -247,6 +252,11 @@ Unnecessary assignment of a value to '{0}' + + Use 'System.HashCode' + Use 'System.HashCode' + + Use coalesce expression Use coalesce expression diff --git a/src/Analyzers/Core/Analyzers/xlf/AnalyzersResources.de.xlf b/src/Analyzers/Core/Analyzers/xlf/AnalyzersResources.de.xlf index 6bb7a42d40240ce163f1f58c16106986a66cd2aa..5c66de0c38e228c555a05b2a2505c6bb6af570f5 100644 --- a/src/Analyzers/Core/Analyzers/xlf/AnalyzersResources.de.xlf +++ b/src/Analyzers/Core/Analyzers/xlf/AnalyzersResources.de.xlf @@ -77,6 +77,11 @@ Format string contains invalid placeholder + + 'GetHashCode' implementation can be simplified + 'GetHashCode' implementation can be simplified + + Invalid format string Invalid format string @@ -247,6 +252,11 @@ Unnecessary assignment of a value to '{0}' + + Use 'System.HashCode' + Use 'System.HashCode' + + Use coalesce expression Use coalesce expression diff --git a/src/Analyzers/Core/Analyzers/xlf/AnalyzersResources.es.xlf b/src/Analyzers/Core/Analyzers/xlf/AnalyzersResources.es.xlf index 1d8f4e009e91cd6145beb101d931b09a7cb7af9a..2dbdf2efcbe1aba75d54abda61ed2f23267f2bfc 100644 --- a/src/Analyzers/Core/Analyzers/xlf/AnalyzersResources.es.xlf +++ b/src/Analyzers/Core/Analyzers/xlf/AnalyzersResources.es.xlf @@ -77,6 +77,11 @@ Format string contains invalid placeholder + + 'GetHashCode' implementation can be simplified + 'GetHashCode' implementation can be simplified + + Invalid format string Invalid format string @@ -247,6 +252,11 @@ Unnecessary assignment of a value to '{0}' + + Use 'System.HashCode' + Use 'System.HashCode' + + Use coalesce expression Use coalesce expression diff --git a/src/Analyzers/Core/Analyzers/xlf/AnalyzersResources.fr.xlf b/src/Analyzers/Core/Analyzers/xlf/AnalyzersResources.fr.xlf index 719f1e5f8c9b7136ce8381eff1cc6c4c028bd2e3..52d47926cf7d48760369595be09575e49240d821 100644 --- a/src/Analyzers/Core/Analyzers/xlf/AnalyzersResources.fr.xlf +++ b/src/Analyzers/Core/Analyzers/xlf/AnalyzersResources.fr.xlf @@ -77,6 +77,11 @@ Format string contains invalid placeholder + + 'GetHashCode' implementation can be simplified + 'GetHashCode' implementation can be simplified + + Invalid format string Invalid format string @@ -247,6 +252,11 @@ Unnecessary assignment of a value to '{0}' + + Use 'System.HashCode' + Use 'System.HashCode' + + Use coalesce expression Use coalesce expression diff --git a/src/Analyzers/Core/Analyzers/xlf/AnalyzersResources.it.xlf b/src/Analyzers/Core/Analyzers/xlf/AnalyzersResources.it.xlf index 788baacc4c0402bf467bb4acf64f1aa9ca867db7..a60565429d12a80997cd6ad5928beb9fb596b114 100644 --- a/src/Analyzers/Core/Analyzers/xlf/AnalyzersResources.it.xlf +++ b/src/Analyzers/Core/Analyzers/xlf/AnalyzersResources.it.xlf @@ -77,6 +77,11 @@ Format string contains invalid placeholder + + 'GetHashCode' implementation can be simplified + 'GetHashCode' implementation can be simplified + + Invalid format string Invalid format string @@ -247,6 +252,11 @@ Unnecessary assignment of a value to '{0}' + + Use 'System.HashCode' + Use 'System.HashCode' + + Use coalesce expression Use coalesce expression diff --git a/src/Analyzers/Core/Analyzers/xlf/AnalyzersResources.ja.xlf b/src/Analyzers/Core/Analyzers/xlf/AnalyzersResources.ja.xlf index 20f2a48b815914b2f05fa3c37f1557c4390a5f08..712ff4dec85297c4571cf9946c9ed63a57979aa6 100644 --- a/src/Analyzers/Core/Analyzers/xlf/AnalyzersResources.ja.xlf +++ b/src/Analyzers/Core/Analyzers/xlf/AnalyzersResources.ja.xlf @@ -77,6 +77,11 @@ Format string contains invalid placeholder + + 'GetHashCode' implementation can be simplified + 'GetHashCode' implementation can be simplified + + Invalid format string Invalid format string @@ -247,6 +252,11 @@ Unnecessary assignment of a value to '{0}' + + Use 'System.HashCode' + Use 'System.HashCode' + + Use coalesce expression Use coalesce expression diff --git a/src/Analyzers/Core/Analyzers/xlf/AnalyzersResources.ko.xlf b/src/Analyzers/Core/Analyzers/xlf/AnalyzersResources.ko.xlf index 9569dd1670275e04cfff1e0b230ea3b0b1608e33..bd87341de835d319312323efc212a7a1fe9321c5 100644 --- a/src/Analyzers/Core/Analyzers/xlf/AnalyzersResources.ko.xlf +++ b/src/Analyzers/Core/Analyzers/xlf/AnalyzersResources.ko.xlf @@ -77,6 +77,11 @@ Format string contains invalid placeholder + + 'GetHashCode' implementation can be simplified + 'GetHashCode' implementation can be simplified + + Invalid format string Invalid format string @@ -247,6 +252,11 @@ Unnecessary assignment of a value to '{0}' + + Use 'System.HashCode' + Use 'System.HashCode' + + Use coalesce expression Use coalesce expression diff --git a/src/Analyzers/Core/Analyzers/xlf/AnalyzersResources.pl.xlf b/src/Analyzers/Core/Analyzers/xlf/AnalyzersResources.pl.xlf index 27aad4fb8611b59303380297368ee2441e65bf75..4cfd07329b3d3fb4abba86d3a6a6dd70013d3754 100644 --- a/src/Analyzers/Core/Analyzers/xlf/AnalyzersResources.pl.xlf +++ b/src/Analyzers/Core/Analyzers/xlf/AnalyzersResources.pl.xlf @@ -77,6 +77,11 @@ Format string contains invalid placeholder + + 'GetHashCode' implementation can be simplified + 'GetHashCode' implementation can be simplified + + Invalid format string Invalid format string @@ -247,6 +252,11 @@ Unnecessary assignment of a value to '{0}' + + Use 'System.HashCode' + Use 'System.HashCode' + + Use coalesce expression Use coalesce expression diff --git a/src/Analyzers/Core/Analyzers/xlf/AnalyzersResources.pt-BR.xlf b/src/Analyzers/Core/Analyzers/xlf/AnalyzersResources.pt-BR.xlf index b665146a17510f9fc0edb6698448304ff10c084a..187469f24da657c7181e467a8cb3b4f6f666641e 100644 --- a/src/Analyzers/Core/Analyzers/xlf/AnalyzersResources.pt-BR.xlf +++ b/src/Analyzers/Core/Analyzers/xlf/AnalyzersResources.pt-BR.xlf @@ -77,6 +77,11 @@ Format string contains invalid placeholder + + 'GetHashCode' implementation can be simplified + 'GetHashCode' implementation can be simplified + + Invalid format string Invalid format string @@ -247,6 +252,11 @@ Unnecessary assignment of a value to '{0}' + + Use 'System.HashCode' + Use 'System.HashCode' + + Use coalesce expression Use coalesce expression diff --git a/src/Analyzers/Core/Analyzers/xlf/AnalyzersResources.ru.xlf b/src/Analyzers/Core/Analyzers/xlf/AnalyzersResources.ru.xlf index edc5379aa1302e2dd4749819f5efe0217dc957f1..cc63674d3c3648a0dcef79f75185fd3bb4ed4617 100644 --- a/src/Analyzers/Core/Analyzers/xlf/AnalyzersResources.ru.xlf +++ b/src/Analyzers/Core/Analyzers/xlf/AnalyzersResources.ru.xlf @@ -77,6 +77,11 @@ Format string contains invalid placeholder + + 'GetHashCode' implementation can be simplified + 'GetHashCode' implementation can be simplified + + Invalid format string Invalid format string @@ -247,6 +252,11 @@ Unnecessary assignment of a value to '{0}' + + Use 'System.HashCode' + Use 'System.HashCode' + + Use coalesce expression Use coalesce expression diff --git a/src/Analyzers/Core/Analyzers/xlf/AnalyzersResources.tr.xlf b/src/Analyzers/Core/Analyzers/xlf/AnalyzersResources.tr.xlf index 39ddb535f2f91f75357a42ef3141c181d3d1d4e3..e066a1c832420b3b03da74e4a80850994df0f943 100644 --- a/src/Analyzers/Core/Analyzers/xlf/AnalyzersResources.tr.xlf +++ b/src/Analyzers/Core/Analyzers/xlf/AnalyzersResources.tr.xlf @@ -77,6 +77,11 @@ Format string contains invalid placeholder + + 'GetHashCode' implementation can be simplified + 'GetHashCode' implementation can be simplified + + Invalid format string Invalid format string @@ -247,6 +252,11 @@ Unnecessary assignment of a value to '{0}' + + Use 'System.HashCode' + Use 'System.HashCode' + + Use coalesce expression Use coalesce expression diff --git a/src/Analyzers/Core/Analyzers/xlf/AnalyzersResources.zh-Hans.xlf b/src/Analyzers/Core/Analyzers/xlf/AnalyzersResources.zh-Hans.xlf index 6502fc519d7a30c4d6aa8f84e690ee8e3ac9dbac..8da7c01b2acf56313323084356b29bcadda98439 100644 --- a/src/Analyzers/Core/Analyzers/xlf/AnalyzersResources.zh-Hans.xlf +++ b/src/Analyzers/Core/Analyzers/xlf/AnalyzersResources.zh-Hans.xlf @@ -77,6 +77,11 @@ Format string contains invalid placeholder + + 'GetHashCode' implementation can be simplified + 'GetHashCode' implementation can be simplified + + Invalid format string Invalid format string @@ -247,6 +252,11 @@ Unnecessary assignment of a value to '{0}' + + Use 'System.HashCode' + Use 'System.HashCode' + + Use coalesce expression Use coalesce expression diff --git a/src/Analyzers/Core/Analyzers/xlf/AnalyzersResources.zh-Hant.xlf b/src/Analyzers/Core/Analyzers/xlf/AnalyzersResources.zh-Hant.xlf index 2615ae7515feb4b43188931ee0b65467f220ca57..64ef51a016dbdff3ecdf5b2a7c98ffd90d4b187f 100644 --- a/src/Analyzers/Core/Analyzers/xlf/AnalyzersResources.zh-Hant.xlf +++ b/src/Analyzers/Core/Analyzers/xlf/AnalyzersResources.zh-Hant.xlf @@ -77,6 +77,11 @@ Format string contains invalid placeholder + + 'GetHashCode' implementation can be simplified + 'GetHashCode' implementation can be simplified + + Invalid format string Invalid format string @@ -247,6 +252,11 @@ Unnecessary assignment of a value to '{0}' + + Use 'System.HashCode' + Use 'System.HashCode' + + Use coalesce expression Use coalesce expression diff --git a/src/Analyzers/Core/CodeFixes/CodeFixes.projitems b/src/Analyzers/Core/CodeFixes/CodeFixes.projitems index 47c65d846b99f5e9c0d59e6798fa87bbd832f6d8..63e45e161c1abdf964689edbcf1972b692041f4d 100644 --- a/src/Analyzers/Core/CodeFixes/CodeFixes.projitems +++ b/src/Analyzers/Core/CodeFixes/CodeFixes.projitems @@ -41,6 +41,7 @@ + diff --git a/src/Features/Core/Portable/UseSystemHashCode/UseSystemHashCodeCodeFixProvider.cs b/src/Analyzers/Core/CodeFixes/UseSystemHashCode/UseSystemHashCodeCodeFixProvider.cs similarity index 91% rename from src/Features/Core/Portable/UseSystemHashCode/UseSystemHashCodeCodeFixProvider.cs rename to src/Analyzers/Core/CodeFixes/UseSystemHashCode/UseSystemHashCodeCodeFixProvider.cs index 301bef06b6382c0fbc4e0376133b0dee5bc57755..8a80679b5b5b8e26d528011196d985cde218248d 100644 --- a/src/Features/Core/Portable/UseSystemHashCode/UseSystemHashCodeCodeFixProvider.cs +++ b/src/Analyzers/Core/CodeFixes/UseSystemHashCode/UseSystemHashCodeCodeFixProvider.cs @@ -51,6 +51,7 @@ public override Task RegisterCodeFixesAsync(CodeFixContext context) SyntaxEditor editor, CancellationToken cancellationToken) { var generator = SyntaxGenerator.GetGenerator(document); + var generatorInternal = document.GetRequiredLanguageService(); var declarationService = document.GetLanguageService(); if (declarationService == null) { @@ -88,16 +89,16 @@ public override Task RegisterCodeFixesAsync(CodeFixContext context) var updatedDecl = generator.WithStatements( methodBlock, generator.CreateGetHashCodeStatementsUsingSystemHashCode( - analyzer.SystemHashCodeType, components)); + generatorInternal, analyzer.SystemHashCodeType, components)); editor.ReplaceNode(methodBlock, updatedDecl); } } } - private class MyCodeAction : CodeAction.DocumentChangeAction + private class MyCodeAction : CustomCodeActions.DocumentChangeAction { public MyCodeAction(Func> createChangedDocument) - : base(FeaturesResources.Use_System_HashCode, createChangedDocument, FeaturesResources.Use_System_HashCode) + : base(AnalyzersResources.Use_System_HashCode, createChangedDocument, AnalyzersResources.Use_System_HashCode) { } } diff --git a/src/EditorFeatures/VisualBasicTest/UseSystemHashCode/UseSystemHashCodeTests.vb b/src/Analyzers/VisualBasic/Tests/UseSystemHashCode/UseSystemHashCodeTests.vb similarity index 100% rename from src/EditorFeatures/VisualBasicTest/UseSystemHashCode/UseSystemHashCodeTests.vb rename to src/Analyzers/VisualBasic/Tests/UseSystemHashCode/UseSystemHashCodeTests.vb diff --git a/src/Analyzers/VisualBasic/Tests/VisualBasicAnalyzers.UnitTests.projitems b/src/Analyzers/VisualBasic/Tests/VisualBasicAnalyzers.UnitTests.projitems index f09dff0afc5a17b24c17494fee51d448960a81df..0cc6c8c97994703e8cff7872efc3c48c9e291c75 100644 --- a/src/Analyzers/VisualBasic/Tests/VisualBasicAnalyzers.UnitTests.projitems +++ b/src/Analyzers/VisualBasic/Tests/VisualBasicAnalyzers.UnitTests.projitems @@ -40,6 +40,7 @@ + diff --git a/src/Features/Core/Portable/FeaturesResources.resx b/src/Features/Core/Portable/FeaturesResources.resx index 7ab511e3effbebe2187e3a59342158119b99d57a..5a6fb9f40b4b39551b0984807ba291ce47c1b30a 100644 --- a/src/Features/Core/Portable/FeaturesResources.resx +++ b/src/Features/Core/Portable/FeaturesResources.resx @@ -1463,12 +1463,6 @@ This version used in: {2} Add null checks for all parameters - - Use 'System.HashCode' - - - 'GetHashCode' implementation can be simplified - Implement '{0}' implicitly diff --git a/src/Features/Core/Portable/GenerateEqualsAndGetHashCodeFromMembers/AbstractGenerateEqualsAndGetHashCodeService.cs b/src/Features/Core/Portable/GenerateEqualsAndGetHashCodeFromMembers/AbstractGenerateEqualsAndGetHashCodeService.cs index d142f2a8fccb6eb2ee71a4a2278fbbb45afd3455..818073e60a9a7c6e3952cb035eda769faeb9b4e1 100644 --- a/src/Features/Core/Portable/GenerateEqualsAndGetHashCodeFromMembers/AbstractGenerateEqualsAndGetHashCodeService.cs +++ b/src/Features/Core/Portable/GenerateEqualsAndGetHashCodeFromMembers/AbstractGenerateEqualsAndGetHashCodeService.cs @@ -155,12 +155,13 @@ public async Task FormatDocumentAsync(Document document, CancellationT if (components.Length > 0 && hashCodeType != null) { - return factory.CreateGetHashCodeStatementsUsingSystemHashCode(hashCodeType, components); + return factory.CreateGetHashCodeStatementsUsingSystemHashCode( + factory.SyntaxGeneratorInternal, hashCodeType, components); } // Otherwise, try to just spit out a reasonable hash code for these members. var statements = factory.CreateGetHashCodeMethodStatements( - compilation, namedType, members, useInt64: false); + factory.SyntaxGeneratorInternal, compilation, namedType, members, useInt64: false); // Unfortunately, our 'reasonable' hash code may overflow in checked contexts. // C# can handle this by adding 'checked{}' around the code, VB has to jump @@ -194,7 +195,7 @@ public async Task FormatDocumentAsync(Document document, CancellationT // // This does mean all hashcodes will be positive. But it will avoid the overflow problem. return factory.CreateGetHashCodeMethodStatements( - compilation, namedType, members, useInt64: true); + factory.SyntaxGeneratorInternal, compilation, namedType, members, useInt64: true); } } } diff --git a/src/Features/Core/Portable/xlf/FeaturesResources.cs.xlf b/src/Features/Core/Portable/xlf/FeaturesResources.cs.xlf index 0a5690b87254813f844d54f328ac724781de6557..8037fa9cf096628a6a93684542edb433eeecb789 100644 --- a/src/Features/Core/Portable/xlf/FeaturesResources.cs.xlf +++ b/src/Features/Core/Portable/xlf/FeaturesResources.cs.xlf @@ -272,11 +272,6 @@ Generovat parametr {0} (a přepsání/implementace) - - 'GetHashCode' implementation can be simplified - Implementace GetHashCode se dá zjednodušit. - - Implement '{0}' explicitly Implementovat rozhraní {0} explicitně @@ -577,11 +572,6 @@ Použijte doporučený vzor Dispose, abyste měli jistotu, že objekty, které lze vyřadit v místním oboru, se vyřadí na všech cestách. Pokud je to možné, zabalte vytváření do příkazu nebo deklarace using. Jinak použijte vzor try-finally s vyhrazenou místní proměnnou deklarovanou před oblastí try a nepodmíněným voláním Dispose pro hodnotu, která není null, v oblasti finally, třeba x?.Dispose(). Pokud se objekt explicitně vyřadí v oblasti try nebo se vlastnictví Dispose převede na jiný objekt nebo metodu, přiřaďte ihned po takové operaci místní proměnné hodnotu null, aby ve finally nedošlo k dvojímu Dispose. - - Use 'System.HashCode' - Použijte System.HashCode. - - Use block body for lambda expressions Pro lambda výrazy používat text bloku diff --git a/src/Features/Core/Portable/xlf/FeaturesResources.de.xlf b/src/Features/Core/Portable/xlf/FeaturesResources.de.xlf index 51151f7cb5d8ab98bdcf22875d28fcacbc7f0073..6404f40b9ed6941037aea045317456963cb3148e 100644 --- a/src/Features/Core/Portable/xlf/FeaturesResources.de.xlf +++ b/src/Features/Core/Portable/xlf/FeaturesResources.de.xlf @@ -272,11 +272,6 @@ Parameter "{0}" (und Außerkraftsetzungen/Implementierungen) generieren - - 'GetHashCode' implementation can be simplified - Die Implementierung von "GetHashCode" kann vereinfacht werden. - - Implement '{0}' explicitly "{0}" explizit implementieren @@ -577,11 +572,6 @@ Verwenden Sie das empfohlene Dispose-Muster, um sicherzustellen, dass löschbare Objekte für den lokalen Bereich in allen Pfaden gelöscht werden. Schließen Sie die Erstellung nach Möglichkeit in einer using-Anweisung oder einer using-Deklaration ein. Verwenden Sie andernfalls ein try-finally-Muster mit einer vor dem try-Bereich deklarierten dedizierten lokalen Variablen und einem Dispose-Aufruf ohne Bedingung für den Nicht-NULL-Wert im finally-Bereich, beispielsweise "x?.Dispose()". Wenn das Objekt explizit innerhalb des try-Bereichs gelöscht oder der Dispose-Besitz auf ein anderes Objekt oder eine andere Methode übertragen wird, weisen Sie der lokalen Variablen gleich nach einem solchen Vorgang NULL zu, um einen doppelten Löschvorgang in "finally" zu vermeiden. - - Use 'System.HashCode' - "System.Hashcode" verwenden - - Use block body for lambda expressions Blocktextkörper für Lambdaausdrücke verwenden diff --git a/src/Features/Core/Portable/xlf/FeaturesResources.es.xlf b/src/Features/Core/Portable/xlf/FeaturesResources.es.xlf index 22b242d6c4f8d958974d3224eb2c130133803ef8..d1e59cf77e43921ee71c700e990df4e8858842b1 100644 --- a/src/Features/Core/Portable/xlf/FeaturesResources.es.xlf +++ b/src/Features/Core/Portable/xlf/FeaturesResources.es.xlf @@ -272,11 +272,6 @@ Generar el parámetro "{0}" (y reemplazos/implementaciones) - - 'GetHashCode' implementation can be simplified - La implementación de "GetHashCode" se puede simplificar. - - Implement '{0}' explicitly Implementar "{0}" de forma explícita @@ -577,11 +572,6 @@ Use el patrón de Dispose recomendado para asegurarse de que los objetos descartables de ámbito local se desechan en todas las rutas de acceso. Si es posible, incluya la creación en una instrucción "using" o una declaración "using". En caso contrario, use un patrón try-finally, con la declaración de una variable local dedicada antes de la región "try" y una invocación de Dispose incondicional en un valor no nulo en la región "finally", por ejemplo, "x?.Dispose()". Si el objeto se desecha de forma explícita en la región "try" o la pertenencia de Dispose se transfiere a otro objeto o método, asigne "null" a la variable local justo después de tal operación para evitar un doble Dispose en "finally". - - Use 'System.HashCode' - Usar "System.HashCode" - - Use block body for lambda expressions Usar cuerpo del bloque para las expresiones lambda diff --git a/src/Features/Core/Portable/xlf/FeaturesResources.fr.xlf b/src/Features/Core/Portable/xlf/FeaturesResources.fr.xlf index 1fa7608eb71ff0ee7b35ebed04866ab2d7713c7b..fcf5938edff7d4281242946b2298edd471b3fb7f 100644 --- a/src/Features/Core/Portable/xlf/FeaturesResources.fr.xlf +++ b/src/Features/Core/Portable/xlf/FeaturesResources.fr.xlf @@ -272,11 +272,6 @@ Générer le paramètre '{0}' (et les substitutions/implémentations) - - 'GetHashCode' implementation can be simplified - L'implémentation de 'GetHashCode' peut être simplifiée - - Implement '{0}' explicitly Implémenter '{0}' explicitement @@ -577,11 +572,6 @@ Utilisez le modèle Dispose recommandé pour vérifier que les objets supprimables de l'étendue locale sont bien supprimés sur tous les chemins. Si possible, enveloppez la création dans une instruction 'using' ou une déclaration 'using'. Sinon, utilisez un modèle try-finally avec une variable locale dédiée déclarée avant la région try et un appel inconditionnel de Dispose sur une valeur non null dans la région 'finally', par exemple 'x?.Dispose()'. Si l'objet est explicitement supprimé dans la région try ou si la propriété de suppression est transférée vers un autre objet ou une autre méthode, affectez la valeur 'null' à la variable locale juste après cette opération pour éviter une double suppression dans 'finally' - - Use 'System.HashCode' - Utiliser 'System.HashCode' - - Use block body for lambda expressions Utiliser le corps de bloc pour les expressions lambda diff --git a/src/Features/Core/Portable/xlf/FeaturesResources.it.xlf b/src/Features/Core/Portable/xlf/FeaturesResources.it.xlf index 093cc7fe966f1a35a681457af3b152cb0f3dc901..8d7724a018bc7b29ca6507c7dc2c955004b951db 100644 --- a/src/Features/Core/Portable/xlf/FeaturesResources.it.xlf +++ b/src/Features/Core/Portable/xlf/FeaturesResources.it.xlf @@ -272,11 +272,6 @@ Generare il parametro '{0}' (e override/implementazioni) - - 'GetHashCode' implementation can be simplified - L'implementazione di 'GetHashCode' può essere semplificata - - Implement '{0}' explicitly Implementa '{0}' in modo esplicito @@ -577,11 +572,6 @@ Usare il criterio dispose consigliato per garantire che gli oggetti eliminabili con ambito locale vengano eliminati in tutti i percorsi. Se possibile, eseguire il wrapping della creazione in un'istruzione 'using' o una dichiarazione 'using'. In caso contrario, usare un criterio try-finally, con una variabile locale dedicata dichiarata prima dell'area try e una chiamata Dispose non condizionale al valore non Null nell'area 'finally', ad esempio 'x?.Dispose()'. Se l'oggetto viene eliminato in modo esplicito nell'area try oppure la proprietà di dispose viene trasferita a un altro oggetto o metodo, assegnare 'null' alla variabile locale subito dopo una tale operazione per evitare di raddoppiare dispose in 'finally' - - Use 'System.HashCode' - Usa 'System.HashCode' - - Use block body for lambda expressions Usa il corpo del blocco per le espressioni lambda diff --git a/src/Features/Core/Portable/xlf/FeaturesResources.ja.xlf b/src/Features/Core/Portable/xlf/FeaturesResources.ja.xlf index 0a46ce5362f955f9e7651c083ca88b1defa8ccc8..cfe742fa24e6ceb64a92c2af7df3e0d57848d4b8 100644 --- a/src/Features/Core/Portable/xlf/FeaturesResources.ja.xlf +++ b/src/Features/Core/Portable/xlf/FeaturesResources.ja.xlf @@ -272,11 +272,6 @@ パラメーター '{0}' の生成 (およびオーバーライド/実装) - - 'GetHashCode' implementation can be simplified - 'GetHashCode' の実装を簡略化できます - - Implement '{0}' explicitly '{0}' を明示的に実装する @@ -577,11 +572,6 @@ 推奨される破棄パターンを使用して、ローカル スコープの破棄可能なオブジェクトがすべてのパスで破棄されるようにします。可能なら、'using' ステートメントまたは 'using' 宣言内で作成を折り返します。または、try-finally パターンを、try 領域の前で宣言された専用のローカル変数と、'finally' 領域の非 null 値での条件なしの Dispose の呼び出し (例: 'x?.Dispose()') とともに使用します。オブジェクトが try 領域内で明示的に破棄されるか、dispose の所有権が他のオブジェクトまたはメソッドに移される場合、その操作のすぐ後で 'null' をローカル変数に割り当てて、'finally' 内での dispose の重複を回避します - - Use 'System.HashCode' - 'System.HashCode' を使用する - - Use block body for lambda expressions ラムダ式にブロック本体を使用する diff --git a/src/Features/Core/Portable/xlf/FeaturesResources.ko.xlf b/src/Features/Core/Portable/xlf/FeaturesResources.ko.xlf index b074b1f339cedb0f407f4dea21d0bb7bdda2f6fb..401f4b4a62030a9508b467bffac97e80e939a6f6 100644 --- a/src/Features/Core/Portable/xlf/FeaturesResources.ko.xlf +++ b/src/Features/Core/Portable/xlf/FeaturesResources.ko.xlf @@ -272,11 +272,6 @@ '{0}' 매개 변수(및 재정의/구현) 생성 - - 'GetHashCode' implementation can be simplified - 'GetHashCode' 구현이 간소화될 수 있습니다. - - Implement '{0}' explicitly '{0}'을(를) 명시적으로 구현 @@ -577,11 +572,6 @@ 권장 dispose 패턴을 사용하여 로컬로 범위가 지정된 삭제 가능한 개체가 모든 경로에서 삭제되도록 합니다. 가능한 경우 'using' 문이나 'using' 선언 내에서 생성을 래핑합니다. 그러지 않으면 try 영역 앞에 선언된 전용 지역 변수 및 'finally' 영역에 있는 null이 아닌 값의 비조건부 Dispose 호출('x?.Dispose()')과 함께 try-finally 패턴을 사용하세요. 개체가 try 영역 내에서 명시적으로 삭제되거나 삭제 소유권이 다른 개체나 메서드로 이전되면 해당 작업 바로 뒤의 지역 변수에 'null'을 할당하여 'finally'에서 이중 삭제를 방지하세요. - - Use 'System.HashCode' - 'System.HashCode' 사용 - - Use block body for lambda expressions 람다 식에 블록 본문 사용 diff --git a/src/Features/Core/Portable/xlf/FeaturesResources.pl.xlf b/src/Features/Core/Portable/xlf/FeaturesResources.pl.xlf index e5aefbfb24d171c4409e9680f320c94e2b455745..c5a9e02a40dff48ca22938dcae5dea3e52f11951 100644 --- a/src/Features/Core/Portable/xlf/FeaturesResources.pl.xlf +++ b/src/Features/Core/Portable/xlf/FeaturesResources.pl.xlf @@ -272,11 +272,6 @@ Generowanie parametru „{0}” (i przesłonięć/implementacji) - - 'GetHashCode' implementation can be simplified - Implementację „GetHashCode” można uprościć - - Implement '{0}' explicitly Jawnie zaimplementuj interfejs „{0}” @@ -577,11 +572,6 @@ Użyj zalecanego wzorca likwidacji, aby upewnić się, że obiekty możliwe do likwidacji w lokalnym zakresie są likwidowane we wszystkich ścieżkach. Jeśli to możliwe, opakuj tworzenie w instrukcji „using” lub deklaracji „using”. W przeciwnym razie użyj wzorca try-finally z dedykowaną zmienną lokalną zadeklarowaną przed regionem try i bezwarunkowym wywołaniem metody Dispose dla wartości innej niż null w regionie „finally”, na przykład „x?.Dispose()”. Jeśli obiekt jest jawnie likwidowany w regionie try lub własność dispose jest przenoszona do innego obiektu lub metody, przypisz wartość „null” do zmiennej lokalnej zaraz po takiej operacji, aby zapobiec podwójnemu wywołaniu dispose w regionie „finally” - - Use 'System.HashCode' - Użyj elementu „System.HashCode” - - Use block body for lambda expressions Użyj treści bloku dla wyrażeń lambda diff --git a/src/Features/Core/Portable/xlf/FeaturesResources.pt-BR.xlf b/src/Features/Core/Portable/xlf/FeaturesResources.pt-BR.xlf index 51affd8e2a5788da64e90ca09963ebf5550ce1c9..7d5bd0dd176448f19c80de3b27045a3e81a330d4 100644 --- a/src/Features/Core/Portable/xlf/FeaturesResources.pt-BR.xlf +++ b/src/Features/Core/Portable/xlf/FeaturesResources.pt-BR.xlf @@ -272,11 +272,6 @@ Gerar o parâmetro '{0}' (e as substituições/implementações) - - 'GetHashCode' implementation can be simplified - A implementação de 'GetHashCode' pode ser simplificada - - Implement '{0}' explicitly Implementar '{0}' explicitamente @@ -577,11 +572,6 @@ Use o padrão de descarte recomendado para garantir que os objetos descartáveis no escopo local sejam descartados em todos os caminhos. Se possível, encapsule a criação em uma instrução 'using' ou em uma declaração 'using'. Caso contrário, use um padrão try-finally, com uma variável local dedicada declarada antes da região try e uma invocação de Dispose incondicional em um valor que não seja nulo na região 'finally', como 'x?.Dispose()'. Se o objeto for descartado explicitamente dentro da região try ou se a propriedade de descarte for transferida para outro objeto ou método, atribua 'null' à variável local logo após essa operação para evitar um descarte duplo em 'finally' - - Use 'System.HashCode' - Use 'System.HashCode' - - Use block body for lambda expressions Usar o corpo do bloco para expressões lambda diff --git a/src/Features/Core/Portable/xlf/FeaturesResources.ru.xlf b/src/Features/Core/Portable/xlf/FeaturesResources.ru.xlf index 13633c0ed8104739a724cc420834d6e45accc28f..d9d99735279f1ed4d12b8e7bbcee6ca790963a7f 100644 --- a/src/Features/Core/Portable/xlf/FeaturesResources.ru.xlf +++ b/src/Features/Core/Portable/xlf/FeaturesResources.ru.xlf @@ -272,11 +272,6 @@ Создать параметр "{0}" (а также переопределения или реализации) - - 'GetHashCode' implementation can be simplified - Реализацию "GetHashCode" можно упростить. - - Implement '{0}' explicitly Реализовать "{0}" явно @@ -577,11 +572,6 @@ Используйте рекомендуемый шаблон для корректного освобождения объектов в локальной области по всем путям. По возможности создание следует заключить в оператор using или объявление using. Если это невозможно, используйте шаблон try-finally с выделенной локальной переменной, объявляемой до области try, и безусловным вызовом Dispose для отличного от NULL значения в области finally, например: x?.Dispose(). Если объект явно освобождается в области try или владение освобождением передается другому объекту или методу, то сразу после такой операции присвойте локальной переменной значение NULL, чтобы предотвратить двойное освобождение в finally. - - Use 'System.HashCode' - Используйте "System.HashCode". - - Use block body for lambda expressions Использовать тело блока для лямбда-выражений diff --git a/src/Features/Core/Portable/xlf/FeaturesResources.tr.xlf b/src/Features/Core/Portable/xlf/FeaturesResources.tr.xlf index 142b62611b87f89b8dee10faf48cf360e58e945c..9701ef1f484c1de0a881be2b8bf1417dd9b15c4d 100644 --- a/src/Features/Core/Portable/xlf/FeaturesResources.tr.xlf +++ b/src/Features/Core/Portable/xlf/FeaturesResources.tr.xlf @@ -272,11 +272,6 @@ '{0}' parametresini (ve geçersiz kılmaları/uygulamaları) üret - - 'GetHashCode' implementation can be simplified - 'GetHashCode' uygulaması basitleştirilebilir - - Implement '{0}' explicitly '{0}' öğesini açıkça uygula @@ -577,11 +572,6 @@ Yerel olarak kapsamı oluşturulan atılabilir nesnelerin tüm yollarda atıldığından emin olmak için önerilen atma desenini kullanın. Mümkünse, oluşturulan nesneyi 'using' deyimi veya 'using' bildirimiyle sarmalayın. Aksi halde, try bölgesinden önce bildirilen ayrılmış bir yerel değişkeni ve 'finally' bölgesinde null olmayan değer üzerinde koşulsuz bir Dispose çağrısı (örneğin, 'x?.Dispose()') olan bir try-finally deseni kullanın. Nesne try bölgesi içinde açıkça atıldıysa veya atma sahipliği başka bir nesne ya da metoda aktarıldıysa, 'finally' bölgesinde çift atma gerçekleşmesini önlemek için bu tür bir işlemden hemen sonra yerel değişkene 'null' atayın - - Use 'System.HashCode' - 'System.HashCode' kullan - - Use block body for lambda expressions Lambda ifadeleri için blok vücut kullanımı diff --git a/src/Features/Core/Portable/xlf/FeaturesResources.zh-Hans.xlf b/src/Features/Core/Portable/xlf/FeaturesResources.zh-Hans.xlf index 7e99b2643df3d17cefb495af8541564a4a8e6416..7f849973add0aafd5bc8a5c927de6a5704ee60ae 100644 --- a/src/Features/Core/Portable/xlf/FeaturesResources.zh-Hans.xlf +++ b/src/Features/Core/Portable/xlf/FeaturesResources.zh-Hans.xlf @@ -272,11 +272,6 @@ 生成参数 {0}(和重写/实现) - - 'GetHashCode' implementation can be simplified - 可简化 "GetHashCode" 实现 - - Implement '{0}' explicitly 显式实现 "{0}" @@ -577,11 +572,6 @@ 使用推荐的释放模式以确保在所有路径中释放局部可释放对象。如果可能,请将创建包装在 "using" 语句或 "using" 声明中。否则,请使用 try-finally 模式,在 try 区域之前声明一个专用的局部变量,在 "finally" 区域中对非 null 值进行无条件 Dispose 调用,比如,"x?.Dispose()"。如果对象显式释放在 try 区域内或释放所有权转让给另一个对象或方法,则在这样的操作之后立即将 "null" 分配给局部变量,以防止在 "finally" 中进行双重释放。 - - Use 'System.HashCode' - 使用 "System.HashCode" - - Use block body for lambda expressions 对 lambda 表达式使用块主体 diff --git a/src/Features/Core/Portable/xlf/FeaturesResources.zh-Hant.xlf b/src/Features/Core/Portable/xlf/FeaturesResources.zh-Hant.xlf index 88c82320bccf9311f1f333ef4e76c80e5fa30254..4326906d039e3816078aaa8b2cea71ce8cd2a468 100644 --- a/src/Features/Core/Portable/xlf/FeaturesResources.zh-Hant.xlf +++ b/src/Features/Core/Portable/xlf/FeaturesResources.zh-Hant.xlf @@ -272,11 +272,6 @@ 產生參數 '{0}' (以及覆寫/實作) - - 'GetHashCode' implementation can be simplified - 'GetHashCode' 實作可簡化 - - Implement '{0}' explicitly 明確實作 '{0}' @@ -577,11 +572,6 @@ 請使用建議的處置模式,確保區域範圍的可處置物件在所有路徑上均會經過處置。在可能的情況下,請將建立包在 'using' 陳述式或 'using' 宣告內。否則,請使用 try-finally 模式,同時在 try 區域之前先宣告專用的區域變數,並在 'finally' 區域中的非 null 值上,設定無條件 Dispose 引動過程,比如 'x?.Dispose()'。如果 try 區域內已明確地處置了該物件,或是處置擁有權已轉移到另一個物件或方法,則請在這類作業之後,對區域變數指派 'null',以避免在 'finally' 中發生雙重處置 - - Use 'System.HashCode' - 使用 'System.HashCode' - - Use block body for lambda expressions 使用 Lambda 運算式的區塊主體 diff --git a/src/Workspaces/CSharp/Portable/CodeGeneration/CSharpSyntaxGenerator.cs b/src/Workspaces/CSharp/Portable/CodeGeneration/CSharpSyntaxGenerator.cs index e6f7fce0795a0095fb3a0cc8fba93a49d939164a..dc40e854c7fad3109bc977a34798a17fef6b5f49 100644 --- a/src/Workspaces/CSharp/Portable/CodeGeneration/CSharpSyntaxGenerator.cs +++ b/src/Workspaces/CSharp/Portable/CodeGeneration/CSharpSyntaxGenerator.cs @@ -2945,12 +2945,6 @@ public override SyntaxNode ThrowExpression(SyntaxNode expression) internal override bool SupportsThrowExpression() => true; - /// - /// C# always requires a type to be present with a local declaration. (Even if that type is - /// var). - /// - internal override bool RequiresLocalDeclarationType() => true; - public override SyntaxNode IfStatement(SyntaxNode condition, IEnumerable trueStatements, IEnumerable falseStatements = null) { if (falseStatements == null) diff --git a/src/Workspaces/Core/Portable/Editing/SyntaxGenerator.cs b/src/Workspaces/Core/Portable/Editing/SyntaxGenerator.cs index d0ae9bd1d415107d4176f1fbc65d30d8079af5f0..972dcb74db40b4dbc42736a7cccd0a84101527fa 100644 --- a/src/Workspaces/Core/Portable/Editing/SyntaxGenerator.cs +++ b/src/Workspaces/Core/Portable/Editing/SyntaxGenerator.cs @@ -1378,7 +1378,7 @@ internal SyntaxNode YieldReturnStatement(SyntaxNode expression) /// . /// if the language allows the type node to be entirely elided. /// - internal abstract bool RequiresLocalDeclarationType(); + internal bool RequiresLocalDeclarationType() => SyntaxGeneratorInternal.RequiresLocalDeclarationType(); /// /// Creates a statement that declares a single local variable. diff --git a/src/Workspaces/Core/Portable/Shared/Extensions/SyntaxGeneratorExtensions_CreateEqualsMethod.cs b/src/Workspaces/Core/Portable/Shared/Extensions/SyntaxGeneratorExtensions_CreateEqualsMethod.cs index f20944ad177ba13e3cea9f8dd57fec92316b0b8c..be76eb3b7cc6ccbbfcdda5f8b04072833a2409e5 100644 --- a/src/Workspaces/Core/Portable/Shared/Extensions/SyntaxGeneratorExtensions_CreateEqualsMethod.cs +++ b/src/Workspaces/Core/Portable/Shared/Extensions/SyntaxGeneratorExtensions_CreateEqualsMethod.cs @@ -16,11 +16,6 @@ namespace Microsoft.CodeAnalysis.Shared.Extensions { internal static partial class SyntaxGeneratorExtensions { - private const string EqualsName = "Equals"; - private const string DefaultName = "Default"; - private const string ObjName = "obj"; - public const string OtherName = "other"; - public static IMethodSymbol CreateEqualsMethod( this SyntaxGenerator factory, Compilation compilation, @@ -147,7 +142,7 @@ public static IMethodSymbol CreateEqualsMethod(this Compilation compilation, Imm // // var myType = (MyType)obj; - var localDeclaration = factory.SimpleLocalDeclarationStatement( + var localDeclaration = factory.SimpleLocalDeclarationStatement(factory.SyntaxGeneratorInternal, containingType, localName, factory.CastExpression(containingType, objNameExpression)); statements.Add(ifStatement); @@ -159,7 +154,7 @@ public static IMethodSymbol CreateEqualsMethod(this Compilation compilation, Imm // // var myType = obj as MyType; - var localDeclaration = factory.SimpleLocalDeclarationStatement( + var localDeclaration = factory.SimpleLocalDeclarationStatement(factory.SyntaxGeneratorInternal, containingType, localName, factory.TryCastExpression(objNameExpression, containingType)); statements.Add(localDeclaration); @@ -367,26 +362,6 @@ private static bool ShouldUseEqualityOperator(ITypeSymbol typeSymbol) return false; } - public static SyntaxNode GetDefaultEqualityComparer( - this SyntaxGenerator factory, - Compilation compilation, - ITypeSymbol type) - { - var equalityComparerType = compilation.EqualityComparerOfTType(); - var constructedType = equalityComparerType.Construct(type); - return factory.MemberAccessExpression( - factory.TypeExpression(constructedType), - factory.IdentifierName(DefaultName)); - } - - private static ITypeSymbol GetType(Compilation compilation, ISymbol symbol) - => symbol switch - { - IFieldSymbol field => field.Type, - IPropertySymbol property => property.Type, - _ => compilation.GetSpecialType(SpecialType.System_Object), - }; - private static bool HasExistingBaseEqualsMethod(INamedTypeSymbol containingType) { // Check if any of our base types override Equals. If so, first check with them. diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/LanguageServices/CSharpSyntaxGeneratorInternal.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/LanguageServices/CSharpSyntaxGeneratorInternal.cs index c78bf4f09d74d7bc1a01b83aff78d6e18d19661d..3a4feead7a2d96b974f6d75ca70d5e49c1fe3c19 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/LanguageServices/CSharpSyntaxGeneratorInternal.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/LanguageServices/CSharpSyntaxGeneratorInternal.cs @@ -73,5 +73,11 @@ internal static ExpressionSyntax Parenthesize(SyntaxNode expression, bool includ internal override SyntaxNode YieldReturnStatement(SyntaxNode expressionOpt = null) => SyntaxFactory.YieldStatement(SyntaxKind.YieldReturnStatement, (ExpressionSyntax)expressionOpt); + + /// + /// C# always requires a type to be present with a local declaration. (Even if that type is + /// var). + /// + internal override bool RequiresLocalDeclarationType() => true; } } diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Extensions/SyntaxGeneratorExtensions.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Extensions/SyntaxGeneratorExtensions.cs index 8769659106f9152632da23f3ecb32bcbe5f049ea..70a007bf3514852f2638e9e411f0d4b501ccd007 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Extensions/SyntaxGeneratorExtensions.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Extensions/SyntaxGeneratorExtensions.cs @@ -10,6 +10,11 @@ namespace Microsoft.CodeAnalysis.Shared.Extensions { internal static partial class SyntaxGeneratorExtensions { + private const string EqualsName = "Equals"; + private const string DefaultName = "Default"; + private const string ObjName = "obj"; + public const string OtherName = "other"; + public static SyntaxNode CreateThrowNotImplementedStatement( this SyntaxGenerator codeDefinitionFactory, Compilation compilation) { @@ -46,5 +51,25 @@ private static SyntaxNode CreateNotImplementedException(SyntaxGenerator codeDefi { return factory.Argument(parameter.RefKind, factory.IdentifierName(parameter.Name)); } + + public static SyntaxNode GetDefaultEqualityComparer( + this SyntaxGenerator factory, + Compilation compilation, + ITypeSymbol type) + { + var equalityComparerType = compilation.EqualityComparerOfTType(); + var constructedType = equalityComparerType.Construct(type); + return factory.MemberAccessExpression( + factory.TypeExpression(constructedType), + factory.IdentifierName(DefaultName)); + } + + private static ITypeSymbol GetType(Compilation compilation, ISymbol symbol) + => symbol switch + { + IFieldSymbol field => field.Type, + IPropertySymbol property => property.Type, + _ => compilation.GetSpecialType(SpecialType.System_Object), + }; } } diff --git a/src/Workspaces/Core/Portable/Shared/Extensions/SyntaxGeneratorExtensions_CreateGetHashCodeMethod.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Extensions/SyntaxGeneratorExtensions_CreateGetHashCodeMethod.cs similarity index 94% rename from src/Workspaces/Core/Portable/Shared/Extensions/SyntaxGeneratorExtensions_CreateGetHashCodeMethod.cs rename to src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Extensions/SyntaxGeneratorExtensions_CreateGetHashCodeMethod.cs index 426dee9b4f16ae8313100010164d6347221c241a..523ac5fda6637fdb47be07f8d4607e8f2c227e42 100644 --- a/src/Workspaces/Core/Portable/Shared/Extensions/SyntaxGeneratorExtensions_CreateGetHashCodeMethod.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Extensions/SyntaxGeneratorExtensions_CreateGetHashCodeMethod.cs @@ -40,7 +40,8 @@ internal static partial class SyntaxGeneratorExtensions } public static ImmutableArray CreateGetHashCodeStatementsUsingSystemHashCode( - this SyntaxGenerator factory, INamedTypeSymbol hashCodeType, ImmutableArray memberReferences) + this SyntaxGenerator factory, SyntaxGeneratorInternal generatorInternal, + INamedTypeSymbol hashCodeType, ImmutableArray memberReferences) { if (memberReferences.Length <= 8) { @@ -53,7 +54,7 @@ internal static partial class SyntaxGeneratorExtensions const string hashName = "hash"; var statements = ArrayBuilder.GetInstance(); - statements.Add(factory.SimpleLocalDeclarationStatement( + statements.Add(factory.SimpleLocalDeclarationStatement(generatorInternal, hashCodeType, hashName, factory.ObjectCreationExpression(hashCodeType))); var localReference = factory.IdentifierName(hashName); @@ -78,6 +79,7 @@ internal static partial class SyntaxGeneratorExtensions /// public static ImmutableArray CreateGetHashCodeMethodStatements( this SyntaxGenerator factory, + SyntaxGeneratorInternal generatorInternal, Compilation compilation, INamedTypeSymbol containingType, ImmutableArray members, @@ -132,7 +134,7 @@ internal static partial class SyntaxGeneratorExtensions const string HashCodeName = "hashCode"; statements.Add(!useInt64 - ? factory.SimpleLocalDeclarationStatement(compilation.GetSpecialType(SpecialType.System_Int32), HashCodeName, CreateLiteralExpression(factory, initHash)) + ? factory.SimpleLocalDeclarationStatement(generatorInternal, compilation.GetSpecialType(SpecialType.System_Int32), HashCodeName, CreateLiteralExpression(factory, initHash)) : factory.LocalDeclarationStatement(compilation.GetSpecialType(SpecialType.System_Int64), HashCodeName, CreateLiteralExpression(factory, initHash))); var hashCodeNameExpression = factory.IdentifierName(HashCodeName); @@ -175,10 +177,10 @@ internal static partial class SyntaxGeneratorExtensions /// type and let the simplifier decide if it should be var or not. /// private static SyntaxNode SimpleLocalDeclarationStatement( - this SyntaxGenerator generator, INamedTypeSymbol namedTypeSymbol, + this SyntaxGenerator generator, SyntaxGeneratorInternal generatorInternal, INamedTypeSymbol namedTypeSymbol, string name, SyntaxNode initializer) { - return generator.RequiresLocalDeclarationType() + return generatorInternal.RequiresLocalDeclarationType() ? generator.LocalDeclarationStatement(namedTypeSymbol, name, initializer) : generator.LocalDeclarationStatement(name, initializer); } diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/LanguageServices/SyntaxGeneratorInternalExtensions/SyntaxGeneratorInternal.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/LanguageServices/SyntaxGeneratorInternalExtensions/SyntaxGeneratorInternal.cs index 68cca9f55cc653a7f2244d13ada41983b891a972..c2d32c378ea711ec708ffef25411a858c555db8f 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/LanguageServices/SyntaxGeneratorInternalExtensions/SyntaxGeneratorInternal.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/LanguageServices/SyntaxGeneratorInternalExtensions/SyntaxGeneratorInternal.cs @@ -52,5 +52,13 @@ internal SyntaxNode LocalDeclarationStatement(SyntaxToken name, SyntaxNode initi /// /// An expression that can be yielded. internal abstract SyntaxNode YieldReturnStatement(SyntaxNode expression); + + /// + /// if the language requires a "TypeExpression" + /// (including ) to be stated when making a + /// . + /// if the language allows the type node to be entirely elided. + /// + internal abstract bool RequiresLocalDeclarationType(); } } diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/WorkspaceExtensions.projitems b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/WorkspaceExtensions.projitems index 05e5161a97e836726c912f8a2627628b1d74a474..e9e13ff7a7faee551d57f9c9e2b2b0a5ed10515d 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/WorkspaceExtensions.projitems +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/WorkspaceExtensions.projitems @@ -12,6 +12,7 @@ + diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/VisualBasic/LanguageServices/VisualBasicSyntaxGeneratorInternal.vb b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/VisualBasic/LanguageServices/VisualBasicSyntaxGeneratorInternal.vb index d9c2159f1a501fdbd72ae118031c53d9e590654c..1c74dbefa75d1757ed67a5f17e4c85995617e5be 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/VisualBasic/LanguageServices/VisualBasicSyntaxGeneratorInternal.vb +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Workspace/VisualBasic/LanguageServices/VisualBasicSyntaxGeneratorInternal.vb @@ -80,5 +80,11 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.CodeGeneration Friend Overrides Function YieldReturnStatement(expression As SyntaxNode) As SyntaxNode Return SyntaxFactory.YieldStatement(DirectCast(expression, ExpressionSyntax)) End Function + + Friend Overrides Function RequiresLocalDeclarationType() As Boolean + ' VB supports `dim x = ...` as well as `dim x as Y = ...`. The local declaration type + ' is not required. + Return False + End Function End Class End Namespace diff --git a/src/Workspaces/VisualBasic/Portable/CodeGeneration/VisualBasicSyntaxGenerator.vb b/src/Workspaces/VisualBasic/Portable/CodeGeneration/VisualBasicSyntaxGenerator.vb index c90bf2dfa96fe2f61bd38bf3d72f45e1989a8a75..892ba346cbd0ccb0c80569a20a900c2c1ff02801 100644 --- a/src/Workspaces/VisualBasic/Portable/CodeGeneration/VisualBasicSyntaxGenerator.vb +++ b/src/Workspaces/VisualBasic/Portable/CodeGeneration/VisualBasicSyntaxGenerator.vb @@ -3721,12 +3721,6 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.CodeGeneration Return False End Function - Friend Overrides Function RequiresLocalDeclarationType() As Boolean - ' VB supports `dim x = ...` as well as `dim x as Y = ...`. The local declaration type - ' is not required. - Return False - End Function - Friend Overrides Function IsPatternExpression(expression As SyntaxNode, pattern As SyntaxNode) As SyntaxNode Throw New NotImplementedException() End Function