未验证 提交 02b346f0 编写于 作者: M Manish Vasani 提交者: GitHub

Merge pull request #43076 from mavasani/PortUseSystemHashCode

Port UseSystemHashCode analyzer/fixer/tests to shared layer
......@@ -73,8 +73,10 @@
<Compile Include="$(MSBuildThisFileDirectory)UsePatternMatching\CSharpAsAndNullCheckTests_FixAllTests.cs" />
<Compile Include="$(MSBuildThisFileDirectory)UsePatternMatching\CSharpIsAndCastCheckDiagnosticAnalyzerTests.cs" />
<Compile Include="$(MSBuildThisFileDirectory)UsePatternMatching\CSharpIsAndCastCheckDiagnosticAnalyzerTests_FixAllTests.cs" />
<Compile Include="$(MSBuildThisFileDirectory)UseSystemHashCode\UseSystemHashCodeTests.cs" />
<Compile Include="$(MSBuildThisFileDirectory)UseThrowExpression\UseThrowExpressionTests.cs" />
<Compile Include="$(MSBuildThisFileDirectory)UseThrowExpression\UseThrowExpressionTests_FixAllTests.cs" />
<Compile Include="$(MSBuildThisFileDirectory)UseVarTestExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)ValidateFormatString\ValidateFormatStringTests.cs" />
</ItemGroup>
<ItemGroup Condition="'$(DefaultLanguageSourceExtension)' != '' AND '$(BuildingInsideVisualStudio)' != 'true'">
......
......@@ -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")]
......
......@@ -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
{
......
......@@ -67,6 +67,9 @@
<Compile Include="$(MSBuildThisFileDirectory)UseNullPropagation\AbstractUseNullPropagationDiagnosticAnalyzer.cs" />
<Compile Include="$(MSBuildThisFileDirectory)UseObjectInitializer\AbstractUseObjectInitializerDiagnosticAnalyzer.cs" />
<Compile Include="$(MSBuildThisFileDirectory)UseObjectInitializer\ObjectCreationExpressionAnalyzer.cs" />
<Compile Include="$(MSBuildThisFileDirectory)UseSystemHashCode\Analyzer.cs" />
<Compile Include="$(MSBuildThisFileDirectory)UseSystemHashCode\Analyzer.OperationDeconstructor.cs" />
<Compile Include="$(MSBuildThisFileDirectory)UseSystemHashCode\UseSystemHashCodeDiagnosticAnalyzer.cs" />
<Compile Include="$(MSBuildThisFileDirectory)UseThrowExpression\AbstractUseThrowExpressionDiagnosticAnalyzer.cs" />
<Compile Include="$(MSBuildThisFileDirectory)ValidateFormatString\AbstractValidateFormatStringDiagnosticAnalyzer.cs" />
<Compile Include="$(MSBuildThisFileDirectory)ValidateFormatString\ValidateFormatStringOption.cs" />
......
......@@ -265,6 +265,12 @@
<data name="Use_explicitly_provided_tuple_name" xml:space="preserve">
<value>Use explicitly provided tuple name</value>
</data>
<data name="Use_System_HashCode" xml:space="preserve">
<value>Use 'System.HashCode'</value>
</data>
<data name="GetHashCode_implementation_can_be_simplified" xml:space="preserve">
<value>'GetHashCode' implementation can be simplified</value>
</data>
<data name="Use_compound_assignment" xml:space="preserve">
<value>Use compound assignment</value>
</data>
......
......@@ -14,7 +14,7 @@
namespace Microsoft.CodeAnalysis.UseSystemHashCode
{
/// <summary>
/// Helper code to support both <see cref="UseSystemHashCodeCodeFixProvider"/> and
/// Helper code to support both "UseSystemHashCodeCodeFixProvider" and
/// <see cref="UseSystemHashCodeDiagnosticAnalyzer"/>.
/// </summary>
internal partial struct Analyzer
......
......@@ -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)))
{
}
......
......@@ -77,6 +77,11 @@
<target state="new">Format string contains invalid placeholder</target>
<note />
</trans-unit>
<trans-unit id="GetHashCode_implementation_can_be_simplified">
<source>'GetHashCode' implementation can be simplified</source>
<target state="new">'GetHashCode' implementation can be simplified</target>
<note />
</trans-unit>
<trans-unit id="Invalid_format_string">
<source>Invalid format string</source>
<target state="new">Invalid format string</target>
......@@ -247,6 +252,11 @@
<target state="new">Unnecessary assignment of a value to '{0}'</target>
<note />
</trans-unit>
<trans-unit id="Use_System_HashCode">
<source>Use 'System.HashCode'</source>
<target state="new">Use 'System.HashCode'</target>
<note />
</trans-unit>
<trans-unit id="Use_coalesce_expression">
<source>Use coalesce expression</source>
<target state="new">Use coalesce expression</target>
......
......@@ -77,6 +77,11 @@
<target state="new">Format string contains invalid placeholder</target>
<note />
</trans-unit>
<trans-unit id="GetHashCode_implementation_can_be_simplified">
<source>'GetHashCode' implementation can be simplified</source>
<target state="new">'GetHashCode' implementation can be simplified</target>
<note />
</trans-unit>
<trans-unit id="Invalid_format_string">
<source>Invalid format string</source>
<target state="new">Invalid format string</target>
......@@ -247,6 +252,11 @@
<target state="new">Unnecessary assignment of a value to '{0}'</target>
<note />
</trans-unit>
<trans-unit id="Use_System_HashCode">
<source>Use 'System.HashCode'</source>
<target state="new">Use 'System.HashCode'</target>
<note />
</trans-unit>
<trans-unit id="Use_coalesce_expression">
<source>Use coalesce expression</source>
<target state="new">Use coalesce expression</target>
......
......@@ -77,6 +77,11 @@
<target state="new">Format string contains invalid placeholder</target>
<note />
</trans-unit>
<trans-unit id="GetHashCode_implementation_can_be_simplified">
<source>'GetHashCode' implementation can be simplified</source>
<target state="new">'GetHashCode' implementation can be simplified</target>
<note />
</trans-unit>
<trans-unit id="Invalid_format_string">
<source>Invalid format string</source>
<target state="new">Invalid format string</target>
......@@ -247,6 +252,11 @@
<target state="new">Unnecessary assignment of a value to '{0}'</target>
<note />
</trans-unit>
<trans-unit id="Use_System_HashCode">
<source>Use 'System.HashCode'</source>
<target state="new">Use 'System.HashCode'</target>
<note />
</trans-unit>
<trans-unit id="Use_coalesce_expression">
<source>Use coalesce expression</source>
<target state="new">Use coalesce expression</target>
......
......@@ -77,6 +77,11 @@
<target state="new">Format string contains invalid placeholder</target>
<note />
</trans-unit>
<trans-unit id="GetHashCode_implementation_can_be_simplified">
<source>'GetHashCode' implementation can be simplified</source>
<target state="new">'GetHashCode' implementation can be simplified</target>
<note />
</trans-unit>
<trans-unit id="Invalid_format_string">
<source>Invalid format string</source>
<target state="new">Invalid format string</target>
......@@ -247,6 +252,11 @@
<target state="new">Unnecessary assignment of a value to '{0}'</target>
<note />
</trans-unit>
<trans-unit id="Use_System_HashCode">
<source>Use 'System.HashCode'</source>
<target state="new">Use 'System.HashCode'</target>
<note />
</trans-unit>
<trans-unit id="Use_coalesce_expression">
<source>Use coalesce expression</source>
<target state="new">Use coalesce expression</target>
......
......@@ -77,6 +77,11 @@
<target state="new">Format string contains invalid placeholder</target>
<note />
</trans-unit>
<trans-unit id="GetHashCode_implementation_can_be_simplified">
<source>'GetHashCode' implementation can be simplified</source>
<target state="new">'GetHashCode' implementation can be simplified</target>
<note />
</trans-unit>
<trans-unit id="Invalid_format_string">
<source>Invalid format string</source>
<target state="new">Invalid format string</target>
......@@ -247,6 +252,11 @@
<target state="new">Unnecessary assignment of a value to '{0}'</target>
<note />
</trans-unit>
<trans-unit id="Use_System_HashCode">
<source>Use 'System.HashCode'</source>
<target state="new">Use 'System.HashCode'</target>
<note />
</trans-unit>
<trans-unit id="Use_coalesce_expression">
<source>Use coalesce expression</source>
<target state="new">Use coalesce expression</target>
......
......@@ -77,6 +77,11 @@
<target state="new">Format string contains invalid placeholder</target>
<note />
</trans-unit>
<trans-unit id="GetHashCode_implementation_can_be_simplified">
<source>'GetHashCode' implementation can be simplified</source>
<target state="new">'GetHashCode' implementation can be simplified</target>
<note />
</trans-unit>
<trans-unit id="Invalid_format_string">
<source>Invalid format string</source>
<target state="new">Invalid format string</target>
......@@ -247,6 +252,11 @@
<target state="new">Unnecessary assignment of a value to '{0}'</target>
<note />
</trans-unit>
<trans-unit id="Use_System_HashCode">
<source>Use 'System.HashCode'</source>
<target state="new">Use 'System.HashCode'</target>
<note />
</trans-unit>
<trans-unit id="Use_coalesce_expression">
<source>Use coalesce expression</source>
<target state="new">Use coalesce expression</target>
......
......@@ -77,6 +77,11 @@
<target state="new">Format string contains invalid placeholder</target>
<note />
</trans-unit>
<trans-unit id="GetHashCode_implementation_can_be_simplified">
<source>'GetHashCode' implementation can be simplified</source>
<target state="new">'GetHashCode' implementation can be simplified</target>
<note />
</trans-unit>
<trans-unit id="Invalid_format_string">
<source>Invalid format string</source>
<target state="new">Invalid format string</target>
......@@ -247,6 +252,11 @@
<target state="new">Unnecessary assignment of a value to '{0}'</target>
<note />
</trans-unit>
<trans-unit id="Use_System_HashCode">
<source>Use 'System.HashCode'</source>
<target state="new">Use 'System.HashCode'</target>
<note />
</trans-unit>
<trans-unit id="Use_coalesce_expression">
<source>Use coalesce expression</source>
<target state="new">Use coalesce expression</target>
......
......@@ -77,6 +77,11 @@
<target state="new">Format string contains invalid placeholder</target>
<note />
</trans-unit>
<trans-unit id="GetHashCode_implementation_can_be_simplified">
<source>'GetHashCode' implementation can be simplified</source>
<target state="new">'GetHashCode' implementation can be simplified</target>
<note />
</trans-unit>
<trans-unit id="Invalid_format_string">
<source>Invalid format string</source>
<target state="new">Invalid format string</target>
......@@ -247,6 +252,11 @@
<target state="new">Unnecessary assignment of a value to '{0}'</target>
<note />
</trans-unit>
<trans-unit id="Use_System_HashCode">
<source>Use 'System.HashCode'</source>
<target state="new">Use 'System.HashCode'</target>
<note />
</trans-unit>
<trans-unit id="Use_coalesce_expression">
<source>Use coalesce expression</source>
<target state="new">Use coalesce expression</target>
......
......@@ -77,6 +77,11 @@
<target state="new">Format string contains invalid placeholder</target>
<note />
</trans-unit>
<trans-unit id="GetHashCode_implementation_can_be_simplified">
<source>'GetHashCode' implementation can be simplified</source>
<target state="new">'GetHashCode' implementation can be simplified</target>
<note />
</trans-unit>
<trans-unit id="Invalid_format_string">
<source>Invalid format string</source>
<target state="new">Invalid format string</target>
......@@ -247,6 +252,11 @@
<target state="new">Unnecessary assignment of a value to '{0}'</target>
<note />
</trans-unit>
<trans-unit id="Use_System_HashCode">
<source>Use 'System.HashCode'</source>
<target state="new">Use 'System.HashCode'</target>
<note />
</trans-unit>
<trans-unit id="Use_coalesce_expression">
<source>Use coalesce expression</source>
<target state="new">Use coalesce expression</target>
......
......@@ -77,6 +77,11 @@
<target state="new">Format string contains invalid placeholder</target>
<note />
</trans-unit>
<trans-unit id="GetHashCode_implementation_can_be_simplified">
<source>'GetHashCode' implementation can be simplified</source>
<target state="new">'GetHashCode' implementation can be simplified</target>
<note />
</trans-unit>
<trans-unit id="Invalid_format_string">
<source>Invalid format string</source>
<target state="new">Invalid format string</target>
......@@ -247,6 +252,11 @@
<target state="new">Unnecessary assignment of a value to '{0}'</target>
<note />
</trans-unit>
<trans-unit id="Use_System_HashCode">
<source>Use 'System.HashCode'</source>
<target state="new">Use 'System.HashCode'</target>
<note />
</trans-unit>
<trans-unit id="Use_coalesce_expression">
<source>Use coalesce expression</source>
<target state="new">Use coalesce expression</target>
......
......@@ -77,6 +77,11 @@
<target state="new">Format string contains invalid placeholder</target>
<note />
</trans-unit>
<trans-unit id="GetHashCode_implementation_can_be_simplified">
<source>'GetHashCode' implementation can be simplified</source>
<target state="new">'GetHashCode' implementation can be simplified</target>
<note />
</trans-unit>
<trans-unit id="Invalid_format_string">
<source>Invalid format string</source>
<target state="new">Invalid format string</target>
......@@ -247,6 +252,11 @@
<target state="new">Unnecessary assignment of a value to '{0}'</target>
<note />
</trans-unit>
<trans-unit id="Use_System_HashCode">
<source>Use 'System.HashCode'</source>
<target state="new">Use 'System.HashCode'</target>
<note />
</trans-unit>
<trans-unit id="Use_coalesce_expression">
<source>Use coalesce expression</source>
<target state="new">Use coalesce expression</target>
......
......@@ -77,6 +77,11 @@
<target state="new">Format string contains invalid placeholder</target>
<note />
</trans-unit>
<trans-unit id="GetHashCode_implementation_can_be_simplified">
<source>'GetHashCode' implementation can be simplified</source>
<target state="new">'GetHashCode' implementation can be simplified</target>
<note />
</trans-unit>
<trans-unit id="Invalid_format_string">
<source>Invalid format string</source>
<target state="new">Invalid format string</target>
......@@ -247,6 +252,11 @@
<target state="new">Unnecessary assignment of a value to '{0}'</target>
<note />
</trans-unit>
<trans-unit id="Use_System_HashCode">
<source>Use 'System.HashCode'</source>
<target state="new">Use 'System.HashCode'</target>
<note />
</trans-unit>
<trans-unit id="Use_coalesce_expression">
<source>Use coalesce expression</source>
<target state="new">Use coalesce expression</target>
......
......@@ -77,6 +77,11 @@
<target state="new">Format string contains invalid placeholder</target>
<note />
</trans-unit>
<trans-unit id="GetHashCode_implementation_can_be_simplified">
<source>'GetHashCode' implementation can be simplified</source>
<target state="new">'GetHashCode' implementation can be simplified</target>
<note />
</trans-unit>
<trans-unit id="Invalid_format_string">
<source>Invalid format string</source>
<target state="new">Invalid format string</target>
......@@ -247,6 +252,11 @@
<target state="new">Unnecessary assignment of a value to '{0}'</target>
<note />
</trans-unit>
<trans-unit id="Use_System_HashCode">
<source>Use 'System.HashCode'</source>
<target state="new">Use 'System.HashCode'</target>
<note />
</trans-unit>
<trans-unit id="Use_coalesce_expression">
<source>Use coalesce expression</source>
<target state="new">Use coalesce expression</target>
......
......@@ -41,6 +41,7 @@
<Compile Include="$(MSBuildThisFileDirectory)UseExplicitTupleName\UseExplicitTupleNameCodeFixProvider.cs" />
<Compile Include="$(MSBuildThisFileDirectory)UseNullPropagation\AbstractUseNullPropagationCodeFixProvider.cs" />
<Compile Include="$(MSBuildThisFileDirectory)UseObjectInitializer\AbstractUseObjectInitializerCodeFixProvider.cs" />
<Compile Include="$(MSBuildThisFileDirectory)UseSystemHashCode\UseSystemHashCodeCodeFixProvider.cs" />
<Compile Include="$(MSBuildThisFileDirectory)UseThrowExpression\UseThrowExpressionCodeFixProvider.cs" />
</ItemGroup>
<ItemGroup Condition="'$(DefaultLanguageSourceExtension)' != '' AND '$(BuildingInsideVisualStudio)' != 'true'">
......
......@@ -51,6 +51,7 @@ public override Task RegisterCodeFixesAsync(CodeFixContext context)
SyntaxEditor editor, CancellationToken cancellationToken)
{
var generator = SyntaxGenerator.GetGenerator(document);
var generatorInternal = document.GetRequiredLanguageService<SyntaxGeneratorInternal>();
var declarationService = document.GetLanguageService<ISymbolDeclarationService>();
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<CancellationToken, Task<Document>> createChangedDocument)
: base(FeaturesResources.Use_System_HashCode, createChangedDocument, FeaturesResources.Use_System_HashCode)
: base(AnalyzersResources.Use_System_HashCode, createChangedDocument, AnalyzersResources.Use_System_HashCode)
{
}
}
......
......@@ -40,6 +40,7 @@
<Compile Include="$(MSBuildThisFileDirectory)UseExplicitTupleName\UseExplicitTupleNameTests.vb" />
<Compile Include="$(MSBuildThisFileDirectory)UseNullPropagation\UseNullPropagationTests.vb" />
<Compile Include="$(MSBuildThisFileDirectory)UseObjectInitializer\UseObjectInitializerTests.vb" />
<Compile Include="$(MSBuildThisFileDirectory)UseSystemHashCode\UseSystemHashCodeTests.vb" />
<Compile Include="$(MSBuildThisFileDirectory)ValidateFormatString\ValidateFormatStringTests.vb" />
</ItemGroup>
<ItemGroup Condition="'$(DefaultLanguageSourceExtension)' != '' AND '$(BuildingInsideVisualStudio)' != 'true'">
......
......@@ -1463,12 +1463,6 @@ This version used in: {2}</value>
<data name="Add_null_checks_for_all_parameters" xml:space="preserve">
<value>Add null checks for all parameters</value>
</data>
<data name="Use_System_HashCode" xml:space="preserve">
<value>Use 'System.HashCode'</value>
</data>
<data name="GetHashCode_implementation_can_be_simplified" xml:space="preserve">
<value>'GetHashCode' implementation can be simplified</value>
</data>
<data name="Implement_0_implicitly" xml:space="preserve">
<value>Implement '{0}' implicitly</value>
</data>
......
......@@ -155,12 +155,13 @@ public async Task<Document> 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<Document> 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);
}
}
}
......@@ -272,11 +272,6 @@
<target state="translated">Generovat parametr {0} (a přepsání/implementace)</target>
<note />
</trans-unit>
<trans-unit id="GetHashCode_implementation_can_be_simplified">
<source>'GetHashCode' implementation can be simplified</source>
<target state="translated">Implementace GetHashCode se dá zjednodušit.</target>
<note />
</trans-unit>
<trans-unit id="Implement_0_explicitly">
<source>Implement '{0}' explicitly</source>
<target state="translated">Implementovat rozhraní {0} explicitně</target>
......@@ -577,11 +572,6 @@
<target state="translated">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.</target>
<note />
</trans-unit>
<trans-unit id="Use_System_HashCode">
<source>Use 'System.HashCode'</source>
<target state="translated">Použijte System.HashCode.</target>
<note />
</trans-unit>
<trans-unit id="Use_block_body_for_lambda_expressions">
<source>Use block body for lambda expressions</source>
<target state="translated">Pro lambda výrazy používat text bloku</target>
......
......@@ -272,11 +272,6 @@
<target state="translated">Parameter "{0}" (und Außerkraftsetzungen/Implementierungen) generieren</target>
<note />
</trans-unit>
<trans-unit id="GetHashCode_implementation_can_be_simplified">
<source>'GetHashCode' implementation can be simplified</source>
<target state="translated">Die Implementierung von "GetHashCode" kann vereinfacht werden.</target>
<note />
</trans-unit>
<trans-unit id="Implement_0_explicitly">
<source>Implement '{0}' explicitly</source>
<target state="translated">"{0}" explizit implementieren</target>
......@@ -577,11 +572,6 @@
<target state="translated">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.</target>
<note />
</trans-unit>
<trans-unit id="Use_System_HashCode">
<source>Use 'System.HashCode'</source>
<target state="translated">"System.Hashcode" verwenden</target>
<note />
</trans-unit>
<trans-unit id="Use_block_body_for_lambda_expressions">
<source>Use block body for lambda expressions</source>
<target state="translated">Blocktextkörper für Lambdaausdrücke verwenden</target>
......
......@@ -272,11 +272,6 @@
<target state="translated">Generar el parámetro "{0}" (y reemplazos/implementaciones)</target>
<note />
</trans-unit>
<trans-unit id="GetHashCode_implementation_can_be_simplified">
<source>'GetHashCode' implementation can be simplified</source>
<target state="translated">La implementación de "GetHashCode" se puede simplificar.</target>
<note />
</trans-unit>
<trans-unit id="Implement_0_explicitly">
<source>Implement '{0}' explicitly</source>
<target state="translated">Implementar "{0}" de forma explícita</target>
......@@ -577,11 +572,6 @@
<target state="translated">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".</target>
<note />
</trans-unit>
<trans-unit id="Use_System_HashCode">
<source>Use 'System.HashCode'</source>
<target state="translated">Usar "System.HashCode"</target>
<note />
</trans-unit>
<trans-unit id="Use_block_body_for_lambda_expressions">
<source>Use block body for lambda expressions</source>
<target state="translated">Usar cuerpo del bloque para las expresiones lambda</target>
......
......@@ -272,11 +272,6 @@
<target state="translated">Générer le paramètre '{0}' (et les substitutions/implémentations)</target>
<note />
</trans-unit>
<trans-unit id="GetHashCode_implementation_can_be_simplified">
<source>'GetHashCode' implementation can be simplified</source>
<target state="translated">L'implémentation de 'GetHashCode' peut être simplifiée</target>
<note />
</trans-unit>
<trans-unit id="Implement_0_explicitly">
<source>Implement '{0}' explicitly</source>
<target state="translated">Implémenter '{0}' explicitement</target>
......@@ -577,11 +572,6 @@
<target state="translated">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'</target>
<note />
</trans-unit>
<trans-unit id="Use_System_HashCode">
<source>Use 'System.HashCode'</source>
<target state="translated">Utiliser 'System.HashCode'</target>
<note />
</trans-unit>
<trans-unit id="Use_block_body_for_lambda_expressions">
<source>Use block body for lambda expressions</source>
<target state="translated">Utiliser le corps de bloc pour les expressions lambda</target>
......
......@@ -272,11 +272,6 @@
<target state="translated">Generare il parametro '{0}' (e override/implementazioni)</target>
<note />
</trans-unit>
<trans-unit id="GetHashCode_implementation_can_be_simplified">
<source>'GetHashCode' implementation can be simplified</source>
<target state="translated">L'implementazione di 'GetHashCode' può essere semplificata</target>
<note />
</trans-unit>
<trans-unit id="Implement_0_explicitly">
<source>Implement '{0}' explicitly</source>
<target state="translated">Implementa '{0}' in modo esplicito</target>
......@@ -577,11 +572,6 @@
<target state="translated">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'</target>
<note />
</trans-unit>
<trans-unit id="Use_System_HashCode">
<source>Use 'System.HashCode'</source>
<target state="translated">Usa 'System.HashCode'</target>
<note />
</trans-unit>
<trans-unit id="Use_block_body_for_lambda_expressions">
<source>Use block body for lambda expressions</source>
<target state="translated">Usa il corpo del blocco per le espressioni lambda</target>
......
......@@ -272,11 +272,6 @@
<target state="translated">パラメーター '{0}' の生成 (およびオーバーライド/実装)</target>
<note />
</trans-unit>
<trans-unit id="GetHashCode_implementation_can_be_simplified">
<source>'GetHashCode' implementation can be simplified</source>
<target state="translated">'GetHashCode' の実装を簡略化できます</target>
<note />
</trans-unit>
<trans-unit id="Implement_0_explicitly">
<source>Implement '{0}' explicitly</source>
<target state="translated">'{0}' を明示的に実装する</target>
......@@ -577,11 +572,6 @@
<target state="translated">推奨される破棄パターンを使用して、ローカル スコープの破棄可能なオブジェクトがすべてのパスで破棄されるようにします。可能なら、'using' ステートメントまたは 'using' 宣言内で作成を折り返します。または、try-finally パターンを、try 領域の前で宣言された専用のローカル変数と、'finally' 領域の非 null 値での条件なしの Dispose の呼び出し (例: 'x?.Dispose()') とともに使用します。オブジェクトが try 領域内で明示的に破棄されるか、dispose の所有権が他のオブジェクトまたはメソッドに移される場合、その操作のすぐ後で 'null' をローカル変数に割り当てて、'finally' 内での dispose の重複を回避します</target>
<note />
</trans-unit>
<trans-unit id="Use_System_HashCode">
<source>Use 'System.HashCode'</source>
<target state="translated">'System.HashCode' を使用する</target>
<note />
</trans-unit>
<trans-unit id="Use_block_body_for_lambda_expressions">
<source>Use block body for lambda expressions</source>
<target state="translated">ラムダ式にブロック本体を使用する</target>
......
......@@ -272,11 +272,6 @@
<target state="translated">'{0}' 매개 변수(및 재정의/구현) 생성</target>
<note />
</trans-unit>
<trans-unit id="GetHashCode_implementation_can_be_simplified">
<source>'GetHashCode' implementation can be simplified</source>
<target state="translated">'GetHashCode' 구현이 간소화될 수 있습니다.</target>
<note />
</trans-unit>
<trans-unit id="Implement_0_explicitly">
<source>Implement '{0}' explicitly</source>
<target state="translated">'{0}'을(를) 명시적으로 구현</target>
......@@ -577,11 +572,6 @@
<target state="translated">권장 dispose 패턴을 사용하여 로컬로 범위가 지정된 삭제 가능한 개체가 모든 경로에서 삭제되도록 합니다. 가능한 경우 'using' 문이나 'using' 선언 내에서 생성을 래핑합니다. 그러지 않으면 try 영역 앞에 선언된 전용 지역 변수 및 'finally' 영역에 있는 null이 아닌 값의 비조건부 Dispose 호출('x?.Dispose()')과 함께 try-finally 패턴을 사용하세요. 개체가 try 영역 내에서 명시적으로 삭제되거나 삭제 소유권이 다른 개체나 메서드로 이전되면 해당 작업 바로 뒤의 지역 변수에 'null'을 할당하여 'finally'에서 이중 삭제를 방지하세요.</target>
<note />
</trans-unit>
<trans-unit id="Use_System_HashCode">
<source>Use 'System.HashCode'</source>
<target state="translated">'System.HashCode' 사용</target>
<note />
</trans-unit>
<trans-unit id="Use_block_body_for_lambda_expressions">
<source>Use block body for lambda expressions</source>
<target state="translated">람다 식에 블록 본문 사용</target>
......
......@@ -272,11 +272,6 @@
<target state="translated">Generowanie parametru „{0}” (i przesłonięć/implementacji)</target>
<note />
</trans-unit>
<trans-unit id="GetHashCode_implementation_can_be_simplified">
<source>'GetHashCode' implementation can be simplified</source>
<target state="translated">Implementację „GetHashCode” można uprościć</target>
<note />
</trans-unit>
<trans-unit id="Implement_0_explicitly">
<source>Implement '{0}' explicitly</source>
<target state="translated">Jawnie zaimplementuj interfejs „{0}”</target>
......@@ -577,11 +572,6 @@
<target state="translated">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”</target>
<note />
</trans-unit>
<trans-unit id="Use_System_HashCode">
<source>Use 'System.HashCode'</source>
<target state="translated">Użyj elementu „System.HashCode”</target>
<note />
</trans-unit>
<trans-unit id="Use_block_body_for_lambda_expressions">
<source>Use block body for lambda expressions</source>
<target state="translated">Użyj treści bloku dla wyrażeń lambda</target>
......
......@@ -272,11 +272,6 @@
<target state="translated">Gerar o parâmetro '{0}' (e as substituições/implementações)</target>
<note />
</trans-unit>
<trans-unit id="GetHashCode_implementation_can_be_simplified">
<source>'GetHashCode' implementation can be simplified</source>
<target state="translated">A implementação de 'GetHashCode' pode ser simplificada</target>
<note />
</trans-unit>
<trans-unit id="Implement_0_explicitly">
<source>Implement '{0}' explicitly</source>
<target state="translated">Implementar '{0}' explicitamente</target>
......@@ -577,11 +572,6 @@
<target state="translated">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'</target>
<note />
</trans-unit>
<trans-unit id="Use_System_HashCode">
<source>Use 'System.HashCode'</source>
<target state="translated">Use 'System.HashCode'</target>
<note />
</trans-unit>
<trans-unit id="Use_block_body_for_lambda_expressions">
<source>Use block body for lambda expressions</source>
<target state="translated">Usar o corpo do bloco para expressões lambda</target>
......
......@@ -272,11 +272,6 @@
<target state="translated">Создать параметр "{0}" (а также переопределения или реализации)</target>
<note />
</trans-unit>
<trans-unit id="GetHashCode_implementation_can_be_simplified">
<source>'GetHashCode' implementation can be simplified</source>
<target state="translated">Реализацию "GetHashCode" можно упростить.</target>
<note />
</trans-unit>
<trans-unit id="Implement_0_explicitly">
<source>Implement '{0}' explicitly</source>
<target state="translated">Реализовать "{0}" явно</target>
......@@ -577,11 +572,6 @@
<target state="translated">Используйте рекомендуемый шаблон для корректного освобождения объектов в локальной области по всем путям. По возможности создание следует заключить в оператор using или объявление using. Если это невозможно, используйте шаблон try-finally с выделенной локальной переменной, объявляемой до области try, и безусловным вызовом Dispose для отличного от NULL значения в области finally, например: x?.Dispose(). Если объект явно освобождается в области try или владение освобождением передается другому объекту или методу, то сразу после такой операции присвойте локальной переменной значение NULL, чтобы предотвратить двойное освобождение в finally.</target>
<note />
</trans-unit>
<trans-unit id="Use_System_HashCode">
<source>Use 'System.HashCode'</source>
<target state="translated">Используйте "System.HashCode".</target>
<note />
</trans-unit>
<trans-unit id="Use_block_body_for_lambda_expressions">
<source>Use block body for lambda expressions</source>
<target state="translated">Использовать тело блока для лямбда-выражений</target>
......
......@@ -272,11 +272,6 @@
<target state="translated">'{0}' parametresini (ve geçersiz kılmaları/uygulamaları) üret</target>
<note />
</trans-unit>
<trans-unit id="GetHashCode_implementation_can_be_simplified">
<source>'GetHashCode' implementation can be simplified</source>
<target state="translated">'GetHashCode' uygulaması basitleştirilebilir</target>
<note />
</trans-unit>
<trans-unit id="Implement_0_explicitly">
<source>Implement '{0}' explicitly</source>
<target state="translated">'{0}' öğesini açıkça uygula</target>
......@@ -577,11 +572,6 @@
<target state="translated">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</target>
<note />
</trans-unit>
<trans-unit id="Use_System_HashCode">
<source>Use 'System.HashCode'</source>
<target state="translated">'System.HashCode' kullan</target>
<note />
</trans-unit>
<trans-unit id="Use_block_body_for_lambda_expressions">
<source>Use block body for lambda expressions</source>
<target state="translated">Lambda ifadeleri için blok vücut kullanımı</target>
......
......@@ -272,11 +272,6 @@
<target state="translated">生成参数 {0}(和重写/实现)</target>
<note />
</trans-unit>
<trans-unit id="GetHashCode_implementation_can_be_simplified">
<source>'GetHashCode' implementation can be simplified</source>
<target state="translated">可简化 "GetHashCode" 实现</target>
<note />
</trans-unit>
<trans-unit id="Implement_0_explicitly">
<source>Implement '{0}' explicitly</source>
<target state="translated">显式实现 "{0}"</target>
......@@ -577,11 +572,6 @@
<target state="translated">使用推荐的释放模式以确保在所有路径中释放局部可释放对象。如果可能,请将创建包装在 "using" 语句或 "using" 声明中。否则,请使用 try-finally 模式,在 try 区域之前声明一个专用的局部变量,在 "finally" 区域中对非 null 值进行无条件 Dispose 调用,比如,"x?.Dispose()"。如果对象显式释放在 try 区域内或释放所有权转让给另一个对象或方法,则在这样的操作之后立即将 "null" 分配给局部变量,以防止在 "finally" 中进行双重释放。</target>
<note />
</trans-unit>
<trans-unit id="Use_System_HashCode">
<source>Use 'System.HashCode'</source>
<target state="translated">使用 "System.HashCode"</target>
<note />
</trans-unit>
<trans-unit id="Use_block_body_for_lambda_expressions">
<source>Use block body for lambda expressions</source>
<target state="translated">对 lambda 表达式使用块主体</target>
......
......@@ -272,11 +272,6 @@
<target state="translated">產生參數 '{0}' (以及覆寫/實作)</target>
<note />
</trans-unit>
<trans-unit id="GetHashCode_implementation_can_be_simplified">
<source>'GetHashCode' implementation can be simplified</source>
<target state="translated">'GetHashCode' 實作可簡化</target>
<note />
</trans-unit>
<trans-unit id="Implement_0_explicitly">
<source>Implement '{0}' explicitly</source>
<target state="translated">明確實作 '{0}'</target>
......@@ -577,11 +572,6 @@
<target state="translated">請使用建議的處置模式,確保區域範圍的可處置物件在所有路徑上均會經過處置。在可能的情況下,請將建立包在 'using' 陳述式或 'using' 宣告內。否則,請使用 try-finally 模式,同時在 try 區域之前先宣告專用的區域變數,並在 'finally' 區域中的非 null 值上,設定無條件 Dispose 引動過程,比如 'x?.Dispose()'。如果 try 區域內已明確地處置了該物件,或是處置擁有權已轉移到另一個物件或方法,則請在這類作業之後,對區域變數指派 'null',以避免在 'finally' 中發生雙重處置</target>
<note />
</trans-unit>
<trans-unit id="Use_System_HashCode">
<source>Use 'System.HashCode'</source>
<target state="translated">使用 'System.HashCode'</target>
<note />
</trans-unit>
<trans-unit id="Use_block_body_for_lambda_expressions">
<source>Use block body for lambda expressions</source>
<target state="translated">使用 Lambda 運算式的區塊主體</target>
......
......@@ -2945,12 +2945,6 @@ public override SyntaxNode ThrowExpression(SyntaxNode expression)
internal override bool SupportsThrowExpression() => true;
/// <summary>
/// C# always requires a type to be present with a local declaration. (Even if that type is
/// <c>var</c>).
/// </summary>
internal override bool RequiresLocalDeclarationType() => true;
public override SyntaxNode IfStatement(SyntaxNode condition, IEnumerable<SyntaxNode> trueStatements, IEnumerable<SyntaxNode> falseStatements = null)
{
if (falseStatements == null)
......
......@@ -1378,7 +1378,7 @@ internal SyntaxNode YieldReturnStatement(SyntaxNode expression)
/// <see cref="LocalDeclarationStatement(ITypeSymbol, string, SyntaxNode, bool)"/>.
/// <see langword="false"/> if the language allows the type node to be entirely elided.
/// </summary>
internal abstract bool RequiresLocalDeclarationType();
internal bool RequiresLocalDeclarationType() => SyntaxGeneratorInternal.RequiresLocalDeclarationType();
/// <summary>
/// Creates a statement that declares a single local variable.
......
......@@ -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.
......
......@@ -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);
/// <summary>
/// C# always requires a type to be present with a local declaration. (Even if that type is
/// <c>var</c>).
/// </summary>
internal override bool RequiresLocalDeclarationType() => true;
}
}
......@@ -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),
};
}
}
......@@ -40,7 +40,8 @@ internal static partial class SyntaxGeneratorExtensions
}
public static ImmutableArray<SyntaxNode> CreateGetHashCodeStatementsUsingSystemHashCode(
this SyntaxGenerator factory, INamedTypeSymbol hashCodeType, ImmutableArray<SyntaxNode> memberReferences)
this SyntaxGenerator factory, SyntaxGeneratorInternal generatorInternal,
INamedTypeSymbol hashCodeType, ImmutableArray<SyntaxNode> memberReferences)
{
if (memberReferences.Length <= 8)
{
......@@ -53,7 +54,7 @@ internal static partial class SyntaxGeneratorExtensions
const string hashName = "hash";
var statements = ArrayBuilder<SyntaxNode>.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
/// </summary>
public static ImmutableArray<SyntaxNode> CreateGetHashCodeMethodStatements(
this SyntaxGenerator factory,
SyntaxGeneratorInternal generatorInternal,
Compilation compilation,
INamedTypeSymbol containingType,
ImmutableArray<ISymbol> 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 <c>var</c> or not.
/// </summary>
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);
}
......
......@@ -52,5 +52,13 @@ internal SyntaxNode LocalDeclarationStatement(SyntaxToken name, SyntaxNode initi
/// </summary>
/// <param name="expression">An expression that can be yielded.</param>
internal abstract SyntaxNode YieldReturnStatement(SyntaxNode expression);
/// <summary>
/// <see langword="true"/> if the language requires a "TypeExpression"
/// (including <see langword="var"/>) to be stated when making a
/// <see cref="LocalDeclarationStatement(SyntaxNode, SyntaxToken, SyntaxNode, bool)"/>.
/// <see langword="false"/> if the language allows the type node to be entirely elided.
/// </summary>
internal abstract bool RequiresLocalDeclarationType();
}
}
......@@ -12,6 +12,7 @@
<Compile Include="$(MSBuildThisFileDirectory)Extensions\ContextQuery\SyntaxContext.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\HostWorkspaceServicesExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\SyntaxGeneratorExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\SyntaxGeneratorExtensions_CreateGetHashCodeMethod.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\SyntaxGeneratorExtensions_Negate.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Helpers\SimplificationHelpers.cs" />
<Compile Include="$(MSBuildThisFileDirectory)LanguageServices\AddImports\AbstractAddImportsService.cs" />
......
......@@ -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
......@@ -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
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册