提交 3e544e91 编写于 作者: H Heejae Chang

Merge branch 'dev15.6' of https://github.com/dotnet/roslyn into remoteCancellation

...@@ -26,4 +26,9 @@ ...@@ -26,4 +26,9 @@
<!-- Do not use generic CodeAction.Create to create CodeAction - not useful for tests --> <!-- Do not use generic CodeAction.Create to create CodeAction - not useful for tests -->
<Rule Id="RS0005" Action="None" /> <Rule Id="RS0005" Action="None" />
</Rules> </Rules>
<Rules AnalyzerId="Microsoft.CodeQuality.Analyzers.QualityGuidelines" RuleNamespace="Microsoft.CodeQuality.Analyzers.QualityGuidelines">
<!-- Mark constant field as 'const' instead of static readonly - not useful for tests -->
<Rule Id="CA1802" Action="None" />
</Rules>
</RuleSet> </RuleSet>
\ No newline at end of file
...@@ -36,15 +36,15 @@ ...@@ -36,15 +36,15 @@
<Rule Id="CA1720" Action="None" /> <Rule Id="CA1720" Action="None" />
<Rule Id="CA1721" Action="None" /> <Rule Id="CA1721" Action="None" />
<Rule Id="CA1724" Action="None" /> <Rule Id="CA1724" Action="None" />
<Rule Id="CA1801" Action="None" /> <!-- unused parameters: broken due to https://github.com/dotnet/roslyn/issues/8884 --> <Rule Id="CA1801" Action="None" /> <!-- https://github.com/dotnet/roslyn/issues/20405: Enable rule CA1801 (remove unused parameter) in Roslyn.sln once we have a fixer for it -->
<Rule Id="CA1802" Action="None" /> <!-- broken due to https://github.com/dotnet/roslyn-analyzers/issues/1175 --> <Rule Id="CA1802" Action="Warning" />
<Rule Id="CA1804" Action="None" /> <!-- broken due to incomplete IOperation support --> <Rule Id="CA1804" Action="None" /> <!-- https://github.com/dotnet/roslyn/issues/20406: Enable rule CA1804 (remove unused local) in Roslyn.sln once we have a fixer for it -->
<Rule Id="CA1806" Action="None" /> <!-- "do not ignore results": we do this in many places, for example fire-and-forget async or HRESULTs we don't care about --> <Rule Id="CA1806" Action="None" /> <!-- "do not ignore results": we do this in many places, for example fire-and-forget async or HRESULTs we don't care about -->
<Rule Id="CA1812" Action="None" /> <!-- disabled as we create many internal types via reflection-based mechanisms --> <Rule Id="CA1812" Action="None" /> <!-- disabled as we create many internal types via reflection-based mechanisms -->
<Rule Id="CA1814" Action="None" /> <!-- prefer jagged arrays to multidimensional: a silly piece of advice --> <Rule Id="CA1814" Action="None" /> <!-- prefer jagged arrays to multidimensional: a silly piece of advice -->
<Rule Id="CA1815" Action="None" /> <Rule Id="CA1815" Action="None" />
<Rule Id="CA1821" Action="None" /> <!-- broken due to https://github.com/dotnet/roslyn-analyzers/issues/1176 --> <Rule Id="CA1821" Action="Warning" />
<Rule Id="CA1823" Action="None" /> <!-- "avoid unused private fields": many issues including https://github.com/dotnet/roslyn-analyzers/issues/933 --> <Rule Id="CA1823" Action="None" /> <!-- https://github.com/dotnet/roslyn/issues/20404: Enable rule CA1823 (remove unused field) once we have a fixer for it -->
<Rule Id="CA1824" Action="None" /> <!-- mark assemblies with NeutralResourcesLanguageAttribute --> <Rule Id="CA1824" Action="None" /> <!-- mark assemblies with NeutralResourcesLanguageAttribute -->
<Rule Id="CA2007" Action="Warning" /> <Rule Id="CA2007" Action="Warning" />
<Rule Id="CA2211" Action="None" /> <Rule Id="CA2211" Action="None" />
...@@ -94,7 +94,7 @@ ...@@ -94,7 +94,7 @@
<Rule Id="RS0027" Action="Error" /> <Rule Id="RS0027" Action="Error" />
</Rules> </Rules>
<Rules AnalyzerId="System.Collections.Immutable.Analyzers" RuleNamespace="System.Collections.Immutable.Analyzers"> <Rules AnalyzerId="System.Collections.Immutable.Analyzers" RuleNamespace="System.Collections.Immutable.Analyzers">
<Rule Id="RS0012" Action="None" /> <Rule Id="RS0012" Action="Warning" />
</Rules> </Rules>
<Rules AnalyzerId="System.Runtime.Analyzers" RuleNamespace="System.Runtime.Analyzers"> <Rules AnalyzerId="System.Runtime.Analyzers" RuleNamespace="System.Runtime.Analyzers">
<Rule Id="CA1305" Action="None" /> <Rule Id="CA1305" Action="None" />
...@@ -102,7 +102,7 @@ ...@@ -102,7 +102,7 @@
<Rule Id="CA1308" Action="None" /> <Rule Id="CA1308" Action="None" />
<Rule Id="CA1810" Action="None" /> <Rule Id="CA1810" Action="None" />
<Rule Id="CA1816" Action="None" /> <Rule Id="CA1816" Action="None" />
<Rule Id="CA1825" Action="None" /> <Rule Id="CA1825" Action="Warning" />
<Rule Id="CA2002" Action="None" /> <Rule Id="CA2002" Action="None" />
<Rule Id="CA2207" Action="None" /> <Rule Id="CA2207" Action="None" />
<Rule Id="CA2208" Action="None" /> <Rule Id="CA2208" Action="None" />
...@@ -110,7 +110,7 @@ ...@@ -110,7 +110,7 @@
<Rule Id="CA2219" Action="None" /> <Rule Id="CA2219" Action="None" />
<Rule Id="CA2241" Action="None" /> <Rule Id="CA2241" Action="None" />
<Rule Id="CA2242" Action="None" /> <Rule Id="CA2242" Action="None" />
<Rule Id="RS0014" Action="None" /> <Rule Id="RS0014" Action="Warning" />
</Rules> </Rules>
<Rules AnalyzerId="System.Runtime.InteropServices.Analyzers" RuleNamespace="System.Runtime.InteropServices.Analyzers"> <Rules AnalyzerId="System.Runtime.InteropServices.Analyzers" RuleNamespace="System.Runtime.InteropServices.Analyzers">
<Rule Id="CA1401" Action="None" /> <Rule Id="CA1401" Action="None" />
......
...@@ -46,7 +46,7 @@ ...@@ -46,7 +46,7 @@
<MicrosoftMetadataVisualizerVersion>1.0.0-beta1-61531-03</MicrosoftMetadataVisualizerVersion> <MicrosoftMetadataVisualizerVersion>1.0.0-beta1-61531-03</MicrosoftMetadataVisualizerVersion>
<MicrosoftMSXMLVersion>8.0.0.0-alpha</MicrosoftMSXMLVersion> <MicrosoftMSXMLVersion>8.0.0.0-alpha</MicrosoftMSXMLVersion>
<MicrosoftNetCompilersVersion>2.3.0-beta3-61821-14</MicrosoftNetCompilersVersion> <MicrosoftNetCompilersVersion>2.3.0-beta3-61821-14</MicrosoftNetCompilersVersion>
<MicrosoftNetRoslynDiagnosticsVersion>2.0.0-beta1-61628-06</MicrosoftNetRoslynDiagnosticsVersion> <MicrosoftNetRoslynDiagnosticsVersion>2.3.0-beta1</MicrosoftNetRoslynDiagnosticsVersion>
<MicrosoftNetCoreILAsmVersion>1.1.0</MicrosoftNetCoreILAsmVersion> <MicrosoftNetCoreILAsmVersion>1.1.0</MicrosoftNetCoreILAsmVersion>
<MicrosoftNETCoreCompilersVersion>2.3.0-beta3-61821-14</MicrosoftNETCoreCompilersVersion> <MicrosoftNETCoreCompilersVersion>2.3.0-beta3-61821-14</MicrosoftNETCoreCompilersVersion>
<MicrosoftNETCoreVersion>5.0.0</MicrosoftNETCoreVersion> <MicrosoftNETCoreVersion>5.0.0</MicrosoftNETCoreVersion>
......
...@@ -15,7 +15,7 @@ ...@@ -15,7 +15,7 @@
<VSIXExpInstallerPackageName>RoslynTools.Microsoft.VSIXExpInstaller</VSIXExpInstallerPackageName> <VSIXExpInstallerPackageName>RoslynTools.Microsoft.VSIXExpInstaller</VSIXExpInstallerPackageName>
<VSIXExpInstallerPackageVersion>0.2.1-beta</VSIXExpInstallerPackageVersion> <VSIXExpInstallerPackageVersion>0.2.1-beta</VSIXExpInstallerPackageVersion>
<RoslynDiagnosticsNugetPackageVersion>$(MicrosoftNetRoslynDiagnosticsVersion)</RoslynDiagnosticsNugetPackageVersion> <RoslynDiagnosticsNugetPackageVersion>$(MicrosoftNetRoslynDiagnosticsVersion)</RoslynDiagnosticsNugetPackageVersion>
<RoslynDiagnosticsPropsFilePath>$(NuGetPackageRoot)\Microsoft.Net.RoslynDiagnostics\$(RoslynDiagnosticsNugetPackageVersion)\build\Microsoft.Net.RoslynDiagnostics.props</RoslynDiagnosticsPropsFilePath> <RoslynDiagnosticsPropsFilePath>$(NuGetPackageRoot)\Microsoft.Net.RoslynDiagnostics\$(RoslynDiagnosticsNugetPackageVersion)\roslyn\Microsoft.Net.RoslynDiagnostics.props</RoslynDiagnosticsPropsFilePath>
<RoslynBuildUtilFilePath>$(NuGetPackageRoot)\Roslyn.Build.Util\0.9.4-portable\lib\dotnet\Roslyn.MSBuild.Util.dll</RoslynBuildUtilFilePath> <RoslynBuildUtilFilePath>$(NuGetPackageRoot)\Roslyn.Build.Util\0.9.4-portable\lib\dotnet\Roslyn.MSBuild.Util.dll</RoslynBuildUtilFilePath>
<RoslynRuntimeIdentifier Condition="'$(RoslynRuntimeIdentifier)' == '' AND '$(OS)' == 'Windows_NT'">win7-x64</RoslynRuntimeIdentifier> <RoslynRuntimeIdentifier Condition="'$(RoslynRuntimeIdentifier)' == '' AND '$(OS)' == 'Windows_NT'">win7-x64</RoslynRuntimeIdentifier>
<Features>strict,IOperation</Features> <Features>strict,IOperation</Features>
......
...@@ -11,8 +11,8 @@ namespace Microsoft.CodeAnalysis.CSharp ...@@ -11,8 +11,8 @@ namespace Microsoft.CodeAnalysis.CSharp
{ {
internal static partial class ErrorFacts internal static partial class ErrorFacts
{ {
private static readonly string s_titleSuffix = "_Title"; private const string s_titleSuffix = "_Title";
private static readonly string s_descriptionSuffix = "_Description"; private const string s_descriptionSuffix = "_Description";
private static readonly Lazy<ImmutableDictionary<ErrorCode, string>> s_helpLinksMap = new Lazy<ImmutableDictionary<ErrorCode, string>>(CreateHelpLinks); private static readonly Lazy<ImmutableDictionary<ErrorCode, string>> s_helpLinksMap = new Lazy<ImmutableDictionary<ErrorCode, string>>(CreateHelpLinks);
private static readonly Lazy<ImmutableDictionary<ErrorCode, string>> s_categoriesMap = new Lazy<ImmutableDictionary<ErrorCode, string>>(CreateCategoriesMap); private static readonly Lazy<ImmutableDictionary<ErrorCode, string>> s_categoriesMap = new Lazy<ImmutableDictionary<ErrorCode, string>>(CreateCategoriesMap);
......
...@@ -4,8 +4,8 @@ namespace Microsoft.CodeAnalysis.CSharp ...@@ -4,8 +4,8 @@ namespace Microsoft.CodeAnalysis.CSharp
{ {
internal static class StateMachineStates internal static class StateMachineStates
{ {
internal readonly static int FinishedStateMachine = -2; internal const int FinishedStateMachine = -2;
internal readonly static int NotStartedStateMachine = -1; internal const int NotStartedStateMachine = -1;
internal readonly static int FirstUnusedState = 0; internal const int FirstUnusedState = 0;
} }
} }
...@@ -28,7 +28,7 @@ internal abstract partial class TypeSymbol : NamespaceOrTypeSymbol, ITypeSymbol ...@@ -28,7 +28,7 @@ internal abstract partial class TypeSymbol : NamespaceOrTypeSymbol, ITypeSymbol
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// TODO (tomat): Consider changing this to an empty name. This name shouldn't ever leak to the user in error messages. // TODO (tomat): Consider changing this to an empty name. This name shouldn't ever leak to the user in error messages.
internal static readonly string ImplicitTypeName = "<invalid-global-code>"; internal const string ImplicitTypeName = "<invalid-global-code>";
// InterfaceInfo for a common case of a type not implementing anything directly or indirectly. // InterfaceInfo for a common case of a type not implementing anything directly or indirectly.
private static readonly InterfaceInfo s_noInterfaces = new InterfaceInfo(); private static readonly InterfaceInfo s_noInterfaces = new InterfaceInfo();
......
...@@ -131,8 +131,8 @@ internal static SyntaxToken CreateMissing(SyntaxKind kind, GreenNode leading, Gr ...@@ -131,8 +131,8 @@ internal static SyntaxToken CreateMissing(SyntaxKind kind, GreenNode leading, Gr
return new MissingTokenWithTrivia(kind, leading, trailing); return new MissingTokenWithTrivia(kind, leading, trailing);
} }
internal static readonly SyntaxKind FirstTokenWithWellKnownText = SyntaxKind.TildeToken; internal const SyntaxKind FirstTokenWithWellKnownText = SyntaxKind.TildeToken;
internal static readonly SyntaxKind LastTokenWithWellKnownText = SyntaxKind.EndOfFileToken; internal const SyntaxKind LastTokenWithWellKnownText = SyntaxKind.EndOfFileToken;
// TODO: eliminate the blank space before the first interesting element? // TODO: eliminate the blank space before the first interesting element?
private static readonly ArrayElement<SyntaxToken>[] s_tokensWithNoTrivia = new ArrayElement<SyntaxToken>[(int)LastTokenWithWellKnownText + 1]; private static readonly ArrayElement<SyntaxToken>[] s_tokensWithNoTrivia = new ArrayElement<SyntaxToken>[(int)LastTokenWithWellKnownText + 1];
......
...@@ -14,7 +14,7 @@ namespace Microsoft.CodeAnalysis.CSharp.UnitTests ...@@ -14,7 +14,7 @@ namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{ {
public class MetadataMemberTests : CSharpTestBase public class MetadataMemberTests : CSharpTestBase
{ {
private static readonly string VTableGapClassIL = @" private const string VTableGapClassIL = @"
.class public auto ansi beforefieldinit Class .class public auto ansi beforefieldinit Class
extends [mscorlib]System.Object extends [mscorlib]System.Object
{ {
......
...@@ -17,7 +17,7 @@ public class NoPia : CSharpTestBase ...@@ -17,7 +17,7 @@ public class NoPia : CSharpTestBase
/// Translation of Roslyn\Main\Open\Compilers\Test\Resources\Core\SymbolsTests\NoPia\Pia1.vb /// Translation of Roslyn\Main\Open\Compilers\Test\Resources\Core\SymbolsTests\NoPia\Pia1.vb
/// Disassembly of Roslyn\Main\Open\Compilers\Test\Resources\Core\SymbolsTests\NoPia\Pia1.dll /// Disassembly of Roslyn\Main\Open\Compilers\Test\Resources\Core\SymbolsTests\NoPia\Pia1.dll
/// </summary> /// </summary>
private static readonly string s_sourcePia1 = private const string s_sourcePia1 =
@" @"
using System; using System;
using System.Reflection; using System.Reflection;
...@@ -58,7 +58,7 @@ public struct S2 ...@@ -58,7 +58,7 @@ public struct S2
/// <summary> /// <summary>
/// Disassembly of Roslyn\Main\Open\Compilers\Test\Resources\Core\SymbolsTests\NoPia\LocalTypes1.dll /// Disassembly of Roslyn\Main\Open\Compilers\Test\Resources\Core\SymbolsTests\NoPia\LocalTypes1.dll
/// </summary> /// </summary>
private static readonly string s_sourceLocalTypes1_IL = private const string s_sourceLocalTypes1_IL =
@" @"
using System; using System;
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;
...@@ -91,7 +91,7 @@ public interface I2 ...@@ -91,7 +91,7 @@ public interface I2
/// <summary> /// <summary>
/// Translation of Roslyn\Main\Open\Compilers\Test\Resources\Core\SymbolsTests\NoPia\LocalTypes1.vb /// Translation of Roslyn\Main\Open\Compilers\Test\Resources\Core\SymbolsTests\NoPia\LocalTypes1.vb
/// </summary> /// </summary>
private static readonly string s_sourceLocalTypes1 = private const string s_sourceLocalTypes1 =
@" @"
using NS1; using NS1;
...@@ -106,7 +106,7 @@ public void Test1(I1 x, I2 y) ...@@ -106,7 +106,7 @@ public void Test1(I1 x, I2 y)
/// <summary> /// <summary>
/// Disassembly of Roslyn\Main\Open\Compilers\Test\Resources\Core\SymbolsTests\NoPia\LocalTypes2.dll /// Disassembly of Roslyn\Main\Open\Compilers\Test\Resources\Core\SymbolsTests\NoPia\LocalTypes2.dll
/// </summary> /// </summary>
private static readonly string s_sourceLocalTypes2_IL = private const string s_sourceLocalTypes2_IL =
@" @"
using NS1; using NS1;
using System; using System;
...@@ -139,7 +139,7 @@ public struct S2 ...@@ -139,7 +139,7 @@ public struct S2
/// <summary> /// <summary>
/// Translation of Roslyn\Main\Open\Compilers\Test\Resources\Core\SymbolsTests\NoPia\LocalTypes2.vb /// Translation of Roslyn\Main\Open\Compilers\Test\Resources\Core\SymbolsTests\NoPia\LocalTypes2.vb
/// </summary> /// </summary>
private static readonly string s_sourceLocalTypes2 = private const string s_sourceLocalTypes2 =
@" @"
using NS1; using NS1;
...@@ -154,7 +154,7 @@ public void Test2(S1 x, S2 y) ...@@ -154,7 +154,7 @@ public void Test2(S1 x, S2 y)
/// <summary> /// <summary>
/// Disassembly of Roslyn\Main\Open\Compilers\Test\Resources\Core\SymbolsTests\NoPia\LocalTypes3.dll /// Disassembly of Roslyn\Main\Open\Compilers\Test\Resources\Core\SymbolsTests\NoPia\LocalTypes3.dll
/// </summary> /// </summary>
private static readonly string s_sourceLocalTypes3_IL = private const string s_sourceLocalTypes3_IL =
@" @"
using System; using System;
using System.Reflection; using System.Reflection;
...@@ -219,7 +219,7 @@ public List<I1> Test6() ...@@ -219,7 +219,7 @@ public List<I1> Test6()
/// <summary> /// <summary>
/// Translation of Roslyn\Main\Open\Compilers\Test\Resources\Core\SymbolsTests\NoPia\LocalTypes3.vb /// Translation of Roslyn\Main\Open\Compilers\Test\Resources\Core\SymbolsTests\NoPia\LocalTypes3.vb
/// </summary> /// </summary>
private static readonly string s_sourceLocalTypes3 = private const string s_sourceLocalTypes3 =
@" @"
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
......
...@@ -171,7 +171,7 @@ struct Name5 {} ...@@ -171,7 +171,7 @@ struct Name5 {}
} }
[WorkItem(527531, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527531")] [WorkItem(527531, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527531")]
[Fact] [Fact(Skip = "https://github.com/dotnet/roslyn/issues/18985")]
public void InterfaceName() public void InterfaceName()
{ {
var text = @" var text = @"
......
...@@ -7841,7 +7841,7 @@ public static int Main() ...@@ -7841,7 +7841,7 @@ public static int Main()
new ErrorDescription { Code = (int)ErrorCode.ERR_CantOverrideNonVirtual, Line = 13, Column = 29 }); new ErrorDescription { Code = (int)ErrorCode.ERR_CantOverrideNonVirtual, Line = 13, Column = 29 });
} }
private static readonly string s_typeWithMixedProperty = @" private const string s_typeWithMixedProperty = @"
.class public auto ansi beforefieldinit Base_VirtGet_Set .class public auto ansi beforefieldinit Base_VirtGet_Set
extends [mscorlib]System.Object extends [mscorlib]System.Object
{ {
......
...@@ -29,8 +29,8 @@ internal class PermissionSetAttributeWithFileReference : Cci.ICustomAttribute ...@@ -29,8 +29,8 @@ internal class PermissionSetAttributeWithFileReference : Cci.ICustomAttribute
{ {
private readonly Cci.ICustomAttribute _sourceAttribute; private readonly Cci.ICustomAttribute _sourceAttribute;
private readonly string _resolvedPermissionSetFilePath; private readonly string _resolvedPermissionSetFilePath;
internal static readonly string FilePropertyName = "File"; internal const string FilePropertyName = "File";
internal static readonly string HexPropertyName = "Hex"; internal const string HexPropertyName = "Hex";
public PermissionSetAttributeWithFileReference(Cci.ICustomAttribute sourceAttribute, string resolvedPermissionSetFilePath) public PermissionSetAttributeWithFileReference(Cci.ICustomAttribute sourceAttribute, string resolvedPermissionSetFilePath)
{ {
......
...@@ -1094,7 +1094,7 @@ protected static ImmutableArray<string> CheckTupleElementNames(int cardinality, ...@@ -1094,7 +1094,7 @@ protected static ImmutableArray<string> CheckTupleElementNames(int cardinality,
#region Diagnostics #region Diagnostics
internal static readonly CompilationStage DefaultDiagnosticsStage = CompilationStage.Compile; internal const CompilationStage DefaultDiagnosticsStage = CompilationStage.Compile;
/// <summary> /// <summary>
/// Gets the diagnostics produced during the parsing stage. /// Gets the diagnostics produced during the parsing stage.
......
...@@ -51,7 +51,7 @@ internal abstract partial class AnalyzerDriver : IDisposable ...@@ -51,7 +51,7 @@ internal abstract partial class AnalyzerDriver : IDisposable
/// This mode should always guarantee that analyzer action callbacks are enabled for generated code, i.e. <see cref="GeneratedCodeAnalysisFlags.Analyze"/> is set. /// This mode should always guarantee that analyzer action callbacks are enabled for generated code, i.e. <see cref="GeneratedCodeAnalysisFlags.Analyze"/> is set.
/// However, the default diagnostic reporting mode is liable to change in future. /// However, the default diagnostic reporting mode is liable to change in future.
/// </remarks> /// </remarks>
internal static readonly GeneratedCodeAnalysisFlags DefaultGeneratedCodeAnalysisFlags = GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics; internal const GeneratedCodeAnalysisFlags DefaultGeneratedCodeAnalysisFlags = GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics;
/// <summary> /// <summary>
/// Map from non-concurrent analyzers to the gate guarding callback into the analyzer. /// Map from non-concurrent analyzers to the gate guarding callback into the analyzer.
......
...@@ -17,9 +17,9 @@ internal static class PathUtilities ...@@ -17,9 +17,9 @@ internal static class PathUtilities
// We consider '/' a directory separator on Unix like systems. // We consider '/' a directory separator on Unix like systems.
// On Windows both / and \ are equally accepted. // On Windows both / and \ are equally accepted.
internal static readonly char DirectorySeparatorChar = PlatformInformation.IsUnix ? '/' : '\\'; internal static readonly char DirectorySeparatorChar = PlatformInformation.IsUnix ? '/' : '\\';
internal static readonly char AltDirectorySeparatorChar = '/'; internal const char AltDirectorySeparatorChar = '/';
internal static readonly string ParentRelativeDirectory = ".."; internal const string ParentRelativeDirectory = "..";
internal static readonly string ThisDirectory = "."; internal const string ThisDirectory = ".";
internal static readonly string DirectorySeparatorStr = new string(DirectorySeparatorChar, 1); internal static readonly string DirectorySeparatorStr = new string(DirectorySeparatorChar, 1);
internal const char VolumeSeparatorChar = ':'; internal const char VolumeSeparatorChar = ':';
internal static bool IsUnixLikePlatform => PlatformInformation.IsUnix; internal static bool IsUnixLikePlatform => PlatformInformation.IsUnix;
......
...@@ -455,8 +455,8 @@ private bool IsMinimalDelta ...@@ -455,8 +455,8 @@ private bool IsMinimalDelta
// Well known dummy cor library types whose refs are used for attaching assembly attributes off within net modules // Well known dummy cor library types whose refs are used for attaching assembly attributes off within net modules
// There is no guarantee the types actually exist in a cor library // There is no guarantee the types actually exist in a cor library
internal static readonly string dummyAssemblyAttributeParentNamespace = "System.Runtime.CompilerServices"; internal const string dummyAssemblyAttributeParentNamespace = "System.Runtime.CompilerServices";
internal static readonly string dummyAssemblyAttributeParentName = "AssemblyAttributesGoHere"; internal const string dummyAssemblyAttributeParentName = "AssemblyAttributesGoHere";
internal static readonly string[,] dummyAssemblyAttributeParentQualifier = { { "", "M" }, { "S", "SM" } }; internal static readonly string[,] dummyAssemblyAttributeParentQualifier = { { "", "M" }, { "S", "SM" } };
private readonly TypeReferenceHandle[,] _dummyAssemblyAttributeParent = { { default(TypeReferenceHandle), default(TypeReferenceHandle) }, { default(TypeReferenceHandle), default(TypeReferenceHandle) } }; private readonly TypeReferenceHandle[,] _dummyAssemblyAttributeParent = { { default(TypeReferenceHandle), default(TypeReferenceHandle) }, { default(TypeReferenceHandle), default(TypeReferenceHandle) } };
......
...@@ -842,22 +842,22 @@ static ObjectWriter() ...@@ -842,22 +842,22 @@ static ObjectWriter()
/// <summary> /// <summary>
/// byte marker mask for encoding compressed uint /// byte marker mask for encoding compressed uint
/// </summary> /// </summary>
internal static readonly byte ByteMarkerMask = 3 << 6; internal const byte ByteMarkerMask = 3 << 6;
/// <summary> /// <summary>
/// byte marker bits for uint encoded in 1 byte. /// byte marker bits for uint encoded in 1 byte.
/// </summary> /// </summary>
internal static readonly byte Byte1Marker = 0; internal const byte Byte1Marker = 0;
/// <summary> /// <summary>
/// byte marker bits for uint encoded in 2 bytes. /// byte marker bits for uint encoded in 2 bytes.
/// </summary> /// </summary>
internal static readonly byte Byte2Marker = 1 << 6; internal const byte Byte2Marker = 1 << 6;
/// <summary> /// <summary>
/// byte marker bits for uint encoded in 4 bytes. /// byte marker bits for uint encoded in 4 bytes.
/// </summary> /// </summary>
internal static readonly byte Byte4Marker = 2 << 6; internal const byte Byte4Marker = 2 << 6;
internal enum EncodingKind : byte internal enum EncodingKind : byte
{ {
......
...@@ -16,7 +16,7 @@ internal abstract class WellKnownAttributeData ...@@ -16,7 +16,7 @@ internal abstract class WellKnownAttributeData
/// For some well-known attributes, the latter case will return string stored in <see cref="StringMissingValue"/> /// For some well-known attributes, the latter case will return string stored in <see cref="StringMissingValue"/>
/// field. /// field.
/// </summary> /// </summary>
public static readonly string StringMissingValue = nameof(StringMissingValue); public const string StringMissingValue = nameof(StringMissingValue);
#if DEBUG #if DEBUG
private bool _isSealed; private bool _isSealed;
......
...@@ -8,7 +8,7 @@ Namespace Microsoft.CodeAnalysis.VisualBasic ...@@ -8,7 +8,7 @@ Namespace Microsoft.CodeAnalysis.VisualBasic
Inherits AbstractLookupSymbolsInfo(Of Symbol) Inherits AbstractLookupSymbolsInfo(Of Symbol)
' TODO: tune pool size ' TODO: tune pool size
Private Shared ReadOnly s_poolSize As Integer = 64 Private Const s_poolSize As Integer = 64
Private Shared ReadOnly s_pool As New ObjectPool(Of LookupSymbolsInfo)(Function() New LookupSymbolsInfo(), s_poolSize) Private Shared ReadOnly s_pool As New ObjectPool(Of LookupSymbolsInfo)(Function() New LookupSymbolsInfo(), s_poolSize)
Private Sub New() Private Sub New()
......
...@@ -8,9 +8,9 @@ Imports Microsoft.CodeAnalysis.VisualBasic.Syntax ...@@ -8,9 +8,9 @@ Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic Namespace Microsoft.CodeAnalysis.VisualBasic
Friend Module StateMachineStates Friend Module StateMachineStates
Public ReadOnly FinishedStateMachine As Integer = -2 Public FinishedStateMachine As Integer = -2
Public ReadOnly NotStartedStateMachine As Integer = -1 Public NotStartedStateMachine As Integer = -1
Public ReadOnly FirstUnusedState As Integer = 0 Public FirstUnusedState As Integer = 0
End Module End Module
End Namespace End Namespace
...@@ -26,7 +26,7 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols ...@@ -26,7 +26,7 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols
' !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ' !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
' TODO (tomat): Consider changing this to an empty name. This name shouldn't ever leak to the user in error messages. ' TODO (tomat): Consider changing this to an empty name. This name shouldn't ever leak to the user in error messages.
Friend Shared ReadOnly ImplicitTypeName As String = "<invalid-global-code>" Friend Const ImplicitTypeName As String = "<invalid-global-code>"
Private Shared ReadOnly s_EmptyTypeSymbols() As TypeSymbol = Array.Empty(Of TypeSymbol) Private Shared ReadOnly s_EmptyTypeSymbols() As TypeSymbol = Array.Empty(Of TypeSymbol)
......
...@@ -546,7 +546,7 @@ End Class ...@@ -546,7 +546,7 @@ End Class
End Module End Module
]]>.Value ]]>.Value
Private Shared ReadOnly s_commonExpectedOutput_ConditionalMethodsTest As String = Private Const s_commonExpectedOutput_ConditionalMethodsTest As String =
"Z.PreservedCalls_AppliedConditional_Method" & vbCrLf & "Z.PreservedCalls_AppliedConditional_Method" & vbCrLf &
"Z.PreservedCalls_InheritedConditional_Method" & vbCrLf & "Z.PreservedCalls_InheritedConditional_Method" & vbCrLf &
"Z.PreservedCalls_MultipleConditional_Method" & vbCrLf & "Z.PreservedCalls_MultipleConditional_Method" & vbCrLf &
......
...@@ -18,7 +18,7 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics ...@@ -18,7 +18,7 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics
Public Class ConversionsTests Public Class ConversionsTests
Inherits BasicTestBase Inherits BasicTestBase
Private Shared ReadOnly s_noConversion As ConversionKind = Nothing Private Const s_noConversion As ConversionKind = Nothing
<Fact()> <Fact()>
Public Sub TryCastDirectCastConversions() Public Sub TryCastDirectCastConversions()
......
...@@ -1431,7 +1431,9 @@ void Method() ...@@ -1431,7 +1431,9 @@ void Method()
public async Task TestSimpleSystemUnsortedUsings1() public async Task TestSimpleSystemUnsortedUsings1()
{ {
await TestAsync( await TestAsync(
@"using B; @"
using C;
using B;
using System; using System;
class Class class Class
...@@ -1451,7 +1453,9 @@ public static void Bar() ...@@ -1451,7 +1453,9 @@ public static void Bar()
} }
} }
}", }",
@"using B; @"
using C;
using B;
using System; using System;
using A; using A;
...@@ -1636,7 +1640,9 @@ void Method() ...@@ -1636,7 +1640,9 @@ void Method()
public async Task TestSimpleSystemUnsortedUsings4() public async Task TestSimpleSystemUnsortedUsings4()
{ {
await TestAsync( await TestAsync(
@"using System; @"
using C;
using System;
using B; using B;
class Class class Class
...@@ -1656,7 +1662,9 @@ public static void Bar() ...@@ -1656,7 +1662,9 @@ public static void Bar()
} }
} }
}", }",
@"using System; @"
using C;
using System;
using B; using B;
using A; using A;
...@@ -4671,6 +4679,111 @@ private void GetEvaluationRuleNames() ...@@ -4671,6 +4679,111 @@ private void GetEvaluationRuleNames()
IEnumerable < Int32 > IEnumerable < Int32 >
return ImmutableArray.CreateRange(); return ImmutableArray.CreateRange();
} }
}");
}
[WorkItem(19796, "https://github.com/dotnet/roslyn/issues/19796")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddImport)]
public async Task TestWhenInRome1()
{
// System is set to be sorted first, but the actual file shows it at the end.
// Keep things sorted, but respect that 'System' is at the end.
await TestAsync(
@"
using B;
using System;
class Class
{
void Method()
{
[|Foo|].Bar();
}
}
namespace A
{
class Foo
{
public static void Bar()
{
}
}
}",
@"
using A;
using B;
using System;
class Class
{
void Method()
{
Foo.Bar();
}
}
namespace A
{
class Foo
{
public static void Bar()
{
}
}
}",
systemSpecialCase: true);
}
[WorkItem(19796, "https://github.com/dotnet/roslyn/issues/19796")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddImport)]
public async Task TestWhenInRome2()
{
// System is set to not be sorted first, but the actual file shows it sorted first.
// Keep things sorted, but respect that 'System' is at the beginning.
await TestAsync(
@"
using System;
using B;
class Class
{
void Method()
{
[|Foo|].Bar();
}
}
namespace A
{
class Foo
{
public static void Bar()
{
}
}
}",
@"
using System;
using A;
using B;
class Class
{
void Method()
{
Foo.Bar();
}
}
namespace A
{
class Foo
{
public static void Bar()
{
}
}
}"); }");
} }
} }
......
...@@ -180,7 +180,7 @@ class Class : IInterface ...@@ -180,7 +180,7 @@ class Class : IInterface
}"); }");
} }
private static readonly string s_tupleElementNamesAttribute = private const string s_tupleElementNamesAttribute =
@"namespace System.Runtime.CompilerServices @"namespace System.Runtime.CompilerServices
{ {
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.ReturnValue | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Event )] [AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.ReturnValue | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Event )]
......
...@@ -127,6 +127,14 @@ ...@@ -127,6 +127,14 @@
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.Remote.ServiceHub" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.Remote.ServiceHub" />
<InternalsVisibleToTest Include="Microsoft.CodeAnalysis.Editor.UI.Wpf" /> <InternalsVisibleToTest Include="Microsoft.CodeAnalysis.Editor.UI.Wpf" />
<InternalsVisibleTo Include="Roslyn.Hosting.Diagnostics" /> <InternalsVisibleTo Include="Roslyn.Hosting.Diagnostics" />
<InternalsVisibleToMonodevelop Include="MonoDevelop.Ide" />
<InternalsVisibleToMonodevelop Include="MonoDevelop.Refactoring" />
<InternalsVisibleToMonodevelop Include="MonoDevelop.CSharpBinding" />
<InternalsVisibleToMonodevelop Include="MonoDevelop.VBNetBinding" />
<InternalsVisibleToMonodevelop Include="MonoDevelop.Ide.Tests" />
<InternalsVisibleToMonodevelop Include="MonoDevelop.Refactoring.Tests" />
<InternalsVisibleToMonodevelop Include="MonoDevelop.CSharpBinding.Tests" />
<InternalsVisibleToMonodevelop Include="MonoDevelop.VBNetBinding.Tests" />
<InternalsVisibleToTest Include="Roslyn.InteractiveWindow.UnitTests" /> <InternalsVisibleToTest Include="Roslyn.InteractiveWindow.UnitTests" />
<InternalsVisibleToTest Include="Roslyn.Services.Editor.CSharp.UnitTests" /> <InternalsVisibleToTest Include="Roslyn.Services.Editor.CSharp.UnitTests" />
<InternalsVisibleToTest Include="Roslyn.Services.Editor.UnitTests" /> <InternalsVisibleToTest Include="Roslyn.Services.Editor.UnitTests" />
......
...@@ -15,7 +15,7 @@ namespace Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.Completion.P ...@@ -15,7 +15,7 @@ namespace Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.Completion.P
{ {
internal sealed class CustomCommitCompletion : Completion3, ICustomCommit internal sealed class CustomCommitCompletion : Completion3, ICustomCommit
{ {
private static readonly string s_glyphCompletionWarning = "GlyphCompletionWarning"; private const string s_glyphCompletionWarning = "GlyphCompletionWarning";
private readonly CompletionPresenterSession _completionPresenterSession; private readonly CompletionPresenterSession _completionPresenterSession;
internal readonly CompletionItem CompletionItem; internal readonly CompletionItem CompletionItem;
private readonly ImageMoniker _imageMoniker; private readonly ImageMoniker _imageMoniker;
......
...@@ -3,6 +3,7 @@ ...@@ -3,6 +3,7 @@
Imports Microsoft.CodeAnalysis.CodeActions Imports Microsoft.CodeAnalysis.CodeActions
Imports Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.CodeFixes
Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.Diagnostics
Imports Microsoft.CodeAnalysis.Editing
Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Diagnostics Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Diagnostics
Imports Microsoft.CodeAnalysis.Remote Imports Microsoft.CodeAnalysis.Remote
Imports Microsoft.CodeAnalysis.Test.Utilities.RemoteHost Imports Microsoft.CodeAnalysis.Test.Utilities.RemoteHost
...@@ -17,9 +18,10 @@ Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeActions.AddImp ...@@ -17,9 +18,10 @@ Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeActions.AddImp
expectedMarkup As String, expectedMarkup As String,
Optional index As Integer = 0, Optional index As Integer = 0,
Optional ignoreTrivia As Boolean = True, Optional ignoreTrivia As Boolean = True,
Optional priority As CodeActionPriority? = Nothing) As Task Optional priority As CodeActionPriority? = Nothing,
Await TestAsync(initialMarkup, expectedMarkup, index, ignoreTrivia, priority, outOfProcess:=False) Optional placeSystemFirst As Boolean = True) As Task
Await TestAsync(initialMarkup, expectedMarkup, index, ignoreTrivia, priority, outOfProcess:=True) Await TestAsync(initialMarkup, expectedMarkup, index, ignoreTrivia, priority, placeSystemFirst, outOfProcess:=False)
Await TestAsync(initialMarkup, expectedMarkup, index, ignoreTrivia, priority, placeSystemFirst, outOfProcess:=True)
End Function End Function
Friend Overloads Async Function TestAsync(initialMarkup As String, Friend Overloads Async Function TestAsync(initialMarkup As String,
...@@ -27,10 +29,13 @@ Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeActions.AddImp ...@@ -27,10 +29,13 @@ Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeActions.AddImp
index As Integer, index As Integer,
ignoreTrivia As Boolean, ignoreTrivia As Boolean,
priority As CodeActionPriority?, priority As CodeActionPriority?,
placeSystemFirst As Boolean,
outOfProcess As Boolean) As Task outOfProcess As Boolean) As Task
Await TestInRegularAndScript1Async( Await TestInRegularAndScript1Async(
initialMarkup, expectedMarkup, index, ignoreTrivia, priority, initialMarkup, expectedMarkup, index, ignoreTrivia, priority,
parameters:=New TestParameters(fixProviderData:=outOfProcess)) parameters:=New TestParameters(
options:=[Option](GenerationOptions.PlaceSystemNamespaceFirst, placeSystemFirst),
fixProviderData:=outOfProcess))
End Function End Function
End Class End Class
...@@ -2355,6 +2360,64 @@ Namespace Y ...@@ -2355,6 +2360,64 @@ Namespace Y
End Module End Module
End Namespace") End Namespace")
End Function End Function
<WorkItem(19796, "https://github.com/dotnet/roslyn/issues/19796")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddImport)>
Public Async Function TestWhenInRome1() As Task
Await TestAsync(
"
Imports System
Imports B
Class Class1
Dim v As [|AType|]
End Class
Namespace A
Public Class AType
End Class
End Namespace",
"
Imports System
Imports A
Imports B
Class Class1
Dim v As AType
End Class
Namespace A
Public Class AType
End Class
End Namespace", placeSystemFirst:=False)
End Function
<WorkItem(19796, "https://github.com/dotnet/roslyn/issues/19796")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddImport)>
Public Async Function TestWhenInRome2() As Task
Await TestAsync(
"
Imports B
Imports System
Class Class1
Dim v As [|AType|]
End Class
Namespace A
Public Class AType
End Class
End Namespace",
"
Imports A
Imports B
Imports System
Class Class1
Dim v As AType
End Class
Namespace A
Public Class AType
End Class
End Namespace", placeSystemFirst:=True)
End Function
End Class End Class
Public Class AddImportTestsWithAddImportDiagnosticProvider Public Class AddImportTestsWithAddImportDiagnosticProvider
......
...@@ -219,7 +219,7 @@ End structure", ...@@ -219,7 +219,7 @@ End structure",
Imports System Imports System
Imports System.Collections.Generic Imports System.Collections.Generic
Structure Program structure Program
Implements IEquatable(Of Program) Implements IEquatable(Of Program)
Public s As String Public s As String
...@@ -231,7 +231,7 @@ Structure Program ...@@ -231,7 +231,7 @@ Structure Program
Public Function Equals(other As Program) As Boolean Implements IEquatable(Of Program).Equals Public Function Equals(other As Program) As Boolean Implements IEquatable(Of Program).Equals
Return s = other.s Return s = other.s
End Function End Function
End Structure", End structure",
chosenSymbols:=Nothing, chosenSymbols:=Nothing,
optionsCallback:=Sub(Options) EnableOption(Options, ImplementIEquatableId), optionsCallback:=Sub(Options) EnableOption(Options, ImplementIEquatableId),
ignoreTrivia:=False) ignoreTrivia:=False)
......
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
#pragma warning disable RS0007 // Avoid zero-length array allocations. #pragma warning disable CA1825 // Avoid zero-length array allocations.
using System; using System;
using System.Collections.ObjectModel; using System.Collections.ObjectModel;
......
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
#pragma warning disable RS0007 // Avoid zero-length array allocations. #pragma warning disable CA1825 // Avoid zero-length array allocations.
using System.Collections.Generic; using System.Collections.Generic;
using System.Collections.ObjectModel; using System.Collections.ObjectModel;
......
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
#pragma warning disable RS0007 // Avoid zero-length array allocations. #pragma warning disable CA1825 // Avoid zero-length array allocations.
using System; using System;
using System.Collections.ObjectModel; using System.Collections.ObjectModel;
......
...@@ -8,7 +8,6 @@ ...@@ -8,7 +8,6 @@
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" /> <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\CodeSharing\Microsoft.CodeSharing.Common.Default.props" /> <Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\CodeSharing\Microsoft.CodeSharing.Common.Default.props" />
<Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\CodeSharing\Microsoft.CodeSharing.Common.props" /> <Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\CodeSharing\Microsoft.CodeSharing.Common.props" />
<PropertyGroup />
<Import Project="ResultProvider.projitems" Label="Shared" /> <Import Project="ResultProvider.projitems" Label="Shared" />
<Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\CodeSharing\Microsoft.CodeSharing.CSharp.targets" /> <Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\CodeSharing\Microsoft.CodeSharing.CSharp.targets" />
</Project> </Project>
\ No newline at end of file
...@@ -12,6 +12,7 @@ ...@@ -12,6 +12,7 @@
<AssemblyName>Roslyn.ExpressionEvaluator.ResultProvider.Test.Utilities</AssemblyName> <AssemblyName>Roslyn.ExpressionEvaluator.ResultProvider.Test.Utilities</AssemblyName>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks> <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<TargetFrameworkVersion>v4.6</TargetFrameworkVersion> <TargetFrameworkVersion>v4.6</TargetFrameworkVersion>
<NoWarn>$(NoWarn);CA1825</NoWarn> <!-- Disable CA1825 (Avoid unnecessary zero-length array allocations. Use Array.Empty<X>() instead) as Array.Empty not available in one of the targets for this shared project -->
</PropertyGroup> </PropertyGroup>
<ItemGroup Label="File References"> <ItemGroup Label="File References">
<Reference Include="Microsoft.CSharp" /> <Reference Include="Microsoft.CSharp" />
......
...@@ -399,7 +399,7 @@ private CompletionItemRules GetRules(string displayText) ...@@ -399,7 +399,7 @@ private CompletionItemRules GetRules(string displayText)
} }
} }
private static readonly string InsertionTextProperty = "insertionText"; private const string InsertionTextProperty = "insertionText";
protected override Task<TextChange?> GetTextChangeAsync(CompletionItem selectedItem, char? ch, CancellationToken cancellationToken) protected override Task<TextChange?> GetTextChangeAsync(CompletionItem selectedItem, char? ch, CancellationToken cancellationToken)
{ {
......
...@@ -10,7 +10,8 @@ ...@@ -10,7 +10,8 @@
namespace Microsoft.CodeAnalysis.CSharp.MakeMethodSynchronous namespace Microsoft.CodeAnalysis.CSharp.MakeMethodSynchronous
{ {
[ExportCodeFixProvider(LanguageNames.CSharp), Shared] [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.MakeMethodSynchronous), Shared]
[ExtensionOrder(After = PredefinedCodeFixProviderNames.AddImport)]
internal class CSharpMakeMethodSynchronousCodeFixProvider : AbstractMakeMethodSynchronousCodeFixProvider internal class CSharpMakeMethodSynchronousCodeFixProvider : AbstractMakeMethodSynchronousCodeFixProvider
{ {
private const string CS1998 = nameof(CS1998); // This async method lacks 'await' operators and will run synchronously. private const string CS1998 = nameof(CS1998); // This async method lacks 'await' operators and will run synchronously.
......
...@@ -98,7 +98,7 @@ public override int GetHashCode() ...@@ -98,7 +98,7 @@ public override int GetHashCode()
document, node, placeSystemNamespaceFirst, hasExistingImport, cancellationToken).ConfigureAwait(false); document, node, placeSystemNamespaceFirst, hasExistingImport, cancellationToken).ConfigureAwait(false);
return GetFixData( return GetFixData(
document, textChanges.ToImmutableArray(), description, document, textChanges, description,
GetTags(document), GetPriority(document)); GetTags(document), GetPriority(document));
} }
......
...@@ -32,6 +32,7 @@ internal static class PredefinedCodeFixProviderNames ...@@ -32,6 +32,7 @@ internal static class PredefinedCodeFixProviderNames
public const string ImplementAbstractClass = nameof(ImplementAbstractClass); public const string ImplementAbstractClass = nameof(ImplementAbstractClass);
public const string ImplementInterface = nameof(ImplementInterface); public const string ImplementInterface = nameof(ImplementInterface);
public const string InsertMissingCast = nameof(InsertMissingCast); public const string InsertMissingCast = nameof(InsertMissingCast);
public const string MakeMethodSynchronous = nameof(MakeMethodSynchronous);
public const string MoveToTopOfFile = nameof(MoveToTopOfFile); public const string MoveToTopOfFile = nameof(MoveToTopOfFile);
public const string PopulateSwitch = nameof(PopulateSwitch); public const string PopulateSwitch = nameof(PopulateSwitch);
public const string QualifyMemberAccess = nameof(QualifyMemberAccess); public const string QualifyMemberAccess = nameof(QualifyMemberAccess);
......
...@@ -19,8 +19,8 @@ namespace Microsoft.CodeAnalysis.CodeFixes.Suppression ...@@ -19,8 +19,8 @@ namespace Microsoft.CodeAnalysis.CodeFixes.Suppression
internal abstract partial class AbstractSuppressionCodeFixProvider : ISuppressionFixProvider internal abstract partial class AbstractSuppressionCodeFixProvider : ISuppressionFixProvider
{ {
public const string SuppressMessageAttributeName = "System.Diagnostics.CodeAnalysis.SuppressMessage"; public const string SuppressMessageAttributeName = "System.Diagnostics.CodeAnalysis.SuppressMessage";
private static readonly string s_globalSuppressionsFileName = "GlobalSuppressions"; private const string s_globalSuppressionsFileName = "GlobalSuppressions";
private static readonly string s_suppressionsFileCommentTemplate = private const string s_suppressionsFileCommentTemplate =
@" @"
{0} This file is used by Code Analysis to maintain SuppressMessage {0} This file is used by Code Analysis to maintain SuppressMessage
{0} attributes that are applied to this project. {0} attributes that are applied to this project.
......
...@@ -19,7 +19,7 @@ internal struct SerializableDocumentHighlights ...@@ -19,7 +19,7 @@ internal struct SerializableDocumentHighlights
public ImmutableArray<HighlightSpan> HighlightSpans; public ImmutableArray<HighlightSpan> HighlightSpans;
public DocumentHighlights Rehydrate(Solution solution) public DocumentHighlights Rehydrate(Solution solution)
=> new DocumentHighlights(solution.GetDocument(DocumentId), HighlightSpans.ToImmutableArray()); => new DocumentHighlights(solution.GetDocument(DocumentId), HighlightSpans);
public static SerializableDocumentHighlights Dehydrate(DocumentHighlights highlights) public static SerializableDocumentHighlights Dehydrate(DocumentHighlights highlights)
=> new SerializableDocumentHighlights => new SerializableDocumentHighlights
......
...@@ -1891,7 +1891,7 @@ internal class FeaturesResources { ...@@ -1891,7 +1891,7 @@ internal class FeaturesResources {
} }
/// <summary> /// <summary>
/// Looks up a localized string similar to Make method synchronous.. /// Looks up a localized string similar to Make method synchronous.
/// </summary> /// </summary>
internal static string Make_method_synchronous { internal static string Make_method_synchronous {
get { get {
......
...@@ -886,7 +886,7 @@ Do you want to continue?</value> ...@@ -886,7 +886,7 @@ Do you want to continue?</value>
<value>Unable to load Analyzer assembly {0}: {1}</value> <value>Unable to load Analyzer assembly {0}: {1}</value>
</data> </data>
<data name="Make_method_synchronous" xml:space="preserve"> <data name="Make_method_synchronous" xml:space="preserve">
<value>Make method synchronous.</value> <value>Make method synchronous</value>
</data> </data>
<data name="Add_this_or_Me_qualification" xml:space="preserve"> <data name="Add_this_or_Me_qualification" xml:space="preserve">
<value>Add 'this' or 'Me' qualification.</value> <value>Add 'this' or 'Me' qualification.</value>
......
...@@ -12,12 +12,12 @@ internal partial class AbstractMetadataAsSourceService ...@@ -12,12 +12,12 @@ internal partial class AbstractMetadataAsSourceService
{ {
internal class DocCommentFormatter internal class DocCommentFormatter
{ {
private static readonly int s_indentSize = 2; private const int s_indentSize = 2;
private static readonly int s_wrapLength = 80; private const int s_wrapLength = 80;
private static readonly string s_summaryHeader = FeaturesResources.Summary_colon; private static readonly string s_summaryHeader = FeaturesResources.Summary_colon;
private static readonly string s_paramHeader = FeaturesResources.Parameters_colon; private static readonly string s_paramHeader = FeaturesResources.Parameters_colon;
private static readonly string s_labelFormat = "{0}:"; private const string s_labelFormat = "{0}:";
private static readonly string s_typeParameterHeader = FeaturesResources.Type_parameters_colon; private static readonly string s_typeParameterHeader = FeaturesResources.Type_parameters_colon;
private static readonly string s_returnsHeader = FeaturesResources.Returns_colon; private static readonly string s_returnsHeader = FeaturesResources.Returns_colon;
private static readonly string s_exceptionsHeader = FeaturesResources.Exceptions_colon; private static readonly string s_exceptionsHeader = FeaturesResources.Exceptions_colon;
......
...@@ -43,7 +43,7 @@ internal INavigateToSearchResult Rehydrate(Solution solution) ...@@ -43,7 +43,7 @@ internal INavigateToSearchResult Rehydrate(Solution solution)
{ {
return new NavigateToSearchResult( return new NavigateToSearchResult(
AdditionalInformation, Kind, MatchKind, IsCaseSensitive, AdditionalInformation, Kind, MatchKind, IsCaseSensitive,
Name, NameMatchSpans.ToImmutableArray(), Name, NameMatchSpans,
SecondarySort, Summary, NavigableItem.Rehydrate(solution)); SecondarySort, Summary, NavigableItem.Rehydrate(solution));
} }
...@@ -113,7 +113,7 @@ public INavigableItem Rehydrate(Solution solution) ...@@ -113,7 +113,7 @@ public INavigableItem Rehydrate(Solution solution)
? ImmutableArray<INavigableItem>.Empty ? ImmutableArray<INavigableItem>.Empty
: ChildItems.SelectAsArray(c => c.Rehydrate(solution)); : ChildItems.SelectAsArray(c => c.Rehydrate(solution));
return new NavigableItem( return new NavigableItem(
Glyph, DisplayTaggedParts.ToImmutableArray(), Glyph, DisplayTaggedParts,
DisplayFileLocation, IsImplicitlyDeclared, DisplayFileLocation, IsImplicitlyDeclared,
solution.GetDocument(Document), solution.GetDocument(Document),
SourceSpan, SourceSpan,
......
...@@ -7,7 +7,8 @@ Imports Microsoft.CodeAnalysis.MakeMethodSynchronous ...@@ -7,7 +7,8 @@ Imports Microsoft.CodeAnalysis.MakeMethodSynchronous
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.MakeMethodSynchronous Namespace Microsoft.CodeAnalysis.VisualBasic.MakeMethodSynchronous
<ExportCodeFixProvider(LanguageNames.VisualBasic), [Shared]> <ExportCodeFixProvider(LanguageNames.VisualBasic, Name:=PredefinedCodeFixProviderNames.MakeMethodSynchronous), [Shared]>
<ExtensionOrder(After:=PredefinedCodeFixProviderNames.AddImport)>
Friend Class VisualBasicMakeMethodSynchronousCodeFixProvider Friend Class VisualBasicMakeMethodSynchronousCodeFixProvider
Inherits AbstractMakeMethodSynchronousCodeFixProvider Inherits AbstractMakeMethodSynchronousCodeFixProvider
......
...@@ -16,7 +16,7 @@ public class Nested<T> ...@@ -16,7 +16,7 @@ public class Nested<T>
{ {
public readonly int A = 1; public readonly int A = 1;
public readonly int B = 2; public readonly int B = 2;
public static readonly int S = 3; public const int S = 3;
} }
} }
......
...@@ -7,7 +7,7 @@ namespace Roslyn.Test.Performance.Utilities ...@@ -7,7 +7,7 @@ namespace Roslyn.Test.Performance.Utilities
{ {
public abstract class VsPerfTest : PerfTest public abstract class VsPerfTest : PerfTest
{ {
private static readonly string _rootSuffix = "RoslynPerf"; private const string _rootSuffix = "RoslynPerf";
private readonly ILogger _logger; private readonly ILogger _logger;
private readonly string _testTemplateName; private readonly string _testTemplateName;
......
...@@ -24,10 +24,10 @@ namespace BuildBoss ...@@ -24,10 +24,10 @@ namespace BuildBoss
internal sealed class StructuredLoggerCheckerUtil : ICheckerUtil internal sealed class StructuredLoggerCheckerUtil : ICheckerUtil
{ {
internal static readonly StringComparer FilePathComparer = StringComparer.OrdinalIgnoreCase; internal static readonly StringComparer FilePathComparer = StringComparer.OrdinalIgnoreCase;
private static readonly string s_copyingFileFrom = "Copying file from \""; private const string s_copyingFileFrom = "Copying file from \"";
private static readonly string s_creatingHardLink = "Creating hard link to copy \""; private const string s_creatingHardLink = "Creating hard link to copy \"";
private static readonly string s_didNotCopy = "Did not copy from file \""; private const string s_didNotCopy = "Did not copy from file \"";
private static readonly string s_to = "\" to \""; private const string s_to = "\" to \"";
private readonly XDocument _document; private readonly XDocument _document;
private readonly Dictionary<string, List<string>> _copyMap = new Dictionary<string, List<string>>(FilePathComparer); private readonly Dictionary<string, List<string>> _copyMap = new Dictionary<string, List<string>>(FilePathComparer);
......
...@@ -44,7 +44,7 @@ class C { ...@@ -44,7 +44,7 @@ class C {
//] //]
}"; }";
private static readonly string s_tryCatchFinallyPreview = @"using System; private const string s_tryCatchFinallyPreview = @"using System;
class C { class C {
void Foo() { void Foo() {
//[ //[
...@@ -58,7 +58,7 @@ class C { ...@@ -58,7 +58,7 @@ class C {
} }
}"; }";
private static readonly string s_ifElsePreview = @"class C { private const string s_ifElsePreview = @"class C {
void Foo() { void Foo() {
//[ //[
if (false) { if (false) {
...@@ -69,7 +69,7 @@ class C { ...@@ -69,7 +69,7 @@ class C {
} }
}"; }";
private static readonly string s_forBlockPreview = @"class C { private const string s_forBlockPreview = @"class C {
void Foo() { void Foo() {
//[ //[
for (int i; i < 10; i++){ for (int i; i < 10; i++){
...@@ -78,7 +78,7 @@ class C { ...@@ -78,7 +78,7 @@ class C {
} }
}"; }";
private static readonly string s_lambdaPreview = @"using System; private const string s_lambdaPreview = @"using System;
class C { class C {
void Foo() { void Foo() {
//[ //[
...@@ -88,7 +88,7 @@ class C { ...@@ -88,7 +88,7 @@ class C {
//] //]
} }
}"; }";
private static readonly string s_anonymousMethodPreview = @"using System; private const string s_anonymousMethodPreview = @"using System;
delegate int D(int x); delegate int D(int x);
...@@ -102,7 +102,7 @@ class C { ...@@ -102,7 +102,7 @@ class C {
} }
}"; }";
private static readonly string s_anonymousTypePreview = @"using System; private const string s_anonymousTypePreview = @"using System;
class C { class C {
void Foo() { void Foo() {
//[ //[
...@@ -112,7 +112,7 @@ class C { ...@@ -112,7 +112,7 @@ class C {
//] //]
} }
}"; }";
private static readonly string s_InitializerPreviewTrue = @"using System; private const string s_InitializerPreviewTrue = @"using System;
using System.Collections.Generic; using System.Collections.Generic;
class C { class C {
...@@ -140,7 +140,7 @@ class B { ...@@ -140,7 +140,7 @@ class B {
public int A { get; set; } public int A { get; set; }
public int B { get; set; } public int B { get; set; }
}"; }";
private static readonly string s_InitializerPreviewFalse = @"using System; private const string s_InitializerPreviewFalse = @"using System;
using System.Collections.Generic; using System.Collections.Generic;
class C { class C {
...@@ -165,7 +165,7 @@ class B { ...@@ -165,7 +165,7 @@ class B {
public int A { get; set; } public int A { get; set; }
public int B { get; set; } public int B { get; set; }
}"; }";
private static readonly string s_objectInitializerPreview = @"using System; private const string s_objectInitializerPreview = @"using System;
class C { class C {
void Foo() { void Foo() {
//[ //[
...@@ -180,7 +180,7 @@ class B { ...@@ -180,7 +180,7 @@ class B {
public int A { get; set; } public int A { get; set; }
public int B { get; set; } public int B { get; set; }
}"; }";
private static readonly string s_queryExpressionPreview = @"using System; private const string s_queryExpressionPreview = @"using System;
using System.Linq; using System.Linq;
using System.Collections.Generic; using System.Collections.Generic;
class C { class C {
......
...@@ -13,7 +13,7 @@ namespace Microsoft.VisualStudio.LanguageServices.CSharp.Options.Formatting ...@@ -13,7 +13,7 @@ namespace Microsoft.VisualStudio.LanguageServices.CSharp.Options.Formatting
/// </summary> /// </summary>
internal class SpacingViewModel : AbstractOptionPreviewViewModel internal class SpacingViewModel : AbstractOptionPreviewViewModel
{ {
private static readonly string s_methodPreview = @" private const string s_methodPreview = @"
class C { class C {
//[ //[
void Foo(){ void Foo(){
...@@ -29,14 +29,14 @@ class C { ...@@ -29,14 +29,14 @@ class C {
} }
}"; }";
private static readonly string s_bracketPreview = @"class C { private const string s_bracketPreview = @"class C {
void Foo(){ void Foo(){
//[ //[
int[] x = new int[10]; int[] x = new int[10];
//] //]
} }
}"; }";
private static readonly string s_forDelimiterPreview = @"class C{ private const string s_forDelimiterPreview = @"class C{
void Foo(int x, object y) { void Foo(int x, object y) {
//[ //[
for (int i; i < x; i++) { for (int i; i < x; i++) {
...@@ -45,7 +45,7 @@ class C { ...@@ -45,7 +45,7 @@ class C {
} }
}"; }";
private static readonly string s_delimiterPreview = @"class C{ private const string s_delimiterPreview = @"class C{
void Foo(int x, object y) { void Foo(int x, object y) {
//[ //[
this.Foo(x, y); this.Foo(x, y);
...@@ -53,7 +53,7 @@ class C { ...@@ -53,7 +53,7 @@ class C {
} }
}"; }";
private static readonly string s_castPreview = @"class C{ private const string s_castPreview = @"class C{
void Foo(object x) { void Foo(object x) {
//[ //[
int y = (int)x; int y = (int)x;
...@@ -61,7 +61,7 @@ class C { ...@@ -61,7 +61,7 @@ class C {
} }
}"; }";
private static readonly string s_expressionPreview = @"class C{ private const string s_expressionPreview = @"class C{
void Foo(int x, object y) { void Foo(int x, object y) {
//[ //[
var x = 3; var x = 3;
...@@ -71,7 +71,7 @@ class C { ...@@ -71,7 +71,7 @@ class C {
} }
}"; }";
private static readonly string s_expressionSpacingPreview = @" private const string s_expressionSpacingPreview = @"
class c { class c {
int Foo(int x, int y) { int Foo(int x, int y) {
//[ //[
...@@ -79,7 +79,7 @@ class c { ...@@ -79,7 +79,7 @@ class c {
//] //]
} }
}"; }";
private static readonly string s_declarationSpacingPreview = @"class MyClass { private const string s_declarationSpacingPreview = @"class MyClass {
//[ //[
int index = 0; int index = 0;
string text = ""Start""; string text = ""Start"";
...@@ -90,7 +90,7 @@ class c { ...@@ -90,7 +90,7 @@ class c {
} }
//] //]
}"; }";
private static readonly string s_baseColonPreview = @"//[ private const string s_baseColonPreview = @"//[
interface I { interface I {
} }
......
...@@ -21,7 +21,7 @@ internal class StyleViewModel : AbstractOptionPreviewViewModel ...@@ -21,7 +21,7 @@ internal class StyleViewModel : AbstractOptionPreviewViewModel
{ {
#region "Preview Text" #region "Preview Text"
private static readonly string s_fieldDeclarationPreviewTrue = @" private const string s_fieldDeclarationPreviewTrue = @"
class C{ class C{
int capacity; int capacity;
void Method() void Method()
...@@ -32,7 +32,7 @@ void Method() ...@@ -32,7 +32,7 @@ void Method()
} }
}"; }";
private static readonly string s_fieldDeclarationPreviewFalse = @" private const string s_fieldDeclarationPreviewFalse = @"
class C{ class C{
int capacity; int capacity;
void Method() void Method()
...@@ -43,7 +43,7 @@ void Method() ...@@ -43,7 +43,7 @@ void Method()
} }
}"; }";
private static readonly string s_propertyDeclarationPreviewTrue = @" private const string s_propertyDeclarationPreviewTrue = @"
class C{ class C{
public int Id { get; set; } public int Id { get; set; }
void Method() void Method()
...@@ -54,7 +54,7 @@ void Method() ...@@ -54,7 +54,7 @@ void Method()
} }
}"; }";
private static readonly string s_propertyDeclarationPreviewFalse = @" private const string s_propertyDeclarationPreviewFalse = @"
class C{ class C{
public int Id { get; set; } public int Id { get; set; }
void Method() void Method()
...@@ -65,7 +65,7 @@ void Method() ...@@ -65,7 +65,7 @@ void Method()
} }
}"; }";
private static readonly string s_eventDeclarationPreviewTrue = @" private const string s_eventDeclarationPreviewTrue = @"
using System; using System;
class C{ class C{
event EventHandler Elapsed; event EventHandler Elapsed;
...@@ -77,7 +77,7 @@ void Handler(object sender, EventArgs args) ...@@ -77,7 +77,7 @@ void Handler(object sender, EventArgs args)
} }
}"; }";
private static readonly string s_eventDeclarationPreviewFalse = @" private const string s_eventDeclarationPreviewFalse = @"
using System; using System;
class C{ class C{
event EventHandler Elapsed; event EventHandler Elapsed;
...@@ -89,7 +89,7 @@ void Handler(object sender, EventArgs args) ...@@ -89,7 +89,7 @@ void Handler(object sender, EventArgs args)
} }
}"; }";
private static readonly string s_methodDeclarationPreviewTrue = @" private const string s_methodDeclarationPreviewTrue = @"
using System; using System;
class C{ class C{
void Display() void Display()
...@@ -100,7 +100,7 @@ void Display() ...@@ -100,7 +100,7 @@ void Display()
} }
}"; }";
private static readonly string s_methodDeclarationPreviewFalse = @" private const string s_methodDeclarationPreviewFalse = @"
using System; using System;
class C{ class C{
void Display() void Display()
...@@ -111,7 +111,7 @@ void Display() ...@@ -111,7 +111,7 @@ void Display()
} }
}"; }";
private static readonly string s_intrinsicPreviewDeclarationTrue = @" private const string s_intrinsicPreviewDeclarationTrue = @"
class Program class Program
{ {
//[ //[
...@@ -123,7 +123,7 @@ static void M(int argument) ...@@ -123,7 +123,7 @@ static void M(int argument)
//] //]
}"; }";
private static readonly string s_intrinsicPreviewDeclarationFalse = @" private const string s_intrinsicPreviewDeclarationFalse = @"
using System; using System;
class Program class Program
{ {
...@@ -136,7 +136,7 @@ static void M(Int32 argument) ...@@ -136,7 +136,7 @@ static void M(Int32 argument)
//] //]
}"; }";
private static readonly string s_intrinsicPreviewMemberAccessTrue = @" private const string s_intrinsicPreviewMemberAccessTrue = @"
class Program class Program
{ {
//[ //[
...@@ -147,7 +147,7 @@ static void M() ...@@ -147,7 +147,7 @@ static void M()
//] //]
}"; }";
private static readonly string s_intrinsicPreviewMemberAccessFalse = @" private const string s_intrinsicPreviewMemberAccessFalse = @"
using System; using System;
class Program class Program
{ {
...@@ -489,7 +489,7 @@ public int GetAge() ...@@ -489,7 +489,7 @@ public int GetAge()
}} }}
"; ";
private static readonly string s_preferExpressionBodyForMethods = @" private const string s_preferExpressionBodyForMethods = @"
using System; using System;
//[ //[
...@@ -502,7 +502,7 @@ class Customer ...@@ -502,7 +502,7 @@ class Customer
//] //]
"; ";
private static readonly string s_preferBlockBodyForMethods = @" private const string s_preferBlockBodyForMethods = @"
using System; using System;
//[ //[
...@@ -518,7 +518,7 @@ public int GetAge() ...@@ -518,7 +518,7 @@ public int GetAge()
//] //]
"; ";
private static readonly string s_preferExpressionBodyForConstructors = @" private const string s_preferExpressionBodyForConstructors = @"
using System; using System;
//[ //[
...@@ -531,7 +531,7 @@ class Customer ...@@ -531,7 +531,7 @@ class Customer
//] //]
"; ";
private static readonly string s_preferBlockBodyForConstructors = @" private const string s_preferBlockBodyForConstructors = @"
using System; using System;
//[ //[
...@@ -547,7 +547,7 @@ public Customer(int age) ...@@ -547,7 +547,7 @@ public Customer(int age)
//] //]
"; ";
private static readonly string s_preferExpressionBodyForOperators = @" private const string s_preferExpressionBodyForOperators = @"
using System; using System;
struct ComplexNumber struct ComplexNumber
...@@ -559,7 +559,7 @@ struct ComplexNumber ...@@ -559,7 +559,7 @@ struct ComplexNumber
} }
"; ";
private static readonly string s_preferBlockBodyForOperators = @" private const string s_preferBlockBodyForOperators = @"
using System; using System;
struct ComplexNumber struct ComplexNumber
...@@ -573,7 +573,7 @@ struct ComplexNumber ...@@ -573,7 +573,7 @@ struct ComplexNumber
} }
"; ";
private static readonly string s_preferExpressionBodyForProperties = @" private const string s_preferExpressionBodyForProperties = @"
using System; using System;
//[ //[
...@@ -585,7 +585,7 @@ class Customer ...@@ -585,7 +585,7 @@ class Customer
//] //]
"; ";
private static readonly string s_preferBlockBodyForProperties = @" private const string s_preferBlockBodyForProperties = @"
using System; using System;
//[ //[
...@@ -597,7 +597,7 @@ class Customer ...@@ -597,7 +597,7 @@ class Customer
//] //]
"; ";
private static readonly string s_preferExpressionBodyForAccessors = @" private const string s_preferExpressionBodyForAccessors = @"
using System; using System;
//[ //[
...@@ -613,7 +613,7 @@ public int Age ...@@ -613,7 +613,7 @@ public int Age
//] //]
"; ";
private static readonly string s_preferBlockBodyForAccessors = @" private const string s_preferBlockBodyForAccessors = @"
using System; using System;
//[ //[
...@@ -629,7 +629,7 @@ public int Age ...@@ -629,7 +629,7 @@ public int Age
//] //]
"; ";
private static readonly string s_preferExpressionBodyForIndexers= @" private const string s_preferExpressionBodyForIndexers = @"
using System; using System;
//[ //[
...@@ -641,7 +641,7 @@ class List<T> ...@@ -641,7 +641,7 @@ class List<T>
//] //]
"; ";
private static readonly string s_preferBlockBodyForIndexers = @" private const string s_preferBlockBodyForIndexers = @"
using System; using System;
//[ //[
......
...@@ -13,7 +13,7 @@ namespace Microsoft.VisualStudio.LanguageServices.CSharp.Options.Formatting ...@@ -13,7 +13,7 @@ namespace Microsoft.VisualStudio.LanguageServices.CSharp.Options.Formatting
/// </summary> /// </summary>
internal class WrappingViewModel : AbstractOptionPreviewViewModel internal class WrappingViewModel : AbstractOptionPreviewViewModel
{ {
private static readonly string s_blockPreview = @" private const string s_blockPreview = @"
class C class C
{ {
//[ //[
...@@ -21,7 +21,7 @@ class C ...@@ -21,7 +21,7 @@ class C
//] //]
}"; }";
private static readonly string s_declarationPreview = @" private const string s_declarationPreview = @"
class C{ class C{
void foo() void foo()
{ {
......
...@@ -9,7 +9,7 @@ internal static class CSharpInteractiveCommands ...@@ -9,7 +9,7 @@ internal static class CSharpInteractiveCommands
public const int InteractiveToolWindow = 0x0001; public const int InteractiveToolWindow = 0x0001;
public const int ResetInteractiveFromProject = 0x0002; public const int ResetInteractiveFromProject = 0x0002;
public static readonly string InteractiveCommandSetIdString = "1492DB0A-85A2-4E43-BF0D-CE55B89A8CC6"; public const string InteractiveCommandSetIdString = "1492DB0A-85A2-4E43-BF0D-CE55B89A8CC6";
public static readonly Guid InteractiveCommandSetId = new Guid(InteractiveCommandSetIdString); public static readonly Guid InteractiveCommandSetId = new Guid(InteractiveCommandSetIdString);
} }
} }
...@@ -14,10 +14,10 @@ internal static class InteractiveCommands ...@@ -14,10 +14,10 @@ internal static class InteractiveCommands
// TODO: Remove pending https://github.com/dotnet/roslyn/issues/8927 . // TODO: Remove pending https://github.com/dotnet/roslyn/issues/8927 .
public const int ExecuteInInteractiveWindow = 0x0010C; public const int ExecuteInInteractiveWindow = 0x0010C;
public static readonly string CSharpInteractiveCommandSetIdString = "1492DB0A-85A2-4E43-BF0D-CE55B89A8CC6"; public const string CSharpInteractiveCommandSetIdString = "1492DB0A-85A2-4E43-BF0D-CE55B89A8CC6";
public static readonly Guid CSharpInteractiveCommandSetId = new Guid(CSharpInteractiveCommandSetIdString); public static readonly Guid CSharpInteractiveCommandSetId = new Guid(CSharpInteractiveCommandSetIdString);
public static readonly string VisualBasicInteractiveCommandSetIdString = "93DF185E-D75B-4FDB-9D47-E90F111971C5"; public const string VisualBasicInteractiveCommandSetIdString = "93DF185E-D75B-4FDB-9D47-E90F111971C5";
public static readonly Guid VisualBasicInteractiveCommandSetId = new Guid(VisualBasicInteractiveCommandSetIdString); public static readonly Guid VisualBasicInteractiveCommandSetId = new Guid(VisualBasicInteractiveCommandSetIdString);
} }
} }
......
...@@ -62,7 +62,7 @@ public static uint ObjectListKindToListType(ObjectListKind kind) ...@@ -62,7 +62,7 @@ public static uint ObjectListKindToListType(ObjectListKind kind)
return 0; return 0;
} }
public static readonly _LIB_LISTFLAGS ClassView = _LIB_LISTFLAGS.LLF_TRUENESTING; public const _LIB_LISTFLAGS ClassView = _LIB_LISTFLAGS.LLF_TRUENESTING;
public static bool IsClassView(uint flags) public static bool IsClassView(uint flags)
{ {
......
...@@ -153,9 +153,13 @@ public void Dispose() ...@@ -153,9 +153,13 @@ public void Dispose()
} }
} }
#pragma warning disable CA1821 // Remove empty Finalizers
#if DEBUG
~InvisibleEditor() ~InvisibleEditor()
{ {
Debug.Assert(Environment.HasShutdownStarted, GetType().Name + " was leaked without Dispose being called."); Debug.Assert(Environment.HasShutdownStarted, GetType().Name + " was leaked without Dispose being called.");
} }
#endif
#pragma warning restore CA1821 // Remove empty Finalizers
} }
} }
...@@ -117,11 +117,15 @@ public void Dispose() ...@@ -117,11 +117,15 @@ public void Dispose()
} }
} }
#pragma warning disable CA1821 // Remove empty Finalizers
#if DEBUG
~WorkspaceUndoTransaction() ~WorkspaceUndoTransaction()
{ {
// make sure we closed it correctly // make sure we closed it correctly
Contract.Requires(!_transactionAlive); Contract.Requires(!_transactionAlive);
} }
#endif
#pragma warning restore CA1821 // Remove empty Finalizers
} }
} }
} }
...@@ -7,7 +7,7 @@ Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.Interactive ...@@ -7,7 +7,7 @@ Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.Interactive
Public Const InteractiveToolWindow = &H1 Public Const InteractiveToolWindow = &H1
Public Const ResetInteractiveFromProject = &H2 Public Const ResetInteractiveFromProject = &H2
Public ReadOnly InteractiveCommandSetIdString As String = "93DF185E-D75B-4FDB-9D47-E90F111971C5" Public Const InteractiveCommandSetIdString As String = "93DF185E-D75B-4FDB-9D47-E90F111971C5"
Public ReadOnly InteractiveCommandSetId As Guid = New Guid(InteractiveCommandSetIdString) Public ReadOnly InteractiveCommandSetId As Guid = New Guid(InteractiveCommandSetIdString)
End Module End Module
End Namespace End Namespace
...@@ -98,6 +98,7 @@ ...@@ -98,6 +98,7 @@
<Compile Include="CodeStyle\TypeStyle\TypeStyleHelper.cs" /> <Compile Include="CodeStyle\TypeStyle\TypeStyleHelper.cs" />
<Compile Include="Composition\CSharpWorkspaceFeatures.cs" /> <Compile Include="Composition\CSharpWorkspaceFeatures.cs" />
<Compile Include="Extensions\BaseMethodDeclarationSyntaxExtensions.cs" /> <Compile Include="Extensions\BaseMethodDeclarationSyntaxExtensions.cs" />
<Compile Include="Extensions\UsingDirectiveSyntaxExtensions.cs" />
<Compile Include="Formatting\CSharpFormattingService.cs" /> <Compile Include="Formatting\CSharpFormattingService.cs" />
<Compile Include="FindSymbols\CSharpDeclaredSymbolInfoFactoryService.cs" /> <Compile Include="FindSymbols\CSharpDeclaredSymbolInfoFactoryService.cs" />
<Compile Include="Simplification\Reducers\CSharpDefaultExpressionReducer.Rewriter.cs" /> <Compile Include="Simplification\Reducers\CSharpDefaultExpressionReducer.Rewriter.cs" />
......
...@@ -4,6 +4,7 @@ ...@@ -4,6 +4,7 @@
using System.Linq; using System.Linq;
using System.Threading; using System.Threading;
using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.AddImports;
using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Utilities; using Microsoft.CodeAnalysis.CSharp.Utilities;
...@@ -119,57 +120,15 @@ private static TextSpan GetUsingsSpan(CompilationUnitSyntax root, NamespaceDecla ...@@ -119,57 +120,15 @@ private static TextSpan GetUsingsSpan(CompilationUnitSyntax root, NamespaceDecla
return root; return root;
} }
var comparer = placeSystemNamespaceFirst
? UsingsAndExternAliasesDirectiveComparer.SystemFirstInstance
: UsingsAndExternAliasesDirectiveComparer.NormalInstance;
var usings = AddUsingDirectives(root, usingDirectives); var usings = AddUsingDirectives(root, usingDirectives);
// Keep usings sorted if they were originally sorted. // Keep usings sorted if they were originally sorted.
if (root.Usings.IsSorted(comparer)) usings.SortUsingDirectives(root.Usings, placeSystemNamespaceFirst);
{
usings.Sort(comparer);
}
if (root.Externs.Count == 0) if (root.Externs.Count == 0)
{ {
if (root.Usings.Count == 0) root = AddImportHelpers.MoveTrivia(
{ CSharpSyntaxFactsService.Instance, root, root.Usings, usings);
// We don't have any existing usings. Move any trivia on the first token
// of the file to the first using.
//
// Don't do this for doc comments, as they belong to the first element
// already in the file (like a class) and we don't want it to move to
// the using.
var firstToken = root.GetFirstToken();
// Remove the leading directives from the first token.
var newFirstToken = firstToken.WithLeadingTrivia(
firstToken.LeadingTrivia.Where(t => IsDocCommentOrElastic(t)));
root = root.ReplaceToken(firstToken, newFirstToken);
// Move the leading trivia from the first token to the first using.
var newFirstUsing = usings[0].WithLeadingTrivia(
firstToken.LeadingTrivia.Where(t => !IsDocCommentOrElastic(t)));
usings[0] = newFirstUsing;
}
else
{
var originalFirstUsing = root.Usings[0];
if (usings[0] != originalFirstUsing)
{
// We added a new first-using. Take the trivia on the existing first using
// And move it to the new using.
var originalFirstUsingCurrentIndex = usings.IndexOf(originalFirstUsing);
var newFirstUsing = usings[0].WithLeadingTrivia(originalFirstUsing.GetLeadingTrivia())
.WithAppendedTrailingTrivia(SyntaxFactory.ElasticCarriageReturnLineFeed);
usings[0] = newFirstUsing;
usings[originalFirstUsingCurrentIndex] = originalFirstUsing.WithoutLeadingTrivia();
}
}
} }
return root.WithUsings( return root.WithUsings(
...@@ -215,6 +174,7 @@ private static bool IsDocCommentOrElastic(SyntaxTrivia t) ...@@ -215,6 +174,7 @@ private static bool IsDocCommentOrElastic(SyntaxTrivia t)
{ {
usings.InsertRange(startOfLastDirective, usingDirectives); usings.InsertRange(startOfLastDirective, usingDirectives);
} }
return usings; return usings;
} }
} }
......
...@@ -2,15 +2,7 @@ ...@@ -2,15 +2,7 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Utilities;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Extensions namespace Microsoft.CodeAnalysis.CSharp.Extensions
{ {
...@@ -27,24 +19,15 @@ internal static class NamespaceDeclarationSyntaxExtensions ...@@ -27,24 +19,15 @@ internal static class NamespaceDeclarationSyntaxExtensions
return namespaceDeclaration; return namespaceDeclaration;
} }
var specialCaseSystem = placeSystemNamespaceFirst; var newUsings = new List<UsingDirectiveSyntax>();
var comparer = specialCaseSystem newUsings.AddRange(namespaceDeclaration.Usings);
? UsingsAndExternAliasesDirectiveComparer.SystemFirstInstance newUsings.AddRange(usingDirectives);
: UsingsAndExternAliasesDirectiveComparer.NormalInstance;
var usings = new List<UsingDirectiveSyntax>(); newUsings.SortUsingDirectives(namespaceDeclaration.Usings, placeSystemNamespaceFirst);
usings.AddRange(namespaceDeclaration.Usings); newUsings = newUsings.Select(u => u.WithAdditionalAnnotations(annotations)).ToList();
usings.AddRange(usingDirectives);
if (namespaceDeclaration.Usings.IsSorted(comparer))
{
usings.Sort(comparer);
}
usings = usings.Select(u => u.WithAdditionalAnnotations(annotations)).ToList();
var newNamespace = namespaceDeclaration.WithUsings(usings.ToSyntaxList());
var newNamespace = namespaceDeclaration.WithUsings(newUsings.ToSyntaxList());
return newNamespace; return newNamespace;
} }
} }
} }
\ No newline at end of file
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Utilities;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Extensions
{
internal static class UsingDirectiveSyntaxExtensions
{
public static void SortUsingDirectives(
this List<UsingDirectiveSyntax> usingDirectives,
SyntaxList<UsingDirectiveSyntax> existingDirectives,
bool placeSystemNamespaceFirst)
{
var systemFirstInstance = UsingsAndExternAliasesDirectiveComparer.SystemFirstInstance;
var normalInstance = UsingsAndExternAliasesDirectiveComparer.NormalInstance;
var specialCaseSystem = placeSystemNamespaceFirst;
var comparers = specialCaseSystem
? (systemFirstInstance, normalInstance)
: (normalInstance, systemFirstInstance);
// First, see if the usings were sorted according to the user's preference. If so,
// keep the same sorting after we add the using. However, if the usings weren't sorted
// according to their preference, then see if they're sorted in the other way. If so
// preserve that sorting as well. That way if the user is working with a file that
// was written on a machine with a different default, the usings will stay in a
// reasonable order.
if (existingDirectives.IsSorted(comparers.Item1))
{
usingDirectives.Sort(comparers.Item1);
}
else if (existingDirectives.IsSorted(comparers.Item2))
{
usingDirectives.Sort(comparers.Item2);
}
}
}
}
\ No newline at end of file
...@@ -32,6 +32,9 @@ private CSharpSyntaxFactsService() ...@@ -32,6 +32,9 @@ private CSharpSyntaxFactsService()
public StringComparer StringComparer { get; } = StringComparer.Ordinal; public StringComparer StringComparer { get; } = StringComparer.Ordinal;
public SyntaxTrivia ElasticCarriageReturnLineFeed
=> SyntaxFactory.ElasticCarriageReturnLineFeed;
protected override IDocumentationCommentService DocumentationCommentService protected override IDocumentationCommentService DocumentationCommentService
=> CSharpDocumentationCommentService.Instance; => CSharpDocumentationCommentService.Instance;
...@@ -1350,6 +1353,9 @@ public bool IsRegularComment(SyntaxTrivia trivia) ...@@ -1350,6 +1353,9 @@ public bool IsRegularComment(SyntaxTrivia trivia)
public bool IsDocumentationComment(SyntaxTrivia trivia) public bool IsDocumentationComment(SyntaxTrivia trivia)
=> trivia.IsDocComment(); => trivia.IsDocComment();
public bool IsElastic(SyntaxTrivia trivia)
=> trivia.IsElastic();
public bool IsDocumentationCommentExteriorTrivia(SyntaxTrivia trivia) public bool IsDocumentationCommentExteriorTrivia(SyntaxTrivia trivia)
=> trivia.Kind() == SyntaxKind.DocumentationCommentExteriorTrivia; => trivia.Kind() == SyntaxKind.DocumentationCommentExteriorTrivia;
......
...@@ -168,7 +168,7 @@ protected override bool CanNodeBeSimplifiedWithoutSpeculation(SyntaxNode node) ...@@ -168,7 +168,7 @@ protected override bool CanNodeBeSimplifiedWithoutSpeculation(SyntaxNode node)
return false; return false;
} }
private static readonly string s_CS8019_UnusedUsingDirective = "CS8019"; private const string s_CS8019_UnusedUsingDirective = "CS8019";
protected override void GetUnusedNamespaceImports(SemanticModel model, HashSet<SyntaxNode> namespaceImports, CancellationToken cancellationToken) protected override void GetUnusedNamespaceImports(SemanticModel model, HashSet<SyntaxNode> namespaceImports, CancellationToken cancellationToken)
{ {
......
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
namespace Microsoft.CodeAnalysis.AddImports
{
internal static class AddImportHelpers
{
public static TRootSyntax MoveTrivia<TRootSyntax, TImportDirectiveSyntax>(
ISyntaxFactsService syntaxFacts,
TRootSyntax root,
SyntaxList<TImportDirectiveSyntax> existingImports,
List<TImportDirectiveSyntax> newImports)
where TRootSyntax : SyntaxNode
where TImportDirectiveSyntax : SyntaxNode
{
if (existingImports.Count == 0)
{
// We don't have any existing usings. Move any trivia on the first token
// of the file to the first using.
//
// Don't do this for doc comments, as they belong to the first element
// already in the file (like a class) and we don't want it to move to
// the using.
var firstToken = root.GetFirstToken();
// Remove the leading directives from the first token.
var newFirstToken = firstToken.WithLeadingTrivia(
firstToken.LeadingTrivia.Where(t => IsDocCommentOrElastic(syntaxFacts, t)));
root = root.ReplaceToken(firstToken, newFirstToken);
// Move the leading trivia from the first token to the first using.
var newFirstUsing = newImports[0].WithLeadingTrivia(
firstToken.LeadingTrivia.Where(t => !IsDocCommentOrElastic(syntaxFacts, t)));
newImports[0] = newFirstUsing;
}
else
{
var originalFirstUsing = existingImports[0];
if (newImports[0] != originalFirstUsing)
{
// We added a new first-using. Take the trivia on the existing first using
// And move it to the new using.
var originalFirstUsingCurrentIndex = newImports.IndexOf(originalFirstUsing);
newImports[0] = newImports[0].WithLeadingTrivia(originalFirstUsing.GetLeadingTrivia());
if (!syntaxFacts.IsEndOfLineTrivia(newImports[0].GetTrailingTrivia().LastOrDefault()))
{
newImports[0] = newImports[0].WithAppendedTrailingTrivia(syntaxFacts.ElasticCarriageReturnLineFeed);
}
newImports[originalFirstUsingCurrentIndex] = originalFirstUsing.WithoutLeadingTrivia();
}
}
return root;
}
private static bool IsDocCommentOrElastic(ISyntaxFactsService syntaxFacts, SyntaxTrivia t)
=> syntaxFacts.IsDocumentationComment(t) || syntaxFacts.IsElastic(t);
}
}
\ No newline at end of file
...@@ -648,7 +648,7 @@ private class SpanMarker ...@@ -648,7 +648,7 @@ private class SpanMarker
public SyntaxAnnotation Annotation { get; } public SyntaxAnnotation Annotation { get; }
public static readonly string AnnotationId = "SpanMarker"; public const string AnnotationId = "SpanMarker";
private SpanMarker(SpanMarkerType type, SpanMarkerType oppositeMarkerType, SyntaxAnnotation annotation) private SpanMarker(SpanMarkerType type, SpanMarkerType oppositeMarkerType, SyntaxAnnotation annotation)
{ {
......
...@@ -15,25 +15,25 @@ namespace Microsoft.CodeAnalysis.CodeFixes ...@@ -15,25 +15,25 @@ namespace Microsoft.CodeAnalysis.CodeFixes
internal static class FixAllLogger internal static class FixAllLogger
{ {
// Fix all context logging. // Fix all context logging.
private static readonly string s_codeFixProvider = "CodeFixProvider"; private const string s_codeFixProvider = "CodeFixProvider";
private static readonly string s_codeActionEquivalenceKey = "CodeActionEquivalenceKey"; private const string s_codeActionEquivalenceKey = "CodeActionEquivalenceKey";
private static readonly string s_fixAllScope = "FixAllScope"; private const string s_fixAllScope = "FixAllScope";
private static readonly string s_languageName = "LanguageName"; private const string s_languageName = "LanguageName";
private static readonly string s_documentCount = "DocumentCount"; private const string s_documentCount = "DocumentCount";
// Fix all computation result logging. // Fix all computation result logging.
private static readonly string s_result = "Result"; private const string s_result = "Result";
private static readonly string s_completed = "Completed"; private const string s_completed = "Completed";
private static readonly string s_timedOut = "TimedOut"; private const string s_timedOut = "TimedOut";
private static readonly string s_cancelled = "Cancelled"; private const string s_cancelled = "Cancelled";
private static readonly string s_allChangesApplied = "AllChangesApplied"; private const string s_allChangesApplied = "AllChangesApplied";
private static readonly string s_subsetOfChangesApplied = "SubsetOfChangesApplied"; private const string s_subsetOfChangesApplied = "SubsetOfChangesApplied";
// Diagnostics and fixes logging. // Diagnostics and fixes logging.
private static readonly string s_documentsWithDiagnosticsToFix = "DocumentsWithDiagnosticsToFix"; private const string s_documentsWithDiagnosticsToFix = "DocumentsWithDiagnosticsToFix";
private static readonly string s_projectsWithDiagnosticsToFix = "ProjectsWithDiagnosticsToFix"; private const string s_projectsWithDiagnosticsToFix = "ProjectsWithDiagnosticsToFix";
private static readonly string s_totalDiagnosticsToFix = "TotalDiagnosticsToFix"; private const string s_totalDiagnosticsToFix = "TotalDiagnosticsToFix";
private static readonly string s_totalFixesToMerge = "TotalFixesToMerge"; private const string s_totalFixesToMerge = "TotalFixesToMerge";
public static void LogState(FixAllState fixAllState, bool isInternalCodeFixProvider) public static void LogState(FixAllState fixAllState, bool isInternalCodeFixProvider)
{ {
......
...@@ -14,6 +14,8 @@ internal interface ISyntaxFactsService : ILanguageService ...@@ -14,6 +14,8 @@ internal interface ISyntaxFactsService : ILanguageService
bool IsCaseSensitive { get; } bool IsCaseSensitive { get; }
StringComparer StringComparer { get; } StringComparer StringComparer { get; }
SyntaxTrivia ElasticCarriageReturnLineFeed { get; }
bool SupportsIndexingInitializer(ParseOptions options); bool SupportsIndexingInitializer(ParseOptions options);
bool SupportsThrowExpression(ParseOptions options); bool SupportsThrowExpression(ParseOptions options);
...@@ -48,6 +50,7 @@ internal interface ISyntaxFactsService : ILanguageService ...@@ -48,6 +50,7 @@ internal interface ISyntaxFactsService : ILanguageService
bool IsRegularComment(SyntaxTrivia trivia); bool IsRegularComment(SyntaxTrivia trivia);
bool IsDocumentationComment(SyntaxTrivia trivia); bool IsDocumentationComment(SyntaxTrivia trivia);
bool IsElastic(SyntaxTrivia trivia);
bool IsDocumentationComment(SyntaxNode node); bool IsDocumentationComment(SyntaxNode node);
bool IsNumericLiteralExpression(SyntaxNode node); bool IsNumericLiteralExpression(SyntaxNode node);
...@@ -304,4 +307,4 @@ internal enum DisplayNameOptions ...@@ -304,4 +307,4 @@ internal enum DisplayNameOptions
IncludeType = 1 << 3, IncludeType = 1 << 3,
IncludeTypeParameters = 1 << 4 IncludeTypeParameters = 1 << 4
} }
} }
\ No newline at end of file
...@@ -16,7 +16,7 @@ namespace Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles ...@@ -16,7 +16,7 @@ namespace Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles
/// </summary> /// </summary>
internal class NamingStylePreferences : IEquatable<NamingStylePreferences> internal class NamingStylePreferences : IEquatable<NamingStylePreferences>
{ {
private readonly static int s_serializationVersion = 4; private const int s_serializationVersion = 4;
public readonly ImmutableArray<SymbolSpecification> SymbolSpecifications; public readonly ImmutableArray<SymbolSpecification> SymbolSpecifications;
public readonly ImmutableArray<NamingStyle> NamingStyles; public readonly ImmutableArray<NamingStyle> NamingStyles;
......
...@@ -31,7 +31,7 @@ internal static partial class ConflictResolver ...@@ -31,7 +31,7 @@ internal static partial class ConflictResolver
propertyStyle: SymbolDisplayPropertyStyle.NameOnly, propertyStyle: SymbolDisplayPropertyStyle.NameOnly,
miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers); miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers);
private static readonly string s_metadataNameSeparators = " .,:<`>()\r\n"; private const string s_metadataNameSeparators = " .,:<`>()\r\n";
/// <summary> /// <summary>
/// Performs the renaming of the symbol in the solution, identifies renaming conflicts and automatically resolves them where possible. /// Performs the renaming of the symbol in the solution, identifies renaming conflicts and automatically resolves them where possible.
......
...@@ -205,6 +205,7 @@ ...@@ -205,6 +205,7 @@
<Compile Include="..\..\..\Compilers\Core\Portable\Syntax\SyntaxTreeExtensions.cs"> <Compile Include="..\..\..\Compilers\Core\Portable\Syntax\SyntaxTreeExtensions.cs">
<Link>InternalUtilities\SyntaxTreeExtensions.cs</Link> <Link>InternalUtilities\SyntaxTreeExtensions.cs</Link>
</Compile> </Compile>
<Compile Include="AddImports\AddImportHelpers.cs" />
<Compile Include="Classification\AbstractClassificationService.cs" /> <Compile Include="Classification\AbstractClassificationService.cs" />
<Compile Include="Classification\IClassificationService.cs" /> <Compile Include="Classification\IClassificationService.cs" />
<Compile Include="ExtensionManager\IInfoBarService.cs" /> <Compile Include="ExtensionManager\IInfoBarService.cs" />
......
...@@ -3,6 +3,7 @@ ...@@ -3,6 +3,7 @@
Imports System.Runtime.CompilerServices Imports System.Runtime.CompilerServices
Imports System.Threading Imports System.Threading
Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.AddImports
Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.CodeAnalysis.VisualBasic.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.Utilities
...@@ -45,44 +46,39 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.Extensions ...@@ -45,44 +46,39 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.Extensions
Return root Return root
End If End If
Dim comparer = If(placeSystemNamespaceFirst, Dim systemFirstInstance = ImportsStatementComparer.SystemFirstInstance
ImportsStatementComparer.SystemFirstInstance, Dim normalInstance = ImportsStatementComparer.NormalInstance
ImportsStatementComparer.NormalInstance)
Dim comparers = If(placeSystemNamespaceFirst,
(systemFirstInstance, normalInstance),
(normalInstance, systemFirstInstance))
Dim [imports] = AddImportsStatements(root, importsStatements) Dim [imports] = AddImportsStatements(root, importsStatements)
' If the user likes to have their Imports statements unsorted, allow them to ' First, see if the imports were sorted according to the user's preference. If so,
If root.Imports.IsSorted(comparer) Then ' keep the same sorting after we add the import. However, if the imports weren't sorted
[imports].Sort(comparer) ' according to their preference, then see if they're sorted in the other way. If so
' preserve that sorting as well. That way if the user is working with a file that
' was written on a machine with a different default, the imports will stay in a
' reasonable order.
If root.Imports.IsSorted(comparers.Item1) Then
[imports].Sort(comparers.Item1)
ElseIf root.Imports.IsSorted(comparers.Item2) Then
[imports].Sort(comparers.Item2)
End If End If
' If any using we added was moved to the first location, then take the trivia from root = AddImportHelpers.MoveTrivia(
' the start of the first token And add it to the using we added. This way things VisualBasicSyntaxFactsService.Instance, root, root.Imports, [imports])
' Like #define's and #r's will stay above the using.
If root.Imports.Count = 0 OrElse [imports](0) IsNot root.Imports(0) Then
Dim firstToken = root.GetFirstToken
' Move the leading directives from the first directive to the New using.
Dim firstImport = [imports](0).WithLeadingTrivia(firstToken.LeadingTrivia.Where(Function(t) Not t.IsKind(SyntaxKind.DocumentationCommentTrivia) AndAlso Not t.IsElastic))
' Remove the leading directives from the first token.
Dim newFirstToken = firstToken.WithLeadingTrivia(firstToken.LeadingTrivia.Where(Function(t) t.IsKind(SyntaxKind.DocumentationCommentTrivia) OrElse t.IsElastic))
' Remove the leading trivia from the first token from the tree.
root = root.ReplaceToken(firstToken, newFirstToken)
' Create the New list of imports Return root.WithImports(
Dim finalImports = New List(Of ImportsStatementSyntax) [imports].Select(Function(u) u.WithAdditionalAnnotations(annotations)).ToSyntaxList())
finalImports.Add(firstImport) End Function
finalImports.AddRange(root.Imports)
finalImports.AddRange(importsStatements.Except({[imports](0)}))
finalImports.Sort(comparer)
[imports] = finalImports
End If
Return root.WithImports([imports].ToSyntaxList).WithAdditionalAnnotations(annotations) Private Function IsDocCommentOrElastic(t As SyntaxTrivia) As Boolean
Return t.Kind() = SyntaxKind.DocumentationCommentTrivia OrElse t.IsElastic()
End Function End Function
Private Function AddImportsStatements(root As CompilationUnitSyntax, importsStatements As IList(Of ImportsStatementSyntax)) As List(Of ImportsStatementSyntax) Private Function AddImportsStatements(root As CompilationUnitSyntax, importsStatements As IList(Of ImportsStatementSyntax)) As List(Of ImportsStatementSyntax)
' We need to try and not place the using inside of a directive if possible. ' We need to try and not place the using inside of a directive if possible.
Dim [imports] = New List(Of ImportsStatementSyntax) Dim [imports] = New List(Of ImportsStatementSyntax)
......
...@@ -5,7 +5,6 @@ Imports System.Composition ...@@ -5,7 +5,6 @@ Imports System.Composition
Imports System.Text Imports System.Text
Imports System.Threading Imports System.Threading
Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Collections
Imports Microsoft.CodeAnalysis.Host Imports Microsoft.CodeAnalysis.Host
Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.Host.Mef
Imports Microsoft.CodeAnalysis.LanguageServices Imports Microsoft.CodeAnalysis.LanguageServices
...@@ -46,6 +45,12 @@ Namespace Microsoft.CodeAnalysis.VisualBasic ...@@ -46,6 +45,12 @@ Namespace Microsoft.CodeAnalysis.VisualBasic
End Get End Get
End Property End Property
Public ReadOnly Property ElasticCarriageReturnLineFeed As SyntaxTrivia Implements ISyntaxFactsService.ElasticCarriageReturnLineFeed
Get
Return SyntaxFactory.ElasticCarriageReturnLineFeed
End Get
End Property
Protected Overrides ReadOnly Property DocumentationCommentService As IDocumentationCommentService Protected Overrides ReadOnly Property DocumentationCommentService As IDocumentationCommentService
Get Get
Return VisualBasicDocumentationCommentService.Instance Return VisualBasicDocumentationCommentService.Instance
...@@ -1502,6 +1507,10 @@ Namespace Microsoft.CodeAnalysis.VisualBasic ...@@ -1502,6 +1507,10 @@ Namespace Microsoft.CodeAnalysis.VisualBasic
Return trivia.Kind = SyntaxKind.DocumentationCommentTrivia Return trivia.Kind = SyntaxKind.DocumentationCommentTrivia
End Function End Function
Public Function IsElastic(trivia As SyntaxTrivia) As Boolean Implements ISyntaxFactsService.IsElastic
Return trivia.IsElastic()
End Function
Public Function IsOnTypeHeader(root As SyntaxNode, position As Integer) As Boolean Implements ISyntaxFactsService.IsOnTypeHeader Public Function IsOnTypeHeader(root As SyntaxNode, position As Integer) As Boolean Implements ISyntaxFactsService.IsOnTypeHeader
Dim statement = root.FindToken(position).GetAncestor(Of TypeStatementSyntax) Dim statement = root.FindToken(position).GetAncestor(Of TypeStatementSyntax)
If statement Is Nothing Then If statement Is Nothing Then
......
...@@ -165,8 +165,8 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.Simplification ...@@ -165,8 +165,8 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.Simplification
TypeOf node.Parent Is FieldDeclarationSyntax TypeOf node.Parent Is FieldDeclarationSyntax
End Function End Function
Private Shared ReadOnly s_BC50000_UnusedImportsClause As String = "BC50000" Private Const s_BC50000_UnusedImportsClause As String = "BC50000"
Private Shared ReadOnly s_BC50001_UnusedImportsStatement As String = "BC50001" Private Const s_BC50001_UnusedImportsStatement As String = "BC50001"
Protected Overrides Sub GetUnusedNamespaceImports(model As SemanticModel, namespaceImports As HashSet(Of SyntaxNode), cancellationToken As CancellationToken) Protected Overrides Sub GetUnusedNamespaceImports(model As SemanticModel, namespaceImports As HashSet(Of SyntaxNode), cancellationToken As CancellationToken)
Dim root = model.SyntaxTree.GetRoot() Dim root = model.SyntaxTree.GetRoot()
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册