repo_name
stringclasses 6
values | pr_number
int64 512
78.9k
| pr_title
stringlengths 3
144
| pr_description
stringlengths 0
30.3k
| author
stringlengths 2
21
| date_created
timestamp[ns, tz=UTC] | date_merged
timestamp[ns, tz=UTC] | previous_commit
stringlengths 40
40
| pr_commit
stringlengths 40
40
| query
stringlengths 17
30.4k
| filepath
stringlengths 9
210
| before_content
stringlengths 0
112M
| after_content
stringlengths 0
112M
| label
int64 -1
1
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
dotnet/roslyn | 55,877 | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute | Part of C# 10 support | davidwengier | 2021-08-25T05:36:27Z | 2021-08-30T20:47:11Z | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | 023d3ca2b5fb429f0b3dcc1efeed39442e232dba | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute. Part of C# 10 support | ./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/CodeStyle/ParenthesesPreference.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace Microsoft.CodeAnalysis.CodeStyle
{
internal enum ParenthesesPreference
{
AlwaysForClarity,
NeverIfUnnecessary,
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace Microsoft.CodeAnalysis.CodeStyle
{
internal enum ParenthesesPreference
{
AlwaysForClarity,
NeverIfUnnecessary,
}
}
| -1 |
dotnet/roslyn | 55,877 | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute | Part of C# 10 support | davidwengier | 2021-08-25T05:36:27Z | 2021-08-30T20:47:11Z | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | 023d3ca2b5fb429f0b3dcc1efeed39442e232dba | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute. Part of C# 10 support | ./src/EditorFeatures/Core/Implementation/InfoBar/EditorInfoBarService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Composition;
using Microsoft.CodeAnalysis.Extensions;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Internal.Log;
namespace Microsoft.CodeAnalysis.Editor.Implementation.Workspaces
{
[ExportWorkspaceService(typeof(IInfoBarService)), Shared]
internal class EditorInfoBarService : IInfoBarService
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public EditorInfoBarService()
{
}
public void ShowInfoBar(string message, params InfoBarUI[] items)
=> Logger.Log(FunctionId.Extension_InfoBar, message);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Composition;
using Microsoft.CodeAnalysis.Extensions;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Internal.Log;
namespace Microsoft.CodeAnalysis.Editor.Implementation.Workspaces
{
[ExportWorkspaceService(typeof(IInfoBarService)), Shared]
internal class EditorInfoBarService : IInfoBarService
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public EditorInfoBarService()
{
}
public void ShowInfoBar(string message, params InfoBarUI[] items)
=> Logger.Log(FunctionId.Extension_InfoBar, message);
}
}
| -1 |
dotnet/roslyn | 55,877 | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute | Part of C# 10 support | davidwengier | 2021-08-25T05:36:27Z | 2021-08-30T20:47:11Z | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | 023d3ca2b5fb429f0b3dcc1efeed39442e232dba | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute. Part of C# 10 support | ./src/Compilers/Test/Core/Platform/Desktop/DesktopRuntimeEnvironmentFactory.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
#if NET472
using System.Collections.Generic;
using Roslyn.Test.Utilities;
namespace Roslyn.Test.Utilities.Desktop
{
public sealed class DesktopRuntimeEnvironmentFactory : IRuntimeEnvironmentFactory
{
public IRuntimeEnvironment Create(IEnumerable<ModuleData> additionalDependencies)
{
return new DesktopRuntimeEnvironment(additionalDependencies);
}
}
}
#endif
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
#if NET472
using System.Collections.Generic;
using Roslyn.Test.Utilities;
namespace Roslyn.Test.Utilities.Desktop
{
public sealed class DesktopRuntimeEnvironmentFactory : IRuntimeEnvironmentFactory
{
public IRuntimeEnvironment Create(IEnumerable<ModuleData> additionalDependencies)
{
return new DesktopRuntimeEnvironment(additionalDependencies);
}
}
}
#endif
| -1 |
dotnet/roslyn | 55,877 | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute | Part of C# 10 support | davidwengier | 2021-08-25T05:36:27Z | 2021-08-30T20:47:11Z | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | 023d3ca2b5fb429f0b3dcc1efeed39442e232dba | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute. Part of C# 10 support | ./src/Interactive/Host/InteractiveHostResources.resx | <?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="Attempt_to_connect_to_process_Sharp_0_failed_retrying" xml:space="preserve">
<value>Attempt to connect to process #{0} failed, retrying ...</value>
</data>
<data name="Cannot_resolve_reference_0" xml:space="preserve">
<value>Cannot resolve reference '{0}'.</value>
</data>
<data name="Loading_context_from_0" xml:space="preserve">
<value>Loading context from '{0}'.</value>
</data>
<data name="Type_Sharphelp_for_more_information" xml:space="preserve">
<value>Type "#help" for more information.</value>
</data>
<data name="Specified_file_not_found_colon_0" xml:space="preserve">
<value>Specified file not found: {0}</value>
</data>
<data name="Specified_file_not_found" xml:space="preserve">
<value>Specified file not found.</value>
</data>
<data name="Searched_in_directory_colon" xml:space="preserve">
<value>Searched in directory:</value>
</data>
<data name="Searched_in_directories_colon" xml:space="preserve">
<value>Searched in directories:</value>
</data>
<data name="plus_additional_0_1" xml:space="preserve">
<value> + additional {0} {1}</value>
</data>
<data name="Unable_to_create_hosting_process" xml:space="preserve">
<value>Unable to create hosting process.</value>
</data>
<data name="Hosting_process_exited_with_exit_code_0" xml:space="preserve">
<value>Hosting process exited with exit code {0}.</value>
</data>
<data name="Failed_to_launch_0_process_exit_code_colon_1_with_output_colon" xml:space="preserve">
<value>Failed to launch '{0}' process (exit code: {1}) with output: </value>
</data>
<data name="Failed_to_create_a_remote_process_for_interactive_code_execution" xml:space="preserve">
<value>Failed to create a remote process for interactive code execution: '{0}'</value>
</data>
<data name="Failed_to_initialize_remote_interactive_process" xml:space="preserve">
<value>Failed to initialize remote interactive process.</value>
</data>
<data name="Interactive_Host_not_initialized" xml:space="preserve">
<value>Interactive Host not initialized.</value>
</data>
</root> | <?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="Attempt_to_connect_to_process_Sharp_0_failed_retrying" xml:space="preserve">
<value>Attempt to connect to process #{0} failed, retrying ...</value>
</data>
<data name="Cannot_resolve_reference_0" xml:space="preserve">
<value>Cannot resolve reference '{0}'.</value>
</data>
<data name="Loading_context_from_0" xml:space="preserve">
<value>Loading context from '{0}'.</value>
</data>
<data name="Type_Sharphelp_for_more_information" xml:space="preserve">
<value>Type "#help" for more information.</value>
</data>
<data name="Specified_file_not_found_colon_0" xml:space="preserve">
<value>Specified file not found: {0}</value>
</data>
<data name="Specified_file_not_found" xml:space="preserve">
<value>Specified file not found.</value>
</data>
<data name="Searched_in_directory_colon" xml:space="preserve">
<value>Searched in directory:</value>
</data>
<data name="Searched_in_directories_colon" xml:space="preserve">
<value>Searched in directories:</value>
</data>
<data name="plus_additional_0_1" xml:space="preserve">
<value> + additional {0} {1}</value>
</data>
<data name="Unable_to_create_hosting_process" xml:space="preserve">
<value>Unable to create hosting process.</value>
</data>
<data name="Hosting_process_exited_with_exit_code_0" xml:space="preserve">
<value>Hosting process exited with exit code {0}.</value>
</data>
<data name="Failed_to_launch_0_process_exit_code_colon_1_with_output_colon" xml:space="preserve">
<value>Failed to launch '{0}' process (exit code: {1}) with output: </value>
</data>
<data name="Failed_to_create_a_remote_process_for_interactive_code_execution" xml:space="preserve">
<value>Failed to create a remote process for interactive code execution: '{0}'</value>
</data>
<data name="Failed_to_initialize_remote_interactive_process" xml:space="preserve">
<value>Failed to initialize remote interactive process.</value>
</data>
<data name="Interactive_Host_not_initialized" xml:space="preserve">
<value>Interactive Host not initialized.</value>
</data>
</root> | -1 |
dotnet/roslyn | 55,877 | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute | Part of C# 10 support | davidwengier | 2021-08-25T05:36:27Z | 2021-08-30T20:47:11Z | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | 023d3ca2b5fb429f0b3dcc1efeed39442e232dba | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute. Part of C# 10 support | ./src/Compilers/Core/Portable/Emit/EmitOptions.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Emit
{
/// <summary>
/// Represents compilation emit options.
/// </summary>
public sealed class EmitOptions : IEquatable<EmitOptions>
{
internal static readonly EmitOptions Default = PlatformInformation.IsWindows
? new EmitOptions()
: new EmitOptions().WithDebugInformationFormat(DebugInformationFormat.PortablePdb);
/// <summary>
/// True to emit an assembly excluding executable code such as method bodies.
/// </summary>
public bool EmitMetadataOnly { get; private set; }
/// <summary>
/// Tolerate errors, producing a PE stream and a success result even in the presence of (some) errors.
/// </summary>
public bool TolerateErrors { get; private set; }
/// <summary>
/// Unless set (private) members that don't affect the language semantics of the resulting assembly will be excluded
/// when emitting metadata-only assemblies as primary output (with <see cref="EmitMetadataOnly"/> on).
/// If emitting a secondary output, this flag is required to be false.
/// </summary>
public bool IncludePrivateMembers { get; private set; }
/// <summary>
/// Type of instrumentation that should be added to the output binary.
/// </summary>
public ImmutableArray<InstrumentationKind> InstrumentationKinds { get; private set; }
/// <summary>
/// Subsystem version
/// </summary>
public SubsystemVersion SubsystemVersion { get; private set; }
/// <summary>
/// Specifies the size of sections in the output file.
/// </summary>
/// <remarks>
/// Valid values are 0, 512, 1024, 2048, 4096 and 8192.
/// If the value is 0 the file alignment is determined based upon the value of <see cref="Platform"/>.
/// </remarks>
public int FileAlignment { get; private set; }
/// <summary>
/// True to enable high entropy virtual address space for the output binary.
/// </summary>
public bool HighEntropyVirtualAddressSpace { get; private set; }
/// <summary>
/// Specifies the preferred base address at which to load the output DLL.
/// </summary>
public ulong BaseAddress { get; private set; }
/// <summary>
/// Debug information format.
/// </summary>
public DebugInformationFormat DebugInformationFormat { get; private set; }
/// <summary>
/// Assembly name override - file name and extension. If not specified the compilation name is used.
/// </summary>
/// <remarks>
/// By default the name of the output assembly is <see cref="Compilation.AssemblyName"/>. Only in rare cases it is necessary
/// to override the name.
///
/// CAUTION: If this is set to a (non-null) value other than the existing compilation output name, then internals-visible-to
/// and assembly references may not work as expected. In particular, things that were visible at bind time, based on the
/// name of the compilation, may not be visible at runtime and vice-versa.
/// </remarks>
public string? OutputNameOverride { get; private set; }
/// <summary>
/// The name of the PDB file to be embedded in the PE image, or null to use the default.
/// </summary>
/// <remarks>
/// If not specified the file name of the source module with an extension changed to "pdb" is used.
/// </remarks>
public string? PdbFilePath { get; private set; }
/// <summary>
/// A crypto hash algorithm used to calculate PDB Checksum stored in the PE/COFF File.
/// If not specified (the value is <c>default(HashAlgorithmName)</c>) the checksum is not calculated.
/// </summary>
public HashAlgorithmName PdbChecksumAlgorithm { get; private set; }
/// <summary>
/// Runtime metadata version.
/// </summary>
public string? RuntimeMetadataVersion { get; private set; }
/// <summary>
/// The encoding used to parse source files that do not have a Byte Order Mark. If specified,
/// is stored in the emitted PDB in order to allow recreating the original compilation.
/// </summary>
public Encoding? DefaultSourceFileEncoding { get; private set; }
/// <summary>
/// If <see cref="DefaultSourceFileEncoding"/> is not specified, the encoding used to parse source files
/// that do not declare their encoding via Byte Order Mark and are not UTF8-encoded.
/// </summary>
public Encoding? FallbackSourceFileEncoding { get; private set; }
// 1.2 BACKCOMPAT OVERLOAD -- DO NOT TOUCH
public EmitOptions(
bool metadataOnly,
DebugInformationFormat debugInformationFormat,
string pdbFilePath,
string outputNameOverride,
int fileAlignment,
ulong baseAddress,
bool highEntropyVirtualAddressSpace,
SubsystemVersion subsystemVersion,
string runtimeMetadataVersion,
bool tolerateErrors,
bool includePrivateMembers)
: this(
metadataOnly,
debugInformationFormat,
pdbFilePath,
outputNameOverride,
fileAlignment,
baseAddress,
highEntropyVirtualAddressSpace,
subsystemVersion,
runtimeMetadataVersion,
tolerateErrors,
includePrivateMembers,
instrumentationKinds: ImmutableArray<InstrumentationKind>.Empty)
{
}
// 2.7 BACKCOMPAT OVERLOAD -- DO NOT TOUCH
public EmitOptions(
bool metadataOnly,
DebugInformationFormat debugInformationFormat,
string pdbFilePath,
string outputNameOverride,
int fileAlignment,
ulong baseAddress,
bool highEntropyVirtualAddressSpace,
SubsystemVersion subsystemVersion,
string runtimeMetadataVersion,
bool tolerateErrors,
bool includePrivateMembers,
ImmutableArray<InstrumentationKind> instrumentationKinds)
: this(
metadataOnly,
debugInformationFormat,
pdbFilePath,
outputNameOverride,
fileAlignment,
baseAddress,
highEntropyVirtualAddressSpace,
subsystemVersion,
runtimeMetadataVersion,
tolerateErrors,
includePrivateMembers,
instrumentationKinds,
pdbChecksumAlgorithm: null)
{
}
// 3.7 BACKCOMPAT OVERLOAD -- DO NOT TOUCH
public EmitOptions(
bool metadataOnly,
DebugInformationFormat debugInformationFormat,
string? pdbFilePath,
string? outputNameOverride,
int fileAlignment,
ulong baseAddress,
bool highEntropyVirtualAddressSpace,
SubsystemVersion subsystemVersion,
string? runtimeMetadataVersion,
bool tolerateErrors,
bool includePrivateMembers,
ImmutableArray<InstrumentationKind> instrumentationKinds,
HashAlgorithmName? pdbChecksumAlgorithm)
: this(
metadataOnly,
debugInformationFormat,
pdbFilePath,
outputNameOverride,
fileAlignment,
baseAddress,
highEntropyVirtualAddressSpace,
subsystemVersion,
runtimeMetadataVersion,
tolerateErrors,
includePrivateMembers,
instrumentationKinds,
pdbChecksumAlgorithm,
defaultSourceFileEncoding: null,
fallbackSourceFileEncoding: null)
{
}
public EmitOptions(
bool metadataOnly = false,
DebugInformationFormat debugInformationFormat = 0,
string? pdbFilePath = null,
string? outputNameOverride = null,
int fileAlignment = 0,
ulong baseAddress = 0,
bool highEntropyVirtualAddressSpace = false,
SubsystemVersion subsystemVersion = default,
string? runtimeMetadataVersion = null,
bool tolerateErrors = false,
bool includePrivateMembers = true,
ImmutableArray<InstrumentationKind> instrumentationKinds = default,
HashAlgorithmName? pdbChecksumAlgorithm = null,
Encoding? defaultSourceFileEncoding = null,
Encoding? fallbackSourceFileEncoding = null)
{
EmitMetadataOnly = metadataOnly;
DebugInformationFormat = (debugInformationFormat == 0) ? DebugInformationFormat.Pdb : debugInformationFormat;
PdbFilePath = pdbFilePath;
OutputNameOverride = outputNameOverride;
FileAlignment = fileAlignment;
BaseAddress = baseAddress;
HighEntropyVirtualAddressSpace = highEntropyVirtualAddressSpace;
SubsystemVersion = subsystemVersion;
RuntimeMetadataVersion = runtimeMetadataVersion;
TolerateErrors = tolerateErrors;
IncludePrivateMembers = includePrivateMembers;
InstrumentationKinds = instrumentationKinds.NullToEmpty();
PdbChecksumAlgorithm = pdbChecksumAlgorithm ?? HashAlgorithmName.SHA256;
DefaultSourceFileEncoding = defaultSourceFileEncoding;
FallbackSourceFileEncoding = fallbackSourceFileEncoding;
}
private EmitOptions(EmitOptions other) : this(
other.EmitMetadataOnly,
other.DebugInformationFormat,
other.PdbFilePath,
other.OutputNameOverride,
other.FileAlignment,
other.BaseAddress,
other.HighEntropyVirtualAddressSpace,
other.SubsystemVersion,
other.RuntimeMetadataVersion,
other.TolerateErrors,
other.IncludePrivateMembers,
other.InstrumentationKinds,
other.PdbChecksumAlgorithm,
other.DefaultSourceFileEncoding,
other.FallbackSourceFileEncoding)
{
}
public override bool Equals(object? obj)
{
return Equals(obj as EmitOptions);
}
public bool Equals(EmitOptions? other)
{
if (ReferenceEquals(other, null))
{
return false;
}
return
EmitMetadataOnly == other.EmitMetadataOnly &&
BaseAddress == other.BaseAddress &&
FileAlignment == other.FileAlignment &&
HighEntropyVirtualAddressSpace == other.HighEntropyVirtualAddressSpace &&
SubsystemVersion.Equals(other.SubsystemVersion) &&
DebugInformationFormat == other.DebugInformationFormat &&
PdbFilePath == other.PdbFilePath &&
PdbChecksumAlgorithm == other.PdbChecksumAlgorithm &&
OutputNameOverride == other.OutputNameOverride &&
RuntimeMetadataVersion == other.RuntimeMetadataVersion &&
TolerateErrors == other.TolerateErrors &&
IncludePrivateMembers == other.IncludePrivateMembers &&
InstrumentationKinds.NullToEmpty().SequenceEqual(other.InstrumentationKinds.NullToEmpty(), (a, b) => a == b) &&
DefaultSourceFileEncoding == other.DefaultSourceFileEncoding &&
FallbackSourceFileEncoding == other.FallbackSourceFileEncoding;
}
public override int GetHashCode()
{
return Hash.Combine(EmitMetadataOnly,
Hash.Combine(BaseAddress.GetHashCode(),
Hash.Combine(FileAlignment,
Hash.Combine(HighEntropyVirtualAddressSpace,
Hash.Combine(SubsystemVersion.GetHashCode(),
Hash.Combine((int)DebugInformationFormat,
Hash.Combine(PdbFilePath,
Hash.Combine(PdbChecksumAlgorithm.GetHashCode(),
Hash.Combine(OutputNameOverride,
Hash.Combine(RuntimeMetadataVersion,
Hash.Combine(TolerateErrors,
Hash.Combine(IncludePrivateMembers,
Hash.Combine(Hash.CombineValues(InstrumentationKinds),
Hash.Combine(DefaultSourceFileEncoding,
Hash.Combine(FallbackSourceFileEncoding, 0)))))))))))))));
}
public static bool operator ==(EmitOptions? left, EmitOptions? right)
{
return object.Equals(left, right);
}
public static bool operator !=(EmitOptions? left, EmitOptions? right)
{
return !object.Equals(left, right);
}
internal void ValidateOptions(DiagnosticBag diagnostics, CommonMessageProvider messageProvider, bool isDeterministic)
{
if (!DebugInformationFormat.IsValid())
{
diagnostics.Add(messageProvider.CreateDiagnostic(messageProvider.ERR_InvalidDebugInformationFormat, Location.None, (int)DebugInformationFormat));
}
foreach (var instrumentationKind in InstrumentationKinds)
{
if (!instrumentationKind.IsValid())
{
diagnostics.Add(messageProvider.CreateDiagnostic(messageProvider.ERR_InvalidInstrumentationKind, Location.None, (int)instrumentationKind));
}
}
if (OutputNameOverride != null)
{
MetadataHelpers.CheckAssemblyOrModuleName(OutputNameOverride, messageProvider, messageProvider.ERR_InvalidOutputName, diagnostics);
}
if (FileAlignment != 0 && !IsValidFileAlignment(FileAlignment))
{
diagnostics.Add(messageProvider.CreateDiagnostic(messageProvider.ERR_InvalidFileAlignment, Location.None, FileAlignment));
}
if (!SubsystemVersion.Equals(SubsystemVersion.None) && !SubsystemVersion.IsValid)
{
diagnostics.Add(messageProvider.CreateDiagnostic(messageProvider.ERR_InvalidSubsystemVersion, Location.None, SubsystemVersion.ToString()));
}
if (PdbChecksumAlgorithm.Name != null)
{
try
{
IncrementalHash.CreateHash(PdbChecksumAlgorithm).Dispose();
}
catch
{
diagnostics.Add(messageProvider.CreateDiagnostic(messageProvider.ERR_InvalidHashAlgorithmName, Location.None, PdbChecksumAlgorithm.ToString()));
}
}
else if (isDeterministic)
{
diagnostics.Add(messageProvider.CreateDiagnostic(messageProvider.ERR_InvalidHashAlgorithmName, Location.None, ""));
}
}
internal bool EmitTestCoverageData => InstrumentationKinds.Contains(InstrumentationKind.TestCoverage);
internal static bool IsValidFileAlignment(int value)
{
switch (value)
{
case 512:
case 1024:
case 2048:
case 4096:
case 8192:
return true;
default:
return false;
}
}
public EmitOptions WithEmitMetadataOnly(bool value)
{
if (EmitMetadataOnly == value)
{
return this;
}
return new EmitOptions(this) { EmitMetadataOnly = value };
}
public EmitOptions WithPdbFilePath(string path)
{
if (PdbFilePath == path)
{
return this;
}
return new EmitOptions(this) { PdbFilePath = path };
}
public EmitOptions WithPdbChecksumAlgorithm(HashAlgorithmName name)
{
if (PdbChecksumAlgorithm == name)
{
return this;
}
return new EmitOptions(this) { PdbChecksumAlgorithm = name };
}
public EmitOptions WithOutputNameOverride(string outputName)
{
if (OutputNameOverride == outputName)
{
return this;
}
return new EmitOptions(this) { OutputNameOverride = outputName };
}
public EmitOptions WithDebugInformationFormat(DebugInformationFormat format)
{
if (DebugInformationFormat == format)
{
return this;
}
return new EmitOptions(this) { DebugInformationFormat = format };
}
/// <summary>
/// Sets the byte alignment for portable executable file sections.
/// </summary>
/// <param name="value">Can be one of the following values: 0, 512, 1024, 2048, 4096, 8192</param>
public EmitOptions WithFileAlignment(int value)
{
if (FileAlignment == value)
{
return this;
}
return new EmitOptions(this) { FileAlignment = value };
}
public EmitOptions WithBaseAddress(ulong value)
{
if (BaseAddress == value)
{
return this;
}
return new EmitOptions(this) { BaseAddress = value };
}
public EmitOptions WithHighEntropyVirtualAddressSpace(bool value)
{
if (HighEntropyVirtualAddressSpace == value)
{
return this;
}
return new EmitOptions(this) { HighEntropyVirtualAddressSpace = value };
}
public EmitOptions WithSubsystemVersion(SubsystemVersion subsystemVersion)
{
if (subsystemVersion.Equals(SubsystemVersion))
{
return this;
}
return new EmitOptions(this) { SubsystemVersion = subsystemVersion };
}
public EmitOptions WithRuntimeMetadataVersion(string version)
{
if (RuntimeMetadataVersion == version)
{
return this;
}
return new EmitOptions(this) { RuntimeMetadataVersion = version };
}
public EmitOptions WithTolerateErrors(bool value)
{
if (TolerateErrors == value)
{
return this;
}
return new EmitOptions(this) { TolerateErrors = value };
}
public EmitOptions WithIncludePrivateMembers(bool value)
{
if (IncludePrivateMembers == value)
{
return this;
}
return new EmitOptions(this) { IncludePrivateMembers = value };
}
public EmitOptions WithInstrumentationKinds(ImmutableArray<InstrumentationKind> instrumentationKinds)
{
if (InstrumentationKinds == instrumentationKinds)
{
return this;
}
return new EmitOptions(this) { InstrumentationKinds = instrumentationKinds };
}
public EmitOptions WithDefaultSourceFileEncoding(Encoding? defaultSourceFileEncoding)
{
if (DefaultSourceFileEncoding == defaultSourceFileEncoding)
{
return this;
}
return new EmitOptions(this) { DefaultSourceFileEncoding = defaultSourceFileEncoding };
}
public EmitOptions WithFallbackSourceFileEncoding(Encoding? fallbackSourceFileEncoding)
{
if (FallbackSourceFileEncoding == fallbackSourceFileEncoding)
{
return this;
}
return new EmitOptions(this) { FallbackSourceFileEncoding = fallbackSourceFileEncoding };
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Emit
{
/// <summary>
/// Represents compilation emit options.
/// </summary>
public sealed class EmitOptions : IEquatable<EmitOptions>
{
internal static readonly EmitOptions Default = PlatformInformation.IsWindows
? new EmitOptions()
: new EmitOptions().WithDebugInformationFormat(DebugInformationFormat.PortablePdb);
/// <summary>
/// True to emit an assembly excluding executable code such as method bodies.
/// </summary>
public bool EmitMetadataOnly { get; private set; }
/// <summary>
/// Tolerate errors, producing a PE stream and a success result even in the presence of (some) errors.
/// </summary>
public bool TolerateErrors { get; private set; }
/// <summary>
/// Unless set (private) members that don't affect the language semantics of the resulting assembly will be excluded
/// when emitting metadata-only assemblies as primary output (with <see cref="EmitMetadataOnly"/> on).
/// If emitting a secondary output, this flag is required to be false.
/// </summary>
public bool IncludePrivateMembers { get; private set; }
/// <summary>
/// Type of instrumentation that should be added to the output binary.
/// </summary>
public ImmutableArray<InstrumentationKind> InstrumentationKinds { get; private set; }
/// <summary>
/// Subsystem version
/// </summary>
public SubsystemVersion SubsystemVersion { get; private set; }
/// <summary>
/// Specifies the size of sections in the output file.
/// </summary>
/// <remarks>
/// Valid values are 0, 512, 1024, 2048, 4096 and 8192.
/// If the value is 0 the file alignment is determined based upon the value of <see cref="Platform"/>.
/// </remarks>
public int FileAlignment { get; private set; }
/// <summary>
/// True to enable high entropy virtual address space for the output binary.
/// </summary>
public bool HighEntropyVirtualAddressSpace { get; private set; }
/// <summary>
/// Specifies the preferred base address at which to load the output DLL.
/// </summary>
public ulong BaseAddress { get; private set; }
/// <summary>
/// Debug information format.
/// </summary>
public DebugInformationFormat DebugInformationFormat { get; private set; }
/// <summary>
/// Assembly name override - file name and extension. If not specified the compilation name is used.
/// </summary>
/// <remarks>
/// By default the name of the output assembly is <see cref="Compilation.AssemblyName"/>. Only in rare cases it is necessary
/// to override the name.
///
/// CAUTION: If this is set to a (non-null) value other than the existing compilation output name, then internals-visible-to
/// and assembly references may not work as expected. In particular, things that were visible at bind time, based on the
/// name of the compilation, may not be visible at runtime and vice-versa.
/// </remarks>
public string? OutputNameOverride { get; private set; }
/// <summary>
/// The name of the PDB file to be embedded in the PE image, or null to use the default.
/// </summary>
/// <remarks>
/// If not specified the file name of the source module with an extension changed to "pdb" is used.
/// </remarks>
public string? PdbFilePath { get; private set; }
/// <summary>
/// A crypto hash algorithm used to calculate PDB Checksum stored in the PE/COFF File.
/// If not specified (the value is <c>default(HashAlgorithmName)</c>) the checksum is not calculated.
/// </summary>
public HashAlgorithmName PdbChecksumAlgorithm { get; private set; }
/// <summary>
/// Runtime metadata version.
/// </summary>
public string? RuntimeMetadataVersion { get; private set; }
/// <summary>
/// The encoding used to parse source files that do not have a Byte Order Mark. If specified,
/// is stored in the emitted PDB in order to allow recreating the original compilation.
/// </summary>
public Encoding? DefaultSourceFileEncoding { get; private set; }
/// <summary>
/// If <see cref="DefaultSourceFileEncoding"/> is not specified, the encoding used to parse source files
/// that do not declare their encoding via Byte Order Mark and are not UTF8-encoded.
/// </summary>
public Encoding? FallbackSourceFileEncoding { get; private set; }
// 1.2 BACKCOMPAT OVERLOAD -- DO NOT TOUCH
public EmitOptions(
bool metadataOnly,
DebugInformationFormat debugInformationFormat,
string pdbFilePath,
string outputNameOverride,
int fileAlignment,
ulong baseAddress,
bool highEntropyVirtualAddressSpace,
SubsystemVersion subsystemVersion,
string runtimeMetadataVersion,
bool tolerateErrors,
bool includePrivateMembers)
: this(
metadataOnly,
debugInformationFormat,
pdbFilePath,
outputNameOverride,
fileAlignment,
baseAddress,
highEntropyVirtualAddressSpace,
subsystemVersion,
runtimeMetadataVersion,
tolerateErrors,
includePrivateMembers,
instrumentationKinds: ImmutableArray<InstrumentationKind>.Empty)
{
}
// 2.7 BACKCOMPAT OVERLOAD -- DO NOT TOUCH
public EmitOptions(
bool metadataOnly,
DebugInformationFormat debugInformationFormat,
string pdbFilePath,
string outputNameOverride,
int fileAlignment,
ulong baseAddress,
bool highEntropyVirtualAddressSpace,
SubsystemVersion subsystemVersion,
string runtimeMetadataVersion,
bool tolerateErrors,
bool includePrivateMembers,
ImmutableArray<InstrumentationKind> instrumentationKinds)
: this(
metadataOnly,
debugInformationFormat,
pdbFilePath,
outputNameOverride,
fileAlignment,
baseAddress,
highEntropyVirtualAddressSpace,
subsystemVersion,
runtimeMetadataVersion,
tolerateErrors,
includePrivateMembers,
instrumentationKinds,
pdbChecksumAlgorithm: null)
{
}
// 3.7 BACKCOMPAT OVERLOAD -- DO NOT TOUCH
public EmitOptions(
bool metadataOnly,
DebugInformationFormat debugInformationFormat,
string? pdbFilePath,
string? outputNameOverride,
int fileAlignment,
ulong baseAddress,
bool highEntropyVirtualAddressSpace,
SubsystemVersion subsystemVersion,
string? runtimeMetadataVersion,
bool tolerateErrors,
bool includePrivateMembers,
ImmutableArray<InstrumentationKind> instrumentationKinds,
HashAlgorithmName? pdbChecksumAlgorithm)
: this(
metadataOnly,
debugInformationFormat,
pdbFilePath,
outputNameOverride,
fileAlignment,
baseAddress,
highEntropyVirtualAddressSpace,
subsystemVersion,
runtimeMetadataVersion,
tolerateErrors,
includePrivateMembers,
instrumentationKinds,
pdbChecksumAlgorithm,
defaultSourceFileEncoding: null,
fallbackSourceFileEncoding: null)
{
}
public EmitOptions(
bool metadataOnly = false,
DebugInformationFormat debugInformationFormat = 0,
string? pdbFilePath = null,
string? outputNameOverride = null,
int fileAlignment = 0,
ulong baseAddress = 0,
bool highEntropyVirtualAddressSpace = false,
SubsystemVersion subsystemVersion = default,
string? runtimeMetadataVersion = null,
bool tolerateErrors = false,
bool includePrivateMembers = true,
ImmutableArray<InstrumentationKind> instrumentationKinds = default,
HashAlgorithmName? pdbChecksumAlgorithm = null,
Encoding? defaultSourceFileEncoding = null,
Encoding? fallbackSourceFileEncoding = null)
{
EmitMetadataOnly = metadataOnly;
DebugInformationFormat = (debugInformationFormat == 0) ? DebugInformationFormat.Pdb : debugInformationFormat;
PdbFilePath = pdbFilePath;
OutputNameOverride = outputNameOverride;
FileAlignment = fileAlignment;
BaseAddress = baseAddress;
HighEntropyVirtualAddressSpace = highEntropyVirtualAddressSpace;
SubsystemVersion = subsystemVersion;
RuntimeMetadataVersion = runtimeMetadataVersion;
TolerateErrors = tolerateErrors;
IncludePrivateMembers = includePrivateMembers;
InstrumentationKinds = instrumentationKinds.NullToEmpty();
PdbChecksumAlgorithm = pdbChecksumAlgorithm ?? HashAlgorithmName.SHA256;
DefaultSourceFileEncoding = defaultSourceFileEncoding;
FallbackSourceFileEncoding = fallbackSourceFileEncoding;
}
private EmitOptions(EmitOptions other) : this(
other.EmitMetadataOnly,
other.DebugInformationFormat,
other.PdbFilePath,
other.OutputNameOverride,
other.FileAlignment,
other.BaseAddress,
other.HighEntropyVirtualAddressSpace,
other.SubsystemVersion,
other.RuntimeMetadataVersion,
other.TolerateErrors,
other.IncludePrivateMembers,
other.InstrumentationKinds,
other.PdbChecksumAlgorithm,
other.DefaultSourceFileEncoding,
other.FallbackSourceFileEncoding)
{
}
public override bool Equals(object? obj)
{
return Equals(obj as EmitOptions);
}
public bool Equals(EmitOptions? other)
{
if (ReferenceEquals(other, null))
{
return false;
}
return
EmitMetadataOnly == other.EmitMetadataOnly &&
BaseAddress == other.BaseAddress &&
FileAlignment == other.FileAlignment &&
HighEntropyVirtualAddressSpace == other.HighEntropyVirtualAddressSpace &&
SubsystemVersion.Equals(other.SubsystemVersion) &&
DebugInformationFormat == other.DebugInformationFormat &&
PdbFilePath == other.PdbFilePath &&
PdbChecksumAlgorithm == other.PdbChecksumAlgorithm &&
OutputNameOverride == other.OutputNameOverride &&
RuntimeMetadataVersion == other.RuntimeMetadataVersion &&
TolerateErrors == other.TolerateErrors &&
IncludePrivateMembers == other.IncludePrivateMembers &&
InstrumentationKinds.NullToEmpty().SequenceEqual(other.InstrumentationKinds.NullToEmpty(), (a, b) => a == b) &&
DefaultSourceFileEncoding == other.DefaultSourceFileEncoding &&
FallbackSourceFileEncoding == other.FallbackSourceFileEncoding;
}
public override int GetHashCode()
{
return Hash.Combine(EmitMetadataOnly,
Hash.Combine(BaseAddress.GetHashCode(),
Hash.Combine(FileAlignment,
Hash.Combine(HighEntropyVirtualAddressSpace,
Hash.Combine(SubsystemVersion.GetHashCode(),
Hash.Combine((int)DebugInformationFormat,
Hash.Combine(PdbFilePath,
Hash.Combine(PdbChecksumAlgorithm.GetHashCode(),
Hash.Combine(OutputNameOverride,
Hash.Combine(RuntimeMetadataVersion,
Hash.Combine(TolerateErrors,
Hash.Combine(IncludePrivateMembers,
Hash.Combine(Hash.CombineValues(InstrumentationKinds),
Hash.Combine(DefaultSourceFileEncoding,
Hash.Combine(FallbackSourceFileEncoding, 0)))))))))))))));
}
public static bool operator ==(EmitOptions? left, EmitOptions? right)
{
return object.Equals(left, right);
}
public static bool operator !=(EmitOptions? left, EmitOptions? right)
{
return !object.Equals(left, right);
}
internal void ValidateOptions(DiagnosticBag diagnostics, CommonMessageProvider messageProvider, bool isDeterministic)
{
if (!DebugInformationFormat.IsValid())
{
diagnostics.Add(messageProvider.CreateDiagnostic(messageProvider.ERR_InvalidDebugInformationFormat, Location.None, (int)DebugInformationFormat));
}
foreach (var instrumentationKind in InstrumentationKinds)
{
if (!instrumentationKind.IsValid())
{
diagnostics.Add(messageProvider.CreateDiagnostic(messageProvider.ERR_InvalidInstrumentationKind, Location.None, (int)instrumentationKind));
}
}
if (OutputNameOverride != null)
{
MetadataHelpers.CheckAssemblyOrModuleName(OutputNameOverride, messageProvider, messageProvider.ERR_InvalidOutputName, diagnostics);
}
if (FileAlignment != 0 && !IsValidFileAlignment(FileAlignment))
{
diagnostics.Add(messageProvider.CreateDiagnostic(messageProvider.ERR_InvalidFileAlignment, Location.None, FileAlignment));
}
if (!SubsystemVersion.Equals(SubsystemVersion.None) && !SubsystemVersion.IsValid)
{
diagnostics.Add(messageProvider.CreateDiagnostic(messageProvider.ERR_InvalidSubsystemVersion, Location.None, SubsystemVersion.ToString()));
}
if (PdbChecksumAlgorithm.Name != null)
{
try
{
IncrementalHash.CreateHash(PdbChecksumAlgorithm).Dispose();
}
catch
{
diagnostics.Add(messageProvider.CreateDiagnostic(messageProvider.ERR_InvalidHashAlgorithmName, Location.None, PdbChecksumAlgorithm.ToString()));
}
}
else if (isDeterministic)
{
diagnostics.Add(messageProvider.CreateDiagnostic(messageProvider.ERR_InvalidHashAlgorithmName, Location.None, ""));
}
}
internal bool EmitTestCoverageData => InstrumentationKinds.Contains(InstrumentationKind.TestCoverage);
internal static bool IsValidFileAlignment(int value)
{
switch (value)
{
case 512:
case 1024:
case 2048:
case 4096:
case 8192:
return true;
default:
return false;
}
}
public EmitOptions WithEmitMetadataOnly(bool value)
{
if (EmitMetadataOnly == value)
{
return this;
}
return new EmitOptions(this) { EmitMetadataOnly = value };
}
public EmitOptions WithPdbFilePath(string path)
{
if (PdbFilePath == path)
{
return this;
}
return new EmitOptions(this) { PdbFilePath = path };
}
public EmitOptions WithPdbChecksumAlgorithm(HashAlgorithmName name)
{
if (PdbChecksumAlgorithm == name)
{
return this;
}
return new EmitOptions(this) { PdbChecksumAlgorithm = name };
}
public EmitOptions WithOutputNameOverride(string outputName)
{
if (OutputNameOverride == outputName)
{
return this;
}
return new EmitOptions(this) { OutputNameOverride = outputName };
}
public EmitOptions WithDebugInformationFormat(DebugInformationFormat format)
{
if (DebugInformationFormat == format)
{
return this;
}
return new EmitOptions(this) { DebugInformationFormat = format };
}
/// <summary>
/// Sets the byte alignment for portable executable file sections.
/// </summary>
/// <param name="value">Can be one of the following values: 0, 512, 1024, 2048, 4096, 8192</param>
public EmitOptions WithFileAlignment(int value)
{
if (FileAlignment == value)
{
return this;
}
return new EmitOptions(this) { FileAlignment = value };
}
public EmitOptions WithBaseAddress(ulong value)
{
if (BaseAddress == value)
{
return this;
}
return new EmitOptions(this) { BaseAddress = value };
}
public EmitOptions WithHighEntropyVirtualAddressSpace(bool value)
{
if (HighEntropyVirtualAddressSpace == value)
{
return this;
}
return new EmitOptions(this) { HighEntropyVirtualAddressSpace = value };
}
public EmitOptions WithSubsystemVersion(SubsystemVersion subsystemVersion)
{
if (subsystemVersion.Equals(SubsystemVersion))
{
return this;
}
return new EmitOptions(this) { SubsystemVersion = subsystemVersion };
}
public EmitOptions WithRuntimeMetadataVersion(string version)
{
if (RuntimeMetadataVersion == version)
{
return this;
}
return new EmitOptions(this) { RuntimeMetadataVersion = version };
}
public EmitOptions WithTolerateErrors(bool value)
{
if (TolerateErrors == value)
{
return this;
}
return new EmitOptions(this) { TolerateErrors = value };
}
public EmitOptions WithIncludePrivateMembers(bool value)
{
if (IncludePrivateMembers == value)
{
return this;
}
return new EmitOptions(this) { IncludePrivateMembers = value };
}
public EmitOptions WithInstrumentationKinds(ImmutableArray<InstrumentationKind> instrumentationKinds)
{
if (InstrumentationKinds == instrumentationKinds)
{
return this;
}
return new EmitOptions(this) { InstrumentationKinds = instrumentationKinds };
}
public EmitOptions WithDefaultSourceFileEncoding(Encoding? defaultSourceFileEncoding)
{
if (DefaultSourceFileEncoding == defaultSourceFileEncoding)
{
return this;
}
return new EmitOptions(this) { DefaultSourceFileEncoding = defaultSourceFileEncoding };
}
public EmitOptions WithFallbackSourceFileEncoding(Encoding? fallbackSourceFileEncoding)
{
if (FallbackSourceFileEncoding == fallbackSourceFileEncoding)
{
return this;
}
return new EmitOptions(this) { FallbackSourceFileEncoding = fallbackSourceFileEncoding };
}
}
}
| -1 |
dotnet/roslyn | 55,877 | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute | Part of C# 10 support | davidwengier | 2021-08-25T05:36:27Z | 2021-08-30T20:47:11Z | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | 023d3ca2b5fb429f0b3dcc1efeed39442e232dba | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute. Part of C# 10 support | ./src/VisualStudio/Xaml/Impl/xlf/Resources.it.xlf | <?xml version="1.0" encoding="utf-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd">
<file datatype="xml" source-language="en" target-language="it" original="../Resources.resx">
<body>
<trans-unit id="RemoveAndSortNamespacesWithAccelerator">
<source>Remove &and Sort Namespaces</source>
<target state="translated">Ri&muovi e ordina spazi dei nomi</target>
<note />
</trans-unit>
<trans-unit id="RemoveUnnecessaryNamespaces">
<source>Remove Unnecessary Namespaces</source>
<target state="translated">Rimuovi spazi dei nomi non necessari</target>
<note />
</trans-unit>
<trans-unit id="Sort_Namespaces">
<source>&Sort Namespaces</source>
<target state="translated">Or&dina spazi dei nomi</target>
<note />
</trans-unit>
</body>
</file>
</xliff> | <?xml version="1.0" encoding="utf-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd">
<file datatype="xml" source-language="en" target-language="it" original="../Resources.resx">
<body>
<trans-unit id="RemoveAndSortNamespacesWithAccelerator">
<source>Remove &and Sort Namespaces</source>
<target state="translated">Ri&muovi e ordina spazi dei nomi</target>
<note />
</trans-unit>
<trans-unit id="RemoveUnnecessaryNamespaces">
<source>Remove Unnecessary Namespaces</source>
<target state="translated">Rimuovi spazi dei nomi non necessari</target>
<note />
</trans-unit>
<trans-unit id="Sort_Namespaces">
<source>&Sort Namespaces</source>
<target state="translated">Or&dina spazi dei nomi</target>
<note />
</trans-unit>
</body>
</file>
</xliff> | -1 |
dotnet/roslyn | 55,877 | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute | Part of C# 10 support | davidwengier | 2021-08-25T05:36:27Z | 2021-08-30T20:47:11Z | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | 023d3ca2b5fb429f0b3dcc1efeed39442e232dba | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute. Part of C# 10 support | ./src/Compilers/Core/Portable/InternalUtilities/PlatformInformation.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.IO;
namespace Roslyn.Utilities
{
/// <summary>
/// This class provides simple properties for determining whether the current platform is Windows or Unix-based.
/// We intentionally do not use System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(...) because
/// it incorrectly reports 'true' for 'Windows' in desktop builds running on Unix-based platforms via Mono.
/// </summary>
internal static class PlatformInformation
{
public static bool IsWindows => Path.DirectorySeparatorChar == '\\';
public static bool IsUnix => Path.DirectorySeparatorChar == '/';
public static bool IsRunningOnMono
{
get
{
try
{
return !(Type.GetType("Mono.Runtime") is null);
}
catch
{
// Arbitrarily assume we're not running on Mono.
return false;
}
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.IO;
namespace Roslyn.Utilities
{
/// <summary>
/// This class provides simple properties for determining whether the current platform is Windows or Unix-based.
/// We intentionally do not use System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(...) because
/// it incorrectly reports 'true' for 'Windows' in desktop builds running on Unix-based platforms via Mono.
/// </summary>
internal static class PlatformInformation
{
public static bool IsWindows => Path.DirectorySeparatorChar == '\\';
public static bool IsUnix => Path.DirectorySeparatorChar == '/';
public static bool IsRunningOnMono
{
get
{
try
{
return !(Type.GetType("Mono.Runtime") is null);
}
catch
{
// Arbitrarily assume we're not running on Mono.
return false;
}
}
}
}
}
| -1 |
dotnet/roslyn | 55,877 | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute | Part of C# 10 support | davidwengier | 2021-08-25T05:36:27Z | 2021-08-30T20:47:11Z | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | 023d3ca2b5fb429f0b3dcc1efeed39442e232dba | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute. Part of C# 10 support | ./src/Compilers/Core/Portable/DiagnosticAnalyzer/SuppressMessageAttributeState.TargetSymbolResolver.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Diagnostics
{
internal partial class SuppressMessageAttributeState
{
private const string s_suppressionPrefix = "~";
[StructLayout(LayoutKind.Auto)]
private struct TargetSymbolResolver
{
private static readonly char[] s_nameDelimiters = { ':', '.', '+', '(', ')', '<', '>', '[', ']', '{', '}', ',', '&', '*', '`' };
private static readonly string[] s_callingConventionStrings =
{
"[vararg]",
"[cdecl]",
"[fastcall]",
"[stdcall]",
"[thiscall]"
};
private static readonly ParameterInfo[] s_noParameters = Array.Empty<ParameterInfo>();
private readonly Compilation _compilation;
private readonly TargetScope _scope;
private readonly string _name;
private int _index;
public TargetSymbolResolver(Compilation compilation, TargetScope scope, string fullyQualifiedName)
{
_compilation = compilation;
_scope = scope;
_name = fullyQualifiedName;
_index = 0;
}
private static string RemovePrefix(string id, string prefix)
{
if (id != null && prefix != null && id.StartsWith(prefix, StringComparison.Ordinal))
{
return id[prefix.Length..];
}
return id;
}
/// <summary>
/// Attempts to resolve the "Target" argument of the global SuppressMessageAttribute to symbols in compilation.
/// </summary>
/// <param name="resolvedWithDocCommentIdFormat">Indicates if resolved "Target" argument is in Roslyn's <see cref="DocumentationCommentId"/> format.</param>
/// <returns>Resolved symbols for the the "Target" argument of the global SuppressMessageAttribute.</returns>
public ImmutableArray<ISymbol> Resolve(out bool resolvedWithDocCommentIdFormat)
{
resolvedWithDocCommentIdFormat = false;
if (string.IsNullOrEmpty(_name))
{
return ImmutableArray<ISymbol>.Empty;
}
// Try to parse the name as declaration ID generated from symbol's documentation comment Id.
var nameWithoutPrefix = RemovePrefix(_name, s_suppressionPrefix);
var docIdResults = DocumentationCommentId.GetSymbolsForDeclarationId(nameWithoutPrefix, _compilation);
if (docIdResults.Length > 0)
{
resolvedWithDocCommentIdFormat = true;
return docIdResults;
}
var results = ArrayBuilder<ISymbol>.GetInstance();
// Parse 'e:' prefix used by FxCop to differentiate between event and non-event symbols of the same name.
bool isEvent = false;
if (_name.Length >= 2 && _name[0] == 'e' && _name[1] == ':')
{
isEvent = true;
_index = 2;
}
INamespaceOrTypeSymbol containingSymbol = _compilation.GlobalNamespace;
bool? segmentIsNamedTypeName = null;
while (true)
{
var segment = ParseNextNameSegment();
// Special case: Roslyn names indexers "this[]" in CSharp, FxCop names them "Item" with parameters in [] brackets
bool isIndexerProperty = false;
if (segment == "Item" && PeekNextChar() == '[')
{
isIndexerProperty = true;
if (_compilation.Language == LanguageNames.CSharp)
{
segment = "this[]";
}
}
var candidateMembers = containingSymbol.GetMembers(segment);
if (candidateMembers.Length == 0)
{
break;
}
if (segmentIsNamedTypeName.HasValue)
{
candidateMembers = segmentIsNamedTypeName.Value ?
candidateMembers.Where(s => s.Kind == SymbolKind.NamedType).ToImmutableArray() :
candidateMembers.Where(s => s.Kind != SymbolKind.NamedType).ToImmutableArray();
segmentIsNamedTypeName = null;
}
int? arity = null;
ParameterInfo[] parameters = null;
// Check for generic arity
if (_scope != TargetScope.Namespace && PeekNextChar() == '`')
{
++_index;
arity = ReadNextInteger();
}
// Check for method or indexer parameter list
var nextChar = PeekNextChar();
if (!isIndexerProperty && nextChar == '(' || isIndexerProperty && nextChar == '[')
{
parameters = ParseParameterList();
if (parameters == null)
{
// Failed to resolve parameter list
break;
}
}
else if (nextChar is '.' or '+')
{
++_index;
if (arity > 0 || nextChar == '+')
{
// The name continues and either has an arity or specifically continues with a '+'
// so segment must be the name of a named type
containingSymbol = GetFirstMatchingNamedType(candidateMembers, arity ?? 0);
}
else
{
// The name continues with a '.' and does not specify a generic arity
// so segment must be the name of a namespace or a named type
containingSymbol = GetFirstMatchingNamespaceOrType(candidateMembers);
}
if (containingSymbol == null)
{
// If we cannot resolve the name on the left of the delimiter, we have no
// hope of finding the symbol.
break;
}
if (containingSymbol.Kind == SymbolKind.NamedType)
{
// If segment resolves to a named type, that restricts what the next segment
// can resolve to depending on whether the name continues with '+' or '.'
segmentIsNamedTypeName = nextChar == '+';
}
continue;
}
if (_scope == TargetScope.Member && !isIndexerProperty && parameters != null)
{
TypeInfo? returnType = null;
if (PeekNextChar() == ':')
{
++_index;
returnType = ParseNamedType(null);
}
foreach (var method in GetMatchingMethods(candidateMembers, arity, parameters, returnType))
{
results.Add(method);
}
break;
}
ISymbol singleResult;
switch (_scope)
{
case TargetScope.Namespace:
singleResult = candidateMembers.FirstOrDefault(s => s.Kind == SymbolKind.Namespace);
break;
case TargetScope.Type:
singleResult = GetFirstMatchingNamedType(candidateMembers, arity ?? 0);
break;
case TargetScope.Member:
if (isIndexerProperty)
{
singleResult = GetFirstMatchingIndexer(candidateMembers, parameters);
}
else if (isEvent)
{
singleResult = candidateMembers.FirstOrDefault(s => s.Kind == SymbolKind.Event);
}
else
{
singleResult = candidateMembers.FirstOrDefault(s =>
s.Kind is not SymbolKind.Namespace and
not SymbolKind.NamedType);
}
break;
default:
throw ExceptionUtilities.UnexpectedValue(_scope);
}
if (singleResult != null)
{
results.Add(singleResult);
}
break;
}
return results.ToImmutableAndFree();
}
private string ParseNextNameSegment()
{
// Ignore optional octothorpe in the member name used by FxCop to differentiate between
// Orcas and Whidbey name providers. The fully-qualified member name format generated by each of
// these name providers is similar enough that we can just ignore this character.
if (PeekNextChar() == '#')
{
++_index;
// Ignore calling convention strings generated by FxCop for methods.
// Methods can't differ solely by calling convention in C# or VB.
if (PeekNextChar() == '[')
{
foreach (string callingConvention in s_callingConventionStrings)
{
if (callingConvention == _name.Substring(_index, callingConvention.Length))
{
_index += callingConvention.Length;
break;
}
}
}
}
string segment;
// Find the end of the next name segment, special case constructors which start with '.'
int delimiterOffset = PeekNextChar() == '.' ?
_name.IndexOfAny(s_nameDelimiters, _index + 1) :
_name.IndexOfAny(s_nameDelimiters, _index);
if (delimiterOffset >= 0)
{
segment = _name[_index..delimiterOffset];
_index = delimiterOffset;
}
else
{
segment = _name[_index..];
_index = _name.Length;
}
return segment;
}
private char PeekNextChar()
{
return _index >= _name.Length ? '\0' : _name[_index];
}
private int ReadNextInteger()
{
int n = 0;
while (_index < _name.Length && char.IsDigit(_name[_index]))
{
n = n * 10 + (_name[_index] - '0');
++_index;
}
return n;
}
private ParameterInfo[] ParseParameterList()
{
// Consume the opening parenthesis or bracket
Debug.Assert(PeekNextChar() is '(' or '[');
++_index;
var nextChar = PeekNextChar();
if (nextChar is ')' or ']')
{
// Empty parameter list
++_index;
return s_noParameters;
}
var builder = new ArrayBuilder<ParameterInfo>();
while (true)
{
var parameter = ParseParameter();
if (parameter != null)
{
builder.Add(parameter.Value);
}
else
{
builder.Free();
return null;
}
if (PeekNextChar() == ',')
{
++_index;
}
else
{
break;
}
}
nextChar = PeekNextChar();
if (nextChar is ')' or ']')
{
// Consume the closing parenthesis or bracket
++_index;
}
else
{
// Malformed parameter list: missing close parenthesis or bracket
builder.Free();
return null;
}
return builder.ToArrayAndFree();
}
private ParameterInfo? ParseParameter()
{
var type = ParseType(null);
if (type == null)
{
return null;
}
var isRefOrOut = PeekNextChar() == '&';
if (isRefOrOut)
{
++_index;
}
return new ParameterInfo(type.Value, isRefOrOut);
}
private TypeInfo? ParseType(ISymbol bindingContext)
{
TypeInfo? result;
IgnoreCustomModifierList();
if (PeekNextChar() == '!')
{
result = ParseIndexedTypeParameter(bindingContext);
}
else
{
result = ParseNamedType(bindingContext);
// If parsing as a named type failed, this could be a named type parameter,
// which we will only be able to resolve once we have a binding context.
if (bindingContext != null && result.HasValue && !result.Value.IsBound)
{
_index = result.Value.StartIndex;
result = ParseNamedTypeParameter(bindingContext);
}
}
if (result == null)
{
return null;
}
if (result.Value.IsBound)
{
var typeSymbol = result.Value.Type;
// Handle pointer and array specifiers for bound types
while (true)
{
IgnoreCustomModifierList();
var nextChar = PeekNextChar();
if (nextChar == '[')
{
typeSymbol = ParseArrayType(typeSymbol);
if (typeSymbol == null)
{
return null;
}
continue;
}
if (nextChar == '*')
{
++_index;
typeSymbol = _compilation.CreatePointerTypeSymbol(typeSymbol);
continue;
}
break;
}
return TypeInfo.Create(typeSymbol);
}
// Skip pointer and array specifiers for unbound types
IgnorePointerAndArraySpecifiers();
return result;
}
private void IgnoreCustomModifierList()
{
// NOTE: There is currently no way to create symbols
// with custom modifiers from outside the compiler layer. In
// particular, there is no language agnostic way to attach custom
// modifiers to symbols. As a result we cannot match symbols which
// have custom modifiers, because their public equals overrides in
// general explicitly check custom modifiers. So we just ignore
// custom modifier lists. This would only matter in the case that
// someone targeted a SuppressMessageAttribute at a method that
// overloads a method from metadata which uses custom modifiers.
if (PeekNextChar() == '{')
{
for (; _index < _name.Length && _name[_index] != '}'; ++_index) { }
}
}
private void IgnorePointerAndArraySpecifiers()
{
bool inBrackets = false;
for (; _index < _name.Length; ++_index)
{
switch (PeekNextChar())
{
case '[':
inBrackets = true;
break;
case ']':
if (!inBrackets)
{
// End of indexer parameter list
return;
}
inBrackets = false;
break;
case '*':
break;
default:
if (!inBrackets)
{
// End of parameter type name
return;
}
break;
}
}
}
private TypeInfo? ParseIndexedTypeParameter(ISymbol bindingContext)
{
var startIndex = _index;
Debug.Assert(PeekNextChar() == '!');
++_index;
if (PeekNextChar() == '!')
{
// !! means this is a method type parameter
++_index;
var methodTypeParameterIndex = ReadNextInteger();
var methodContext = bindingContext as IMethodSymbol;
if (methodContext != null)
{
var count = methodContext.TypeParameters.Length;
if (count > 0 && methodTypeParameterIndex < count)
{
return TypeInfo.Create(methodContext.TypeParameters[methodTypeParameterIndex]);
}
// No such parameter
return null;
}
// If there is no method context, then the type is unbound and must be bound later
return TypeInfo.CreateUnbound(startIndex);
}
// ! means this is a regular type parameter
var typeParameterIndex = ReadNextInteger();
if (bindingContext != null)
{
var typeParameter = GetNthTypeParameter(bindingContext.ContainingType, typeParameterIndex);
if (typeParameter != null)
{
return TypeInfo.Create(typeParameter);
}
// no such parameter
return null;
}
// If there is no binding context, then the type is unbound and must be bound later
return TypeInfo.CreateUnbound(startIndex);
}
private TypeInfo? ParseNamedTypeParameter(ISymbol bindingContext)
{
Debug.Assert(bindingContext != null);
var typeParameterName = ParseNextNameSegment();
var methodContext = bindingContext as IMethodSymbol;
if (methodContext != null)
{
// Check this method's type parameters for a name that matches
for (int i = 0; i < methodContext.TypeParameters.Length; ++i)
{
if (methodContext.TypeParameters[i].Name == typeParameterName)
{
return TypeInfo.Create(methodContext.TypeArguments[i]);
}
}
}
// Walk up the symbol tree until we find a type parameter with a name that matches
for (var containingType = bindingContext.ContainingType; containingType != null; containingType = containingType.ContainingType)
{
for (int i = 0; i < containingType.TypeParameters.Length; ++i)
{
if (containingType.TypeParameters[i].Name == typeParameterName)
{
return TypeInfo.Create(containingType.TypeArguments[i]);
}
}
}
return null;
}
private TypeInfo? ParseNamedType(ISymbol bindingContext)
{
INamespaceOrTypeSymbol containingSymbol = _compilation.GlobalNamespace;
int startIndex = _index;
while (true)
{
var segment = ParseNextNameSegment();
var candidateMembers = containingSymbol.GetMembers(segment);
if (candidateMembers.Length == 0)
{
return TypeInfo.CreateUnbound(startIndex);
}
int arity = 0;
TypeInfo[] typeArguments = null;
// Check for generic arity
if (PeekNextChar() == '`')
{
++_index;
arity = ReadNextInteger();
}
// Check for type argument list
if (PeekNextChar() == '<')
{
typeArguments = ParseTypeArgumentList(bindingContext);
if (typeArguments == null)
{
return null;
}
if (typeArguments.Any(a => !a.IsBound))
{
return TypeInfo.CreateUnbound(startIndex);
}
}
var nextChar = PeekNextChar();
if (nextChar is '.' or '+')
{
++_index;
if (arity > 0 || nextChar == '+')
{
// Segment is the name of a named type since the name has an arity or continues with a '+'
containingSymbol = GetFirstMatchingNamedType(candidateMembers, arity);
}
else
{
// Segment is the name of a namespace or type because the name continues with a '.'
containingSymbol = GetFirstMatchingNamespaceOrType(candidateMembers);
}
if (containingSymbol == null)
{
// If we cannot resolve the name on the left of the delimiter, we have no
// hope of finding the symbol.
return null;
}
continue;
}
INamedTypeSymbol typeSymbol = GetFirstMatchingNamedType(candidateMembers, arity);
if (typeSymbol == null)
{
return null;
}
if (typeArguments != null)
{
typeSymbol = typeSymbol.Construct(typeArguments.Select(t => t.Type).ToArray());
}
return TypeInfo.Create(typeSymbol);
}
}
private TypeInfo[] ParseTypeArgumentList(ISymbol bindingContext)
{
Debug.Assert(PeekNextChar() == '<');
++_index;
var builder = new ArrayBuilder<TypeInfo>();
while (true)
{
var type = ParseType(bindingContext);
if (type == null)
{
builder.Free();
return null;
}
builder.Add(type.Value);
if (PeekNextChar() == ',')
{
++_index;
}
else
{
break;
}
}
if (PeekNextChar() == '>')
{
++_index;
}
else
{
builder.Free();
return null;
}
return builder.ToArrayAndFree();
}
private ITypeSymbol ParseArrayType(ITypeSymbol typeSymbol)
{
Debug.Assert(PeekNextChar() == '[');
++_index;
int rank = 1;
while (true)
{
var nextChar = PeekNextChar();
if (nextChar == ',')
{
++rank;
}
else if (nextChar == ']')
{
++_index;
return _compilation.CreateArrayTypeSymbol(typeSymbol, rank);
}
else if (!char.IsDigit(nextChar) && nextChar != '.')
{
// Malformed array type specifier: invalid character
return null;
}
++_index;
}
}
private ISymbol GetFirstMatchingIndexer(ImmutableArray<ISymbol> candidateMembers, ParameterInfo[] parameters)
{
foreach (var symbol in candidateMembers)
{
var propertySymbol = symbol as IPropertySymbol;
if (propertySymbol != null && AllParametersMatch(propertySymbol.Parameters, parameters))
{
return propertySymbol;
}
}
return null;
}
private ImmutableArray<IMethodSymbol> GetMatchingMethods(ImmutableArray<ISymbol> candidateMembers, int? arity, ParameterInfo[] parameters, TypeInfo? returnType)
{
var builder = new ArrayBuilder<IMethodSymbol>();
foreach (var symbol in candidateMembers)
{
var methodSymbol = symbol as IMethodSymbol;
if (methodSymbol == null ||
(arity != null && methodSymbol.Arity != arity))
{
continue;
}
if (!AllParametersMatch(methodSymbol.Parameters, parameters))
{
continue;
}
if (returnType == null)
{
// If no return type specified, then any matches
builder.Add(methodSymbol);
}
else
{
// If return type is specified, then it must match
var boundReturnType = BindParameterOrReturnType(methodSymbol, returnType.Value);
if (boundReturnType != null && methodSymbol.ReturnType.Equals(boundReturnType))
{
builder.Add(methodSymbol);
}
}
}
return builder.ToImmutableAndFree();
}
private bool AllParametersMatch(ImmutableArray<IParameterSymbol> symbolParameters, ParameterInfo[] expectedParameters)
{
if (symbolParameters.Length != expectedParameters.Length)
{
return false;
}
for (int i = 0; i < expectedParameters.Length; ++i)
{
if (!ParameterMatches(symbolParameters[i], expectedParameters[i]))
{
return false;
}
}
return true;
}
private bool ParameterMatches(IParameterSymbol symbol, ParameterInfo parameterInfo)
{
// same ref'ness?
if ((symbol.RefKind == RefKind.None) == parameterInfo.IsRefOrOut)
{
return false;
}
var parameterType = BindParameterOrReturnType(symbol.ContainingSymbol, parameterInfo.Type);
return parameterType != null && symbol.Type.Equals(parameterType);
}
private ITypeSymbol BindParameterOrReturnType(ISymbol bindingContext, TypeInfo type)
{
if (type.IsBound)
{
return type.Type;
}
var currentIndex = _index;
_index = type.StartIndex;
var result = this.ParseType(bindingContext);
_index = currentIndex;
return result?.Type;
}
private static INamedTypeSymbol GetFirstMatchingNamedType(ImmutableArray<ISymbol> candidateMembers, int arity)
{
return (INamedTypeSymbol)candidateMembers.FirstOrDefault(s =>
s.Kind == SymbolKind.NamedType &&
((INamedTypeSymbol)s).Arity == arity);
}
private static INamespaceOrTypeSymbol GetFirstMatchingNamespaceOrType(ImmutableArray<ISymbol> candidateMembers)
{
return (INamespaceOrTypeSymbol)candidateMembers
.FirstOrDefault(s =>
s.Kind is SymbolKind.Namespace or
SymbolKind.NamedType);
}
private static ITypeParameterSymbol GetNthTypeParameter(INamedTypeSymbol typeSymbol, int n)
{
var containingTypeParameterCount = GetTypeParameterCount(typeSymbol.ContainingType);
if (n < containingTypeParameterCount)
{
return GetNthTypeParameter(typeSymbol.ContainingType, n);
}
return typeSymbol.TypeParameters[n - containingTypeParameterCount];
}
private static int GetTypeParameterCount(INamedTypeSymbol typeSymbol)
{
if (typeSymbol == null)
{
return 0;
}
return typeSymbol.TypeParameters.Length + GetTypeParameterCount(typeSymbol.ContainingType);
}
[StructLayout(LayoutKind.Auto)]
private struct TypeInfo
{
// The type, may be null if unbound.
public readonly ITypeSymbol Type;
// The start index into this.name for parsing this type if the type is not known
// This index is used when rebinding later when the method context is known
public readonly int StartIndex;
public bool IsBound => this.Type != null;
private TypeInfo(ITypeSymbol type, int startIndex)
{
this.Type = type;
this.StartIndex = startIndex;
}
public static TypeInfo Create(ITypeSymbol type)
{
Debug.Assert(type != null);
return new TypeInfo(type, -1);
}
public static TypeInfo CreateUnbound(int startIndex)
{
Debug.Assert(startIndex >= 0);
return new TypeInfo(null, startIndex);
}
}
[StructLayout(LayoutKind.Auto)]
private struct ParameterInfo
{
public readonly TypeInfo Type;
public readonly bool IsRefOrOut;
public ParameterInfo(TypeInfo type, bool isRefOrOut)
{
this.Type = type;
this.IsRefOrOut = isRefOrOut;
}
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Diagnostics
{
internal partial class SuppressMessageAttributeState
{
private const string s_suppressionPrefix = "~";
[StructLayout(LayoutKind.Auto)]
private struct TargetSymbolResolver
{
private static readonly char[] s_nameDelimiters = { ':', '.', '+', '(', ')', '<', '>', '[', ']', '{', '}', ',', '&', '*', '`' };
private static readonly string[] s_callingConventionStrings =
{
"[vararg]",
"[cdecl]",
"[fastcall]",
"[stdcall]",
"[thiscall]"
};
private static readonly ParameterInfo[] s_noParameters = Array.Empty<ParameterInfo>();
private readonly Compilation _compilation;
private readonly TargetScope _scope;
private readonly string _name;
private int _index;
public TargetSymbolResolver(Compilation compilation, TargetScope scope, string fullyQualifiedName)
{
_compilation = compilation;
_scope = scope;
_name = fullyQualifiedName;
_index = 0;
}
private static string RemovePrefix(string id, string prefix)
{
if (id != null && prefix != null && id.StartsWith(prefix, StringComparison.Ordinal))
{
return id[prefix.Length..];
}
return id;
}
/// <summary>
/// Attempts to resolve the "Target" argument of the global SuppressMessageAttribute to symbols in compilation.
/// </summary>
/// <param name="resolvedWithDocCommentIdFormat">Indicates if resolved "Target" argument is in Roslyn's <see cref="DocumentationCommentId"/> format.</param>
/// <returns>Resolved symbols for the the "Target" argument of the global SuppressMessageAttribute.</returns>
public ImmutableArray<ISymbol> Resolve(out bool resolvedWithDocCommentIdFormat)
{
resolvedWithDocCommentIdFormat = false;
if (string.IsNullOrEmpty(_name))
{
return ImmutableArray<ISymbol>.Empty;
}
// Try to parse the name as declaration ID generated from symbol's documentation comment Id.
var nameWithoutPrefix = RemovePrefix(_name, s_suppressionPrefix);
var docIdResults = DocumentationCommentId.GetSymbolsForDeclarationId(nameWithoutPrefix, _compilation);
if (docIdResults.Length > 0)
{
resolvedWithDocCommentIdFormat = true;
return docIdResults;
}
var results = ArrayBuilder<ISymbol>.GetInstance();
// Parse 'e:' prefix used by FxCop to differentiate between event and non-event symbols of the same name.
bool isEvent = false;
if (_name.Length >= 2 && _name[0] == 'e' && _name[1] == ':')
{
isEvent = true;
_index = 2;
}
INamespaceOrTypeSymbol containingSymbol = _compilation.GlobalNamespace;
bool? segmentIsNamedTypeName = null;
while (true)
{
var segment = ParseNextNameSegment();
// Special case: Roslyn names indexers "this[]" in CSharp, FxCop names them "Item" with parameters in [] brackets
bool isIndexerProperty = false;
if (segment == "Item" && PeekNextChar() == '[')
{
isIndexerProperty = true;
if (_compilation.Language == LanguageNames.CSharp)
{
segment = "this[]";
}
}
var candidateMembers = containingSymbol.GetMembers(segment);
if (candidateMembers.Length == 0)
{
break;
}
if (segmentIsNamedTypeName.HasValue)
{
candidateMembers = segmentIsNamedTypeName.Value ?
candidateMembers.Where(s => s.Kind == SymbolKind.NamedType).ToImmutableArray() :
candidateMembers.Where(s => s.Kind != SymbolKind.NamedType).ToImmutableArray();
segmentIsNamedTypeName = null;
}
int? arity = null;
ParameterInfo[] parameters = null;
// Check for generic arity
if (_scope != TargetScope.Namespace && PeekNextChar() == '`')
{
++_index;
arity = ReadNextInteger();
}
// Check for method or indexer parameter list
var nextChar = PeekNextChar();
if (!isIndexerProperty && nextChar == '(' || isIndexerProperty && nextChar == '[')
{
parameters = ParseParameterList();
if (parameters == null)
{
// Failed to resolve parameter list
break;
}
}
else if (nextChar is '.' or '+')
{
++_index;
if (arity > 0 || nextChar == '+')
{
// The name continues and either has an arity or specifically continues with a '+'
// so segment must be the name of a named type
containingSymbol = GetFirstMatchingNamedType(candidateMembers, arity ?? 0);
}
else
{
// The name continues with a '.' and does not specify a generic arity
// so segment must be the name of a namespace or a named type
containingSymbol = GetFirstMatchingNamespaceOrType(candidateMembers);
}
if (containingSymbol == null)
{
// If we cannot resolve the name on the left of the delimiter, we have no
// hope of finding the symbol.
break;
}
if (containingSymbol.Kind == SymbolKind.NamedType)
{
// If segment resolves to a named type, that restricts what the next segment
// can resolve to depending on whether the name continues with '+' or '.'
segmentIsNamedTypeName = nextChar == '+';
}
continue;
}
if (_scope == TargetScope.Member && !isIndexerProperty && parameters != null)
{
TypeInfo? returnType = null;
if (PeekNextChar() == ':')
{
++_index;
returnType = ParseNamedType(null);
}
foreach (var method in GetMatchingMethods(candidateMembers, arity, parameters, returnType))
{
results.Add(method);
}
break;
}
ISymbol singleResult;
switch (_scope)
{
case TargetScope.Namespace:
singleResult = candidateMembers.FirstOrDefault(s => s.Kind == SymbolKind.Namespace);
break;
case TargetScope.Type:
singleResult = GetFirstMatchingNamedType(candidateMembers, arity ?? 0);
break;
case TargetScope.Member:
if (isIndexerProperty)
{
singleResult = GetFirstMatchingIndexer(candidateMembers, parameters);
}
else if (isEvent)
{
singleResult = candidateMembers.FirstOrDefault(s => s.Kind == SymbolKind.Event);
}
else
{
singleResult = candidateMembers.FirstOrDefault(s =>
s.Kind is not SymbolKind.Namespace and
not SymbolKind.NamedType);
}
break;
default:
throw ExceptionUtilities.UnexpectedValue(_scope);
}
if (singleResult != null)
{
results.Add(singleResult);
}
break;
}
return results.ToImmutableAndFree();
}
private string ParseNextNameSegment()
{
// Ignore optional octothorpe in the member name used by FxCop to differentiate between
// Orcas and Whidbey name providers. The fully-qualified member name format generated by each of
// these name providers is similar enough that we can just ignore this character.
if (PeekNextChar() == '#')
{
++_index;
// Ignore calling convention strings generated by FxCop for methods.
// Methods can't differ solely by calling convention in C# or VB.
if (PeekNextChar() == '[')
{
foreach (string callingConvention in s_callingConventionStrings)
{
if (callingConvention == _name.Substring(_index, callingConvention.Length))
{
_index += callingConvention.Length;
break;
}
}
}
}
string segment;
// Find the end of the next name segment, special case constructors which start with '.'
int delimiterOffset = PeekNextChar() == '.' ?
_name.IndexOfAny(s_nameDelimiters, _index + 1) :
_name.IndexOfAny(s_nameDelimiters, _index);
if (delimiterOffset >= 0)
{
segment = _name[_index..delimiterOffset];
_index = delimiterOffset;
}
else
{
segment = _name[_index..];
_index = _name.Length;
}
return segment;
}
private char PeekNextChar()
{
return _index >= _name.Length ? '\0' : _name[_index];
}
private int ReadNextInteger()
{
int n = 0;
while (_index < _name.Length && char.IsDigit(_name[_index]))
{
n = n * 10 + (_name[_index] - '0');
++_index;
}
return n;
}
private ParameterInfo[] ParseParameterList()
{
// Consume the opening parenthesis or bracket
Debug.Assert(PeekNextChar() is '(' or '[');
++_index;
var nextChar = PeekNextChar();
if (nextChar is ')' or ']')
{
// Empty parameter list
++_index;
return s_noParameters;
}
var builder = new ArrayBuilder<ParameterInfo>();
while (true)
{
var parameter = ParseParameter();
if (parameter != null)
{
builder.Add(parameter.Value);
}
else
{
builder.Free();
return null;
}
if (PeekNextChar() == ',')
{
++_index;
}
else
{
break;
}
}
nextChar = PeekNextChar();
if (nextChar is ')' or ']')
{
// Consume the closing parenthesis or bracket
++_index;
}
else
{
// Malformed parameter list: missing close parenthesis or bracket
builder.Free();
return null;
}
return builder.ToArrayAndFree();
}
private ParameterInfo? ParseParameter()
{
var type = ParseType(null);
if (type == null)
{
return null;
}
var isRefOrOut = PeekNextChar() == '&';
if (isRefOrOut)
{
++_index;
}
return new ParameterInfo(type.Value, isRefOrOut);
}
private TypeInfo? ParseType(ISymbol bindingContext)
{
TypeInfo? result;
IgnoreCustomModifierList();
if (PeekNextChar() == '!')
{
result = ParseIndexedTypeParameter(bindingContext);
}
else
{
result = ParseNamedType(bindingContext);
// If parsing as a named type failed, this could be a named type parameter,
// which we will only be able to resolve once we have a binding context.
if (bindingContext != null && result.HasValue && !result.Value.IsBound)
{
_index = result.Value.StartIndex;
result = ParseNamedTypeParameter(bindingContext);
}
}
if (result == null)
{
return null;
}
if (result.Value.IsBound)
{
var typeSymbol = result.Value.Type;
// Handle pointer and array specifiers for bound types
while (true)
{
IgnoreCustomModifierList();
var nextChar = PeekNextChar();
if (nextChar == '[')
{
typeSymbol = ParseArrayType(typeSymbol);
if (typeSymbol == null)
{
return null;
}
continue;
}
if (nextChar == '*')
{
++_index;
typeSymbol = _compilation.CreatePointerTypeSymbol(typeSymbol);
continue;
}
break;
}
return TypeInfo.Create(typeSymbol);
}
// Skip pointer and array specifiers for unbound types
IgnorePointerAndArraySpecifiers();
return result;
}
private void IgnoreCustomModifierList()
{
// NOTE: There is currently no way to create symbols
// with custom modifiers from outside the compiler layer. In
// particular, there is no language agnostic way to attach custom
// modifiers to symbols. As a result we cannot match symbols which
// have custom modifiers, because their public equals overrides in
// general explicitly check custom modifiers. So we just ignore
// custom modifier lists. This would only matter in the case that
// someone targeted a SuppressMessageAttribute at a method that
// overloads a method from metadata which uses custom modifiers.
if (PeekNextChar() == '{')
{
for (; _index < _name.Length && _name[_index] != '}'; ++_index) { }
}
}
private void IgnorePointerAndArraySpecifiers()
{
bool inBrackets = false;
for (; _index < _name.Length; ++_index)
{
switch (PeekNextChar())
{
case '[':
inBrackets = true;
break;
case ']':
if (!inBrackets)
{
// End of indexer parameter list
return;
}
inBrackets = false;
break;
case '*':
break;
default:
if (!inBrackets)
{
// End of parameter type name
return;
}
break;
}
}
}
private TypeInfo? ParseIndexedTypeParameter(ISymbol bindingContext)
{
var startIndex = _index;
Debug.Assert(PeekNextChar() == '!');
++_index;
if (PeekNextChar() == '!')
{
// !! means this is a method type parameter
++_index;
var methodTypeParameterIndex = ReadNextInteger();
var methodContext = bindingContext as IMethodSymbol;
if (methodContext != null)
{
var count = methodContext.TypeParameters.Length;
if (count > 0 && methodTypeParameterIndex < count)
{
return TypeInfo.Create(methodContext.TypeParameters[methodTypeParameterIndex]);
}
// No such parameter
return null;
}
// If there is no method context, then the type is unbound and must be bound later
return TypeInfo.CreateUnbound(startIndex);
}
// ! means this is a regular type parameter
var typeParameterIndex = ReadNextInteger();
if (bindingContext != null)
{
var typeParameter = GetNthTypeParameter(bindingContext.ContainingType, typeParameterIndex);
if (typeParameter != null)
{
return TypeInfo.Create(typeParameter);
}
// no such parameter
return null;
}
// If there is no binding context, then the type is unbound and must be bound later
return TypeInfo.CreateUnbound(startIndex);
}
private TypeInfo? ParseNamedTypeParameter(ISymbol bindingContext)
{
Debug.Assert(bindingContext != null);
var typeParameterName = ParseNextNameSegment();
var methodContext = bindingContext as IMethodSymbol;
if (methodContext != null)
{
// Check this method's type parameters for a name that matches
for (int i = 0; i < methodContext.TypeParameters.Length; ++i)
{
if (methodContext.TypeParameters[i].Name == typeParameterName)
{
return TypeInfo.Create(methodContext.TypeArguments[i]);
}
}
}
// Walk up the symbol tree until we find a type parameter with a name that matches
for (var containingType = bindingContext.ContainingType; containingType != null; containingType = containingType.ContainingType)
{
for (int i = 0; i < containingType.TypeParameters.Length; ++i)
{
if (containingType.TypeParameters[i].Name == typeParameterName)
{
return TypeInfo.Create(containingType.TypeArguments[i]);
}
}
}
return null;
}
private TypeInfo? ParseNamedType(ISymbol bindingContext)
{
INamespaceOrTypeSymbol containingSymbol = _compilation.GlobalNamespace;
int startIndex = _index;
while (true)
{
var segment = ParseNextNameSegment();
var candidateMembers = containingSymbol.GetMembers(segment);
if (candidateMembers.Length == 0)
{
return TypeInfo.CreateUnbound(startIndex);
}
int arity = 0;
TypeInfo[] typeArguments = null;
// Check for generic arity
if (PeekNextChar() == '`')
{
++_index;
arity = ReadNextInteger();
}
// Check for type argument list
if (PeekNextChar() == '<')
{
typeArguments = ParseTypeArgumentList(bindingContext);
if (typeArguments == null)
{
return null;
}
if (typeArguments.Any(a => !a.IsBound))
{
return TypeInfo.CreateUnbound(startIndex);
}
}
var nextChar = PeekNextChar();
if (nextChar is '.' or '+')
{
++_index;
if (arity > 0 || nextChar == '+')
{
// Segment is the name of a named type since the name has an arity or continues with a '+'
containingSymbol = GetFirstMatchingNamedType(candidateMembers, arity);
}
else
{
// Segment is the name of a namespace or type because the name continues with a '.'
containingSymbol = GetFirstMatchingNamespaceOrType(candidateMembers);
}
if (containingSymbol == null)
{
// If we cannot resolve the name on the left of the delimiter, we have no
// hope of finding the symbol.
return null;
}
continue;
}
INamedTypeSymbol typeSymbol = GetFirstMatchingNamedType(candidateMembers, arity);
if (typeSymbol == null)
{
return null;
}
if (typeArguments != null)
{
typeSymbol = typeSymbol.Construct(typeArguments.Select(t => t.Type).ToArray());
}
return TypeInfo.Create(typeSymbol);
}
}
private TypeInfo[] ParseTypeArgumentList(ISymbol bindingContext)
{
Debug.Assert(PeekNextChar() == '<');
++_index;
var builder = new ArrayBuilder<TypeInfo>();
while (true)
{
var type = ParseType(bindingContext);
if (type == null)
{
builder.Free();
return null;
}
builder.Add(type.Value);
if (PeekNextChar() == ',')
{
++_index;
}
else
{
break;
}
}
if (PeekNextChar() == '>')
{
++_index;
}
else
{
builder.Free();
return null;
}
return builder.ToArrayAndFree();
}
private ITypeSymbol ParseArrayType(ITypeSymbol typeSymbol)
{
Debug.Assert(PeekNextChar() == '[');
++_index;
int rank = 1;
while (true)
{
var nextChar = PeekNextChar();
if (nextChar == ',')
{
++rank;
}
else if (nextChar == ']')
{
++_index;
return _compilation.CreateArrayTypeSymbol(typeSymbol, rank);
}
else if (!char.IsDigit(nextChar) && nextChar != '.')
{
// Malformed array type specifier: invalid character
return null;
}
++_index;
}
}
private ISymbol GetFirstMatchingIndexer(ImmutableArray<ISymbol> candidateMembers, ParameterInfo[] parameters)
{
foreach (var symbol in candidateMembers)
{
var propertySymbol = symbol as IPropertySymbol;
if (propertySymbol != null && AllParametersMatch(propertySymbol.Parameters, parameters))
{
return propertySymbol;
}
}
return null;
}
private ImmutableArray<IMethodSymbol> GetMatchingMethods(ImmutableArray<ISymbol> candidateMembers, int? arity, ParameterInfo[] parameters, TypeInfo? returnType)
{
var builder = new ArrayBuilder<IMethodSymbol>();
foreach (var symbol in candidateMembers)
{
var methodSymbol = symbol as IMethodSymbol;
if (methodSymbol == null ||
(arity != null && methodSymbol.Arity != arity))
{
continue;
}
if (!AllParametersMatch(methodSymbol.Parameters, parameters))
{
continue;
}
if (returnType == null)
{
// If no return type specified, then any matches
builder.Add(methodSymbol);
}
else
{
// If return type is specified, then it must match
var boundReturnType = BindParameterOrReturnType(methodSymbol, returnType.Value);
if (boundReturnType != null && methodSymbol.ReturnType.Equals(boundReturnType))
{
builder.Add(methodSymbol);
}
}
}
return builder.ToImmutableAndFree();
}
private bool AllParametersMatch(ImmutableArray<IParameterSymbol> symbolParameters, ParameterInfo[] expectedParameters)
{
if (symbolParameters.Length != expectedParameters.Length)
{
return false;
}
for (int i = 0; i < expectedParameters.Length; ++i)
{
if (!ParameterMatches(symbolParameters[i], expectedParameters[i]))
{
return false;
}
}
return true;
}
private bool ParameterMatches(IParameterSymbol symbol, ParameterInfo parameterInfo)
{
// same ref'ness?
if ((symbol.RefKind == RefKind.None) == parameterInfo.IsRefOrOut)
{
return false;
}
var parameterType = BindParameterOrReturnType(symbol.ContainingSymbol, parameterInfo.Type);
return parameterType != null && symbol.Type.Equals(parameterType);
}
private ITypeSymbol BindParameterOrReturnType(ISymbol bindingContext, TypeInfo type)
{
if (type.IsBound)
{
return type.Type;
}
var currentIndex = _index;
_index = type.StartIndex;
var result = this.ParseType(bindingContext);
_index = currentIndex;
return result?.Type;
}
private static INamedTypeSymbol GetFirstMatchingNamedType(ImmutableArray<ISymbol> candidateMembers, int arity)
{
return (INamedTypeSymbol)candidateMembers.FirstOrDefault(s =>
s.Kind == SymbolKind.NamedType &&
((INamedTypeSymbol)s).Arity == arity);
}
private static INamespaceOrTypeSymbol GetFirstMatchingNamespaceOrType(ImmutableArray<ISymbol> candidateMembers)
{
return (INamespaceOrTypeSymbol)candidateMembers
.FirstOrDefault(s =>
s.Kind is SymbolKind.Namespace or
SymbolKind.NamedType);
}
private static ITypeParameterSymbol GetNthTypeParameter(INamedTypeSymbol typeSymbol, int n)
{
var containingTypeParameterCount = GetTypeParameterCount(typeSymbol.ContainingType);
if (n < containingTypeParameterCount)
{
return GetNthTypeParameter(typeSymbol.ContainingType, n);
}
return typeSymbol.TypeParameters[n - containingTypeParameterCount];
}
private static int GetTypeParameterCount(INamedTypeSymbol typeSymbol)
{
if (typeSymbol == null)
{
return 0;
}
return typeSymbol.TypeParameters.Length + GetTypeParameterCount(typeSymbol.ContainingType);
}
[StructLayout(LayoutKind.Auto)]
private struct TypeInfo
{
// The type, may be null if unbound.
public readonly ITypeSymbol Type;
// The start index into this.name for parsing this type if the type is not known
// This index is used when rebinding later when the method context is known
public readonly int StartIndex;
public bool IsBound => this.Type != null;
private TypeInfo(ITypeSymbol type, int startIndex)
{
this.Type = type;
this.StartIndex = startIndex;
}
public static TypeInfo Create(ITypeSymbol type)
{
Debug.Assert(type != null);
return new TypeInfo(type, -1);
}
public static TypeInfo CreateUnbound(int startIndex)
{
Debug.Assert(startIndex >= 0);
return new TypeInfo(null, startIndex);
}
}
[StructLayout(LayoutKind.Auto)]
private struct ParameterInfo
{
public readonly TypeInfo Type;
public readonly bool IsRefOrOut;
public ParameterInfo(TypeInfo type, bool isRefOrOut)
{
this.Type = type;
this.IsRefOrOut = isRefOrOut;
}
}
}
}
}
| -1 |
dotnet/roslyn | 55,877 | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute | Part of C# 10 support | davidwengier | 2021-08-25T05:36:27Z | 2021-08-30T20:47:11Z | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | 023d3ca2b5fb429f0b3dcc1efeed39442e232dba | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute. Part of C# 10 support | ./src/Features/Core/Portable/Shared/Extensions/DocumentExtensions.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Completion;
using Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Formatting.Rules;
using Microsoft.CodeAnalysis.Shared.Naming;
using Microsoft.CodeAnalysis.Simplification;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
using static Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles.SymbolSpecification;
namespace Microsoft.CodeAnalysis.Shared.Extensions
{
internal static class DocumentExtensions
{
public static bool ShouldHideAdvancedMembers(this Document document)
{
// Since we don't actually have a way to configure this per-document, we can fetch from the solution
return document.Project.Solution.Options.GetOption(CompletionOptions.HideAdvancedMembers, document.Project.Language);
}
public static async Task<Document> ReplaceNodeAsync<TNode>(this Document document, TNode oldNode, TNode newNode, CancellationToken cancellationToken)
where TNode : SyntaxNode
{
var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
return document.ReplaceNode(root, oldNode, newNode);
}
public static Document ReplaceNodeSynchronously<TNode>(this Document document, TNode oldNode, TNode newNode, CancellationToken cancellationToken)
where TNode : SyntaxNode
{
var root = document.GetRequiredSyntaxRootSynchronously(cancellationToken);
return document.ReplaceNode(root, oldNode, newNode);
}
public static Document ReplaceNode<TNode>(this Document document, SyntaxNode root, TNode oldNode, TNode newNode)
where TNode : SyntaxNode
{
Debug.Assert(document.GetRequiredSyntaxRootSynchronously(CancellationToken.None) == root);
var newRoot = root.ReplaceNode(oldNode, newNode);
return document.WithSyntaxRoot(newRoot);
}
public static async Task<Document> ReplaceNodesAsync(this Document document,
IEnumerable<SyntaxNode> nodes,
Func<SyntaxNode, SyntaxNode, SyntaxNode> computeReplacementNode,
CancellationToken cancellationToken)
{
var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var newRoot = root.ReplaceNodes(nodes, computeReplacementNode);
return document.WithSyntaxRoot(newRoot);
}
public static async Task<ImmutableArray<T>> GetUnionItemsFromDocumentAndLinkedDocumentsAsync<T>(
this Document document,
IEqualityComparer<T> comparer,
Func<Document, Task<ImmutableArray<T>>> getItemsWorker)
{
var totalItems = new HashSet<T>(comparer);
var values = await getItemsWorker(document).ConfigureAwait(false);
totalItems.AddRange(values.NullToEmpty());
foreach (var linkedDocumentId in document.GetLinkedDocumentIds())
{
values = await getItemsWorker(document.Project.Solution.GetRequiredDocument(linkedDocumentId)).ConfigureAwait(false);
totalItems.AddRange(values.NullToEmpty());
}
return totalItems.ToImmutableArray();
}
public static async Task<bool> IsValidContextForDocumentOrLinkedDocumentsAsync(
this Document document,
Func<Document, CancellationToken, Task<bool>> contextChecker,
CancellationToken cancellationToken)
{
if (await contextChecker(document, cancellationToken).ConfigureAwait(false))
{
return true;
}
var solution = document.Project.Solution;
foreach (var linkedDocumentId in document.GetLinkedDocumentIds())
{
var linkedDocument = solution.GetRequiredDocument(linkedDocumentId);
if (await contextChecker(linkedDocument, cancellationToken).ConfigureAwait(false))
{
return true;
}
}
return false;
}
/// <summary>
/// Gets the set of naming rules the user has set for this document. Will include a set of default naming rules
/// that match if the user hasn't specified any for a particular symbol type. The are added at the end so they
/// will only be used if the user hasn't specified a preference.
/// </summary>
public static Task<ImmutableArray<NamingRule>> GetNamingRulesAsync(
this Document document, CancellationToken cancellationToken)
=> document.GetNamingRulesAsync(FallbackNamingRules.Default, cancellationToken);
/// <summary>
/// Get the user-specified naming rules, with the added <paramref name="defaultRules"/>.
/// </summary>
public static async Task<ImmutableArray<NamingRule>> GetNamingRulesAsync(this Document document,
ImmutableArray<NamingRule> defaultRules, CancellationToken cancellationToken)
{
var options = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false);
var namingStyleOptions = options.GetOption(NamingStyleOptions.NamingPreferences);
var rules = namingStyleOptions.CreateRules().NamingRules;
return defaultRules.IsDefaultOrEmpty ? rules : rules.AddRange(defaultRules);
}
public static async Task<NamingRule> GetApplicableNamingRuleAsync(this Document document, ISymbol symbol, CancellationToken cancellationToken)
{
var rules = await document.GetNamingRulesAsync(cancellationToken).ConfigureAwait(false);
foreach (var rule in rules)
{
if (rule.SymbolSpecification.AppliesTo(symbol))
return rule;
}
throw ExceptionUtilities.Unreachable;
}
public static async Task<NamingRule> GetApplicableNamingRuleAsync(
this Document document, SymbolKind symbolKind, Accessibility accessibility, CancellationToken cancellationToken)
{
var rules = await document.GetNamingRulesAsync(cancellationToken).ConfigureAwait(false);
foreach (var rule in rules)
{
if (rule.SymbolSpecification.AppliesTo(symbolKind, accessibility))
return rule;
}
throw ExceptionUtilities.Unreachable;
}
public static async Task<NamingRule> GetApplicableNamingRuleAsync(
this Document document, SymbolKindOrTypeKind kind, DeclarationModifiers modifiers, Accessibility? accessibility, CancellationToken cancellationToken)
{
var rules = await document.GetNamingRulesAsync(cancellationToken).ConfigureAwait(false);
foreach (var rule in rules)
{
if (rule.SymbolSpecification.AppliesTo(kind, modifiers, accessibility))
return rule;
}
throw ExceptionUtilities.Unreachable;
}
public static ImmutableArray<AbstractFormattingRule> GetFormattingRules(this Document document, TextSpan span, IEnumerable<AbstractFormattingRule>? additionalRules)
{
var workspace = document.Project.Solution.Workspace;
var formattingRuleFactory = workspace.Services.GetRequiredService<IHostDependentFormattingRuleFactoryService>();
// Not sure why this is being done... there aren't any docs on CreateRule either.
var position = (span.Start + span.End) / 2;
var rules = ImmutableArray.Create(formattingRuleFactory.CreateRule(document, position));
if (additionalRules != null)
{
rules = rules.AddRange(additionalRules);
}
return rules.AddRange(Formatter.GetDefaultFormattingRules(document));
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Completion;
using Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Formatting.Rules;
using Microsoft.CodeAnalysis.Shared.Naming;
using Microsoft.CodeAnalysis.Simplification;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
using static Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles.SymbolSpecification;
namespace Microsoft.CodeAnalysis.Shared.Extensions
{
internal static class DocumentExtensions
{
public static bool ShouldHideAdvancedMembers(this Document document)
{
// Since we don't actually have a way to configure this per-document, we can fetch from the solution
return document.Project.Solution.Options.GetOption(CompletionOptions.HideAdvancedMembers, document.Project.Language);
}
public static async Task<Document> ReplaceNodeAsync<TNode>(this Document document, TNode oldNode, TNode newNode, CancellationToken cancellationToken)
where TNode : SyntaxNode
{
var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
return document.ReplaceNode(root, oldNode, newNode);
}
public static Document ReplaceNodeSynchronously<TNode>(this Document document, TNode oldNode, TNode newNode, CancellationToken cancellationToken)
where TNode : SyntaxNode
{
var root = document.GetRequiredSyntaxRootSynchronously(cancellationToken);
return document.ReplaceNode(root, oldNode, newNode);
}
public static Document ReplaceNode<TNode>(this Document document, SyntaxNode root, TNode oldNode, TNode newNode)
where TNode : SyntaxNode
{
Debug.Assert(document.GetRequiredSyntaxRootSynchronously(CancellationToken.None) == root);
var newRoot = root.ReplaceNode(oldNode, newNode);
return document.WithSyntaxRoot(newRoot);
}
public static async Task<Document> ReplaceNodesAsync(this Document document,
IEnumerable<SyntaxNode> nodes,
Func<SyntaxNode, SyntaxNode, SyntaxNode> computeReplacementNode,
CancellationToken cancellationToken)
{
var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var newRoot = root.ReplaceNodes(nodes, computeReplacementNode);
return document.WithSyntaxRoot(newRoot);
}
public static async Task<ImmutableArray<T>> GetUnionItemsFromDocumentAndLinkedDocumentsAsync<T>(
this Document document,
IEqualityComparer<T> comparer,
Func<Document, Task<ImmutableArray<T>>> getItemsWorker)
{
var totalItems = new HashSet<T>(comparer);
var values = await getItemsWorker(document).ConfigureAwait(false);
totalItems.AddRange(values.NullToEmpty());
foreach (var linkedDocumentId in document.GetLinkedDocumentIds())
{
values = await getItemsWorker(document.Project.Solution.GetRequiredDocument(linkedDocumentId)).ConfigureAwait(false);
totalItems.AddRange(values.NullToEmpty());
}
return totalItems.ToImmutableArray();
}
public static async Task<bool> IsValidContextForDocumentOrLinkedDocumentsAsync(
this Document document,
Func<Document, CancellationToken, Task<bool>> contextChecker,
CancellationToken cancellationToken)
{
if (await contextChecker(document, cancellationToken).ConfigureAwait(false))
{
return true;
}
var solution = document.Project.Solution;
foreach (var linkedDocumentId in document.GetLinkedDocumentIds())
{
var linkedDocument = solution.GetRequiredDocument(linkedDocumentId);
if (await contextChecker(linkedDocument, cancellationToken).ConfigureAwait(false))
{
return true;
}
}
return false;
}
/// <summary>
/// Gets the set of naming rules the user has set for this document. Will include a set of default naming rules
/// that match if the user hasn't specified any for a particular symbol type. The are added at the end so they
/// will only be used if the user hasn't specified a preference.
/// </summary>
public static Task<ImmutableArray<NamingRule>> GetNamingRulesAsync(
this Document document, CancellationToken cancellationToken)
=> document.GetNamingRulesAsync(FallbackNamingRules.Default, cancellationToken);
/// <summary>
/// Get the user-specified naming rules, with the added <paramref name="defaultRules"/>.
/// </summary>
public static async Task<ImmutableArray<NamingRule>> GetNamingRulesAsync(this Document document,
ImmutableArray<NamingRule> defaultRules, CancellationToken cancellationToken)
{
var options = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false);
var namingStyleOptions = options.GetOption(NamingStyleOptions.NamingPreferences);
var rules = namingStyleOptions.CreateRules().NamingRules;
return defaultRules.IsDefaultOrEmpty ? rules : rules.AddRange(defaultRules);
}
public static async Task<NamingRule> GetApplicableNamingRuleAsync(this Document document, ISymbol symbol, CancellationToken cancellationToken)
{
var rules = await document.GetNamingRulesAsync(cancellationToken).ConfigureAwait(false);
foreach (var rule in rules)
{
if (rule.SymbolSpecification.AppliesTo(symbol))
return rule;
}
throw ExceptionUtilities.Unreachable;
}
public static async Task<NamingRule> GetApplicableNamingRuleAsync(
this Document document, SymbolKind symbolKind, Accessibility accessibility, CancellationToken cancellationToken)
{
var rules = await document.GetNamingRulesAsync(cancellationToken).ConfigureAwait(false);
foreach (var rule in rules)
{
if (rule.SymbolSpecification.AppliesTo(symbolKind, accessibility))
return rule;
}
throw ExceptionUtilities.Unreachable;
}
public static async Task<NamingRule> GetApplicableNamingRuleAsync(
this Document document, SymbolKindOrTypeKind kind, DeclarationModifiers modifiers, Accessibility? accessibility, CancellationToken cancellationToken)
{
var rules = await document.GetNamingRulesAsync(cancellationToken).ConfigureAwait(false);
foreach (var rule in rules)
{
if (rule.SymbolSpecification.AppliesTo(kind, modifiers, accessibility))
return rule;
}
throw ExceptionUtilities.Unreachable;
}
public static ImmutableArray<AbstractFormattingRule> GetFormattingRules(this Document document, TextSpan span, IEnumerable<AbstractFormattingRule>? additionalRules)
{
var workspace = document.Project.Solution.Workspace;
var formattingRuleFactory = workspace.Services.GetRequiredService<IHostDependentFormattingRuleFactoryService>();
// Not sure why this is being done... there aren't any docs on CreateRule either.
var position = (span.Start + span.End) / 2;
var rules = ImmutableArray.Create(formattingRuleFactory.CreateRule(document, position));
if (additionalRules != null)
{
rules = rules.AddRange(additionalRules);
}
return rules.AddRange(Formatter.GetDefaultFormattingRules(document));
}
}
}
| -1 |
dotnet/roslyn | 55,877 | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute | Part of C# 10 support | davidwengier | 2021-08-25T05:36:27Z | 2021-08-30T20:47:11Z | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | 023d3ca2b5fb429f0b3dcc1efeed39442e232dba | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute. Part of C# 10 support | ./src/Compilers/CSharp/Portable/FlowAnalysis/AbstractFlowPass.ILocalState.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
namespace Microsoft.CodeAnalysis.CSharp
{
internal partial class AbstractFlowPass<TLocalState, TLocalFunctionState>
{
/// <summary>
/// This is the "top" state of the data flow lattice. Generally, it is considered the state
/// which is reachable, but no information is yet available. This is the state used at the
/// start of method bodies.
/// </summary>
protected abstract TLocalState TopState();
/// <summary>
/// This is the absolute "bottom" state of the data flow lattice. C# does not specify a
/// difference between unreachable states, so there can only be one. This is the state used
/// for unreachable code, like statements after a "return" or "throw" statement.
/// </summary>
protected abstract TLocalState UnreachableState();
/// <summary>
/// This should be a reachable state that won't affect another reachable state in a
/// <see cref="Join(ref TLocalState, ref TLocalState)"/>.
///
/// Nontrivial implementation is required for DataFlowsOutWalker or any flow analysis pass
/// that "tracks unassignments" like the nullable walker. The result should be a state, for
/// each variable, that is the strongest result possible (i.e. definitely assigned for the
/// data flow passes, or not null for the nullable analysis).
/// operation.
/// </summary>
protected virtual TLocalState ReachableBottomState() => default;
/// <summary>
/// The "Join" operation is used when two separate control flow paths converge at a single
/// statement. This operation is used to combine the if/else paths of a conditional, or two
/// "goto" statements to the same label, for example.
///
/// According to convention, Join moves "up" the lattice, so the following equations must hold:
/// 1. Join(Unreachable(), X) = X
/// 2. Join(Top, X) = Top
///
/// </summary>
/// <returns>
/// True if <paramref name="self"/> was changed. False otherwise.
/// </returns>
protected abstract bool Join(ref TLocalState self, ref TLocalState other);
/// <summary>
/// The Meet operation is the inverse of <see cref="Join(ref TLocalState, ref TLocalState)"/>.
/// It's used when combining state additively, like when the state from a return statement
/// inside a 'try' clause is combined with the end state of a 'finally' clause.
///
/// This moves "down" our flow lattice, by convention. The following equations must hold:
/// 1. Meet(Unreachable, X) = Unreachable
/// 2. Meet(ReachableBottom, X - Unreachable) = ReachableBottom
/// 3. Meet(Top, X) = X
///
/// </summary>
protected abstract bool Meet(ref TLocalState self, ref TLocalState other);
internal interface ILocalState
{
/// <summary>
/// Produce a duplicate of this flow analysis state.
/// </summary>
TLocalState Clone();
/// <summary>
/// Is the code reachable?
/// </summary>
bool Reachable { get; }
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
namespace Microsoft.CodeAnalysis.CSharp
{
internal partial class AbstractFlowPass<TLocalState, TLocalFunctionState>
{
/// <summary>
/// This is the "top" state of the data flow lattice. Generally, it is considered the state
/// which is reachable, but no information is yet available. This is the state used at the
/// start of method bodies.
/// </summary>
protected abstract TLocalState TopState();
/// <summary>
/// This is the absolute "bottom" state of the data flow lattice. C# does not specify a
/// difference between unreachable states, so there can only be one. This is the state used
/// for unreachable code, like statements after a "return" or "throw" statement.
/// </summary>
protected abstract TLocalState UnreachableState();
/// <summary>
/// This should be a reachable state that won't affect another reachable state in a
/// <see cref="Join(ref TLocalState, ref TLocalState)"/>.
///
/// Nontrivial implementation is required for DataFlowsOutWalker or any flow analysis pass
/// that "tracks unassignments" like the nullable walker. The result should be a state, for
/// each variable, that is the strongest result possible (i.e. definitely assigned for the
/// data flow passes, or not null for the nullable analysis).
/// operation.
/// </summary>
protected virtual TLocalState ReachableBottomState() => default;
/// <summary>
/// The "Join" operation is used when two separate control flow paths converge at a single
/// statement. This operation is used to combine the if/else paths of a conditional, or two
/// "goto" statements to the same label, for example.
///
/// According to convention, Join moves "up" the lattice, so the following equations must hold:
/// 1. Join(Unreachable(), X) = X
/// 2. Join(Top, X) = Top
///
/// </summary>
/// <returns>
/// True if <paramref name="self"/> was changed. False otherwise.
/// </returns>
protected abstract bool Join(ref TLocalState self, ref TLocalState other);
/// <summary>
/// The Meet operation is the inverse of <see cref="Join(ref TLocalState, ref TLocalState)"/>.
/// It's used when combining state additively, like when the state from a return statement
/// inside a 'try' clause is combined with the end state of a 'finally' clause.
///
/// This moves "down" our flow lattice, by convention. The following equations must hold:
/// 1. Meet(Unreachable, X) = Unreachable
/// 2. Meet(ReachableBottom, X - Unreachable) = ReachableBottom
/// 3. Meet(Top, X) = X
///
/// </summary>
protected abstract bool Meet(ref TLocalState self, ref TLocalState other);
internal interface ILocalState
{
/// <summary>
/// Produce a duplicate of this flow analysis state.
/// </summary>
TLocalState Clone();
/// <summary>
/// Is the code reachable?
/// </summary>
bool Reachable { get; }
}
}
}
| -1 |
dotnet/roslyn | 55,877 | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute | Part of C# 10 support | davidwengier | 2021-08-25T05:36:27Z | 2021-08-30T20:47:11Z | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | 023d3ca2b5fb429f0b3dcc1efeed39442e232dba | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute. Part of C# 10 support | ./src/Tools/IdeBenchmarks/SQLitePersistentStorageBenchmark.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using BenchmarkDotNet.Attributes;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.PersistentStorage;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.SQLite.v2;
using Microsoft.CodeAnalysis.Storage;
using Microsoft.CodeAnalysis.Test.Utilities;
namespace IdeBenchmarks
{
public class SQLitePersistentStorageBenchmarks
{
private readonly UseExportProviderAttribute _useExportProviderAttribute = new UseExportProviderAttribute();
// Run the test with different ratios of reads/writes.
[Params(0, 25, 50, 75, 100)]
public int ReadPercentage { get; set; }
private TestWorkspace _workspace;
private SQLitePersistentStorageService _storageService;
private IChecksummedPersistentStorage _storage;
private Document _document;
private Random _random;
public SQLitePersistentStorageBenchmarks()
{
_document = null!;
_storage = null!;
_storageService = null!;
_workspace = null!;
_random = null!;
}
[GlobalSetup]
public void GlobalSetup()
{
_useExportProviderAttribute.Before(null);
if (_workspace != null)
{
throw new InvalidOperationException();
}
_workspace = TestWorkspace.Create(
@"<Workspace>
<Project Language=""NoCompilation"" CommonReferences=""false"">
<Document>
// a no-compilation document
</Document>
</Project>
</Workspace>");
// Explicitly choose the sqlite db to test.
_workspace.TryApplyChanges(_workspace.CurrentSolution.WithOptions(_workspace.Options
.WithChangedOption(StorageOptions.Database, StorageDatabase.SQLite)
.WithChangedOption(StorageOptions.DatabaseMustSucceed, true)));
var connectionPoolService = _workspace.ExportProvider.GetExportedValue<SQLiteConnectionPoolService>();
_storageService = new SQLitePersistentStorageService(
_workspace.Options, connectionPoolService, new LocationService(),
_workspace.ExportProvider.GetExportedValue<IAsynchronousOperationListenerProvider>().GetListener(FeatureAttribute.PersistentStorage));
var solution = _workspace.CurrentSolution;
_storage = _storageService.GetStorageWorkerAsync(_workspace, SolutionKey.ToSolutionKey(solution), solution, CancellationToken.None).AsTask().GetAwaiter().GetResult();
Console.WriteLine("Storage type: " + _storage.GetType());
_document = _workspace.CurrentSolution.Projects.Single().Documents.Single();
_random = new Random(0);
}
[GlobalCleanup]
public void GlobalCleanup()
{
if (_workspace == null)
{
throw new InvalidOperationException();
}
_document = null!;
_storage.Dispose();
_storage = null!;
_storageService = null!;
_workspace.Dispose();
_workspace = null!;
_useExportProviderAttribute.After(null);
}
private static readonly byte[] s_bytes = new byte[1000];
[Benchmark(Baseline = true)]
public Task PerfAsync()
{
const int capacity = 1000;
var tasks = new List<Task>(capacity);
// Create a lot of overlapping reads and writes to the DB to several different keys. The
// percentage of reads and writes is parameterized above, allowing us to validate
// performance with several different usage patterns.
for (var i = 0; i < capacity; i++)
{
var name = _random.Next(0, 4).ToString();
if (_random.Next(0, 100) < ReadPercentage)
{
tasks.Add(Task.Run(async () =>
{
using var stream = await _storage.ReadStreamAsync(_document, name);
}));
}
else
{
tasks.Add(Task.Run(async () =>
{
using var stream = new MemoryStream(s_bytes);
await _storage.WriteStreamAsync(_document, name, stream);
}));
}
}
return Task.WhenAll(tasks);
}
private class LocationService : IPersistentStorageLocationService
{
public bool IsSupported(Workspace workspace) => true;
public string TryGetStorageLocation(Solution _)
{
// Store the db in a different random temp dir.
var tempDir = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
Console.WriteLine("Creating: " + tempDir);
Directory.CreateDirectory(tempDir);
return tempDir;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using BenchmarkDotNet.Attributes;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.PersistentStorage;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.SQLite.v2;
using Microsoft.CodeAnalysis.Storage;
using Microsoft.CodeAnalysis.Test.Utilities;
namespace IdeBenchmarks
{
public class SQLitePersistentStorageBenchmarks
{
private readonly UseExportProviderAttribute _useExportProviderAttribute = new UseExportProviderAttribute();
// Run the test with different ratios of reads/writes.
[Params(0, 25, 50, 75, 100)]
public int ReadPercentage { get; set; }
private TestWorkspace _workspace;
private SQLitePersistentStorageService _storageService;
private IChecksummedPersistentStorage _storage;
private Document _document;
private Random _random;
public SQLitePersistentStorageBenchmarks()
{
_document = null!;
_storage = null!;
_storageService = null!;
_workspace = null!;
_random = null!;
}
[GlobalSetup]
public void GlobalSetup()
{
_useExportProviderAttribute.Before(null);
if (_workspace != null)
{
throw new InvalidOperationException();
}
_workspace = TestWorkspace.Create(
@"<Workspace>
<Project Language=""NoCompilation"" CommonReferences=""false"">
<Document>
// a no-compilation document
</Document>
</Project>
</Workspace>");
// Explicitly choose the sqlite db to test.
_workspace.TryApplyChanges(_workspace.CurrentSolution.WithOptions(_workspace.Options
.WithChangedOption(StorageOptions.Database, StorageDatabase.SQLite)
.WithChangedOption(StorageOptions.DatabaseMustSucceed, true)));
var connectionPoolService = _workspace.ExportProvider.GetExportedValue<SQLiteConnectionPoolService>();
_storageService = new SQLitePersistentStorageService(
_workspace.Options, connectionPoolService, new LocationService(),
_workspace.ExportProvider.GetExportedValue<IAsynchronousOperationListenerProvider>().GetListener(FeatureAttribute.PersistentStorage));
var solution = _workspace.CurrentSolution;
_storage = _storageService.GetStorageWorkerAsync(_workspace, SolutionKey.ToSolutionKey(solution), solution, CancellationToken.None).AsTask().GetAwaiter().GetResult();
Console.WriteLine("Storage type: " + _storage.GetType());
_document = _workspace.CurrentSolution.Projects.Single().Documents.Single();
_random = new Random(0);
}
[GlobalCleanup]
public void GlobalCleanup()
{
if (_workspace == null)
{
throw new InvalidOperationException();
}
_document = null!;
_storage.Dispose();
_storage = null!;
_storageService = null!;
_workspace.Dispose();
_workspace = null!;
_useExportProviderAttribute.After(null);
}
private static readonly byte[] s_bytes = new byte[1000];
[Benchmark(Baseline = true)]
public Task PerfAsync()
{
const int capacity = 1000;
var tasks = new List<Task>(capacity);
// Create a lot of overlapping reads and writes to the DB to several different keys. The
// percentage of reads and writes is parameterized above, allowing us to validate
// performance with several different usage patterns.
for (var i = 0; i < capacity; i++)
{
var name = _random.Next(0, 4).ToString();
if (_random.Next(0, 100) < ReadPercentage)
{
tasks.Add(Task.Run(async () =>
{
using var stream = await _storage.ReadStreamAsync(_document, name);
}));
}
else
{
tasks.Add(Task.Run(async () =>
{
using var stream = new MemoryStream(s_bytes);
await _storage.WriteStreamAsync(_document, name, stream);
}));
}
}
return Task.WhenAll(tasks);
}
private class LocationService : IPersistentStorageLocationService
{
public bool IsSupported(Workspace workspace) => true;
public string TryGetStorageLocation(Solution _)
{
// Store the db in a different random temp dir.
var tempDir = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
Console.WriteLine("Creating: " + tempDir);
Directory.CreateDirectory(tempDir);
return tempDir;
}
}
}
}
| -1 |
dotnet/roslyn | 55,877 | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute | Part of C# 10 support | davidwengier | 2021-08-25T05:36:27Z | 2021-08-30T20:47:11Z | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | 023d3ca2b5fb429f0b3dcc1efeed39442e232dba | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute. Part of C# 10 support | ./src/VisualStudio/CSharp/Impl/Options/Formatting/FormattingSpacingPage.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Runtime.InteropServices;
using Microsoft.VisualStudio.LanguageServices.Implementation.Options;
namespace Microsoft.VisualStudio.LanguageServices.CSharp.Options.Formatting
{
[Guid(Guids.CSharpOptionPageFormattingSpacingIdString)]
internal class FormattingSpacingPage : AbstractOptionPage
{
protected override AbstractOptionPageControl CreateOptionPage(IServiceProvider serviceProvider, OptionStore optionStore)
=> new OptionPreviewControl(serviceProvider, optionStore, (o, s) => new SpacingViewModel(o, s));
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Runtime.InteropServices;
using Microsoft.VisualStudio.LanguageServices.Implementation.Options;
namespace Microsoft.VisualStudio.LanguageServices.CSharp.Options.Formatting
{
[Guid(Guids.CSharpOptionPageFormattingSpacingIdString)]
internal class FormattingSpacingPage : AbstractOptionPage
{
protected override AbstractOptionPageControl CreateOptionPage(IServiceProvider serviceProvider, OptionStore optionStore)
=> new OptionPreviewControl(serviceProvider, optionStore, (o, s) => new SpacingViewModel(o, s));
}
}
| -1 |
dotnet/roslyn | 55,877 | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute | Part of C# 10 support | davidwengier | 2021-08-25T05:36:27Z | 2021-08-30T20:47:11Z | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | 023d3ca2b5fb429f0b3dcc1efeed39442e232dba | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute. Part of C# 10 support | ./src/Tools/ExternalAccess/FSharp/Internal/Editor/FSharpEditorInlineRenameService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Linq;
using System.Collections.Generic;
using System.Composition;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor;
using Microsoft.CodeAnalysis.ExternalAccess.FSharp.Editor;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
using System.Collections.Immutable;
namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.Internal.Editor
{
internal static class FSharpInlineRenameReplacementKindHelpers
{
public static InlineRenameReplacementKind ConvertTo(FSharpInlineRenameReplacementKind kind)
{
switch (kind)
{
case FSharpInlineRenameReplacementKind.NoConflict:
{
return InlineRenameReplacementKind.NoConflict;
}
case FSharpInlineRenameReplacementKind.ResolvedReferenceConflict:
{
return InlineRenameReplacementKind.ResolvedReferenceConflict;
}
case FSharpInlineRenameReplacementKind.ResolvedNonReferenceConflict:
{
return InlineRenameReplacementKind.ResolvedNonReferenceConflict;
}
case FSharpInlineRenameReplacementKind.UnresolvedConflict:
{
return InlineRenameReplacementKind.UnresolvedConflict;
}
case FSharpInlineRenameReplacementKind.Complexified:
{
return InlineRenameReplacementKind.Complexified;
}
default:
{
throw ExceptionUtilities.UnexpectedValue(kind);
}
}
}
}
internal class FSharpInlineRenameReplacementInfo : IInlineRenameReplacementInfo
{
private readonly IFSharpInlineRenameReplacementInfo _info;
public FSharpInlineRenameReplacementInfo(IFSharpInlineRenameReplacementInfo info)
{
_info = info;
}
public Solution NewSolution => _info.NewSolution;
public bool ReplacementTextValid => _info.ReplacementTextValid;
public IEnumerable<DocumentId> DocumentIds => _info.DocumentIds;
public IEnumerable<InlineRenameReplacement> GetReplacements(DocumentId documentId)
{
return _info.GetReplacements(documentId)?.Select(x =>
new InlineRenameReplacement(FSharpInlineRenameReplacementKindHelpers.ConvertTo(x.Kind), x.OriginalSpan, x.NewSpan));
}
}
internal class FSharpInlineRenameLocationSet : IInlineRenameLocationSet
{
private readonly IFSharpInlineRenameLocationSet _set;
private readonly IList<InlineRenameLocation> _locations;
public FSharpInlineRenameLocationSet(IFSharpInlineRenameLocationSet set)
{
_set = set;
_locations = set.Locations?.Select(x => new InlineRenameLocation(x.Document, x.TextSpan)).ToList();
}
public IList<InlineRenameLocation> Locations => _locations;
public async Task<IInlineRenameReplacementInfo> GetReplacementsAsync(string replacementText, OptionSet optionSet, CancellationToken cancellationToken)
{
var info = await _set.GetReplacementsAsync(replacementText, optionSet, cancellationToken).ConfigureAwait(false);
if (info != null)
{
return new FSharpInlineRenameReplacementInfo(info);
}
else
{
return null;
}
}
}
internal class FSharpInlineRenameInfo : IInlineRenameInfo
{
private readonly IFSharpInlineRenameInfo _info;
public FSharpInlineRenameInfo(IFSharpInlineRenameInfo info)
{
_info = info;
}
public bool CanRename => _info.CanRename;
public string LocalizedErrorMessage => _info.LocalizedErrorMessage;
public TextSpan TriggerSpan => _info.TriggerSpan;
public bool HasOverloads => _info.HasOverloads;
public bool ForceRenameOverloads => _info.ForceRenameOverloads;
public string DisplayName => _info.DisplayName;
public string FullDisplayName => _info.FullDisplayName;
public Glyph Glyph => FSharpGlyphHelpers.ConvertTo(_info.Glyph);
// This property isn't currently supported in F# since it would involve modifying the IFSharpInlineRenameInfo interface.
public ImmutableArray<DocumentSpan> DefinitionLocations => default;
public async Task<IInlineRenameLocationSet> FindRenameLocationsAsync(OptionSet optionSet, CancellationToken cancellationToken)
{
var set = await _info.FindRenameLocationsAsync(optionSet, cancellationToken).ConfigureAwait(false);
if (set != null)
{
return new FSharpInlineRenameLocationSet(set);
}
else
{
return null;
}
}
public TextSpan? GetConflictEditSpan(InlineRenameLocation location, string triggerText, string replacementText, CancellationToken cancellationToken)
{
return _info.GetConflictEditSpan(new FSharpInlineRenameLocation(location.Document, location.TextSpan), replacementText, cancellationToken);
}
public string GetFinalSymbolName(string replacementText)
{
return _info.GetFinalSymbolName(replacementText);
}
public TextSpan GetReferenceEditSpan(InlineRenameLocation location, string triggerText, CancellationToken cancellationToken)
{
return _info.GetReferenceEditSpan(new FSharpInlineRenameLocation(location.Document, location.TextSpan), cancellationToken);
}
public bool TryOnAfterGlobalSymbolRenamed(Workspace workspace, IEnumerable<DocumentId> changedDocumentIDs, string replacementText)
{
return _info.TryOnAfterGlobalSymbolRenamed(workspace, changedDocumentIDs, replacementText);
}
public bool TryOnBeforeGlobalSymbolRenamed(Workspace workspace, IEnumerable<DocumentId> changedDocumentIDs, string replacementText)
{
return _info.TryOnBeforeGlobalSymbolRenamed(workspace, changedDocumentIDs, replacementText);
}
}
[Shared]
[ExportLanguageService(typeof(IEditorInlineRenameService), LanguageNames.FSharp)]
internal class FSharpEditorInlineRenameService : IEditorInlineRenameService
{
private readonly IFSharpEditorInlineRenameService _service;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public FSharpEditorInlineRenameService(IFSharpEditorInlineRenameService service)
{
_service = service;
}
public async Task<IInlineRenameInfo> GetRenameInfoAsync(Document document, int position, CancellationToken cancellationToken)
{
var info = await _service.GetRenameInfoAsync(document, position, cancellationToken).ConfigureAwait(false);
if (info != null)
{
return new FSharpInlineRenameInfo(info);
}
else
{
return null;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Linq;
using System.Collections.Generic;
using System.Composition;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor;
using Microsoft.CodeAnalysis.ExternalAccess.FSharp.Editor;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
using System.Collections.Immutable;
namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.Internal.Editor
{
internal static class FSharpInlineRenameReplacementKindHelpers
{
public static InlineRenameReplacementKind ConvertTo(FSharpInlineRenameReplacementKind kind)
{
switch (kind)
{
case FSharpInlineRenameReplacementKind.NoConflict:
{
return InlineRenameReplacementKind.NoConflict;
}
case FSharpInlineRenameReplacementKind.ResolvedReferenceConflict:
{
return InlineRenameReplacementKind.ResolvedReferenceConflict;
}
case FSharpInlineRenameReplacementKind.ResolvedNonReferenceConflict:
{
return InlineRenameReplacementKind.ResolvedNonReferenceConflict;
}
case FSharpInlineRenameReplacementKind.UnresolvedConflict:
{
return InlineRenameReplacementKind.UnresolvedConflict;
}
case FSharpInlineRenameReplacementKind.Complexified:
{
return InlineRenameReplacementKind.Complexified;
}
default:
{
throw ExceptionUtilities.UnexpectedValue(kind);
}
}
}
}
internal class FSharpInlineRenameReplacementInfo : IInlineRenameReplacementInfo
{
private readonly IFSharpInlineRenameReplacementInfo _info;
public FSharpInlineRenameReplacementInfo(IFSharpInlineRenameReplacementInfo info)
{
_info = info;
}
public Solution NewSolution => _info.NewSolution;
public bool ReplacementTextValid => _info.ReplacementTextValid;
public IEnumerable<DocumentId> DocumentIds => _info.DocumentIds;
public IEnumerable<InlineRenameReplacement> GetReplacements(DocumentId documentId)
{
return _info.GetReplacements(documentId)?.Select(x =>
new InlineRenameReplacement(FSharpInlineRenameReplacementKindHelpers.ConvertTo(x.Kind), x.OriginalSpan, x.NewSpan));
}
}
internal class FSharpInlineRenameLocationSet : IInlineRenameLocationSet
{
private readonly IFSharpInlineRenameLocationSet _set;
private readonly IList<InlineRenameLocation> _locations;
public FSharpInlineRenameLocationSet(IFSharpInlineRenameLocationSet set)
{
_set = set;
_locations = set.Locations?.Select(x => new InlineRenameLocation(x.Document, x.TextSpan)).ToList();
}
public IList<InlineRenameLocation> Locations => _locations;
public async Task<IInlineRenameReplacementInfo> GetReplacementsAsync(string replacementText, OptionSet optionSet, CancellationToken cancellationToken)
{
var info = await _set.GetReplacementsAsync(replacementText, optionSet, cancellationToken).ConfigureAwait(false);
if (info != null)
{
return new FSharpInlineRenameReplacementInfo(info);
}
else
{
return null;
}
}
}
internal class FSharpInlineRenameInfo : IInlineRenameInfo
{
private readonly IFSharpInlineRenameInfo _info;
public FSharpInlineRenameInfo(IFSharpInlineRenameInfo info)
{
_info = info;
}
public bool CanRename => _info.CanRename;
public string LocalizedErrorMessage => _info.LocalizedErrorMessage;
public TextSpan TriggerSpan => _info.TriggerSpan;
public bool HasOverloads => _info.HasOverloads;
public bool ForceRenameOverloads => _info.ForceRenameOverloads;
public string DisplayName => _info.DisplayName;
public string FullDisplayName => _info.FullDisplayName;
public Glyph Glyph => FSharpGlyphHelpers.ConvertTo(_info.Glyph);
// This property isn't currently supported in F# since it would involve modifying the IFSharpInlineRenameInfo interface.
public ImmutableArray<DocumentSpan> DefinitionLocations => default;
public async Task<IInlineRenameLocationSet> FindRenameLocationsAsync(OptionSet optionSet, CancellationToken cancellationToken)
{
var set = await _info.FindRenameLocationsAsync(optionSet, cancellationToken).ConfigureAwait(false);
if (set != null)
{
return new FSharpInlineRenameLocationSet(set);
}
else
{
return null;
}
}
public TextSpan? GetConflictEditSpan(InlineRenameLocation location, string triggerText, string replacementText, CancellationToken cancellationToken)
{
return _info.GetConflictEditSpan(new FSharpInlineRenameLocation(location.Document, location.TextSpan), replacementText, cancellationToken);
}
public string GetFinalSymbolName(string replacementText)
{
return _info.GetFinalSymbolName(replacementText);
}
public TextSpan GetReferenceEditSpan(InlineRenameLocation location, string triggerText, CancellationToken cancellationToken)
{
return _info.GetReferenceEditSpan(new FSharpInlineRenameLocation(location.Document, location.TextSpan), cancellationToken);
}
public bool TryOnAfterGlobalSymbolRenamed(Workspace workspace, IEnumerable<DocumentId> changedDocumentIDs, string replacementText)
{
return _info.TryOnAfterGlobalSymbolRenamed(workspace, changedDocumentIDs, replacementText);
}
public bool TryOnBeforeGlobalSymbolRenamed(Workspace workspace, IEnumerable<DocumentId> changedDocumentIDs, string replacementText)
{
return _info.TryOnBeforeGlobalSymbolRenamed(workspace, changedDocumentIDs, replacementText);
}
}
[Shared]
[ExportLanguageService(typeof(IEditorInlineRenameService), LanguageNames.FSharp)]
internal class FSharpEditorInlineRenameService : IEditorInlineRenameService
{
private readonly IFSharpEditorInlineRenameService _service;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public FSharpEditorInlineRenameService(IFSharpEditorInlineRenameService service)
{
_service = service;
}
public async Task<IInlineRenameInfo> GetRenameInfoAsync(Document document, int position, CancellationToken cancellationToken)
{
var info = await _service.GetRenameInfoAsync(document, position, cancellationToken).ConfigureAwait(false);
if (info != null)
{
return new FSharpInlineRenameInfo(info);
}
else
{
return null;
}
}
}
}
| -1 |
dotnet/roslyn | 55,877 | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute | Part of C# 10 support | davidwengier | 2021-08-25T05:36:27Z | 2021-08-30T20:47:11Z | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | 023d3ca2b5fb429f0b3dcc1efeed39442e232dba | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute. Part of C# 10 support | ./src/Compilers/CSharp/Portable/Binder/LocalScopeBinder.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
internal partial class LocalScopeBinder : Binder
{
private ImmutableArray<LocalSymbol> _locals;
private ImmutableArray<LocalFunctionSymbol> _localFunctions;
private ImmutableArray<LabelSymbol> _labels;
private readonly uint _localScopeDepth;
internal LocalScopeBinder(Binder next)
: this(next, next.Flags)
{
}
internal LocalScopeBinder(Binder next, BinderFlags flags)
: base(next, flags)
{
var parentDepth = next.LocalScopeDepth;
if (parentDepth != Binder.TopLevelScope)
{
_localScopeDepth = parentDepth + 1;
}
else
{
//NOTE: TopLevel is special.
//For our purpose parameters and top level locals are on that level.
var parentScope = next;
while (parentScope != null)
{
if (parentScope is InMethodBinder || parentScope is WithLambdaParametersBinder)
{
_localScopeDepth = Binder.TopLevelScope;
break;
}
if (parentScope is LocalScopeBinder)
{
_localScopeDepth = Binder.TopLevelScope + 1;
break;
}
parentScope = parentScope.Next;
Debug.Assert(parentScope != null);
}
}
}
internal sealed override ImmutableArray<LocalSymbol> Locals
{
get
{
if (_locals.IsDefault)
{
ImmutableInterlocked.InterlockedCompareExchange(ref _locals, BuildLocals(), default(ImmutableArray<LocalSymbol>));
}
return _locals;
}
}
protected virtual ImmutableArray<LocalSymbol> BuildLocals()
{
return ImmutableArray<LocalSymbol>.Empty;
}
internal sealed override ImmutableArray<LocalFunctionSymbol> LocalFunctions
{
get
{
if (_localFunctions.IsDefault)
{
ImmutableInterlocked.InterlockedCompareExchange(ref _localFunctions, BuildLocalFunctions(), default(ImmutableArray<LocalFunctionSymbol>));
}
return _localFunctions;
}
}
protected virtual ImmutableArray<LocalFunctionSymbol> BuildLocalFunctions()
{
return ImmutableArray<LocalFunctionSymbol>.Empty;
}
internal sealed override ImmutableArray<LabelSymbol> Labels
{
get
{
if (_labels.IsDefault)
{
ImmutableInterlocked.InterlockedCompareExchange(ref _labels, BuildLabels(), default(ImmutableArray<LabelSymbol>));
}
return _labels;
}
}
protected virtual ImmutableArray<LabelSymbol> BuildLabels()
{
return ImmutableArray<LabelSymbol>.Empty;
}
private SmallDictionary<string, LocalSymbol> _lazyLocalsMap;
private SmallDictionary<string, LocalSymbol> LocalsMap
{
get
{
if (_lazyLocalsMap == null && this.Locals.Length > 0)
{
_lazyLocalsMap = BuildMap(this.Locals);
}
return _lazyLocalsMap;
}
}
private SmallDictionary<string, LocalFunctionSymbol> _lazyLocalFunctionsMap;
private SmallDictionary<string, LocalFunctionSymbol> LocalFunctionsMap
{
get
{
if (_lazyLocalFunctionsMap == null && this.LocalFunctions.Length > 0)
{
_lazyLocalFunctionsMap = BuildMap(this.LocalFunctions);
}
return _lazyLocalFunctionsMap;
}
}
private SmallDictionary<string, LabelSymbol> _lazyLabelsMap;
private SmallDictionary<string, LabelSymbol> LabelsMap
{
get
{
if (_lazyLabelsMap == null && this.Labels.Length > 0)
{
_lazyLabelsMap = BuildMap(this.Labels);
}
return _lazyLabelsMap;
}
}
private static SmallDictionary<string, TSymbol> BuildMap<TSymbol>(ImmutableArray<TSymbol> array)
where TSymbol : Symbol
{
Debug.Assert(array.Length > 0);
var map = new SmallDictionary<string, TSymbol>();
// NOTE: in a rare case of having two symbols with same name the one closer to the array's start wins.
for (int i = array.Length - 1; i >= 0; i--)
{
var symbol = array[i];
map[symbol.Name] = symbol;
}
return map;
}
protected ImmutableArray<LocalSymbol> BuildLocals(SyntaxList<StatementSyntax> statements, Binder enclosingBinder)
{
#if DEBUG
Binder currentBinder = enclosingBinder;
while (true)
{
if (this == currentBinder)
{
break;
}
currentBinder = currentBinder.Next;
}
#endif
ArrayBuilder<LocalSymbol> locals = ArrayBuilder<LocalSymbol>.GetInstance();
foreach (var statement in statements)
{
BuildLocals(enclosingBinder, statement, locals);
}
return locals.ToImmutableAndFree();
}
internal void BuildLocals(Binder enclosingBinder, StatementSyntax statement, ArrayBuilder<LocalSymbol> locals)
{
var innerStatement = statement;
// drill into any LabeledStatements -- atomic LabelStatements have been bound into
// wrapped LabeledStatements by this point
while (innerStatement.Kind() == SyntaxKind.LabeledStatement)
{
innerStatement = ((LabeledStatementSyntax)innerStatement).Statement;
}
switch (innerStatement.Kind())
{
case SyntaxKind.LocalDeclarationStatement:
{
Binder localDeclarationBinder = enclosingBinder.GetBinder(innerStatement) ?? enclosingBinder;
var decl = (LocalDeclarationStatementSyntax)innerStatement;
decl.Declaration.Type.VisitRankSpecifiers((rankSpecifier, args) =>
{
foreach (var expression in rankSpecifier.Sizes)
{
if (expression.Kind() != SyntaxKind.OmittedArraySizeExpression)
{
ExpressionVariableFinder.FindExpressionVariables(args.localScopeBinder, args.locals, expression, args.localDeclarationBinder);
}
}
}, (localScopeBinder: this, locals: locals, localDeclarationBinder: localDeclarationBinder));
LocalDeclarationKind kind;
if (decl.IsConst)
{
kind = LocalDeclarationKind.Constant;
}
else if (decl.UsingKeyword != default(SyntaxToken))
{
kind = LocalDeclarationKind.UsingVariable;
}
else
{
kind = LocalDeclarationKind.RegularVariable;
}
foreach (var vdecl in decl.Declaration.Variables)
{
var localSymbol = MakeLocal(decl.Declaration, vdecl, kind, localDeclarationBinder);
locals.Add(localSymbol);
// also gather expression-declared variables from the bracketed argument lists and the initializers
ExpressionVariableFinder.FindExpressionVariables(this, locals, vdecl, localDeclarationBinder);
}
}
break;
case SyntaxKind.ExpressionStatement:
case SyntaxKind.IfStatement:
case SyntaxKind.YieldReturnStatement:
case SyntaxKind.ReturnStatement:
case SyntaxKind.ThrowStatement:
case SyntaxKind.GotoCaseStatement:
ExpressionVariableFinder.FindExpressionVariables(this, locals, innerStatement, enclosingBinder.GetBinder(innerStatement) ?? enclosingBinder);
break;
case SyntaxKind.SwitchStatement:
var switchStatement = (SwitchStatementSyntax)innerStatement;
ExpressionVariableFinder.FindExpressionVariables(this, locals, innerStatement, enclosingBinder.GetBinder(switchStatement.Expression) ?? enclosingBinder);
break;
case SyntaxKind.LockStatement:
Binder statementBinder = enclosingBinder.GetBinder(innerStatement);
Debug.Assert(statementBinder != null); // Lock always has a binder.
ExpressionVariableFinder.FindExpressionVariables(this, locals, innerStatement, statementBinder);
break;
default:
// no other statement introduces local variables into the enclosing scope
break;
}
}
protected ImmutableArray<LocalFunctionSymbol> BuildLocalFunctions(SyntaxList<StatementSyntax> statements)
{
ArrayBuilder<LocalFunctionSymbol> locals = null;
foreach (var statement in statements)
{
BuildLocalFunctions(statement, ref locals);
}
return locals?.ToImmutableAndFree() ?? ImmutableArray<LocalFunctionSymbol>.Empty;
}
internal void BuildLocalFunctions(StatementSyntax statement, ref ArrayBuilder<LocalFunctionSymbol> locals)
{
var innerStatement = statement;
// drill into any LabeledStatements -- atomic LabelStatements have been bound into
// wrapped LabeledStatements by this point
while (innerStatement.Kind() == SyntaxKind.LabeledStatement)
{
innerStatement = ((LabeledStatementSyntax)innerStatement).Statement;
}
if (innerStatement.Kind() == SyntaxKind.LocalFunctionStatement)
{
var decl = (LocalFunctionStatementSyntax)innerStatement;
if (locals == null)
{
locals = ArrayBuilder<LocalFunctionSymbol>.GetInstance();
}
var localSymbol = MakeLocalFunction(decl);
locals.Add(localSymbol);
}
}
protected SourceLocalSymbol MakeLocal(VariableDeclarationSyntax declaration, VariableDeclaratorSyntax declarator, LocalDeclarationKind kind, Binder initializerBinderOpt = null)
{
return SourceLocalSymbol.MakeLocal(
this.ContainingMemberOrLambda,
this,
true,
declaration.Type,
declarator.Identifier,
kind,
declarator.Initializer,
initializerBinderOpt);
}
protected LocalFunctionSymbol MakeLocalFunction(LocalFunctionStatementSyntax declaration)
{
return new LocalFunctionSymbol(
this,
this.ContainingMemberOrLambda,
declaration);
}
protected void BuildLabels(SyntaxList<StatementSyntax> statements, ref ArrayBuilder<LabelSymbol> labels)
{
var containingMethod = (MethodSymbol)this.ContainingMemberOrLambda;
foreach (var statement in statements)
{
BuildLabels(containingMethod, statement, ref labels);
}
}
internal static void BuildLabels(MethodSymbol containingMethod, StatementSyntax statement, ref ArrayBuilder<LabelSymbol> labels)
{
while (statement.Kind() == SyntaxKind.LabeledStatement)
{
var labeledStatement = (LabeledStatementSyntax)statement;
if (labels == null)
{
labels = ArrayBuilder<LabelSymbol>.GetInstance();
}
var labelSymbol = new SourceLabelSymbol(containingMethod, labeledStatement.Identifier);
labels.Add(labelSymbol);
statement = labeledStatement.Statement;
}
}
/// <summary>
/// Call this when you are sure there is a local declaration on this token. Returns the local.
/// </summary>
protected override SourceLocalSymbol LookupLocal(SyntaxToken nameToken)
{
LocalSymbol result = null;
if (LocalsMap != null && LocalsMap.TryGetValue(nameToken.ValueText, out result))
{
if (result.IdentifierToken == nameToken) return (SourceLocalSymbol)result;
// in error cases we might have more than one declaration of the same name in the same scope
foreach (var local in this.Locals)
{
if (local.IdentifierToken == nameToken)
{
return (SourceLocalSymbol)local;
}
}
}
return base.LookupLocal(nameToken);
}
protected override LocalFunctionSymbol LookupLocalFunction(SyntaxToken nameToken)
{
LocalFunctionSymbol result = null;
if (LocalFunctionsMap != null && LocalFunctionsMap.TryGetValue(nameToken.ValueText, out result))
{
if (result.NameToken == nameToken) return result;
// in error cases we might have more than one declaration of the same name in the same scope
foreach (var local in this.LocalFunctions)
{
if (local.NameToken == nameToken)
{
return local;
}
}
}
return base.LookupLocalFunction(nameToken);
}
internal override uint LocalScopeDepth => _localScopeDepth;
internal override void LookupSymbolsInSingleBinder(
LookupResult result, string name, int arity, ConsList<TypeSymbol> basesBeingResolved, LookupOptions options, Binder originalBinder, bool diagnose, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo)
{
Debug.Assert(options.AreValid());
Debug.Assert(result.IsClear);
if ((options & LookupOptions.LabelsOnly) != 0)
{
var labelsMap = this.LabelsMap;
if (labelsMap != null)
{
LabelSymbol labelSymbol;
if (labelsMap.TryGetValue(name, out labelSymbol))
{
result.MergeEqual(LookupResult.Good(labelSymbol));
}
}
return;
}
var localsMap = this.LocalsMap;
if (localsMap != null && (options & LookupOptions.NamespaceAliasesOnly) == 0)
{
LocalSymbol localSymbol;
if (localsMap.TryGetValue(name, out localSymbol))
{
result.MergeEqual(originalBinder.CheckViability(localSymbol, arity, options, null, diagnose, ref useSiteInfo, basesBeingResolved));
}
}
var localFunctionsMap = this.LocalFunctionsMap;
if (localFunctionsMap != null && options.CanConsiderLocals())
{
LocalFunctionSymbol localSymbol;
if (localFunctionsMap.TryGetValue(name, out localSymbol))
{
result.MergeEqual(originalBinder.CheckViability(localSymbol, arity, options, null, diagnose, ref useSiteInfo, basesBeingResolved));
}
}
}
protected override void AddLookupSymbolsInfoInSingleBinder(LookupSymbolsInfo result, LookupOptions options, Binder originalBinder)
{
Debug.Assert(options.AreValid());
if ((options & LookupOptions.LabelsOnly) != 0)
{
if (this.LabelsMap != null)
{
foreach (var label in this.LabelsMap)
{
result.AddSymbol(label.Value, label.Key, 0);
}
}
}
if (options.CanConsiderLocals())
{
if (this.LocalsMap != null)
{
foreach (var local in this.LocalsMap)
{
if (originalBinder.CanAddLookupSymbolInfo(local.Value, options, result, null))
{
result.AddSymbol(local.Value, local.Key, 0);
}
}
}
if (this.LocalFunctionsMap != null)
{
foreach (var local in this.LocalFunctionsMap)
{
if (originalBinder.CanAddLookupSymbolInfo(local.Value, options, result, null))
{
result.AddSymbol(local.Value, local.Key, 0);
}
}
}
}
}
private bool ReportConflictWithLocal(Symbol local, Symbol newSymbol, string name, Location newLocation, BindingDiagnosticBag diagnostics)
{
// Quirk of the way we represent lambda parameters.
SymbolKind newSymbolKind = (object)newSymbol == null ? SymbolKind.Parameter : newSymbol.Kind;
if (newSymbolKind == SymbolKind.ErrorType) return true;
var declaredInThisScope = false;
declaredInThisScope |= newSymbolKind == SymbolKind.Local && this.Locals.Contains((LocalSymbol)newSymbol);
declaredInThisScope |= newSymbolKind == SymbolKind.Method && this.LocalFunctions.Contains((LocalFunctionSymbol)newSymbol);
if (declaredInThisScope && newLocation.SourceSpan.Start >= local.Locations[0].SourceSpan.Start)
{
// A local variable or function named '{0}' is already defined in this scope
diagnostics.Add(ErrorCode.ERR_LocalDuplicate, newLocation, name);
return true;
}
switch (newSymbolKind)
{
case SymbolKind.Local:
case SymbolKind.Parameter:
case SymbolKind.Method:
case SymbolKind.TypeParameter:
// A local or parameter named '{0}' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
diagnostics.Add(ErrorCode.ERR_LocalIllegallyOverrides, newLocation, name);
return true;
case SymbolKind.RangeVariable:
// The range variable '{0}' conflicts with a previous declaration of '{0}'
diagnostics.Add(ErrorCode.ERR_QueryRangeVariableOverrides, newLocation, name);
return true;
}
Debug.Assert(false, "what else can be declared inside a local scope?");
diagnostics.Add(ErrorCode.ERR_InternalError, newLocation);
return false;
}
internal virtual bool EnsureSingleDefinition(Symbol symbol, string name, Location location, BindingDiagnosticBag diagnostics)
{
LocalSymbol existingLocal = null;
LocalFunctionSymbol existingLocalFunction = null;
var localsMap = this.LocalsMap;
var localFunctionsMap = this.LocalFunctionsMap;
// TODO: Handle case where 'name' exists in both localsMap and localFunctionsMap. Right now locals are preferred over local functions.
if ((localsMap != null && localsMap.TryGetValue(name, out existingLocal)) ||
(localFunctionsMap != null && localFunctionsMap.TryGetValue(name, out existingLocalFunction)))
{
var existingSymbol = (Symbol)existingLocal ?? existingLocalFunction;
if (symbol == existingSymbol)
{
// reference to same symbol, by far the most common case.
return false;
}
return ReportConflictWithLocal(existingSymbol, symbol, name, location, diagnostics);
}
return false;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
internal partial class LocalScopeBinder : Binder
{
private ImmutableArray<LocalSymbol> _locals;
private ImmutableArray<LocalFunctionSymbol> _localFunctions;
private ImmutableArray<LabelSymbol> _labels;
private readonly uint _localScopeDepth;
internal LocalScopeBinder(Binder next)
: this(next, next.Flags)
{
}
internal LocalScopeBinder(Binder next, BinderFlags flags)
: base(next, flags)
{
var parentDepth = next.LocalScopeDepth;
if (parentDepth != Binder.TopLevelScope)
{
_localScopeDepth = parentDepth + 1;
}
else
{
//NOTE: TopLevel is special.
//For our purpose parameters and top level locals are on that level.
var parentScope = next;
while (parentScope != null)
{
if (parentScope is InMethodBinder || parentScope is WithLambdaParametersBinder)
{
_localScopeDepth = Binder.TopLevelScope;
break;
}
if (parentScope is LocalScopeBinder)
{
_localScopeDepth = Binder.TopLevelScope + 1;
break;
}
parentScope = parentScope.Next;
Debug.Assert(parentScope != null);
}
}
}
internal sealed override ImmutableArray<LocalSymbol> Locals
{
get
{
if (_locals.IsDefault)
{
ImmutableInterlocked.InterlockedCompareExchange(ref _locals, BuildLocals(), default(ImmutableArray<LocalSymbol>));
}
return _locals;
}
}
protected virtual ImmutableArray<LocalSymbol> BuildLocals()
{
return ImmutableArray<LocalSymbol>.Empty;
}
internal sealed override ImmutableArray<LocalFunctionSymbol> LocalFunctions
{
get
{
if (_localFunctions.IsDefault)
{
ImmutableInterlocked.InterlockedCompareExchange(ref _localFunctions, BuildLocalFunctions(), default(ImmutableArray<LocalFunctionSymbol>));
}
return _localFunctions;
}
}
protected virtual ImmutableArray<LocalFunctionSymbol> BuildLocalFunctions()
{
return ImmutableArray<LocalFunctionSymbol>.Empty;
}
internal sealed override ImmutableArray<LabelSymbol> Labels
{
get
{
if (_labels.IsDefault)
{
ImmutableInterlocked.InterlockedCompareExchange(ref _labels, BuildLabels(), default(ImmutableArray<LabelSymbol>));
}
return _labels;
}
}
protected virtual ImmutableArray<LabelSymbol> BuildLabels()
{
return ImmutableArray<LabelSymbol>.Empty;
}
private SmallDictionary<string, LocalSymbol> _lazyLocalsMap;
private SmallDictionary<string, LocalSymbol> LocalsMap
{
get
{
if (_lazyLocalsMap == null && this.Locals.Length > 0)
{
_lazyLocalsMap = BuildMap(this.Locals);
}
return _lazyLocalsMap;
}
}
private SmallDictionary<string, LocalFunctionSymbol> _lazyLocalFunctionsMap;
private SmallDictionary<string, LocalFunctionSymbol> LocalFunctionsMap
{
get
{
if (_lazyLocalFunctionsMap == null && this.LocalFunctions.Length > 0)
{
_lazyLocalFunctionsMap = BuildMap(this.LocalFunctions);
}
return _lazyLocalFunctionsMap;
}
}
private SmallDictionary<string, LabelSymbol> _lazyLabelsMap;
private SmallDictionary<string, LabelSymbol> LabelsMap
{
get
{
if (_lazyLabelsMap == null && this.Labels.Length > 0)
{
_lazyLabelsMap = BuildMap(this.Labels);
}
return _lazyLabelsMap;
}
}
private static SmallDictionary<string, TSymbol> BuildMap<TSymbol>(ImmutableArray<TSymbol> array)
where TSymbol : Symbol
{
Debug.Assert(array.Length > 0);
var map = new SmallDictionary<string, TSymbol>();
// NOTE: in a rare case of having two symbols with same name the one closer to the array's start wins.
for (int i = array.Length - 1; i >= 0; i--)
{
var symbol = array[i];
map[symbol.Name] = symbol;
}
return map;
}
protected ImmutableArray<LocalSymbol> BuildLocals(SyntaxList<StatementSyntax> statements, Binder enclosingBinder)
{
#if DEBUG
Binder currentBinder = enclosingBinder;
while (true)
{
if (this == currentBinder)
{
break;
}
currentBinder = currentBinder.Next;
}
#endif
ArrayBuilder<LocalSymbol> locals = ArrayBuilder<LocalSymbol>.GetInstance();
foreach (var statement in statements)
{
BuildLocals(enclosingBinder, statement, locals);
}
return locals.ToImmutableAndFree();
}
internal void BuildLocals(Binder enclosingBinder, StatementSyntax statement, ArrayBuilder<LocalSymbol> locals)
{
var innerStatement = statement;
// drill into any LabeledStatements -- atomic LabelStatements have been bound into
// wrapped LabeledStatements by this point
while (innerStatement.Kind() == SyntaxKind.LabeledStatement)
{
innerStatement = ((LabeledStatementSyntax)innerStatement).Statement;
}
switch (innerStatement.Kind())
{
case SyntaxKind.LocalDeclarationStatement:
{
Binder localDeclarationBinder = enclosingBinder.GetBinder(innerStatement) ?? enclosingBinder;
var decl = (LocalDeclarationStatementSyntax)innerStatement;
decl.Declaration.Type.VisitRankSpecifiers((rankSpecifier, args) =>
{
foreach (var expression in rankSpecifier.Sizes)
{
if (expression.Kind() != SyntaxKind.OmittedArraySizeExpression)
{
ExpressionVariableFinder.FindExpressionVariables(args.localScopeBinder, args.locals, expression, args.localDeclarationBinder);
}
}
}, (localScopeBinder: this, locals: locals, localDeclarationBinder: localDeclarationBinder));
LocalDeclarationKind kind;
if (decl.IsConst)
{
kind = LocalDeclarationKind.Constant;
}
else if (decl.UsingKeyword != default(SyntaxToken))
{
kind = LocalDeclarationKind.UsingVariable;
}
else
{
kind = LocalDeclarationKind.RegularVariable;
}
foreach (var vdecl in decl.Declaration.Variables)
{
var localSymbol = MakeLocal(decl.Declaration, vdecl, kind, localDeclarationBinder);
locals.Add(localSymbol);
// also gather expression-declared variables from the bracketed argument lists and the initializers
ExpressionVariableFinder.FindExpressionVariables(this, locals, vdecl, localDeclarationBinder);
}
}
break;
case SyntaxKind.ExpressionStatement:
case SyntaxKind.IfStatement:
case SyntaxKind.YieldReturnStatement:
case SyntaxKind.ReturnStatement:
case SyntaxKind.ThrowStatement:
case SyntaxKind.GotoCaseStatement:
ExpressionVariableFinder.FindExpressionVariables(this, locals, innerStatement, enclosingBinder.GetBinder(innerStatement) ?? enclosingBinder);
break;
case SyntaxKind.SwitchStatement:
var switchStatement = (SwitchStatementSyntax)innerStatement;
ExpressionVariableFinder.FindExpressionVariables(this, locals, innerStatement, enclosingBinder.GetBinder(switchStatement.Expression) ?? enclosingBinder);
break;
case SyntaxKind.LockStatement:
Binder statementBinder = enclosingBinder.GetBinder(innerStatement);
Debug.Assert(statementBinder != null); // Lock always has a binder.
ExpressionVariableFinder.FindExpressionVariables(this, locals, innerStatement, statementBinder);
break;
default:
// no other statement introduces local variables into the enclosing scope
break;
}
}
protected ImmutableArray<LocalFunctionSymbol> BuildLocalFunctions(SyntaxList<StatementSyntax> statements)
{
ArrayBuilder<LocalFunctionSymbol> locals = null;
foreach (var statement in statements)
{
BuildLocalFunctions(statement, ref locals);
}
return locals?.ToImmutableAndFree() ?? ImmutableArray<LocalFunctionSymbol>.Empty;
}
internal void BuildLocalFunctions(StatementSyntax statement, ref ArrayBuilder<LocalFunctionSymbol> locals)
{
var innerStatement = statement;
// drill into any LabeledStatements -- atomic LabelStatements have been bound into
// wrapped LabeledStatements by this point
while (innerStatement.Kind() == SyntaxKind.LabeledStatement)
{
innerStatement = ((LabeledStatementSyntax)innerStatement).Statement;
}
if (innerStatement.Kind() == SyntaxKind.LocalFunctionStatement)
{
var decl = (LocalFunctionStatementSyntax)innerStatement;
if (locals == null)
{
locals = ArrayBuilder<LocalFunctionSymbol>.GetInstance();
}
var localSymbol = MakeLocalFunction(decl);
locals.Add(localSymbol);
}
}
protected SourceLocalSymbol MakeLocal(VariableDeclarationSyntax declaration, VariableDeclaratorSyntax declarator, LocalDeclarationKind kind, Binder initializerBinderOpt = null)
{
return SourceLocalSymbol.MakeLocal(
this.ContainingMemberOrLambda,
this,
true,
declaration.Type,
declarator.Identifier,
kind,
declarator.Initializer,
initializerBinderOpt);
}
protected LocalFunctionSymbol MakeLocalFunction(LocalFunctionStatementSyntax declaration)
{
return new LocalFunctionSymbol(
this,
this.ContainingMemberOrLambda,
declaration);
}
protected void BuildLabels(SyntaxList<StatementSyntax> statements, ref ArrayBuilder<LabelSymbol> labels)
{
var containingMethod = (MethodSymbol)this.ContainingMemberOrLambda;
foreach (var statement in statements)
{
BuildLabels(containingMethod, statement, ref labels);
}
}
internal static void BuildLabels(MethodSymbol containingMethod, StatementSyntax statement, ref ArrayBuilder<LabelSymbol> labels)
{
while (statement.Kind() == SyntaxKind.LabeledStatement)
{
var labeledStatement = (LabeledStatementSyntax)statement;
if (labels == null)
{
labels = ArrayBuilder<LabelSymbol>.GetInstance();
}
var labelSymbol = new SourceLabelSymbol(containingMethod, labeledStatement.Identifier);
labels.Add(labelSymbol);
statement = labeledStatement.Statement;
}
}
/// <summary>
/// Call this when you are sure there is a local declaration on this token. Returns the local.
/// </summary>
protected override SourceLocalSymbol LookupLocal(SyntaxToken nameToken)
{
LocalSymbol result = null;
if (LocalsMap != null && LocalsMap.TryGetValue(nameToken.ValueText, out result))
{
if (result.IdentifierToken == nameToken) return (SourceLocalSymbol)result;
// in error cases we might have more than one declaration of the same name in the same scope
foreach (var local in this.Locals)
{
if (local.IdentifierToken == nameToken)
{
return (SourceLocalSymbol)local;
}
}
}
return base.LookupLocal(nameToken);
}
protected override LocalFunctionSymbol LookupLocalFunction(SyntaxToken nameToken)
{
LocalFunctionSymbol result = null;
if (LocalFunctionsMap != null && LocalFunctionsMap.TryGetValue(nameToken.ValueText, out result))
{
if (result.NameToken == nameToken) return result;
// in error cases we might have more than one declaration of the same name in the same scope
foreach (var local in this.LocalFunctions)
{
if (local.NameToken == nameToken)
{
return local;
}
}
}
return base.LookupLocalFunction(nameToken);
}
internal override uint LocalScopeDepth => _localScopeDepth;
internal override void LookupSymbolsInSingleBinder(
LookupResult result, string name, int arity, ConsList<TypeSymbol> basesBeingResolved, LookupOptions options, Binder originalBinder, bool diagnose, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo)
{
Debug.Assert(options.AreValid());
Debug.Assert(result.IsClear);
if ((options & LookupOptions.LabelsOnly) != 0)
{
var labelsMap = this.LabelsMap;
if (labelsMap != null)
{
LabelSymbol labelSymbol;
if (labelsMap.TryGetValue(name, out labelSymbol))
{
result.MergeEqual(LookupResult.Good(labelSymbol));
}
}
return;
}
var localsMap = this.LocalsMap;
if (localsMap != null && (options & LookupOptions.NamespaceAliasesOnly) == 0)
{
LocalSymbol localSymbol;
if (localsMap.TryGetValue(name, out localSymbol))
{
result.MergeEqual(originalBinder.CheckViability(localSymbol, arity, options, null, diagnose, ref useSiteInfo, basesBeingResolved));
}
}
var localFunctionsMap = this.LocalFunctionsMap;
if (localFunctionsMap != null && options.CanConsiderLocals())
{
LocalFunctionSymbol localSymbol;
if (localFunctionsMap.TryGetValue(name, out localSymbol))
{
result.MergeEqual(originalBinder.CheckViability(localSymbol, arity, options, null, diagnose, ref useSiteInfo, basesBeingResolved));
}
}
}
protected override void AddLookupSymbolsInfoInSingleBinder(LookupSymbolsInfo result, LookupOptions options, Binder originalBinder)
{
Debug.Assert(options.AreValid());
if ((options & LookupOptions.LabelsOnly) != 0)
{
if (this.LabelsMap != null)
{
foreach (var label in this.LabelsMap)
{
result.AddSymbol(label.Value, label.Key, 0);
}
}
}
if (options.CanConsiderLocals())
{
if (this.LocalsMap != null)
{
foreach (var local in this.LocalsMap)
{
if (originalBinder.CanAddLookupSymbolInfo(local.Value, options, result, null))
{
result.AddSymbol(local.Value, local.Key, 0);
}
}
}
if (this.LocalFunctionsMap != null)
{
foreach (var local in this.LocalFunctionsMap)
{
if (originalBinder.CanAddLookupSymbolInfo(local.Value, options, result, null))
{
result.AddSymbol(local.Value, local.Key, 0);
}
}
}
}
}
private bool ReportConflictWithLocal(Symbol local, Symbol newSymbol, string name, Location newLocation, BindingDiagnosticBag diagnostics)
{
// Quirk of the way we represent lambda parameters.
SymbolKind newSymbolKind = (object)newSymbol == null ? SymbolKind.Parameter : newSymbol.Kind;
if (newSymbolKind == SymbolKind.ErrorType) return true;
var declaredInThisScope = false;
declaredInThisScope |= newSymbolKind == SymbolKind.Local && this.Locals.Contains((LocalSymbol)newSymbol);
declaredInThisScope |= newSymbolKind == SymbolKind.Method && this.LocalFunctions.Contains((LocalFunctionSymbol)newSymbol);
if (declaredInThisScope && newLocation.SourceSpan.Start >= local.Locations[0].SourceSpan.Start)
{
// A local variable or function named '{0}' is already defined in this scope
diagnostics.Add(ErrorCode.ERR_LocalDuplicate, newLocation, name);
return true;
}
switch (newSymbolKind)
{
case SymbolKind.Local:
case SymbolKind.Parameter:
case SymbolKind.Method:
case SymbolKind.TypeParameter:
// A local or parameter named '{0}' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
diagnostics.Add(ErrorCode.ERR_LocalIllegallyOverrides, newLocation, name);
return true;
case SymbolKind.RangeVariable:
// The range variable '{0}' conflicts with a previous declaration of '{0}'
diagnostics.Add(ErrorCode.ERR_QueryRangeVariableOverrides, newLocation, name);
return true;
}
Debug.Assert(false, "what else can be declared inside a local scope?");
diagnostics.Add(ErrorCode.ERR_InternalError, newLocation);
return false;
}
internal virtual bool EnsureSingleDefinition(Symbol symbol, string name, Location location, BindingDiagnosticBag diagnostics)
{
LocalSymbol existingLocal = null;
LocalFunctionSymbol existingLocalFunction = null;
var localsMap = this.LocalsMap;
var localFunctionsMap = this.LocalFunctionsMap;
// TODO: Handle case where 'name' exists in both localsMap and localFunctionsMap. Right now locals are preferred over local functions.
if ((localsMap != null && localsMap.TryGetValue(name, out existingLocal)) ||
(localFunctionsMap != null && localFunctionsMap.TryGetValue(name, out existingLocalFunction)))
{
var existingSymbol = (Symbol)existingLocal ?? existingLocalFunction;
if (symbol == existingSymbol)
{
// reference to same symbol, by far the most common case.
return false;
}
return ReportConflictWithLocal(existingSymbol, symbol, name, location, diagnostics);
}
return false;
}
}
}
| -1 |
dotnet/roslyn | 55,877 | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute | Part of C# 10 support | davidwengier | 2021-08-25T05:36:27Z | 2021-08-30T20:47:11Z | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | 023d3ca2b5fb429f0b3dcc1efeed39442e232dba | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute. Part of C# 10 support | ./src/EditorFeatures/VisualBasic/xlf/VBEditorResources.tr.xlf | <?xml version="1.0" encoding="utf-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd">
<file datatype="xml" source-language="en" target-language="tr" original="../VBEditorResources.resx">
<body>
<trans-unit id="Add_Missing_Imports_on_Paste">
<source>Add Missing Imports on Paste</source>
<target state="translated">Yapıştırırken Eksik Import İfadelerini Ekle</target>
<note>"imports" is a language specific term and should not be localized</note>
</trans-unit>
<trans-unit id="Adding_missing_imports">
<source>Adding missing imports...</source>
<target state="translated">Eksik import ifadeleri ekleniyor...</target>
<note>Thread awaited dialog text. "imports" is a language specific term and should not be localized</note>
</trans-unit>
<trans-unit id="Case_Correction">
<source>Case Correction</source>
<target state="translated">Büyük/Küçük Harf Düzeltmesi</target>
<note />
</trans-unit>
<trans-unit id="Correcting_word_casing">
<source>Correcting word casing...</source>
<target state="translated">Sözcük büyük/küçük harfleri düzeltiliyor...</target>
<note />
</trans-unit>
<trans-unit id="This_call_is_required_by_the_designer">
<source>This call is required by the designer.</source>
<target state="translated">Bu çağrı tasarımcı için gerekli.</target>
<note />
</trans-unit>
<trans-unit id="Add_any_initialization_after_the_InitializeComponent_call">
<source>Add any initialization after the InitializeComponent() call.</source>
<target state="translated">InitializeComponent() çağrısından sonra başlangıç değer ekleyin.</target>
<note />
</trans-unit>
<trans-unit id="End_Construct">
<source>End Construct</source>
<target state="translated">Bitiş Yapısı</target>
<note />
</trans-unit>
<trans-unit id="Smart_Indenting">
<source>Smart Indenting</source>
<target state="translated">Akıllı Girintileme</target>
<note />
</trans-unit>
<trans-unit id="Formatting_Document">
<source>Formatting Document...</source>
<target state="translated">Belge biçimlendiriliyor...</target>
<note />
</trans-unit>
<trans-unit id="Insert_new_line">
<source>Insert new line</source>
<target state="translated">Yeni Satır Ekle</target>
<note />
</trans-unit>
<trans-unit id="Format_Paste">
<source>Format Paste</source>
<target state="translated">Yapıştırmayı Biçimlendir</target>
<note />
</trans-unit>
<trans-unit id="Formatting_pasted_text">
<source>Formatting pasted text...</source>
<target state="translated">Yapıştırılan metin biçimlendiriliyor...</target>
<note />
</trans-unit>
<trans-unit id="Paste">
<source>Paste</source>
<target state="translated">Yapıştır</target>
<note />
</trans-unit>
<trans-unit id="Format_on_Save">
<source>Format on Save</source>
<target state="translated">Kaydetmede Biçimlendir</target>
<note />
</trans-unit>
<trans-unit id="Committing_line">
<source>Committing line</source>
<target state="translated">Satır işleniyor</target>
<note />
</trans-unit>
<trans-unit id="Visual_Basic_Pretty_List">
<source>Visual Basic Pretty List</source>
<target state="translated">Visual Basic Düzgün Listesi</target>
<note />
</trans-unit>
<trans-unit id="not_supported">
<source>not supported</source>
<target state="translated">Desteklenmiyor</target>
<note />
</trans-unit>
<trans-unit id="Generate_Member">
<source>Generate Member</source>
<target state="translated">Üye Üret</target>
<note />
</trans-unit>
<trans-unit id="Line_commit">
<source>Line commit</source>
<target state="translated">Satır işleme</target>
<note />
</trans-unit>
<trans-unit id="Implement_Abstract_Class_Or_Interface">
<source>Implement Abstract Class Or Interface</source>
<target state="translated">Abstract Sınıfını veya Interface Uygula</target>
<note />
</trans-unit>
</body>
</file>
</xliff> | <?xml version="1.0" encoding="utf-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd">
<file datatype="xml" source-language="en" target-language="tr" original="../VBEditorResources.resx">
<body>
<trans-unit id="Add_Missing_Imports_on_Paste">
<source>Add Missing Imports on Paste</source>
<target state="translated">Yapıştırırken Eksik Import İfadelerini Ekle</target>
<note>"imports" is a language specific term and should not be localized</note>
</trans-unit>
<trans-unit id="Adding_missing_imports">
<source>Adding missing imports...</source>
<target state="translated">Eksik import ifadeleri ekleniyor...</target>
<note>Thread awaited dialog text. "imports" is a language specific term and should not be localized</note>
</trans-unit>
<trans-unit id="Case_Correction">
<source>Case Correction</source>
<target state="translated">Büyük/Küçük Harf Düzeltmesi</target>
<note />
</trans-unit>
<trans-unit id="Correcting_word_casing">
<source>Correcting word casing...</source>
<target state="translated">Sözcük büyük/küçük harfleri düzeltiliyor...</target>
<note />
</trans-unit>
<trans-unit id="This_call_is_required_by_the_designer">
<source>This call is required by the designer.</source>
<target state="translated">Bu çağrı tasarımcı için gerekli.</target>
<note />
</trans-unit>
<trans-unit id="Add_any_initialization_after_the_InitializeComponent_call">
<source>Add any initialization after the InitializeComponent() call.</source>
<target state="translated">InitializeComponent() çağrısından sonra başlangıç değer ekleyin.</target>
<note />
</trans-unit>
<trans-unit id="End_Construct">
<source>End Construct</source>
<target state="translated">Bitiş Yapısı</target>
<note />
</trans-unit>
<trans-unit id="Smart_Indenting">
<source>Smart Indenting</source>
<target state="translated">Akıllı Girintileme</target>
<note />
</trans-unit>
<trans-unit id="Formatting_Document">
<source>Formatting Document...</source>
<target state="translated">Belge biçimlendiriliyor...</target>
<note />
</trans-unit>
<trans-unit id="Insert_new_line">
<source>Insert new line</source>
<target state="translated">Yeni Satır Ekle</target>
<note />
</trans-unit>
<trans-unit id="Format_Paste">
<source>Format Paste</source>
<target state="translated">Yapıştırmayı Biçimlendir</target>
<note />
</trans-unit>
<trans-unit id="Formatting_pasted_text">
<source>Formatting pasted text...</source>
<target state="translated">Yapıştırılan metin biçimlendiriliyor...</target>
<note />
</trans-unit>
<trans-unit id="Paste">
<source>Paste</source>
<target state="translated">Yapıştır</target>
<note />
</trans-unit>
<trans-unit id="Format_on_Save">
<source>Format on Save</source>
<target state="translated">Kaydetmede Biçimlendir</target>
<note />
</trans-unit>
<trans-unit id="Committing_line">
<source>Committing line</source>
<target state="translated">Satır işleniyor</target>
<note />
</trans-unit>
<trans-unit id="Visual_Basic_Pretty_List">
<source>Visual Basic Pretty List</source>
<target state="translated">Visual Basic Düzgün Listesi</target>
<note />
</trans-unit>
<trans-unit id="not_supported">
<source>not supported</source>
<target state="translated">Desteklenmiyor</target>
<note />
</trans-unit>
<trans-unit id="Generate_Member">
<source>Generate Member</source>
<target state="translated">Üye Üret</target>
<note />
</trans-unit>
<trans-unit id="Line_commit">
<source>Line commit</source>
<target state="translated">Satır işleme</target>
<note />
</trans-unit>
<trans-unit id="Implement_Abstract_Class_Or_Interface">
<source>Implement Abstract Class Or Interface</source>
<target state="translated">Abstract Sınıfını veya Interface Uygula</target>
<note />
</trans-unit>
</body>
</file>
</xliff> | -1 |
dotnet/roslyn | 55,877 | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute | Part of C# 10 support | davidwengier | 2021-08-25T05:36:27Z | 2021-08-30T20:47:11Z | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | 023d3ca2b5fb429f0b3dcc1efeed39442e232dba | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute. Part of C# 10 support | ./src/Compilers/CSharp/Portable/Syntax/XmlNameAttributeElementKind.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.CSharp.Syntax
{
public enum XmlNameAttributeElementKind : byte
{
Parameter = 0,
ParameterReference = 1,
TypeParameter = 2,
TypeParameterReference = 3,
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.CSharp.Syntax
{
public enum XmlNameAttributeElementKind : byte
{
Parameter = 0,
ParameterReference = 1,
TypeParameter = 2,
TypeParameterReference = 3,
}
}
| -1 |
dotnet/roslyn | 55,877 | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute | Part of C# 10 support | davidwengier | 2021-08-25T05:36:27Z | 2021-08-30T20:47:11Z | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | 023d3ca2b5fb429f0b3dcc1efeed39442e232dba | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute. Part of C# 10 support | ./src/Features/Core/Portable/CodeRefactorings/ICodeRefactoringHelpersService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.CodeAnalysis.Host;
namespace Microsoft.CodeAnalysis.CodeRefactorings
{
internal interface ICodeRefactoringHelpersService : IWorkspaceService
{
bool ActiveInlineRenameSession { get; }
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.CodeAnalysis.Host;
namespace Microsoft.CodeAnalysis.CodeRefactorings
{
internal interface ICodeRefactoringHelpersService : IWorkspaceService
{
bool ActiveInlineRenameSession { get; }
}
}
| -1 |
dotnet/roslyn | 55,877 | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute | Part of C# 10 support | davidwengier | 2021-08-25T05:36:27Z | 2021-08-30T20:47:11Z | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | 023d3ca2b5fb429f0b3dcc1efeed39442e232dba | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute. Part of C# 10 support | ./src/CodeStyle/Core/Analyzers/xlf/CodeStyleResources.pl.xlf | <?xml version="1.0" encoding="utf-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd">
<file datatype="xml" source-language="en" target-language="pl" original="../CodeStyleResources.resx">
<body>
<trans-unit id="A_language_name_cannot_be_specified_for_this_option">
<source>A language name cannot be specified for this option.</source>
<target state="translated">Nie można określić nazwy języka dla tej opcji.</target>
<note />
</trans-unit>
<trans-unit id="A_language_name_must_be_specified_for_this_option">
<source>A language name must be specified for this option.</source>
<target state="translated">Nazwa języka musi zostać określona dla tej opcji.</target>
<note />
</trans-unit>
<trans-unit id="Arrays_with_more_than_one_dimension_cannot_be_serialized">
<source>Arrays with more than one dimension cannot be serialized.</source>
<target state="translated">Nie można przeprowadzić serializacji tablic z więcej niż jednym wymiarem.</target>
<note />
</trans-unit>
<trans-unit id="Cannot_serialize_type_0">
<source>Cannot serialize type '{0}'.</source>
<target state="translated">Nie można serializować typu „{0}”.</target>
<note />
</trans-unit>
<trans-unit id="Deserialization_reader_for_0_read_incorrect_number_of_values">
<source>Deserialization reader for '{0}' read incorrect number of values.</source>
<target state="translated">Czytnik deserializacji dla elementu „{0}” odczytuje nieprawidłową liczbę wartości.</target>
<note />
</trans-unit>
<trans-unit id="Error">
<source>Error</source>
<target state="translated">Błąd</target>
<note />
</trans-unit>
<trans-unit id="Fix_formatting">
<source>Fix formatting</source>
<target state="translated">Napraw formatowanie</target>
<note />
</trans-unit>
<trans-unit id="Indentation_and_spacing">
<source>Indentation and spacing</source>
<target state="translated">Wcięcia i odstępy</target>
<note />
</trans-unit>
<trans-unit id="New_line_preferences">
<source>New line preferences</source>
<target state="translated">Preferencje nowego wiersza</target>
<note />
</trans-unit>
<trans-unit id="None">
<source>None</source>
<target state="translated">brak</target>
<note />
</trans-unit>
<trans-unit id="Refactoring_Only">
<source>Refactoring Only</source>
<target state="translated">Tylko refaktoryzacja</target>
<note />
</trans-unit>
<trans-unit id="Stream_is_too_long">
<source>Stream is too long.</source>
<target state="translated">Strumień jest za długi.</target>
<note />
</trans-unit>
<trans-unit id="Suggestion">
<source>Suggestion</source>
<target state="translated">Sugestia</target>
<note />
</trans-unit>
<trans-unit id="The_type_0_is_not_understood_by_the_serialization_binder">
<source>The type '{0}' is not understood by the serialization binder.</source>
<target state="translated">Typ „{0}” nie jest zrozumiały dla integratora serializacji.</target>
<note />
</trans-unit>
<trans-unit id="Value_too_large_to_be_represented_as_a_30_bit_unsigned_integer">
<source>Value too large to be represented as a 30 bit unsigned integer.</source>
<target state="translated">Wartość jest zbyt duża, dlatego nie może być reprezentowana jako 30-bitowa liczba całkowita bez znaku.</target>
<note />
</trans-unit>
<trans-unit id="Warning">
<source>Warning</source>
<target state="translated">Ostrzeżenie</target>
<note />
</trans-unit>
</body>
</file>
</xliff> | <?xml version="1.0" encoding="utf-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd">
<file datatype="xml" source-language="en" target-language="pl" original="../CodeStyleResources.resx">
<body>
<trans-unit id="A_language_name_cannot_be_specified_for_this_option">
<source>A language name cannot be specified for this option.</source>
<target state="translated">Nie można określić nazwy języka dla tej opcji.</target>
<note />
</trans-unit>
<trans-unit id="A_language_name_must_be_specified_for_this_option">
<source>A language name must be specified for this option.</source>
<target state="translated">Nazwa języka musi zostać określona dla tej opcji.</target>
<note />
</trans-unit>
<trans-unit id="Arrays_with_more_than_one_dimension_cannot_be_serialized">
<source>Arrays with more than one dimension cannot be serialized.</source>
<target state="translated">Nie można przeprowadzić serializacji tablic z więcej niż jednym wymiarem.</target>
<note />
</trans-unit>
<trans-unit id="Cannot_serialize_type_0">
<source>Cannot serialize type '{0}'.</source>
<target state="translated">Nie można serializować typu „{0}”.</target>
<note />
</trans-unit>
<trans-unit id="Deserialization_reader_for_0_read_incorrect_number_of_values">
<source>Deserialization reader for '{0}' read incorrect number of values.</source>
<target state="translated">Czytnik deserializacji dla elementu „{0}” odczytuje nieprawidłową liczbę wartości.</target>
<note />
</trans-unit>
<trans-unit id="Error">
<source>Error</source>
<target state="translated">Błąd</target>
<note />
</trans-unit>
<trans-unit id="Fix_formatting">
<source>Fix formatting</source>
<target state="translated">Napraw formatowanie</target>
<note />
</trans-unit>
<trans-unit id="Indentation_and_spacing">
<source>Indentation and spacing</source>
<target state="translated">Wcięcia i odstępy</target>
<note />
</trans-unit>
<trans-unit id="New_line_preferences">
<source>New line preferences</source>
<target state="translated">Preferencje nowego wiersza</target>
<note />
</trans-unit>
<trans-unit id="None">
<source>None</source>
<target state="translated">brak</target>
<note />
</trans-unit>
<trans-unit id="Refactoring_Only">
<source>Refactoring Only</source>
<target state="translated">Tylko refaktoryzacja</target>
<note />
</trans-unit>
<trans-unit id="Stream_is_too_long">
<source>Stream is too long.</source>
<target state="translated">Strumień jest za długi.</target>
<note />
</trans-unit>
<trans-unit id="Suggestion">
<source>Suggestion</source>
<target state="translated">Sugestia</target>
<note />
</trans-unit>
<trans-unit id="The_type_0_is_not_understood_by_the_serialization_binder">
<source>The type '{0}' is not understood by the serialization binder.</source>
<target state="translated">Typ „{0}” nie jest zrozumiały dla integratora serializacji.</target>
<note />
</trans-unit>
<trans-unit id="Value_too_large_to_be_represented_as_a_30_bit_unsigned_integer">
<source>Value too large to be represented as a 30 bit unsigned integer.</source>
<target state="translated">Wartość jest zbyt duża, dlatego nie może być reprezentowana jako 30-bitowa liczba całkowita bez znaku.</target>
<note />
</trans-unit>
<trans-unit id="Warning">
<source>Warning</source>
<target state="translated">Ostrzeżenie</target>
<note />
</trans-unit>
</body>
</file>
</xliff> | -1 |
dotnet/roslyn | 55,877 | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute | Part of C# 10 support | davidwengier | 2021-08-25T05:36:27Z | 2021-08-30T20:47:11Z | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | 023d3ca2b5fb429f0b3dcc1efeed39442e232dba | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute. Part of C# 10 support | ./src/Compilers/CSharp/Test/Semantic/Semantics/MemberResolutionResultTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.CodeAnalysis.CSharp.Symbols;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.Semantic.UnitTests.Semantics
{
public class MemberResolutionResultTests
{
[Fact]
public void Equality()
{
var d = default(MemberResolutionResult<MethodSymbol>);
Assert.Throws<NotSupportedException>(() => d.Equals(d));
Assert.Throws<NotSupportedException>(() => d.GetHashCode());
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.CodeAnalysis.CSharp.Symbols;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.Semantic.UnitTests.Semantics
{
public class MemberResolutionResultTests
{
[Fact]
public void Equality()
{
var d = default(MemberResolutionResult<MethodSymbol>);
Assert.Throws<NotSupportedException>(() => d.Equals(d));
Assert.Throws<NotSupportedException>(() => d.GetHashCode());
}
}
}
| -1 |
dotnet/roslyn | 55,877 | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute | Part of C# 10 support | davidwengier | 2021-08-25T05:36:27Z | 2021-08-30T20:47:11Z | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | 023d3ca2b5fb429f0b3dcc1efeed39442e232dba | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute. Part of C# 10 support | ./src/VisualStudio/Core/Def/ExternalAccess/VSTypeScript/Api/VSTypeScriptVisualStudioProjectWrapper.LSPContainedDocumentServiceProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.CodeAnalysis.Host;
namespace Microsoft.VisualStudio.LanguageServices.ExternalAccess.VSTypeScript.Api
{
internal sealed partial class VSTypeScriptVisualStudioProjectWrapper
{
private sealed class LspContainedDocumentServiceProvider : IDocumentServiceProvider, IDocumentOperationService
{
private readonly VirtualDocumentPropertiesService _documentPropertiesService;
private LspContainedDocumentServiceProvider()
{
_documentPropertiesService = VirtualDocumentPropertiesService.Instance;
}
public static LspContainedDocumentServiceProvider Instance = new LspContainedDocumentServiceProvider();
bool IDocumentOperationService.CanApplyChange => true;
bool IDocumentOperationService.SupportDiagnostics => true;
TService? IDocumentServiceProvider.GetService<TService>() where TService : class
{
if (typeof(TService) == typeof(DocumentPropertiesService))
{
return (TService)(object)_documentPropertiesService;
}
return this as TService;
}
private sealed class VirtualDocumentPropertiesService : DocumentPropertiesService
{
private const string _lspClientName = "TypeScript";
private VirtualDocumentPropertiesService() { }
public static VirtualDocumentPropertiesService Instance = new VirtualDocumentPropertiesService();
public override string? DiagnosticsLspClientName => _lspClientName;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.CodeAnalysis.Host;
namespace Microsoft.VisualStudio.LanguageServices.ExternalAccess.VSTypeScript.Api
{
internal sealed partial class VSTypeScriptVisualStudioProjectWrapper
{
private sealed class LspContainedDocumentServiceProvider : IDocumentServiceProvider, IDocumentOperationService
{
private readonly VirtualDocumentPropertiesService _documentPropertiesService;
private LspContainedDocumentServiceProvider()
{
_documentPropertiesService = VirtualDocumentPropertiesService.Instance;
}
public static LspContainedDocumentServiceProvider Instance = new LspContainedDocumentServiceProvider();
bool IDocumentOperationService.CanApplyChange => true;
bool IDocumentOperationService.SupportDiagnostics => true;
TService? IDocumentServiceProvider.GetService<TService>() where TService : class
{
if (typeof(TService) == typeof(DocumentPropertiesService))
{
return (TService)(object)_documentPropertiesService;
}
return this as TService;
}
private sealed class VirtualDocumentPropertiesService : DocumentPropertiesService
{
private const string _lspClientName = "TypeScript";
private VirtualDocumentPropertiesService() { }
public static VirtualDocumentPropertiesService Instance = new VirtualDocumentPropertiesService();
public override string? DiagnosticsLspClientName => _lspClientName;
}
}
}
}
| -1 |
dotnet/roslyn | 55,877 | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute | Part of C# 10 support | davidwengier | 2021-08-25T05:36:27Z | 2021-08-30T20:47:11Z | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | 023d3ca2b5fb429f0b3dcc1efeed39442e232dba | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute. Part of C# 10 support | ./src/Features/Core/Portable/Diagnostics/IDiagnosticUpdateSourceRegistrationService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
namespace Microsoft.CodeAnalysis.Diagnostics
{
/// <summary>
/// A service that let people to register new IDiagnosticUpdateSource
/// </summary>
internal interface IDiagnosticUpdateSourceRegistrationService
{
/// <summary>
/// Register new IDiagnosticUpdateSource
///
/// Currently, it doesn't support unregister since our event is asynchronous and unregistering source that deal with asynchronous event is not straight forward.
/// </summary>
void Register(IDiagnosticUpdateSource source);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
namespace Microsoft.CodeAnalysis.Diagnostics
{
/// <summary>
/// A service that let people to register new IDiagnosticUpdateSource
/// </summary>
internal interface IDiagnosticUpdateSourceRegistrationService
{
/// <summary>
/// Register new IDiagnosticUpdateSource
///
/// Currently, it doesn't support unregister since our event is asynchronous and unregistering source that deal with asynchronous event is not straight forward.
/// </summary>
void Register(IDiagnosticUpdateSource source);
}
}
| -1 |
dotnet/roslyn | 55,877 | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute | Part of C# 10 support | davidwengier | 2021-08-25T05:36:27Z | 2021-08-30T20:47:11Z | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | 023d3ca2b5fb429f0b3dcc1efeed39442e232dba | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute. Part of C# 10 support | ./src/Features/Core/Portable/CodeRefactorings/MoveType/MoveTypeCodeRefactoringProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Composition;
using System.Diagnostics.CodeAnalysis;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Shared.Extensions;
namespace Microsoft.CodeAnalysis.CodeRefactorings.MoveType
{
[ExportCodeRefactoringProvider(LanguageNames.CSharp, LanguageNames.VisualBasic,
Name = PredefinedCodeRefactoringProviderNames.MoveTypeToFile), Shared]
internal class MoveTypeCodeRefactoringProvider : CodeRefactoringProvider
{
[ImportingConstructor]
[SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")]
public MoveTypeCodeRefactoringProvider()
{
}
public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context)
{
var (document, textSpan, cancellationToken) = context;
var workspace = document.Project.Solution.Workspace;
if (workspace.Kind == WorkspaceKind.MiscellaneousFiles)
{
return;
}
if (document.IsGeneratedCode(cancellationToken))
{
return;
}
var service = document.GetLanguageService<IMoveTypeService>();
var actions = await service.GetRefactoringAsync(document, textSpan, cancellationToken).ConfigureAwait(false);
context.RegisterRefactorings(actions);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Composition;
using System.Diagnostics.CodeAnalysis;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Shared.Extensions;
namespace Microsoft.CodeAnalysis.CodeRefactorings.MoveType
{
[ExportCodeRefactoringProvider(LanguageNames.CSharp, LanguageNames.VisualBasic,
Name = PredefinedCodeRefactoringProviderNames.MoveTypeToFile), Shared]
internal class MoveTypeCodeRefactoringProvider : CodeRefactoringProvider
{
[ImportingConstructor]
[SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")]
public MoveTypeCodeRefactoringProvider()
{
}
public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context)
{
var (document, textSpan, cancellationToken) = context;
var workspace = document.Project.Solution.Workspace;
if (workspace.Kind == WorkspaceKind.MiscellaneousFiles)
{
return;
}
if (document.IsGeneratedCode(cancellationToken))
{
return;
}
var service = document.GetLanguageService<IMoveTypeService>();
var actions = await service.GetRefactoringAsync(document, textSpan, cancellationToken).ConfigureAwait(false);
context.RegisterRefactorings(actions);
}
}
}
| -1 |
dotnet/roslyn | 55,877 | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute | Part of C# 10 support | davidwengier | 2021-08-25T05:36:27Z | 2021-08-30T20:47:11Z | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | 023d3ca2b5fb429f0b3dcc1efeed39442e232dba | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute. Part of C# 10 support | ./src/EditorFeatures/Core/Implementation/AutomaticCompletion/BraceCompletionSessionProvider.BraceCompletionSession.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Diagnostics;
using System.Threading;
using Microsoft.CodeAnalysis.BraceCompletion;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.Text.Shared.Extensions;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.BraceCompletion;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Operations;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Implementation.AutomaticCompletion
{
internal partial class BraceCompletionSessionProvider
{
// ported and modified from "Platform\Text\Impl\BraceCompletion\BraceCompletionDefaultSession.cs"
//
// we want to provide better context based brace completion but IBraceCompletionContext is too simple for that.
// fortunately, editor provides another extension point where we have more control over brace completion but we do not
// want to re-implement logics base session provider already provides. so I ported editor's default session and
// modified it little bit so that we can use it as base class.
private class BraceCompletionSession : ForegroundThreadAffinitizedObject, IBraceCompletionSession
{
#region Private Members
public char OpeningBrace { get; }
public char ClosingBrace { get; }
public ITrackingPoint OpeningPoint { get; private set; }
public ITrackingPoint ClosingPoint { get; private set; }
public ITextBuffer SubjectBuffer { get; }
public ITextView TextView { get; }
private readonly ITextUndoHistory _undoHistory;
private readonly IEditorOperations _editorOperations;
private readonly IBraceCompletionService _service;
#endregion
#region Constructors
public BraceCompletionSession(
ITextView textView, ITextBuffer subjectBuffer,
SnapshotPoint openingPoint, char openingBrace, char closingBrace, ITextUndoHistory undoHistory,
IEditorOperationsFactoryService editorOperationsFactoryService, IBraceCompletionService service,
IThreadingContext threadingContext)
: base(threadingContext, assertIsForeground: true)
{
this.TextView = textView;
this.SubjectBuffer = subjectBuffer;
this.OpeningBrace = openingBrace;
this.ClosingBrace = closingBrace;
this.ClosingPoint = SubjectBuffer.CurrentSnapshot.CreateTrackingPoint(openingPoint.Position, PointTrackingMode.Positive);
_undoHistory = undoHistory;
_editorOperations = editorOperationsFactoryService.GetEditorOperations(textView);
_service = service;
}
#endregion
#region IBraceCompletionSession Methods
public void Start()
{
this.AssertIsForeground();
// Brace completion is not cancellable.
if (!this.TryStart(CancellationToken.None))
{
EndSession();
}
}
private bool TryStart(CancellationToken cancellationToken)
{
this.AssertIsForeground();
var closingSnapshotPoint = ClosingPoint.GetPoint(SubjectBuffer.CurrentSnapshot);
if (closingSnapshotPoint.Position < 1)
{
Debug.Fail("The closing point was not found at the expected position.");
return false;
}
var openingSnapshotPoint = closingSnapshotPoint.Subtract(1);
if (openingSnapshotPoint.GetChar() != OpeningBrace)
{
// there is a bug in editor brace completion engine on projection buffer that already fixed in vs_pro. until that is FIed to use
// I will make this not to assert
// Debug.Fail("The opening brace was not found at the expected position.");
return false;
}
OpeningPoint = SubjectBuffer.CurrentSnapshot.CreateTrackingPoint(openingSnapshotPoint, PointTrackingMode.Positive);
var context = GetBraceCompletionContext();
if (context == null)
{
return false;
}
var braceResult = _service.GetBraceCompletionAsync(context.Value, cancellationToken).WaitAndGetResult(cancellationToken);
if (braceResult == null)
{
return false;
}
using var caretPreservingTransaction = new CaretPreservingEditTransaction(EditorFeaturesResources.Brace_Completion, _undoHistory, _editorOperations);
// Apply the change to complete the brace.
ApplyBraceCompletionResult(braceResult.Value);
// switch the closing point from positive to negative tracking so that the closing point stays against the closing brace
ClosingPoint = SubjectBuffer.CurrentSnapshot.CreateTrackingPoint(ClosingPoint.GetPoint(SubjectBuffer.CurrentSnapshot), PointTrackingMode.Negative);
var contextAfterStart = GetBraceCompletionContext();
if (contextAfterStart != null)
{
var changesAfterStart = _service.GetTextChangesAfterCompletionAsync(contextAfterStart.Value, cancellationToken).WaitAndGetResult(cancellationToken);
if (changesAfterStart != null)
{
ApplyBraceCompletionResult(changesAfterStart.Value);
}
}
caretPreservingTransaction.Complete();
return true;
}
public void PreBackspace(out bool handledCommand)
{
this.AssertIsForeground();
handledCommand = false;
var caretPos = this.GetCaretPosition();
var snapshot = SubjectBuffer.CurrentSnapshot;
if (caretPos.HasValue && caretPos.Value.Position > 0 && (caretPos.Value.Position - 1) == OpeningPoint.GetPoint(snapshot).Position
&& !HasForwardTyping)
{
using var undo = CreateUndoTransaction();
using var edit = SubjectBuffer.CreateEdit();
var span = new SnapshotSpan(OpeningPoint.GetPoint(snapshot), ClosingPoint.GetPoint(snapshot));
edit.Delete(span);
if (edit.HasFailedChanges)
{
edit.Cancel();
undo.Cancel();
Debug.Fail("Unable to clear braces");
}
else
{
// handle the command so the backspace does
// not go through since we've already cleared the braces
handledCommand = true;
edit.ApplyAndLogExceptions();
undo.Complete();
EndSession();
}
}
}
public void PostBackspace()
{
}
public void PreOverType(out bool handledCommand)
{
this.AssertIsForeground();
handledCommand = false;
if (ClosingPoint == null)
{
return;
}
// Brace completion is not cancellable.
var cancellationToken = CancellationToken.None;
var snapshot = this.SubjectBuffer.CurrentSnapshot;
var closingSnapshotPoint = ClosingPoint.GetPoint(snapshot);
if (!HasForwardTyping && AllowOverType())
{
var caretPos = this.GetCaretPosition();
Debug.Assert(caretPos.HasValue && caretPos.Value.Position < closingSnapshotPoint.Position);
// ensure that we are within the session before clearing
if (caretPos.HasValue && caretPos.Value.Position < closingSnapshotPoint.Position && closingSnapshotPoint.Position > 0)
{
using var undo = CreateUndoTransaction();
_editorOperations.AddBeforeTextBufferChangePrimitive();
var span = new SnapshotSpan(caretPos.Value, closingSnapshotPoint.Subtract(1));
using var edit = SubjectBuffer.CreateEdit();
edit.Delete(span);
if (edit.HasFailedChanges)
{
Debug.Fail("Unable to clear closing brace");
edit.Cancel();
undo.Cancel();
}
else
{
handledCommand = true;
edit.ApplyAndLogExceptions();
MoveCaretToClosingPoint();
_editorOperations.AddAfterTextBufferChangePrimitive();
undo.Complete();
}
}
}
return;
bool AllowOverType()
{
var context = GetBraceCompletionContext();
return context != null && _service.AllowOverTypeAsync(context.Value, cancellationToken).WaitAndGetResult(cancellationToken);
}
}
public void PostOverType()
{
}
public void PreTab(out bool handledCommand)
{
this.AssertIsForeground();
handledCommand = false;
if (!HasForwardTyping)
{
handledCommand = true;
using var undo = CreateUndoTransaction();
_editorOperations.AddBeforeTextBufferChangePrimitive();
MoveCaretToClosingPoint();
_editorOperations.AddAfterTextBufferChangePrimitive();
undo.Complete();
}
}
public void PreReturn(out bool handledCommand)
=> handledCommand = false;
public void PostReturn()
{
this.AssertIsForeground();
if (this.GetCaretPosition().HasValue)
{
var closingSnapshotPoint = ClosingPoint.GetPoint(SubjectBuffer.CurrentSnapshot);
if (closingSnapshotPoint.Position > 0 && HasNoForwardTyping(this.GetCaretPosition().Value, closingSnapshotPoint.Subtract(1)))
{
var context = GetBraceCompletionContext();
if (context == null)
{
return;
}
var documentOptions = context.Value.Document.GetOptionsAsync().WaitAndGetResult(CancellationToken.None);
var changesAfterReturn = _service.GetTextChangeAfterReturnAsync(context.Value, documentOptions, CancellationToken.None).WaitAndGetResult(CancellationToken.None);
if (changesAfterReturn != null)
{
using var caretPreservingTransaction = new CaretPreservingEditTransaction(EditorFeaturesResources.Brace_Completion, _undoHistory, _editorOperations);
ApplyBraceCompletionResult(changesAfterReturn.Value);
caretPreservingTransaction.Complete();
}
}
}
}
public void Finish()
{
}
#endregion
#region Unused IBraceCompletionSession Methods
public void PostTab() { }
public void PreDelete(out bool handledCommand)
=> handledCommand = false;
public void PostDelete() { }
#endregion
#region Private Helpers
private void EndSession()
{
// set the points to null to get off the stack
// the stack will determine that the current point
// is not contained within the session if either are null
OpeningPoint = null;
ClosingPoint = null;
}
// check if there any typing between the caret the closing point
private bool HasForwardTyping
{
get
{
this.AssertIsForeground();
var closingSnapshotPoint = ClosingPoint.GetPoint(SubjectBuffer.CurrentSnapshot);
if (closingSnapshotPoint.Position > 0)
{
var caretPos = this.GetCaretPosition();
if (caretPos.HasValue && !HasNoForwardTyping(caretPos.Value, closingSnapshotPoint.Subtract(1)))
{
return true;
}
}
return false;
}
}
// verify that there is only whitespace between the two given points
private static bool HasNoForwardTyping(SnapshotPoint caretPoint, SnapshotPoint endPoint)
{
Debug.Assert(caretPoint.Snapshot == endPoint.Snapshot, "snapshots do not match");
if (caretPoint.Snapshot == endPoint.Snapshot)
{
if (caretPoint == endPoint)
{
return true;
}
if (caretPoint.Position < endPoint.Position)
{
var span = new SnapshotSpan(caretPoint, endPoint);
return string.IsNullOrWhiteSpace(span.GetText());
}
}
return false;
}
internal ITextUndoTransaction CreateUndoTransaction()
=> _undoHistory.CreateTransaction(EditorFeaturesResources.Brace_Completion);
private void MoveCaretToClosingPoint()
{
this.AssertIsForeground();
var closingSnapshotPoint = ClosingPoint.GetPoint(SubjectBuffer.CurrentSnapshot);
// find the position just after the closing brace in the view's text buffer
var afterBrace = TextView.BufferGraph.MapUpToBuffer(closingSnapshotPoint,
PointTrackingMode.Negative, PositionAffinity.Predecessor, TextView.TextBuffer);
Debug.Assert(afterBrace.HasValue, "Unable to move caret to closing point");
if (afterBrace.HasValue)
{
TextView.Caret.MoveTo(afterBrace.Value);
}
}
private BraceCompletionContext? GetBraceCompletionContext()
{
this.AssertIsForeground();
var snapshot = SubjectBuffer.CurrentSnapshot;
var document = snapshot.GetOpenDocumentInCurrentContextWithChanges();
if (document == null)
{
return null;
}
var closingSnapshotPoint = ClosingPoint.GetPosition(snapshot);
var openingSnapshotPoint = OpeningPoint.GetPosition(snapshot);
// The user is actively typing so the caret position should not be null.
var caretPosition = this.GetCaretPosition().Value.Position;
return new BraceCompletionContext(document, openingSnapshotPoint, closingSnapshotPoint, caretPosition);
}
private void ApplyBraceCompletionResult(BraceCompletionResult result)
{
this.AssertIsForeground();
using var edit = SubjectBuffer.CreateEdit();
foreach (var change in result.TextChanges)
{
edit.Replace(change.Span.ToSpan(), change.NewText);
}
edit.ApplyAndLogExceptions();
try
{
Contract.ThrowIfFalse(SubjectBuffer.CurrentSnapshot[OpeningPoint.GetPosition(SubjectBuffer.CurrentSnapshot)] == OpeningBrace,
"The opening point does not match the opening brace character");
Contract.ThrowIfFalse(SubjectBuffer.CurrentSnapshot[ClosingPoint.GetPosition(SubjectBuffer.CurrentSnapshot) - 1] == ClosingBrace,
"The closing point does not match the closing brace character");
}
catch (Exception e) when (FatalError.ReportAndCatch(e))
{
return;
}
var caretLine = SubjectBuffer.CurrentSnapshot.GetLineFromLineNumber(result.CaretLocation.Line);
TextView.TryMoveCaretToAndEnsureVisible(new VirtualSnapshotPoint(caretLine, result.CaretLocation.Character));
}
#endregion
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Diagnostics;
using System.Threading;
using Microsoft.CodeAnalysis.BraceCompletion;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.Text.Shared.Extensions;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.BraceCompletion;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Operations;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Implementation.AutomaticCompletion
{
internal partial class BraceCompletionSessionProvider
{
// ported and modified from "Platform\Text\Impl\BraceCompletion\BraceCompletionDefaultSession.cs"
//
// we want to provide better context based brace completion but IBraceCompletionContext is too simple for that.
// fortunately, editor provides another extension point where we have more control over brace completion but we do not
// want to re-implement logics base session provider already provides. so I ported editor's default session and
// modified it little bit so that we can use it as base class.
private class BraceCompletionSession : ForegroundThreadAffinitizedObject, IBraceCompletionSession
{
#region Private Members
public char OpeningBrace { get; }
public char ClosingBrace { get; }
public ITrackingPoint OpeningPoint { get; private set; }
public ITrackingPoint ClosingPoint { get; private set; }
public ITextBuffer SubjectBuffer { get; }
public ITextView TextView { get; }
private readonly ITextUndoHistory _undoHistory;
private readonly IEditorOperations _editorOperations;
private readonly IBraceCompletionService _service;
#endregion
#region Constructors
public BraceCompletionSession(
ITextView textView, ITextBuffer subjectBuffer,
SnapshotPoint openingPoint, char openingBrace, char closingBrace, ITextUndoHistory undoHistory,
IEditorOperationsFactoryService editorOperationsFactoryService, IBraceCompletionService service,
IThreadingContext threadingContext)
: base(threadingContext, assertIsForeground: true)
{
this.TextView = textView;
this.SubjectBuffer = subjectBuffer;
this.OpeningBrace = openingBrace;
this.ClosingBrace = closingBrace;
this.ClosingPoint = SubjectBuffer.CurrentSnapshot.CreateTrackingPoint(openingPoint.Position, PointTrackingMode.Positive);
_undoHistory = undoHistory;
_editorOperations = editorOperationsFactoryService.GetEditorOperations(textView);
_service = service;
}
#endregion
#region IBraceCompletionSession Methods
public void Start()
{
this.AssertIsForeground();
// Brace completion is not cancellable.
if (!this.TryStart(CancellationToken.None))
{
EndSession();
}
}
private bool TryStart(CancellationToken cancellationToken)
{
this.AssertIsForeground();
var closingSnapshotPoint = ClosingPoint.GetPoint(SubjectBuffer.CurrentSnapshot);
if (closingSnapshotPoint.Position < 1)
{
Debug.Fail("The closing point was not found at the expected position.");
return false;
}
var openingSnapshotPoint = closingSnapshotPoint.Subtract(1);
if (openingSnapshotPoint.GetChar() != OpeningBrace)
{
// there is a bug in editor brace completion engine on projection buffer that already fixed in vs_pro. until that is FIed to use
// I will make this not to assert
// Debug.Fail("The opening brace was not found at the expected position.");
return false;
}
OpeningPoint = SubjectBuffer.CurrentSnapshot.CreateTrackingPoint(openingSnapshotPoint, PointTrackingMode.Positive);
var context = GetBraceCompletionContext();
if (context == null)
{
return false;
}
var braceResult = _service.GetBraceCompletionAsync(context.Value, cancellationToken).WaitAndGetResult(cancellationToken);
if (braceResult == null)
{
return false;
}
using var caretPreservingTransaction = new CaretPreservingEditTransaction(EditorFeaturesResources.Brace_Completion, _undoHistory, _editorOperations);
// Apply the change to complete the brace.
ApplyBraceCompletionResult(braceResult.Value);
// switch the closing point from positive to negative tracking so that the closing point stays against the closing brace
ClosingPoint = SubjectBuffer.CurrentSnapshot.CreateTrackingPoint(ClosingPoint.GetPoint(SubjectBuffer.CurrentSnapshot), PointTrackingMode.Negative);
var contextAfterStart = GetBraceCompletionContext();
if (contextAfterStart != null)
{
var changesAfterStart = _service.GetTextChangesAfterCompletionAsync(contextAfterStart.Value, cancellationToken).WaitAndGetResult(cancellationToken);
if (changesAfterStart != null)
{
ApplyBraceCompletionResult(changesAfterStart.Value);
}
}
caretPreservingTransaction.Complete();
return true;
}
public void PreBackspace(out bool handledCommand)
{
this.AssertIsForeground();
handledCommand = false;
var caretPos = this.GetCaretPosition();
var snapshot = SubjectBuffer.CurrentSnapshot;
if (caretPos.HasValue && caretPos.Value.Position > 0 && (caretPos.Value.Position - 1) == OpeningPoint.GetPoint(snapshot).Position
&& !HasForwardTyping)
{
using var undo = CreateUndoTransaction();
using var edit = SubjectBuffer.CreateEdit();
var span = new SnapshotSpan(OpeningPoint.GetPoint(snapshot), ClosingPoint.GetPoint(snapshot));
edit.Delete(span);
if (edit.HasFailedChanges)
{
edit.Cancel();
undo.Cancel();
Debug.Fail("Unable to clear braces");
}
else
{
// handle the command so the backspace does
// not go through since we've already cleared the braces
handledCommand = true;
edit.ApplyAndLogExceptions();
undo.Complete();
EndSession();
}
}
}
public void PostBackspace()
{
}
public void PreOverType(out bool handledCommand)
{
this.AssertIsForeground();
handledCommand = false;
if (ClosingPoint == null)
{
return;
}
// Brace completion is not cancellable.
var cancellationToken = CancellationToken.None;
var snapshot = this.SubjectBuffer.CurrentSnapshot;
var closingSnapshotPoint = ClosingPoint.GetPoint(snapshot);
if (!HasForwardTyping && AllowOverType())
{
var caretPos = this.GetCaretPosition();
Debug.Assert(caretPos.HasValue && caretPos.Value.Position < closingSnapshotPoint.Position);
// ensure that we are within the session before clearing
if (caretPos.HasValue && caretPos.Value.Position < closingSnapshotPoint.Position && closingSnapshotPoint.Position > 0)
{
using var undo = CreateUndoTransaction();
_editorOperations.AddBeforeTextBufferChangePrimitive();
var span = new SnapshotSpan(caretPos.Value, closingSnapshotPoint.Subtract(1));
using var edit = SubjectBuffer.CreateEdit();
edit.Delete(span);
if (edit.HasFailedChanges)
{
Debug.Fail("Unable to clear closing brace");
edit.Cancel();
undo.Cancel();
}
else
{
handledCommand = true;
edit.ApplyAndLogExceptions();
MoveCaretToClosingPoint();
_editorOperations.AddAfterTextBufferChangePrimitive();
undo.Complete();
}
}
}
return;
bool AllowOverType()
{
var context = GetBraceCompletionContext();
return context != null && _service.AllowOverTypeAsync(context.Value, cancellationToken).WaitAndGetResult(cancellationToken);
}
}
public void PostOverType()
{
}
public void PreTab(out bool handledCommand)
{
this.AssertIsForeground();
handledCommand = false;
if (!HasForwardTyping)
{
handledCommand = true;
using var undo = CreateUndoTransaction();
_editorOperations.AddBeforeTextBufferChangePrimitive();
MoveCaretToClosingPoint();
_editorOperations.AddAfterTextBufferChangePrimitive();
undo.Complete();
}
}
public void PreReturn(out bool handledCommand)
=> handledCommand = false;
public void PostReturn()
{
this.AssertIsForeground();
if (this.GetCaretPosition().HasValue)
{
var closingSnapshotPoint = ClosingPoint.GetPoint(SubjectBuffer.CurrentSnapshot);
if (closingSnapshotPoint.Position > 0 && HasNoForwardTyping(this.GetCaretPosition().Value, closingSnapshotPoint.Subtract(1)))
{
var context = GetBraceCompletionContext();
if (context == null)
{
return;
}
var documentOptions = context.Value.Document.GetOptionsAsync().WaitAndGetResult(CancellationToken.None);
var changesAfterReturn = _service.GetTextChangeAfterReturnAsync(context.Value, documentOptions, CancellationToken.None).WaitAndGetResult(CancellationToken.None);
if (changesAfterReturn != null)
{
using var caretPreservingTransaction = new CaretPreservingEditTransaction(EditorFeaturesResources.Brace_Completion, _undoHistory, _editorOperations);
ApplyBraceCompletionResult(changesAfterReturn.Value);
caretPreservingTransaction.Complete();
}
}
}
}
public void Finish()
{
}
#endregion
#region Unused IBraceCompletionSession Methods
public void PostTab() { }
public void PreDelete(out bool handledCommand)
=> handledCommand = false;
public void PostDelete() { }
#endregion
#region Private Helpers
private void EndSession()
{
// set the points to null to get off the stack
// the stack will determine that the current point
// is not contained within the session if either are null
OpeningPoint = null;
ClosingPoint = null;
}
// check if there any typing between the caret the closing point
private bool HasForwardTyping
{
get
{
this.AssertIsForeground();
var closingSnapshotPoint = ClosingPoint.GetPoint(SubjectBuffer.CurrentSnapshot);
if (closingSnapshotPoint.Position > 0)
{
var caretPos = this.GetCaretPosition();
if (caretPos.HasValue && !HasNoForwardTyping(caretPos.Value, closingSnapshotPoint.Subtract(1)))
{
return true;
}
}
return false;
}
}
// verify that there is only whitespace between the two given points
private static bool HasNoForwardTyping(SnapshotPoint caretPoint, SnapshotPoint endPoint)
{
Debug.Assert(caretPoint.Snapshot == endPoint.Snapshot, "snapshots do not match");
if (caretPoint.Snapshot == endPoint.Snapshot)
{
if (caretPoint == endPoint)
{
return true;
}
if (caretPoint.Position < endPoint.Position)
{
var span = new SnapshotSpan(caretPoint, endPoint);
return string.IsNullOrWhiteSpace(span.GetText());
}
}
return false;
}
internal ITextUndoTransaction CreateUndoTransaction()
=> _undoHistory.CreateTransaction(EditorFeaturesResources.Brace_Completion);
private void MoveCaretToClosingPoint()
{
this.AssertIsForeground();
var closingSnapshotPoint = ClosingPoint.GetPoint(SubjectBuffer.CurrentSnapshot);
// find the position just after the closing brace in the view's text buffer
var afterBrace = TextView.BufferGraph.MapUpToBuffer(closingSnapshotPoint,
PointTrackingMode.Negative, PositionAffinity.Predecessor, TextView.TextBuffer);
Debug.Assert(afterBrace.HasValue, "Unable to move caret to closing point");
if (afterBrace.HasValue)
{
TextView.Caret.MoveTo(afterBrace.Value);
}
}
private BraceCompletionContext? GetBraceCompletionContext()
{
this.AssertIsForeground();
var snapshot = SubjectBuffer.CurrentSnapshot;
var document = snapshot.GetOpenDocumentInCurrentContextWithChanges();
if (document == null)
{
return null;
}
var closingSnapshotPoint = ClosingPoint.GetPosition(snapshot);
var openingSnapshotPoint = OpeningPoint.GetPosition(snapshot);
// The user is actively typing so the caret position should not be null.
var caretPosition = this.GetCaretPosition().Value.Position;
return new BraceCompletionContext(document, openingSnapshotPoint, closingSnapshotPoint, caretPosition);
}
private void ApplyBraceCompletionResult(BraceCompletionResult result)
{
this.AssertIsForeground();
using var edit = SubjectBuffer.CreateEdit();
foreach (var change in result.TextChanges)
{
edit.Replace(change.Span.ToSpan(), change.NewText);
}
edit.ApplyAndLogExceptions();
try
{
Contract.ThrowIfFalse(SubjectBuffer.CurrentSnapshot[OpeningPoint.GetPosition(SubjectBuffer.CurrentSnapshot)] == OpeningBrace,
"The opening point does not match the opening brace character");
Contract.ThrowIfFalse(SubjectBuffer.CurrentSnapshot[ClosingPoint.GetPosition(SubjectBuffer.CurrentSnapshot) - 1] == ClosingBrace,
"The closing point does not match the closing brace character");
}
catch (Exception e) when (FatalError.ReportAndCatch(e))
{
return;
}
var caretLine = SubjectBuffer.CurrentSnapshot.GetLineFromLineNumber(result.CaretLocation.Line);
TextView.TryMoveCaretToAndEnsureVisible(new VirtualSnapshotPoint(caretLine, result.CaretLocation.Character));
}
#endregion
}
}
}
| -1 |
dotnet/roslyn | 55,877 | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute | Part of C# 10 support | davidwengier | 2021-08-25T05:36:27Z | 2021-08-30T20:47:11Z | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | 023d3ca2b5fb429f0b3dcc1efeed39442e232dba | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute. Part of C# 10 support | ./src/Compilers/CSharp/Portable/Symbols/Source/SourceClonedParameterSymbol.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using System.Diagnostics;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
/// <summary>
/// Represents a source parameter cloned from another <see cref="SourceParameterSymbol"/>, when they must share attribute data and default constant value.
/// For example, parameters on a property symbol are cloned to generate parameters on accessors.
/// Similarly parameters on delegate invoke method are cloned to delegate begin/end invoke methods.
/// </summary>
internal abstract class SourceClonedParameterSymbol : SourceParameterSymbolBase
{
// if true suppresses params-array and default value:
private readonly bool _suppressOptional;
protected readonly SourceParameterSymbol _originalParam;
internal SourceClonedParameterSymbol(SourceParameterSymbol originalParam, Symbol newOwner, int newOrdinal, bool suppressOptional)
: base(newOwner, newOrdinal)
{
Debug.Assert((object)originalParam != null);
_suppressOptional = suppressOptional;
_originalParam = originalParam;
}
public override bool IsImplicitlyDeclared => true;
public override bool IsDiscard => _originalParam.IsDiscard;
public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences
{
get
{
// Since you can't get from the syntax node that represents the original parameter
// back to this symbol we decided not to return the original syntax node here.
return ImmutableArray<SyntaxReference>.Empty;
}
}
public override bool IsParams
{
get { return !_suppressOptional && _originalParam.IsParams; }
}
internal override bool IsMetadataOptional
{
get
{
// pseudo-custom attributes are not suppressed:
return _suppressOptional ? _originalParam.HasOptionalAttribute : _originalParam.IsMetadataOptional;
}
}
internal override ConstantValue ExplicitDefaultConstantValue
{
get
{
// pseudo-custom attributes are not suppressed:
return _suppressOptional ? _originalParam.DefaultValueFromAttributes : _originalParam.ExplicitDefaultConstantValue;
}
}
internal override ConstantValue DefaultValueFromAttributes
{
get { return _originalParam.DefaultValueFromAttributes; }
}
#region Forwarded
public override TypeWithAnnotations TypeWithAnnotations
{
get { return _originalParam.TypeWithAnnotations; }
}
public override RefKind RefKind
{
get { return _originalParam.RefKind; }
}
internal override bool IsMetadataIn
{
get { return _originalParam.IsMetadataIn; }
}
internal override bool IsMetadataOut
{
get { return _originalParam.IsMetadataOut; }
}
public override ImmutableArray<Location> Locations
{
get { return _originalParam.Locations; }
}
public override ImmutableArray<CSharpAttributeData> GetAttributes()
{
return _originalParam.GetAttributes();
}
public sealed override string Name
{
get { return _originalParam.Name; }
}
public override ImmutableArray<CustomModifier> RefCustomModifiers
{
get { return _originalParam.RefCustomModifiers; }
}
internal override MarshalPseudoCustomAttributeData MarshallingInformation
{
get { return _originalParam.MarshallingInformation; }
}
internal override bool IsIDispatchConstant
{
get { return _originalParam.IsIDispatchConstant; }
}
internal override bool IsIUnknownConstant
{
get { return _originalParam.IsIUnknownConstant; }
}
internal override FlowAnalysisAnnotations FlowAnalysisAnnotations
{
get { return FlowAnalysisAnnotations.None; }
}
internal override ImmutableHashSet<string> NotNullIfParameterNotNull
{
get { return ImmutableHashSet<string>.Empty; }
}
internal override ImmutableArray<int> InterpolatedStringHandlerArgumentIndexes => throw ExceptionUtilities.Unreachable;
internal override bool HasInterpolatedStringHandlerArgumentError => throw ExceptionUtilities.Unreachable;
#endregion
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using System.Diagnostics;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
/// <summary>
/// Represents a source parameter cloned from another <see cref="SourceParameterSymbol"/>, when they must share attribute data and default constant value.
/// For example, parameters on a property symbol are cloned to generate parameters on accessors.
/// Similarly parameters on delegate invoke method are cloned to delegate begin/end invoke methods.
/// </summary>
internal abstract class SourceClonedParameterSymbol : SourceParameterSymbolBase
{
// if true suppresses params-array and default value:
private readonly bool _suppressOptional;
protected readonly SourceParameterSymbol _originalParam;
internal SourceClonedParameterSymbol(SourceParameterSymbol originalParam, Symbol newOwner, int newOrdinal, bool suppressOptional)
: base(newOwner, newOrdinal)
{
Debug.Assert((object)originalParam != null);
_suppressOptional = suppressOptional;
_originalParam = originalParam;
}
public override bool IsImplicitlyDeclared => true;
public override bool IsDiscard => _originalParam.IsDiscard;
public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences
{
get
{
// Since you can't get from the syntax node that represents the original parameter
// back to this symbol we decided not to return the original syntax node here.
return ImmutableArray<SyntaxReference>.Empty;
}
}
public override bool IsParams
{
get { return !_suppressOptional && _originalParam.IsParams; }
}
internal override bool IsMetadataOptional
{
get
{
// pseudo-custom attributes are not suppressed:
return _suppressOptional ? _originalParam.HasOptionalAttribute : _originalParam.IsMetadataOptional;
}
}
internal override ConstantValue ExplicitDefaultConstantValue
{
get
{
// pseudo-custom attributes are not suppressed:
return _suppressOptional ? _originalParam.DefaultValueFromAttributes : _originalParam.ExplicitDefaultConstantValue;
}
}
internal override ConstantValue DefaultValueFromAttributes
{
get { return _originalParam.DefaultValueFromAttributes; }
}
#region Forwarded
public override TypeWithAnnotations TypeWithAnnotations
{
get { return _originalParam.TypeWithAnnotations; }
}
public override RefKind RefKind
{
get { return _originalParam.RefKind; }
}
internal override bool IsMetadataIn
{
get { return _originalParam.IsMetadataIn; }
}
internal override bool IsMetadataOut
{
get { return _originalParam.IsMetadataOut; }
}
public override ImmutableArray<Location> Locations
{
get { return _originalParam.Locations; }
}
public override ImmutableArray<CSharpAttributeData> GetAttributes()
{
return _originalParam.GetAttributes();
}
public sealed override string Name
{
get { return _originalParam.Name; }
}
public override ImmutableArray<CustomModifier> RefCustomModifiers
{
get { return _originalParam.RefCustomModifiers; }
}
internal override MarshalPseudoCustomAttributeData MarshallingInformation
{
get { return _originalParam.MarshallingInformation; }
}
internal override bool IsIDispatchConstant
{
get { return _originalParam.IsIDispatchConstant; }
}
internal override bool IsIUnknownConstant
{
get { return _originalParam.IsIUnknownConstant; }
}
internal override FlowAnalysisAnnotations FlowAnalysisAnnotations
{
get { return FlowAnalysisAnnotations.None; }
}
internal override ImmutableHashSet<string> NotNullIfParameterNotNull
{
get { return ImmutableHashSet<string>.Empty; }
}
internal override ImmutableArray<int> InterpolatedStringHandlerArgumentIndexes => throw ExceptionUtilities.Unreachable;
internal override bool HasInterpolatedStringHandlerArgumentError => throw ExceptionUtilities.Unreachable;
#endregion
}
}
| -1 |
dotnet/roslyn | 55,877 | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute | Part of C# 10 support | davidwengier | 2021-08-25T05:36:27Z | 2021-08-30T20:47:11Z | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | 023d3ca2b5fb429f0b3dcc1efeed39442e232dba | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute. Part of C# 10 support | ./src/CodeStyle/VisualBasic/Analyzers/xlf/VBCodeStyleResources.zh-Hant.xlf | <?xml version="1.0" encoding="utf-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd">
<file datatype="xml" source-language="en" target-language="zh-Hant" original="../VBCodeStyleResources.resx">
<body>
<trans-unit id="EmptyResource">
<source>Remove this value when another is added.</source>
<target state="translated">當新增另一個值時移除此值。</target>
<note>https://github.com/Microsoft/msbuild/issues/1661</note>
</trans-unit>
</body>
</file>
</xliff> | <?xml version="1.0" encoding="utf-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd">
<file datatype="xml" source-language="en" target-language="zh-Hant" original="../VBCodeStyleResources.resx">
<body>
<trans-unit id="EmptyResource">
<source>Remove this value when another is added.</source>
<target state="translated">當新增另一個值時移除此值。</target>
<note>https://github.com/Microsoft/msbuild/issues/1661</note>
</trans-unit>
</body>
</file>
</xliff> | -1 |
dotnet/roslyn | 55,877 | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute | Part of C# 10 support | davidwengier | 2021-08-25T05:36:27Z | 2021-08-30T20:47:11Z | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | 023d3ca2b5fb429f0b3dcc1efeed39442e232dba | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute. Part of C# 10 support | ./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Formatting/Rules/WrappingFormattingRule.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Formatting.Rules;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.CSharp.Formatting
{
internal sealed class WrappingFormattingRule : BaseFormattingRule
{
private readonly CachedOptions _options;
public WrappingFormattingRule()
: this(new CachedOptions(null))
{
}
private WrappingFormattingRule(CachedOptions options)
{
_options = options;
}
public override AbstractFormattingRule WithOptions(AnalyzerConfigOptions options)
{
var cachedOptions = new CachedOptions(options);
if (cachedOptions == _options)
{
return this;
}
return new WrappingFormattingRule(cachedOptions);
}
public override void AddSuppressOperations(List<SuppressOperation> list, SyntaxNode node, in NextSuppressOperationAction nextOperation)
{
nextOperation.Invoke();
AddBraceSuppressOperations(list, node);
AddStatementExceptBlockSuppressOperations(list, node);
AddSpecificNodesSuppressOperations(list, node);
if (!_options.WrappingPreserveSingleLine)
{
RemoveSuppressOperationForBlock(list, node);
}
if (!_options.WrappingKeepStatementsOnSingleLine)
{
RemoveSuppressOperationForStatementMethodDeclaration(list, node);
}
}
private static (SyntaxToken firstToken, SyntaxToken lastToken) GetSpecificNodeSuppressionTokenRange(SyntaxNode node)
{
var embeddedStatement = node.GetEmbeddedStatement();
if (embeddedStatement != null)
{
var firstTokenOfEmbeddedStatement = embeddedStatement.GetFirstToken(includeZeroWidth: true);
var firstToken = firstTokenOfEmbeddedStatement.GetPreviousToken(includeZeroWidth: true);
if (embeddedStatement.IsKind(SyntaxKind.Block))
{
return (firstToken, embeddedStatement.GetLastToken(includeZeroWidth: true));
}
else
{
return (firstToken, firstTokenOfEmbeddedStatement);
}
}
return node switch
{
SwitchSectionSyntax switchSection => (switchSection.GetFirstToken(includeZeroWidth: true), switchSection.GetLastToken(includeZeroWidth: true)),
AnonymousMethodExpressionSyntax anonymousMethod => (anonymousMethod.DelegateKeyword, anonymousMethod.GetLastToken(includeZeroWidth: true)),
_ => default,
};
}
private static void AddSpecificNodesSuppressOperations(List<SuppressOperation> list, SyntaxNode node)
{
var (firstToken, lastToken) = GetSpecificNodeSuppressionTokenRange(node);
if (!firstToken.IsKind(SyntaxKind.None) || !lastToken.IsKind(SyntaxKind.None))
{
AddSuppressWrappingIfOnSingleLineOperation(list, firstToken, lastToken);
}
}
private static void AddStatementExceptBlockSuppressOperations(List<SuppressOperation> list, SyntaxNode node)
{
if (!(node is StatementSyntax statementNode) || statementNode.Kind() == SyntaxKind.Block)
{
return;
}
var firstToken = statementNode.GetFirstToken(includeZeroWidth: true);
var lastToken = statementNode.GetLastToken(includeZeroWidth: true);
AddSuppressWrappingIfOnSingleLineOperation(list, firstToken, lastToken);
}
private static void RemoveSuppressOperationForStatementMethodDeclaration(List<SuppressOperation> list, SyntaxNode node)
{
if (!(!(node is StatementSyntax statementNode) || statementNode.Kind() == SyntaxKind.Block))
{
var firstToken = statementNode.GetFirstToken(includeZeroWidth: true);
var lastToken = statementNode.GetLastToken(includeZeroWidth: true);
RemoveSuppressOperation(list, firstToken, lastToken);
}
var tokens = GetSpecificNodeSuppressionTokenRange(node);
if (!tokens.firstToken.IsKind(SyntaxKind.None) || !tokens.lastToken.IsKind(SyntaxKind.None))
{
RemoveSuppressOperation(list, tokens.firstToken, tokens.lastToken);
}
var ifStatementNode = node as IfStatementSyntax;
if (ifStatementNode?.Else != null)
{
RemoveSuppressOperation(list, ifStatementNode.Else.ElseKeyword, ifStatementNode.Else.Statement.GetFirstToken(includeZeroWidth: true));
}
}
private static void RemoveSuppressOperationForBlock(List<SuppressOperation> list, SyntaxNode node)
{
var bracePair = GetBracePair(node);
if (!bracePair.IsValidBracePair())
{
return;
}
var firstTokenOfNode = node.GetFirstToken(includeZeroWidth: true);
if (node.IsLambdaBodyBlock())
{
// include lambda itself.
firstTokenOfNode = node.Parent!.GetFirstToken(includeZeroWidth: true);
}
// suppress wrapping on whole construct that owns braces and also brace pair itself if it is on same line
RemoveSuppressOperation(list, firstTokenOfNode, bracePair.closeBrace);
RemoveSuppressOperation(list, bracePair.openBrace, bracePair.closeBrace);
}
private static (SyntaxToken openBrace, SyntaxToken closeBrace) GetBracePair(SyntaxNode node)
{
if (node is BaseMethodDeclarationSyntax methodDeclaration && methodDeclaration.Body != null)
{
return (methodDeclaration.Body.OpenBraceToken, methodDeclaration.Body.CloseBraceToken);
}
if (node is PropertyDeclarationSyntax propertyDeclaration && propertyDeclaration.AccessorList != null)
{
return (propertyDeclaration.AccessorList.OpenBraceToken, propertyDeclaration.AccessorList.CloseBraceToken);
}
if (node is AccessorDeclarationSyntax accessorDeclaration && accessorDeclaration.Body != null)
{
return (accessorDeclaration.Body.OpenBraceToken, accessorDeclaration.Body.CloseBraceToken);
}
return node.GetBracePair();
}
private static void RemoveSuppressOperation(
List<SuppressOperation> list,
SyntaxToken startToken,
SyntaxToken endToken)
{
if (startToken.Kind() == SyntaxKind.None || endToken.Kind() == SyntaxKind.None)
{
return;
}
var span = TextSpan.FromBounds(startToken.SpanStart, endToken.Span.End);
list.RemoveOrTransformAll(
(operation, span) =>
{
if (operation.TextSpan.Start >= span.Start && operation.TextSpan.End <= span.End && operation.Option.HasFlag(SuppressOption.NoWrappingIfOnSingleLine))
return null;
return operation;
},
span);
}
private readonly struct CachedOptions : IEquatable<CachedOptions>
{
public readonly bool WrappingPreserveSingleLine;
public readonly bool WrappingKeepStatementsOnSingleLine;
public CachedOptions(AnalyzerConfigOptions? options)
{
WrappingPreserveSingleLine = GetOptionOrDefault(options, CSharpFormattingOptions2.WrappingPreserveSingleLine);
WrappingKeepStatementsOnSingleLine = GetOptionOrDefault(options, CSharpFormattingOptions2.WrappingKeepStatementsOnSingleLine);
}
public static bool operator ==(CachedOptions left, CachedOptions right)
=> left.Equals(right);
public static bool operator !=(CachedOptions left, CachedOptions right)
=> !(left == right);
private static T GetOptionOrDefault<T>(AnalyzerConfigOptions? options, Option2<T> option)
{
if (options is null)
return option.DefaultValue;
return options.GetOption(option);
}
public override bool Equals(object? obj)
=> obj is CachedOptions options && Equals(options);
public bool Equals(CachedOptions other)
{
return WrappingPreserveSingleLine == other.WrappingPreserveSingleLine
&& WrappingKeepStatementsOnSingleLine == other.WrappingKeepStatementsOnSingleLine;
}
public override int GetHashCode()
{
var hashCode = 0;
hashCode = (hashCode << 1) + (WrappingPreserveSingleLine ? 1 : 0);
hashCode = (hashCode << 1) + (WrappingKeepStatementsOnSingleLine ? 1 : 0);
return hashCode;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Formatting.Rules;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.CSharp.Formatting
{
internal sealed class WrappingFormattingRule : BaseFormattingRule
{
private readonly CachedOptions _options;
public WrappingFormattingRule()
: this(new CachedOptions(null))
{
}
private WrappingFormattingRule(CachedOptions options)
{
_options = options;
}
public override AbstractFormattingRule WithOptions(AnalyzerConfigOptions options)
{
var cachedOptions = new CachedOptions(options);
if (cachedOptions == _options)
{
return this;
}
return new WrappingFormattingRule(cachedOptions);
}
public override void AddSuppressOperations(List<SuppressOperation> list, SyntaxNode node, in NextSuppressOperationAction nextOperation)
{
nextOperation.Invoke();
AddBraceSuppressOperations(list, node);
AddStatementExceptBlockSuppressOperations(list, node);
AddSpecificNodesSuppressOperations(list, node);
if (!_options.WrappingPreserveSingleLine)
{
RemoveSuppressOperationForBlock(list, node);
}
if (!_options.WrappingKeepStatementsOnSingleLine)
{
RemoveSuppressOperationForStatementMethodDeclaration(list, node);
}
}
private static (SyntaxToken firstToken, SyntaxToken lastToken) GetSpecificNodeSuppressionTokenRange(SyntaxNode node)
{
var embeddedStatement = node.GetEmbeddedStatement();
if (embeddedStatement != null)
{
var firstTokenOfEmbeddedStatement = embeddedStatement.GetFirstToken(includeZeroWidth: true);
var firstToken = firstTokenOfEmbeddedStatement.GetPreviousToken(includeZeroWidth: true);
if (embeddedStatement.IsKind(SyntaxKind.Block))
{
return (firstToken, embeddedStatement.GetLastToken(includeZeroWidth: true));
}
else
{
return (firstToken, firstTokenOfEmbeddedStatement);
}
}
return node switch
{
SwitchSectionSyntax switchSection => (switchSection.GetFirstToken(includeZeroWidth: true), switchSection.GetLastToken(includeZeroWidth: true)),
AnonymousMethodExpressionSyntax anonymousMethod => (anonymousMethod.DelegateKeyword, anonymousMethod.GetLastToken(includeZeroWidth: true)),
_ => default,
};
}
private static void AddSpecificNodesSuppressOperations(List<SuppressOperation> list, SyntaxNode node)
{
var (firstToken, lastToken) = GetSpecificNodeSuppressionTokenRange(node);
if (!firstToken.IsKind(SyntaxKind.None) || !lastToken.IsKind(SyntaxKind.None))
{
AddSuppressWrappingIfOnSingleLineOperation(list, firstToken, lastToken);
}
}
private static void AddStatementExceptBlockSuppressOperations(List<SuppressOperation> list, SyntaxNode node)
{
if (!(node is StatementSyntax statementNode) || statementNode.Kind() == SyntaxKind.Block)
{
return;
}
var firstToken = statementNode.GetFirstToken(includeZeroWidth: true);
var lastToken = statementNode.GetLastToken(includeZeroWidth: true);
AddSuppressWrappingIfOnSingleLineOperation(list, firstToken, lastToken);
}
private static void RemoveSuppressOperationForStatementMethodDeclaration(List<SuppressOperation> list, SyntaxNode node)
{
if (!(!(node is StatementSyntax statementNode) || statementNode.Kind() == SyntaxKind.Block))
{
var firstToken = statementNode.GetFirstToken(includeZeroWidth: true);
var lastToken = statementNode.GetLastToken(includeZeroWidth: true);
RemoveSuppressOperation(list, firstToken, lastToken);
}
var tokens = GetSpecificNodeSuppressionTokenRange(node);
if (!tokens.firstToken.IsKind(SyntaxKind.None) || !tokens.lastToken.IsKind(SyntaxKind.None))
{
RemoveSuppressOperation(list, tokens.firstToken, tokens.lastToken);
}
var ifStatementNode = node as IfStatementSyntax;
if (ifStatementNode?.Else != null)
{
RemoveSuppressOperation(list, ifStatementNode.Else.ElseKeyword, ifStatementNode.Else.Statement.GetFirstToken(includeZeroWidth: true));
}
}
private static void RemoveSuppressOperationForBlock(List<SuppressOperation> list, SyntaxNode node)
{
var bracePair = GetBracePair(node);
if (!bracePair.IsValidBracePair())
{
return;
}
var firstTokenOfNode = node.GetFirstToken(includeZeroWidth: true);
if (node.IsLambdaBodyBlock())
{
// include lambda itself.
firstTokenOfNode = node.Parent!.GetFirstToken(includeZeroWidth: true);
}
// suppress wrapping on whole construct that owns braces and also brace pair itself if it is on same line
RemoveSuppressOperation(list, firstTokenOfNode, bracePair.closeBrace);
RemoveSuppressOperation(list, bracePair.openBrace, bracePair.closeBrace);
}
private static (SyntaxToken openBrace, SyntaxToken closeBrace) GetBracePair(SyntaxNode node)
{
if (node is BaseMethodDeclarationSyntax methodDeclaration && methodDeclaration.Body != null)
{
return (methodDeclaration.Body.OpenBraceToken, methodDeclaration.Body.CloseBraceToken);
}
if (node is PropertyDeclarationSyntax propertyDeclaration && propertyDeclaration.AccessorList != null)
{
return (propertyDeclaration.AccessorList.OpenBraceToken, propertyDeclaration.AccessorList.CloseBraceToken);
}
if (node is AccessorDeclarationSyntax accessorDeclaration && accessorDeclaration.Body != null)
{
return (accessorDeclaration.Body.OpenBraceToken, accessorDeclaration.Body.CloseBraceToken);
}
return node.GetBracePair();
}
private static void RemoveSuppressOperation(
List<SuppressOperation> list,
SyntaxToken startToken,
SyntaxToken endToken)
{
if (startToken.Kind() == SyntaxKind.None || endToken.Kind() == SyntaxKind.None)
{
return;
}
var span = TextSpan.FromBounds(startToken.SpanStart, endToken.Span.End);
list.RemoveOrTransformAll(
(operation, span) =>
{
if (operation.TextSpan.Start >= span.Start && operation.TextSpan.End <= span.End && operation.Option.HasFlag(SuppressOption.NoWrappingIfOnSingleLine))
return null;
return operation;
},
span);
}
private readonly struct CachedOptions : IEquatable<CachedOptions>
{
public readonly bool WrappingPreserveSingleLine;
public readonly bool WrappingKeepStatementsOnSingleLine;
public CachedOptions(AnalyzerConfigOptions? options)
{
WrappingPreserveSingleLine = GetOptionOrDefault(options, CSharpFormattingOptions2.WrappingPreserveSingleLine);
WrappingKeepStatementsOnSingleLine = GetOptionOrDefault(options, CSharpFormattingOptions2.WrappingKeepStatementsOnSingleLine);
}
public static bool operator ==(CachedOptions left, CachedOptions right)
=> left.Equals(right);
public static bool operator !=(CachedOptions left, CachedOptions right)
=> !(left == right);
private static T GetOptionOrDefault<T>(AnalyzerConfigOptions? options, Option2<T> option)
{
if (options is null)
return option.DefaultValue;
return options.GetOption(option);
}
public override bool Equals(object? obj)
=> obj is CachedOptions options && Equals(options);
public bool Equals(CachedOptions other)
{
return WrappingPreserveSingleLine == other.WrappingPreserveSingleLine
&& WrappingKeepStatementsOnSingleLine == other.WrappingKeepStatementsOnSingleLine;
}
public override int GetHashCode()
{
var hashCode = 0;
hashCode = (hashCode << 1) + (WrappingPreserveSingleLine ? 1 : 0);
hashCode = (hashCode << 1) + (WrappingKeepStatementsOnSingleLine ? 1 : 0);
return hashCode;
}
}
}
}
| -1 |
dotnet/roslyn | 55,877 | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute | Part of C# 10 support | davidwengier | 2021-08-25T05:36:27Z | 2021-08-30T20:47:11Z | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | 023d3ca2b5fb429f0b3dcc1efeed39442e232dba | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute. Part of C# 10 support | ./src/Compilers/Core/Portable/Diagnostic/DiagnosticFormatter.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Globalization;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// Formats <see cref="Diagnostic"/> messages.
/// </summary>
public class DiagnosticFormatter
{
/// <summary>
/// Formats the <see cref="Diagnostic"/> message using the optional <see cref="IFormatProvider"/>.
/// </summary>
/// <param name="diagnostic">The diagnostic.</param>
/// <param name="formatter">The formatter; or null to use the default formatter.</param>
/// <returns>The formatted message.</returns>
public virtual string Format(Diagnostic diagnostic, IFormatProvider? formatter = null)
{
if (diagnostic == null)
{
throw new ArgumentNullException(nameof(diagnostic));
}
var culture = formatter as CultureInfo;
switch (diagnostic.Location.Kind)
{
case LocationKind.SourceFile:
case LocationKind.XmlFile:
case LocationKind.ExternalFile:
var span = diagnostic.Location.GetLineSpan();
var mappedSpan = diagnostic.Location.GetMappedLineSpan();
if (!span.IsValid || !mappedSpan.IsValid)
{
goto default;
}
string? path, basePath;
if (mappedSpan.HasMappedPath)
{
path = mappedSpan.Path;
basePath = span.Path;
}
else
{
path = span.Path;
basePath = null;
}
return string.Format(formatter, "{0}{1}: {2}: {3}",
FormatSourcePath(path, basePath, formatter),
FormatSourceSpan(mappedSpan.Span, formatter),
GetMessagePrefix(diagnostic),
diagnostic.GetMessage(culture));
default:
return string.Format(formatter, "{0}: {1}",
GetMessagePrefix(diagnostic),
diagnostic.GetMessage(culture));
}
}
internal virtual string FormatSourcePath(string path, string? basePath, IFormatProvider? formatter)
{
// ignore base path
return path;
}
internal virtual string FormatSourceSpan(LinePositionSpan span, IFormatProvider? formatter)
{
return string.Format("({0},{1})", span.Start.Line + 1, span.Start.Character + 1);
}
internal string GetMessagePrefix(Diagnostic diagnostic)
{
string prefix;
switch (diagnostic.Severity)
{
case DiagnosticSeverity.Hidden:
prefix = "hidden";
break;
case DiagnosticSeverity.Info:
prefix = "info";
break;
case DiagnosticSeverity.Warning:
prefix = "warning";
break;
case DiagnosticSeverity.Error:
prefix = "error";
break;
default:
throw ExceptionUtilities.UnexpectedValue(diagnostic.Severity);
}
return string.Format("{0} {1}", prefix, diagnostic.Id);
}
internal static readonly DiagnosticFormatter Instance = new DiagnosticFormatter();
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Globalization;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// Formats <see cref="Diagnostic"/> messages.
/// </summary>
public class DiagnosticFormatter
{
/// <summary>
/// Formats the <see cref="Diagnostic"/> message using the optional <see cref="IFormatProvider"/>.
/// </summary>
/// <param name="diagnostic">The diagnostic.</param>
/// <param name="formatter">The formatter; or null to use the default formatter.</param>
/// <returns>The formatted message.</returns>
public virtual string Format(Diagnostic diagnostic, IFormatProvider? formatter = null)
{
if (diagnostic == null)
{
throw new ArgumentNullException(nameof(diagnostic));
}
var culture = formatter as CultureInfo;
switch (diagnostic.Location.Kind)
{
case LocationKind.SourceFile:
case LocationKind.XmlFile:
case LocationKind.ExternalFile:
var span = diagnostic.Location.GetLineSpan();
var mappedSpan = diagnostic.Location.GetMappedLineSpan();
if (!span.IsValid || !mappedSpan.IsValid)
{
goto default;
}
string? path, basePath;
if (mappedSpan.HasMappedPath)
{
path = mappedSpan.Path;
basePath = span.Path;
}
else
{
path = span.Path;
basePath = null;
}
return string.Format(formatter, "{0}{1}: {2}: {3}",
FormatSourcePath(path, basePath, formatter),
FormatSourceSpan(mappedSpan.Span, formatter),
GetMessagePrefix(diagnostic),
diagnostic.GetMessage(culture));
default:
return string.Format(formatter, "{0}: {1}",
GetMessagePrefix(diagnostic),
diagnostic.GetMessage(culture));
}
}
internal virtual string FormatSourcePath(string path, string? basePath, IFormatProvider? formatter)
{
// ignore base path
return path;
}
internal virtual string FormatSourceSpan(LinePositionSpan span, IFormatProvider? formatter)
{
return string.Format("({0},{1})", span.Start.Line + 1, span.Start.Character + 1);
}
internal string GetMessagePrefix(Diagnostic diagnostic)
{
string prefix;
switch (diagnostic.Severity)
{
case DiagnosticSeverity.Hidden:
prefix = "hidden";
break;
case DiagnosticSeverity.Info:
prefix = "info";
break;
case DiagnosticSeverity.Warning:
prefix = "warning";
break;
case DiagnosticSeverity.Error:
prefix = "error";
break;
default:
throw ExceptionUtilities.UnexpectedValue(diagnostic.Severity);
}
return string.Format("{0} {1}", prefix, diagnostic.Id);
}
internal static readonly DiagnosticFormatter Instance = new DiagnosticFormatter();
}
}
| -1 |
dotnet/roslyn | 55,877 | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute | Part of C# 10 support | davidwengier | 2021-08-25T05:36:27Z | 2021-08-30T20:47:11Z | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | 023d3ca2b5fb429f0b3dcc1efeed39442e232dba | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute. Part of C# 10 support | ./src/EditorFeatures/TestUtilities/QuickInfo/ToolTipAssert.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Linq;
using System.Text;
using Microsoft.CodeAnalysis.Classification;
using Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.QuickInfo;
using Microsoft.VisualStudio.Core.Imaging;
using Microsoft.VisualStudio.Imaging;
using Microsoft.VisualStudio.Text.Adornments;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Test.Utilities.QuickInfo
{
public static class ToolTipAssert
{
public static void EqualContent(object expected, object actual)
{
try
{
Assert.IsType(expected.GetType(), actual);
if (expected is ContainerElement containerElement)
{
EqualContainerElement(containerElement, (ContainerElement)actual);
return;
}
if (expected is ImageElement imageElement)
{
EqualImageElement(imageElement, (ImageElement)actual);
return;
}
if (expected is ClassifiedTextElement classifiedTextElement)
{
EqualClassifiedTextElement(classifiedTextElement, (ClassifiedTextElement)actual);
return;
}
if (expected is ClassifiedTextRun classifiedTextRun)
{
EqualClassifiedTextRun(classifiedTextRun, (ClassifiedTextRun)actual);
return;
}
throw ExceptionUtilities.Unreachable;
}
catch (Exception)
{
var renderedExpected = ContainerToString(expected);
var renderedActual = ContainerToString(actual);
AssertEx.EqualOrDiff(renderedExpected, renderedActual);
// This is not expected to be hit, but it will be hit if the difference cannot be detected within the diff
throw;
}
}
private static void EqualContainerElement(ContainerElement expected, ContainerElement actual)
{
Assert.Equal(expected.Style, actual.Style);
Assert.Equal(expected.Elements.Count(), actual.Elements.Count());
foreach (var (expectedElement, actualElement) in expected.Elements.Zip(actual.Elements, (expectedElement, actualElement) => (expectedElement, actualElement)))
{
EqualContent(expectedElement, actualElement);
}
}
private static void EqualImageElement(ImageElement expected, ImageElement actual)
{
Assert.Equal(expected.ImageId.Guid, actual.ImageId.Guid);
Assert.Equal(expected.ImageId.Id, actual.ImageId.Id);
Assert.Equal(expected.AutomationName, actual.AutomationName);
}
private static void EqualClassifiedTextElement(ClassifiedTextElement expected, ClassifiedTextElement actual)
{
Assert.Equal(expected.Runs.Count(), actual.Runs.Count());
foreach (var (expectedRun, actualRun) in expected.Runs.Zip(actual.Runs, (expectedRun, actualRun) => (expectedRun, actualRun)))
{
EqualClassifiedTextRun(expectedRun, actualRun);
}
}
private static void EqualClassifiedTextRun(ClassifiedTextRun expected, ClassifiedTextRun actual)
{
Assert.Equal(expected.ClassificationTypeName, actual.ClassificationTypeName);
Assert.Equal(expected.Text, actual.Text);
Assert.Equal(expected.Tooltip, actual.Tooltip);
Assert.Equal(expected.Style, actual.Style);
if (expected.NavigationAction is null)
{
Assert.Equal(expected.NavigationAction, actual.NavigationAction);
}
else if (expected.NavigationAction.Target is QuickInfoHyperLink hyperLink)
{
Assert.Same(expected.NavigationAction, hyperLink.NavigationAction);
var actualTarget = Assert.IsType<QuickInfoHyperLink>(actual.NavigationAction.Target);
Assert.Same(actual.NavigationAction, actualTarget.NavigationAction);
Assert.Equal(hyperLink, actualTarget);
}
else
{
// Cannot validate this navigation action
Assert.NotNull(actual.NavigationAction);
Assert.IsNotType<QuickInfoHyperLink>(actual.NavigationAction.Target);
}
}
private static string ContainerToString(object element)
{
var result = new StringBuilder();
ContainerToString(element, "", result);
return result.ToString();
}
private static void ContainerToString(object element, string indent, StringBuilder result)
{
result.Append($"{indent}New {element.GetType().Name}(");
if (element is ContainerElement container)
{
result.AppendLine();
indent += " ";
result.AppendLine($"{indent}{ContainerStyleToString(container.Style)},");
var elements = container.Elements.ToArray();
for (var i = 0; i < elements.Length; i++)
{
ContainerToString(elements[i], indent, result);
if (i < elements.Length - 1)
result.AppendLine(",");
else
result.Append(")");
}
return;
}
if (element is ImageElement image)
{
var guid = GetKnownImageGuid(image.ImageId.Guid);
var id = GetKnownImageId(image.ImageId.Id);
result.Append($"New {nameof(ImageId)}({guid}, {id}))");
return;
}
if (element is ClassifiedTextElement classifiedTextElement)
{
result.AppendLine();
indent += " ";
var runs = classifiedTextElement.Runs.ToArray();
for (var i = 0; i < runs.Length; i++)
{
ContainerToString(runs[i], indent, result);
if (i < runs.Length - 1)
result.AppendLine(",");
else
result.Append(")");
}
return;
}
if (element is ClassifiedTextRun classifiedTextRun)
{
var classification = GetKnownClassification(classifiedTextRun.ClassificationTypeName);
result.Append($"{classification}, \"{classifiedTextRun.Text.Replace("\"", "\"\"")}\"");
if (classifiedTextRun.NavigationAction is object || !string.IsNullOrEmpty(classifiedTextRun.Tooltip))
{
var tooltip = classifiedTextRun.Tooltip is object ? $"\"{classifiedTextRun.Tooltip.Replace("\"", "\"\"")}\"" : "Nothing";
if (classifiedTextRun.NavigationAction?.Target is QuickInfoHyperLink hyperLink)
{
result.Append($", QuickInfoHyperLink.TestAccessor.CreateNavigationAction(new Uri(\"{hyperLink.Uri}\", UriKind.Absolute))");
}
else
{
result.Append(", navigationAction:=Sub() Return");
}
result.Append($", {tooltip}");
}
if (classifiedTextRun.Style != ClassifiedTextRunStyle.Plain)
{
result.Append($", {TextRunStyleToString(classifiedTextRun.Style)}");
}
result.Append(")");
return;
}
throw ExceptionUtilities.Unreachable;
}
private static string ContainerStyleToString(ContainerElementStyle style)
{
var stringValue = style.ToString();
return string.Join(" Or ", stringValue.Split(new[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries).Select(value => $"{nameof(ContainerElementStyle)}.{value}"));
}
private static string TextRunStyleToString(ClassifiedTextRunStyle style)
{
var stringValue = style.ToString();
return string.Join(" Or ", stringValue.Split(new[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries).Select(value => $"{nameof(ClassifiedTextRunStyle)}.{value}"));
}
private static string GetKnownClassification(string classification)
{
foreach (var field in typeof(ClassificationTypeNames).GetFields())
{
if (!field.IsStatic)
continue;
var value = field.GetValue(null) as string;
if (value == classification)
return $"{nameof(ClassificationTypeNames)}.{field.Name}";
}
return $"\"{classification}\"";
}
private static string GetKnownImageGuid(Guid guid)
{
foreach (var field in typeof(KnownImageIds).GetFields())
{
if (!field.IsStatic)
continue;
var value = field.GetValue(null) as Guid?;
if (value == guid)
return $"{nameof(KnownImageIds)}.{field.Name}";
}
return guid.ToString();
}
private static string GetKnownImageId(int id)
{
foreach (var field in typeof(KnownImageIds).GetFields())
{
if (!field.IsStatic)
continue;
var value = field.GetValue(null) as int?;
if (value == id)
return $"{nameof(KnownImageIds)}.{field.Name}";
}
return id.ToString();
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Linq;
using System.Text;
using Microsoft.CodeAnalysis.Classification;
using Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.QuickInfo;
using Microsoft.VisualStudio.Core.Imaging;
using Microsoft.VisualStudio.Imaging;
using Microsoft.VisualStudio.Text.Adornments;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Test.Utilities.QuickInfo
{
public static class ToolTipAssert
{
public static void EqualContent(object expected, object actual)
{
try
{
Assert.IsType(expected.GetType(), actual);
if (expected is ContainerElement containerElement)
{
EqualContainerElement(containerElement, (ContainerElement)actual);
return;
}
if (expected is ImageElement imageElement)
{
EqualImageElement(imageElement, (ImageElement)actual);
return;
}
if (expected is ClassifiedTextElement classifiedTextElement)
{
EqualClassifiedTextElement(classifiedTextElement, (ClassifiedTextElement)actual);
return;
}
if (expected is ClassifiedTextRun classifiedTextRun)
{
EqualClassifiedTextRun(classifiedTextRun, (ClassifiedTextRun)actual);
return;
}
throw ExceptionUtilities.Unreachable;
}
catch (Exception)
{
var renderedExpected = ContainerToString(expected);
var renderedActual = ContainerToString(actual);
AssertEx.EqualOrDiff(renderedExpected, renderedActual);
// This is not expected to be hit, but it will be hit if the difference cannot be detected within the diff
throw;
}
}
private static void EqualContainerElement(ContainerElement expected, ContainerElement actual)
{
Assert.Equal(expected.Style, actual.Style);
Assert.Equal(expected.Elements.Count(), actual.Elements.Count());
foreach (var (expectedElement, actualElement) in expected.Elements.Zip(actual.Elements, (expectedElement, actualElement) => (expectedElement, actualElement)))
{
EqualContent(expectedElement, actualElement);
}
}
private static void EqualImageElement(ImageElement expected, ImageElement actual)
{
Assert.Equal(expected.ImageId.Guid, actual.ImageId.Guid);
Assert.Equal(expected.ImageId.Id, actual.ImageId.Id);
Assert.Equal(expected.AutomationName, actual.AutomationName);
}
private static void EqualClassifiedTextElement(ClassifiedTextElement expected, ClassifiedTextElement actual)
{
Assert.Equal(expected.Runs.Count(), actual.Runs.Count());
foreach (var (expectedRun, actualRun) in expected.Runs.Zip(actual.Runs, (expectedRun, actualRun) => (expectedRun, actualRun)))
{
EqualClassifiedTextRun(expectedRun, actualRun);
}
}
private static void EqualClassifiedTextRun(ClassifiedTextRun expected, ClassifiedTextRun actual)
{
Assert.Equal(expected.ClassificationTypeName, actual.ClassificationTypeName);
Assert.Equal(expected.Text, actual.Text);
Assert.Equal(expected.Tooltip, actual.Tooltip);
Assert.Equal(expected.Style, actual.Style);
if (expected.NavigationAction is null)
{
Assert.Equal(expected.NavigationAction, actual.NavigationAction);
}
else if (expected.NavigationAction.Target is QuickInfoHyperLink hyperLink)
{
Assert.Same(expected.NavigationAction, hyperLink.NavigationAction);
var actualTarget = Assert.IsType<QuickInfoHyperLink>(actual.NavigationAction.Target);
Assert.Same(actual.NavigationAction, actualTarget.NavigationAction);
Assert.Equal(hyperLink, actualTarget);
}
else
{
// Cannot validate this navigation action
Assert.NotNull(actual.NavigationAction);
Assert.IsNotType<QuickInfoHyperLink>(actual.NavigationAction.Target);
}
}
private static string ContainerToString(object element)
{
var result = new StringBuilder();
ContainerToString(element, "", result);
return result.ToString();
}
private static void ContainerToString(object element, string indent, StringBuilder result)
{
result.Append($"{indent}New {element.GetType().Name}(");
if (element is ContainerElement container)
{
result.AppendLine();
indent += " ";
result.AppendLine($"{indent}{ContainerStyleToString(container.Style)},");
var elements = container.Elements.ToArray();
for (var i = 0; i < elements.Length; i++)
{
ContainerToString(elements[i], indent, result);
if (i < elements.Length - 1)
result.AppendLine(",");
else
result.Append(")");
}
return;
}
if (element is ImageElement image)
{
var guid = GetKnownImageGuid(image.ImageId.Guid);
var id = GetKnownImageId(image.ImageId.Id);
result.Append($"New {nameof(ImageId)}({guid}, {id}))");
return;
}
if (element is ClassifiedTextElement classifiedTextElement)
{
result.AppendLine();
indent += " ";
var runs = classifiedTextElement.Runs.ToArray();
for (var i = 0; i < runs.Length; i++)
{
ContainerToString(runs[i], indent, result);
if (i < runs.Length - 1)
result.AppendLine(",");
else
result.Append(")");
}
return;
}
if (element is ClassifiedTextRun classifiedTextRun)
{
var classification = GetKnownClassification(classifiedTextRun.ClassificationTypeName);
result.Append($"{classification}, \"{classifiedTextRun.Text.Replace("\"", "\"\"")}\"");
if (classifiedTextRun.NavigationAction is object || !string.IsNullOrEmpty(classifiedTextRun.Tooltip))
{
var tooltip = classifiedTextRun.Tooltip is object ? $"\"{classifiedTextRun.Tooltip.Replace("\"", "\"\"")}\"" : "Nothing";
if (classifiedTextRun.NavigationAction?.Target is QuickInfoHyperLink hyperLink)
{
result.Append($", QuickInfoHyperLink.TestAccessor.CreateNavigationAction(new Uri(\"{hyperLink.Uri}\", UriKind.Absolute))");
}
else
{
result.Append(", navigationAction:=Sub() Return");
}
result.Append($", {tooltip}");
}
if (classifiedTextRun.Style != ClassifiedTextRunStyle.Plain)
{
result.Append($", {TextRunStyleToString(classifiedTextRun.Style)}");
}
result.Append(")");
return;
}
throw ExceptionUtilities.Unreachable;
}
private static string ContainerStyleToString(ContainerElementStyle style)
{
var stringValue = style.ToString();
return string.Join(" Or ", stringValue.Split(new[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries).Select(value => $"{nameof(ContainerElementStyle)}.{value}"));
}
private static string TextRunStyleToString(ClassifiedTextRunStyle style)
{
var stringValue = style.ToString();
return string.Join(" Or ", stringValue.Split(new[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries).Select(value => $"{nameof(ClassifiedTextRunStyle)}.{value}"));
}
private static string GetKnownClassification(string classification)
{
foreach (var field in typeof(ClassificationTypeNames).GetFields())
{
if (!field.IsStatic)
continue;
var value = field.GetValue(null) as string;
if (value == classification)
return $"{nameof(ClassificationTypeNames)}.{field.Name}";
}
return $"\"{classification}\"";
}
private static string GetKnownImageGuid(Guid guid)
{
foreach (var field in typeof(KnownImageIds).GetFields())
{
if (!field.IsStatic)
continue;
var value = field.GetValue(null) as Guid?;
if (value == guid)
return $"{nameof(KnownImageIds)}.{field.Name}";
}
return guid.ToString();
}
private static string GetKnownImageId(int id)
{
foreach (var field in typeof(KnownImageIds).GetFields())
{
if (!field.IsStatic)
continue;
var value = field.GetValue(null) as int?;
if (value == id)
return $"{nameof(KnownImageIds)}.{field.Name}";
}
return id.ToString();
}
}
}
| -1 |
dotnet/roslyn | 55,877 | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute | Part of C# 10 support | davidwengier | 2021-08-25T05:36:27Z | 2021-08-30T20:47:11Z | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | 023d3ca2b5fb429f0b3dcc1efeed39442e232dba | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute. Part of C# 10 support | ./src/Compilers/CSharp/Portable/Syntax/CSharpSyntaxNode.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
/// <summary>
/// Represents a non-terminal node in the syntax tree.
/// </summary>
//The fact that this type implements IMessageSerializable
//enables it to be used as an argument to a diagnostic. This allows diagnostics
//to defer the realization of strings. Often diagnostics generated while binding
//in service of a SemanticModel API are never realized. So this
//deferral can result in meaningful savings of strings.
public abstract partial class CSharpSyntaxNode : SyntaxNode, IFormattable
{
internal CSharpSyntaxNode(GreenNode green, SyntaxNode? parent, int position)
: base(green, parent, position)
{
}
/// <summary>
/// Used by structured trivia which has "parent == null", and therefore must know its
/// SyntaxTree explicitly when created.
/// </summary>
internal CSharpSyntaxNode(GreenNode green, int position, SyntaxTree syntaxTree)
: base(green, position, syntaxTree)
{
}
/// <summary>
/// Returns a non-null <see cref="SyntaxTree"/> that owns this node.
/// If this node was created with an explicit non-null <see cref="SyntaxTree"/>, returns that tree.
/// Otherwise, if this node has a non-null parent, then returns the parent's <see cref="SyntaxTree"/>.
/// Otherwise, returns a newly created <see cref="SyntaxTree"/> rooted at this node, preserving this node's reference identity.
/// </summary>
internal new SyntaxTree SyntaxTree
{
get
{
var result = this._syntaxTree ?? ComputeSyntaxTree(this);
Debug.Assert(result != null);
return result;
}
}
private static SyntaxTree ComputeSyntaxTree(CSharpSyntaxNode node)
{
ArrayBuilder<CSharpSyntaxNode>? nodes = null;
SyntaxTree? tree = null;
// Find the nearest parent with a non-null syntax tree
while (true)
{
tree = node._syntaxTree;
if (tree != null)
{
break;
}
var parent = node.Parent;
if (parent == null)
{
// set the tree on the root node atomically
Interlocked.CompareExchange(ref node._syntaxTree, CSharpSyntaxTree.CreateWithoutClone(node), null);
tree = node._syntaxTree;
break;
}
tree = parent._syntaxTree;
if (tree != null)
{
node._syntaxTree = tree;
break;
}
(nodes ?? (nodes = ArrayBuilder<CSharpSyntaxNode>.GetInstance())).Add(node);
node = parent;
}
// Propagate the syntax tree downwards if necessary
if (nodes != null)
{
Debug.Assert(tree != null);
foreach (var n in nodes)
{
var existingTree = n._syntaxTree;
if (existingTree != null)
{
Debug.Assert(existingTree == tree, "how could this node belong to a different tree?");
// yield the race
break;
}
n._syntaxTree = tree;
}
nodes.Free();
}
return tree;
}
public abstract TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor);
public abstract void Accept(CSharpSyntaxVisitor visitor);
/// <summary>
/// The node that contains this node in its Children collection.
/// </summary>
internal new CSharpSyntaxNode? Parent
{
get
{
return (CSharpSyntaxNode?)base.Parent;
}
}
internal new CSharpSyntaxNode? ParentOrStructuredTriviaParent
{
get
{
return (CSharpSyntaxNode?)base.ParentOrStructuredTriviaParent;
}
}
// TODO: may be eventually not needed
internal Syntax.InternalSyntax.CSharpSyntaxNode CsGreen
{
get { return (Syntax.InternalSyntax.CSharpSyntaxNode)this.Green; }
}
/// <summary>
/// Returns the <see cref="SyntaxKind"/> of the node.
/// </summary>
public SyntaxKind Kind()
{
return (SyntaxKind)this.Green.RawKind;
}
/// <summary>
/// The language name that this node is syntax of.
/// </summary>
public override string Language
{
get { return LanguageNames.CSharp; }
}
/// <summary>
/// The list of trivia that appears before this node in the source code.
/// </summary>
public new SyntaxTriviaList GetLeadingTrivia()
{
var firstToken = this.GetFirstToken(includeZeroWidth: true);
return firstToken.LeadingTrivia;
}
/// <summary>
/// The list of trivia that appears after this node in the source code.
/// </summary>
public new SyntaxTriviaList GetTrailingTrivia()
{
var lastToken = this.GetLastToken(includeZeroWidth: true);
return lastToken.TrailingTrivia;
}
#region serialization
/// <summary>
/// Deserialize a syntax node from the byte stream.
/// </summary>
public static SyntaxNode DeserializeFrom(Stream stream, CancellationToken cancellationToken = default)
{
if (stream == null)
{
throw new ArgumentNullException(nameof(stream));
}
if (!stream.CanRead)
{
throw new InvalidOperationException(CodeAnalysisResources.TheStreamCannotBeReadFrom);
}
using var reader = ObjectReader.TryGetReader(stream, leaveOpen: true, cancellationToken);
if (reader == null)
{
throw new ArgumentException(CodeAnalysisResources.Stream_contains_invalid_data, nameof(stream));
}
var root = (Syntax.InternalSyntax.CSharpSyntaxNode)reader.ReadValue();
return root.CreateRed();
}
#endregion
/// <summary>
/// Gets a <see cref="Location"/> for this node.
/// </summary>
public new Location GetLocation()
{
return new SourceLocation(this);
}
/// <summary>
/// Gets a SyntaxReference for this syntax node. SyntaxReferences can be used to
/// regain access to a syntax node without keeping the entire tree and source text in
/// memory.
/// </summary>
internal new SyntaxReference GetReference()
{
return this.SyntaxTree.GetReference(this);
}
/// <summary>
/// Gets a list of all the diagnostics in the sub tree that has this node as its root.
/// This method does not filter diagnostics based on #pragmas and compiler options
/// like nowarn, warnaserror etc.
/// </summary>
public new IEnumerable<Diagnostic> GetDiagnostics()
{
return this.SyntaxTree.GetDiagnostics(this);
}
#region Directives
internal IList<DirectiveTriviaSyntax> GetDirectives(Func<DirectiveTriviaSyntax, bool>? filter = null)
{
return ((SyntaxNodeOrToken)this).GetDirectives<DirectiveTriviaSyntax>(filter);
}
/// <summary>
/// Gets the first directive of the tree rooted by this node.
/// </summary>
public DirectiveTriviaSyntax? GetFirstDirective(Func<DirectiveTriviaSyntax, bool>? predicate = null)
{
foreach (var child in this.ChildNodesAndTokens())
{
if (child.ContainsDirectives)
{
if (child.AsNode(out var node))
{
var d = node.GetFirstDirective(predicate);
if (d != null)
{
return d;
}
}
else
{
var token = child.AsToken();
// directives can only occur in leading trivia
foreach (var tr in token.LeadingTrivia)
{
if (tr.IsDirective)
{
var d = (DirectiveTriviaSyntax)tr.GetStructure()!;
if (predicate == null || predicate(d))
{
return d;
}
}
}
}
}
}
return null;
}
/// <summary>
/// Gets the last directive of the tree rooted by this node.
/// </summary>
public DirectiveTriviaSyntax? GetLastDirective(Func<DirectiveTriviaSyntax, bool>? predicate = null)
{
foreach (var child in this.ChildNodesAndTokens().Reverse())
{
if (child.ContainsDirectives)
{
if (child.AsNode(out var node))
{
var d = node.GetLastDirective(predicate);
if (d != null)
{
return d;
}
}
else
{
var token = child.AsToken();
// directives can only occur in leading trivia
foreach (var tr in token.LeadingTrivia.Reverse())
{
if (tr.IsDirective)
{
var d = (DirectiveTriviaSyntax)tr.GetStructure()!;
if (predicate == null || predicate(d))
{
return d;
}
}
}
}
}
}
return null;
}
#endregion
#region Token Lookup
/// <summary>
/// Gets the first token of the tree rooted by this node.
/// </summary>
/// <param name="includeZeroWidth">True if zero width tokens should be included, false by
/// default.</param>
/// <param name="includeSkipped">True if skipped tokens should be included, false by default.</param>
/// <param name="includeDirectives">True if directives should be included, false by default.</param>
/// <param name="includeDocumentationComments">True if documentation comments should be
/// included, false by default.</param>
/// <returns></returns>
public new SyntaxToken GetFirstToken(bool includeZeroWidth = false, bool includeSkipped = false, bool includeDirectives = false, bool includeDocumentationComments = false)
{
return base.GetFirstToken(includeZeroWidth, includeSkipped, includeDirectives, includeDocumentationComments);
}
/// <summary>
/// Gets the first token of the tree rooted by this node.
/// </summary>
/// <param name="predicate">Only tokens for which this predicate returns true are included. Pass null to include
/// all tokens.</param>
/// <param name="stepInto">Steps into trivia if this is not null. Only trivia for which this delegate returns
/// true are included.</param>
/// <returns></returns>
internal SyntaxToken GetFirstToken(Func<SyntaxToken, bool>? predicate, Func<SyntaxTrivia, bool>? stepInto = null)
{
return SyntaxNavigator.Instance.GetFirstToken(this, predicate, stepInto);
}
/// <summary>
/// Gets the last non-zero-width token of the tree rooted by this node.
/// </summary>
/// <param name="includeZeroWidth">True if zero width tokens should be included, false by
/// default.</param>
/// <param name="includeSkipped">True if skipped tokens should be included, false by default.</param>
/// <param name="includeDirectives">True if directives should be included, false by default.</param>
/// <param name="includeDocumentationComments">True if documentation comments should be
/// included, false by default.</param>
/// <returns></returns>
public new SyntaxToken GetLastToken(bool includeZeroWidth = false, bool includeSkipped = false, bool includeDirectives = false, bool includeDocumentationComments = false)
{
return base.GetLastToken(includeZeroWidth, includeSkipped, includeDirectives, includeDocumentationComments);
}
/// <summary>
/// Finds a token according to the following rules:
/// 1) If position matches the End of the node/s FullSpan and the node is CompilationUnit,
/// then EoF is returned.
///
/// 2) If node.FullSpan.Contains(position) then the token that contains given position is
/// returned.
///
/// 3) Otherwise an ArgumentOutOfRangeException is thrown
/// </summary>
public new SyntaxToken FindToken(int position, bool findInsideTrivia = false)
{
return base.FindToken(position, findInsideTrivia);
}
/// <summary>
/// Finds a token according to the following rules:
/// 1) If position matches the End of the node/s FullSpan and the node is CompilationUnit,
/// then EoF is returned.
///
/// 2) If node.FullSpan.Contains(position) then the token that contains given position is
/// returned.
///
/// 3) Otherwise an ArgumentOutOfRangeException is thrown
/// </summary>
internal SyntaxToken FindTokenIncludingCrefAndNameAttributes(int position)
{
SyntaxToken nonTriviaToken = this.FindToken(position, findInsideTrivia: false);
SyntaxTrivia trivia = GetTriviaFromSyntaxToken(position, nonTriviaToken);
if (!SyntaxFacts.IsDocumentationCommentTrivia(trivia.Kind()))
{
return nonTriviaToken;
}
Debug.Assert(trivia.HasStructure);
SyntaxToken triviaToken = ((CSharpSyntaxNode)trivia.GetStructure()!).FindTokenInternal(position);
// CONSIDER: We might want to use the trivia token anywhere within a doc comment.
// Otherwise, we'll fall back on the enclosing scope outside of name and cref
// attribute values.
CSharpSyntaxNode? curr = (CSharpSyntaxNode?)triviaToken.Parent;
while (curr != null)
{
// Don't return a trivia token unless we're in the scope of a cref or name attribute.
if (curr.Kind() == SyntaxKind.XmlCrefAttribute || curr.Kind() == SyntaxKind.XmlNameAttribute)
{
return LookupPosition.IsInXmlAttributeValue(position, (XmlAttributeSyntax)curr)
? triviaToken
: nonTriviaToken;
}
curr = curr.Parent;
}
return nonTriviaToken;
}
#endregion
#region Trivia Lookup
/// <summary>
/// Finds a descendant trivia of this node at the specified position, where the position is
/// within the span of the node.
/// </summary>
/// <param name="position">The character position of the trivia relative to the beginning of
/// the file.</param>
/// <param name="stepInto">Specifies a function that determines per trivia node, whether to
/// descend into structured trivia of that node.</param>
/// <returns></returns>
public new SyntaxTrivia FindTrivia(int position, Func<SyntaxTrivia, bool> stepInto)
{
return base.FindTrivia(position, stepInto);
}
/// <summary>
/// Finds a descendant trivia of this node whose span includes the supplied position.
/// </summary>
/// <param name="position">The character position of the trivia relative to the beginning of
/// the file.</param>
/// <param name="findInsideTrivia">Whether to search inside structured trivia.</param>
public new SyntaxTrivia FindTrivia(int position, bool findInsideTrivia = false)
{
return base.FindTrivia(position, findInsideTrivia);
}
#endregion
#region SyntaxNode members
/// <summary>
/// Determine if this node is structurally equivalent to another.
/// </summary>
/// <param name="other"></param>
/// <returns></returns>
protected override bool EquivalentToCore(SyntaxNode other)
{
throw ExceptionUtilities.Unreachable;
}
protected override SyntaxTree SyntaxTreeCore
{
get
{
return this.SyntaxTree;
}
}
protected internal override SyntaxNode ReplaceCore<TNode>(
IEnumerable<TNode>? nodes = null,
Func<TNode, TNode, SyntaxNode>? computeReplacementNode = null,
IEnumerable<SyntaxToken>? tokens = null,
Func<SyntaxToken, SyntaxToken, SyntaxToken>? computeReplacementToken = null,
IEnumerable<SyntaxTrivia>? trivia = null,
Func<SyntaxTrivia, SyntaxTrivia, SyntaxTrivia>? computeReplacementTrivia = null)
{
return SyntaxReplacer.Replace(this, nodes, computeReplacementNode, tokens, computeReplacementToken, trivia, computeReplacementTrivia).AsRootOfNewTreeWithOptionsFrom(this.SyntaxTree);
}
protected internal override SyntaxNode ReplaceNodeInListCore(SyntaxNode originalNode, IEnumerable<SyntaxNode> replacementNodes)
{
return SyntaxReplacer.ReplaceNodeInList(this, originalNode, replacementNodes).AsRootOfNewTreeWithOptionsFrom(this.SyntaxTree);
}
protected internal override SyntaxNode InsertNodesInListCore(SyntaxNode nodeInList, IEnumerable<SyntaxNode> nodesToInsert, bool insertBefore)
{
return SyntaxReplacer.InsertNodeInList(this, nodeInList, nodesToInsert, insertBefore).AsRootOfNewTreeWithOptionsFrom(this.SyntaxTree);
}
protected internal override SyntaxNode ReplaceTokenInListCore(SyntaxToken originalToken, IEnumerable<SyntaxToken> newTokens)
{
return SyntaxReplacer.ReplaceTokenInList(this, originalToken, newTokens).AsRootOfNewTreeWithOptionsFrom(this.SyntaxTree);
}
protected internal override SyntaxNode InsertTokensInListCore(SyntaxToken originalToken, IEnumerable<SyntaxToken> newTokens, bool insertBefore)
{
return SyntaxReplacer.InsertTokenInList(this, originalToken, newTokens, insertBefore).AsRootOfNewTreeWithOptionsFrom(this.SyntaxTree);
}
protected internal override SyntaxNode ReplaceTriviaInListCore(SyntaxTrivia originalTrivia, IEnumerable<SyntaxTrivia> newTrivia)
{
return SyntaxReplacer.ReplaceTriviaInList(this, originalTrivia, newTrivia).AsRootOfNewTreeWithOptionsFrom(this.SyntaxTree);
}
protected internal override SyntaxNode InsertTriviaInListCore(SyntaxTrivia originalTrivia, IEnumerable<SyntaxTrivia> newTrivia, bool insertBefore)
{
return SyntaxReplacer.InsertTriviaInList(this, originalTrivia, newTrivia, insertBefore).AsRootOfNewTreeWithOptionsFrom(this.SyntaxTree);
}
protected internal override SyntaxNode? RemoveNodesCore(IEnumerable<SyntaxNode> nodes, SyntaxRemoveOptions options)
{
return SyntaxNodeRemover.RemoveNodes(this, nodes.Cast<CSharpSyntaxNode>(), options).AsRootOfNewTreeWithOptionsFrom(this.SyntaxTree);
}
protected internal override SyntaxNode NormalizeWhitespaceCore(string indentation, string eol, bool elasticTrivia)
{
return SyntaxNormalizer.Normalize(this, indentation, eol, elasticTrivia).AsRootOfNewTreeWithOptionsFrom(this.SyntaxTree);
}
protected override bool IsEquivalentToCore(SyntaxNode node, bool topLevel = false)
{
return SyntaxFactory.AreEquivalent(this, (CSharpSyntaxNode)node, topLevel);
}
internal override bool ShouldCreateWeakList()
{
if (this.Kind() == SyntaxKind.Block)
{
var parent = this.Parent;
if (parent is MemberDeclarationSyntax || parent is AccessorDeclarationSyntax)
{
return true;
}
}
return false;
}
#endregion
string IFormattable.ToString(string? format, IFormatProvider? formatProvider)
{
return ToString();
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
/// <summary>
/// Represents a non-terminal node in the syntax tree.
/// </summary>
//The fact that this type implements IMessageSerializable
//enables it to be used as an argument to a diagnostic. This allows diagnostics
//to defer the realization of strings. Often diagnostics generated while binding
//in service of a SemanticModel API are never realized. So this
//deferral can result in meaningful savings of strings.
public abstract partial class CSharpSyntaxNode : SyntaxNode, IFormattable
{
internal CSharpSyntaxNode(GreenNode green, SyntaxNode? parent, int position)
: base(green, parent, position)
{
}
/// <summary>
/// Used by structured trivia which has "parent == null", and therefore must know its
/// SyntaxTree explicitly when created.
/// </summary>
internal CSharpSyntaxNode(GreenNode green, int position, SyntaxTree syntaxTree)
: base(green, position, syntaxTree)
{
}
/// <summary>
/// Returns a non-null <see cref="SyntaxTree"/> that owns this node.
/// If this node was created with an explicit non-null <see cref="SyntaxTree"/>, returns that tree.
/// Otherwise, if this node has a non-null parent, then returns the parent's <see cref="SyntaxTree"/>.
/// Otherwise, returns a newly created <see cref="SyntaxTree"/> rooted at this node, preserving this node's reference identity.
/// </summary>
internal new SyntaxTree SyntaxTree
{
get
{
var result = this._syntaxTree ?? ComputeSyntaxTree(this);
Debug.Assert(result != null);
return result;
}
}
private static SyntaxTree ComputeSyntaxTree(CSharpSyntaxNode node)
{
ArrayBuilder<CSharpSyntaxNode>? nodes = null;
SyntaxTree? tree = null;
// Find the nearest parent with a non-null syntax tree
while (true)
{
tree = node._syntaxTree;
if (tree != null)
{
break;
}
var parent = node.Parent;
if (parent == null)
{
// set the tree on the root node atomically
Interlocked.CompareExchange(ref node._syntaxTree, CSharpSyntaxTree.CreateWithoutClone(node), null);
tree = node._syntaxTree;
break;
}
tree = parent._syntaxTree;
if (tree != null)
{
node._syntaxTree = tree;
break;
}
(nodes ?? (nodes = ArrayBuilder<CSharpSyntaxNode>.GetInstance())).Add(node);
node = parent;
}
// Propagate the syntax tree downwards if necessary
if (nodes != null)
{
Debug.Assert(tree != null);
foreach (var n in nodes)
{
var existingTree = n._syntaxTree;
if (existingTree != null)
{
Debug.Assert(existingTree == tree, "how could this node belong to a different tree?");
// yield the race
break;
}
n._syntaxTree = tree;
}
nodes.Free();
}
return tree;
}
public abstract TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor);
public abstract void Accept(CSharpSyntaxVisitor visitor);
/// <summary>
/// The node that contains this node in its Children collection.
/// </summary>
internal new CSharpSyntaxNode? Parent
{
get
{
return (CSharpSyntaxNode?)base.Parent;
}
}
internal new CSharpSyntaxNode? ParentOrStructuredTriviaParent
{
get
{
return (CSharpSyntaxNode?)base.ParentOrStructuredTriviaParent;
}
}
// TODO: may be eventually not needed
internal Syntax.InternalSyntax.CSharpSyntaxNode CsGreen
{
get { return (Syntax.InternalSyntax.CSharpSyntaxNode)this.Green; }
}
/// <summary>
/// Returns the <see cref="SyntaxKind"/> of the node.
/// </summary>
public SyntaxKind Kind()
{
return (SyntaxKind)this.Green.RawKind;
}
/// <summary>
/// The language name that this node is syntax of.
/// </summary>
public override string Language
{
get { return LanguageNames.CSharp; }
}
/// <summary>
/// The list of trivia that appears before this node in the source code.
/// </summary>
public new SyntaxTriviaList GetLeadingTrivia()
{
var firstToken = this.GetFirstToken(includeZeroWidth: true);
return firstToken.LeadingTrivia;
}
/// <summary>
/// The list of trivia that appears after this node in the source code.
/// </summary>
public new SyntaxTriviaList GetTrailingTrivia()
{
var lastToken = this.GetLastToken(includeZeroWidth: true);
return lastToken.TrailingTrivia;
}
#region serialization
/// <summary>
/// Deserialize a syntax node from the byte stream.
/// </summary>
public static SyntaxNode DeserializeFrom(Stream stream, CancellationToken cancellationToken = default)
{
if (stream == null)
{
throw new ArgumentNullException(nameof(stream));
}
if (!stream.CanRead)
{
throw new InvalidOperationException(CodeAnalysisResources.TheStreamCannotBeReadFrom);
}
using var reader = ObjectReader.TryGetReader(stream, leaveOpen: true, cancellationToken);
if (reader == null)
{
throw new ArgumentException(CodeAnalysisResources.Stream_contains_invalid_data, nameof(stream));
}
var root = (Syntax.InternalSyntax.CSharpSyntaxNode)reader.ReadValue();
return root.CreateRed();
}
#endregion
/// <summary>
/// Gets a <see cref="Location"/> for this node.
/// </summary>
public new Location GetLocation()
{
return new SourceLocation(this);
}
/// <summary>
/// Gets a SyntaxReference for this syntax node. SyntaxReferences can be used to
/// regain access to a syntax node without keeping the entire tree and source text in
/// memory.
/// </summary>
internal new SyntaxReference GetReference()
{
return this.SyntaxTree.GetReference(this);
}
/// <summary>
/// Gets a list of all the diagnostics in the sub tree that has this node as its root.
/// This method does not filter diagnostics based on #pragmas and compiler options
/// like nowarn, warnaserror etc.
/// </summary>
public new IEnumerable<Diagnostic> GetDiagnostics()
{
return this.SyntaxTree.GetDiagnostics(this);
}
#region Directives
internal IList<DirectiveTriviaSyntax> GetDirectives(Func<DirectiveTriviaSyntax, bool>? filter = null)
{
return ((SyntaxNodeOrToken)this).GetDirectives<DirectiveTriviaSyntax>(filter);
}
/// <summary>
/// Gets the first directive of the tree rooted by this node.
/// </summary>
public DirectiveTriviaSyntax? GetFirstDirective(Func<DirectiveTriviaSyntax, bool>? predicate = null)
{
foreach (var child in this.ChildNodesAndTokens())
{
if (child.ContainsDirectives)
{
if (child.AsNode(out var node))
{
var d = node.GetFirstDirective(predicate);
if (d != null)
{
return d;
}
}
else
{
var token = child.AsToken();
// directives can only occur in leading trivia
foreach (var tr in token.LeadingTrivia)
{
if (tr.IsDirective)
{
var d = (DirectiveTriviaSyntax)tr.GetStructure()!;
if (predicate == null || predicate(d))
{
return d;
}
}
}
}
}
}
return null;
}
/// <summary>
/// Gets the last directive of the tree rooted by this node.
/// </summary>
public DirectiveTriviaSyntax? GetLastDirective(Func<DirectiveTriviaSyntax, bool>? predicate = null)
{
foreach (var child in this.ChildNodesAndTokens().Reverse())
{
if (child.ContainsDirectives)
{
if (child.AsNode(out var node))
{
var d = node.GetLastDirective(predicate);
if (d != null)
{
return d;
}
}
else
{
var token = child.AsToken();
// directives can only occur in leading trivia
foreach (var tr in token.LeadingTrivia.Reverse())
{
if (tr.IsDirective)
{
var d = (DirectiveTriviaSyntax)tr.GetStructure()!;
if (predicate == null || predicate(d))
{
return d;
}
}
}
}
}
}
return null;
}
#endregion
#region Token Lookup
/// <summary>
/// Gets the first token of the tree rooted by this node.
/// </summary>
/// <param name="includeZeroWidth">True if zero width tokens should be included, false by
/// default.</param>
/// <param name="includeSkipped">True if skipped tokens should be included, false by default.</param>
/// <param name="includeDirectives">True if directives should be included, false by default.</param>
/// <param name="includeDocumentationComments">True if documentation comments should be
/// included, false by default.</param>
/// <returns></returns>
public new SyntaxToken GetFirstToken(bool includeZeroWidth = false, bool includeSkipped = false, bool includeDirectives = false, bool includeDocumentationComments = false)
{
return base.GetFirstToken(includeZeroWidth, includeSkipped, includeDirectives, includeDocumentationComments);
}
/// <summary>
/// Gets the first token of the tree rooted by this node.
/// </summary>
/// <param name="predicate">Only tokens for which this predicate returns true are included. Pass null to include
/// all tokens.</param>
/// <param name="stepInto">Steps into trivia if this is not null. Only trivia for which this delegate returns
/// true are included.</param>
/// <returns></returns>
internal SyntaxToken GetFirstToken(Func<SyntaxToken, bool>? predicate, Func<SyntaxTrivia, bool>? stepInto = null)
{
return SyntaxNavigator.Instance.GetFirstToken(this, predicate, stepInto);
}
/// <summary>
/// Gets the last non-zero-width token of the tree rooted by this node.
/// </summary>
/// <param name="includeZeroWidth">True if zero width tokens should be included, false by
/// default.</param>
/// <param name="includeSkipped">True if skipped tokens should be included, false by default.</param>
/// <param name="includeDirectives">True if directives should be included, false by default.</param>
/// <param name="includeDocumentationComments">True if documentation comments should be
/// included, false by default.</param>
/// <returns></returns>
public new SyntaxToken GetLastToken(bool includeZeroWidth = false, bool includeSkipped = false, bool includeDirectives = false, bool includeDocumentationComments = false)
{
return base.GetLastToken(includeZeroWidth, includeSkipped, includeDirectives, includeDocumentationComments);
}
/// <summary>
/// Finds a token according to the following rules:
/// 1) If position matches the End of the node/s FullSpan and the node is CompilationUnit,
/// then EoF is returned.
///
/// 2) If node.FullSpan.Contains(position) then the token that contains given position is
/// returned.
///
/// 3) Otherwise an ArgumentOutOfRangeException is thrown
/// </summary>
public new SyntaxToken FindToken(int position, bool findInsideTrivia = false)
{
return base.FindToken(position, findInsideTrivia);
}
/// <summary>
/// Finds a token according to the following rules:
/// 1) If position matches the End of the node/s FullSpan and the node is CompilationUnit,
/// then EoF is returned.
///
/// 2) If node.FullSpan.Contains(position) then the token that contains given position is
/// returned.
///
/// 3) Otherwise an ArgumentOutOfRangeException is thrown
/// </summary>
internal SyntaxToken FindTokenIncludingCrefAndNameAttributes(int position)
{
SyntaxToken nonTriviaToken = this.FindToken(position, findInsideTrivia: false);
SyntaxTrivia trivia = GetTriviaFromSyntaxToken(position, nonTriviaToken);
if (!SyntaxFacts.IsDocumentationCommentTrivia(trivia.Kind()))
{
return nonTriviaToken;
}
Debug.Assert(trivia.HasStructure);
SyntaxToken triviaToken = ((CSharpSyntaxNode)trivia.GetStructure()!).FindTokenInternal(position);
// CONSIDER: We might want to use the trivia token anywhere within a doc comment.
// Otherwise, we'll fall back on the enclosing scope outside of name and cref
// attribute values.
CSharpSyntaxNode? curr = (CSharpSyntaxNode?)triviaToken.Parent;
while (curr != null)
{
// Don't return a trivia token unless we're in the scope of a cref or name attribute.
if (curr.Kind() == SyntaxKind.XmlCrefAttribute || curr.Kind() == SyntaxKind.XmlNameAttribute)
{
return LookupPosition.IsInXmlAttributeValue(position, (XmlAttributeSyntax)curr)
? triviaToken
: nonTriviaToken;
}
curr = curr.Parent;
}
return nonTriviaToken;
}
#endregion
#region Trivia Lookup
/// <summary>
/// Finds a descendant trivia of this node at the specified position, where the position is
/// within the span of the node.
/// </summary>
/// <param name="position">The character position of the trivia relative to the beginning of
/// the file.</param>
/// <param name="stepInto">Specifies a function that determines per trivia node, whether to
/// descend into structured trivia of that node.</param>
/// <returns></returns>
public new SyntaxTrivia FindTrivia(int position, Func<SyntaxTrivia, bool> stepInto)
{
return base.FindTrivia(position, stepInto);
}
/// <summary>
/// Finds a descendant trivia of this node whose span includes the supplied position.
/// </summary>
/// <param name="position">The character position of the trivia relative to the beginning of
/// the file.</param>
/// <param name="findInsideTrivia">Whether to search inside structured trivia.</param>
public new SyntaxTrivia FindTrivia(int position, bool findInsideTrivia = false)
{
return base.FindTrivia(position, findInsideTrivia);
}
#endregion
#region SyntaxNode members
/// <summary>
/// Determine if this node is structurally equivalent to another.
/// </summary>
/// <param name="other"></param>
/// <returns></returns>
protected override bool EquivalentToCore(SyntaxNode other)
{
throw ExceptionUtilities.Unreachable;
}
protected override SyntaxTree SyntaxTreeCore
{
get
{
return this.SyntaxTree;
}
}
protected internal override SyntaxNode ReplaceCore<TNode>(
IEnumerable<TNode>? nodes = null,
Func<TNode, TNode, SyntaxNode>? computeReplacementNode = null,
IEnumerable<SyntaxToken>? tokens = null,
Func<SyntaxToken, SyntaxToken, SyntaxToken>? computeReplacementToken = null,
IEnumerable<SyntaxTrivia>? trivia = null,
Func<SyntaxTrivia, SyntaxTrivia, SyntaxTrivia>? computeReplacementTrivia = null)
{
return SyntaxReplacer.Replace(this, nodes, computeReplacementNode, tokens, computeReplacementToken, trivia, computeReplacementTrivia).AsRootOfNewTreeWithOptionsFrom(this.SyntaxTree);
}
protected internal override SyntaxNode ReplaceNodeInListCore(SyntaxNode originalNode, IEnumerable<SyntaxNode> replacementNodes)
{
return SyntaxReplacer.ReplaceNodeInList(this, originalNode, replacementNodes).AsRootOfNewTreeWithOptionsFrom(this.SyntaxTree);
}
protected internal override SyntaxNode InsertNodesInListCore(SyntaxNode nodeInList, IEnumerable<SyntaxNode> nodesToInsert, bool insertBefore)
{
return SyntaxReplacer.InsertNodeInList(this, nodeInList, nodesToInsert, insertBefore).AsRootOfNewTreeWithOptionsFrom(this.SyntaxTree);
}
protected internal override SyntaxNode ReplaceTokenInListCore(SyntaxToken originalToken, IEnumerable<SyntaxToken> newTokens)
{
return SyntaxReplacer.ReplaceTokenInList(this, originalToken, newTokens).AsRootOfNewTreeWithOptionsFrom(this.SyntaxTree);
}
protected internal override SyntaxNode InsertTokensInListCore(SyntaxToken originalToken, IEnumerable<SyntaxToken> newTokens, bool insertBefore)
{
return SyntaxReplacer.InsertTokenInList(this, originalToken, newTokens, insertBefore).AsRootOfNewTreeWithOptionsFrom(this.SyntaxTree);
}
protected internal override SyntaxNode ReplaceTriviaInListCore(SyntaxTrivia originalTrivia, IEnumerable<SyntaxTrivia> newTrivia)
{
return SyntaxReplacer.ReplaceTriviaInList(this, originalTrivia, newTrivia).AsRootOfNewTreeWithOptionsFrom(this.SyntaxTree);
}
protected internal override SyntaxNode InsertTriviaInListCore(SyntaxTrivia originalTrivia, IEnumerable<SyntaxTrivia> newTrivia, bool insertBefore)
{
return SyntaxReplacer.InsertTriviaInList(this, originalTrivia, newTrivia, insertBefore).AsRootOfNewTreeWithOptionsFrom(this.SyntaxTree);
}
protected internal override SyntaxNode? RemoveNodesCore(IEnumerable<SyntaxNode> nodes, SyntaxRemoveOptions options)
{
return SyntaxNodeRemover.RemoveNodes(this, nodes.Cast<CSharpSyntaxNode>(), options).AsRootOfNewTreeWithOptionsFrom(this.SyntaxTree);
}
protected internal override SyntaxNode NormalizeWhitespaceCore(string indentation, string eol, bool elasticTrivia)
{
return SyntaxNormalizer.Normalize(this, indentation, eol, elasticTrivia).AsRootOfNewTreeWithOptionsFrom(this.SyntaxTree);
}
protected override bool IsEquivalentToCore(SyntaxNode node, bool topLevel = false)
{
return SyntaxFactory.AreEquivalent(this, (CSharpSyntaxNode)node, topLevel);
}
internal override bool ShouldCreateWeakList()
{
if (this.Kind() == SyntaxKind.Block)
{
var parent = this.Parent;
if (parent is MemberDeclarationSyntax || parent is AccessorDeclarationSyntax)
{
return true;
}
}
return false;
}
#endregion
string IFormattable.ToString(string? format, IFormatProvider? formatProvider)
{
return ToString();
}
}
}
| -1 |
dotnet/roslyn | 55,877 | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute | Part of C# 10 support | davidwengier | 2021-08-25T05:36:27Z | 2021-08-30T20:47:11Z | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | 023d3ca2b5fb429f0b3dcc1efeed39442e232dba | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute. Part of C# 10 support | ./eng/common/sdl/packages.config | <?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Microsoft.Guardian.Cli" version="0.53.3"/>
</packages>
| <?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Microsoft.Guardian.Cli" version="0.53.3"/>
</packages>
| -1 |
dotnet/roslyn | 55,877 | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute | Part of C# 10 support | davidwengier | 2021-08-25T05:36:27Z | 2021-08-30T20:47:11Z | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | 023d3ca2b5fb429f0b3dcc1efeed39442e232dba | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute. Part of C# 10 support | ./src/Compilers/VisualBasic/Portable/Syntax/VisualBasicSyntaxNode_TreeTraversalHelpers.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
'-----------------------------------------------------------------------------------------------------------
' Contains syntax tree traversal methods.
'-----------------------------------------------------------------------------------------------------------
Namespace Microsoft.CodeAnalysis.VisualBasic
Partial Public Class VisualBasicSyntaxNode
''' <summary>
''' Finds a token according to the following rules:
''' 1) If position matches the End of the node's Span, then its last token is returned.
'''
''' 2) If node.FullSpan.Contains(position) then the token that contains given position is returned.
'''
''' 3) Otherwise an IndexOutOfRange is thrown
''' </summary>
Public Shadows Function FindToken(position As Integer, Optional findInsideTrivia As Boolean = False) As SyntaxToken
Return MyBase.FindToken(position, findInsideTrivia)
End Function
Public Shadows Function FindTrivia(textPosition As Integer, Optional findInsideTrivia As Boolean = False) As SyntaxTrivia
Return MyBase.FindTrivia(textPosition, findInsideTrivia)
End Function
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
'-----------------------------------------------------------------------------------------------------------
' Contains syntax tree traversal methods.
'-----------------------------------------------------------------------------------------------------------
Namespace Microsoft.CodeAnalysis.VisualBasic
Partial Public Class VisualBasicSyntaxNode
''' <summary>
''' Finds a token according to the following rules:
''' 1) If position matches the End of the node's Span, then its last token is returned.
'''
''' 2) If node.FullSpan.Contains(position) then the token that contains given position is returned.
'''
''' 3) Otherwise an IndexOutOfRange is thrown
''' </summary>
Public Shadows Function FindToken(position As Integer, Optional findInsideTrivia As Boolean = False) As SyntaxToken
Return MyBase.FindToken(position, findInsideTrivia)
End Function
Public Shadows Function FindTrivia(textPosition As Integer, Optional findInsideTrivia As Boolean = False) As SyntaxTrivia
Return MyBase.FindTrivia(textPosition, findInsideTrivia)
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,877 | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute | Part of C# 10 support | davidwengier | 2021-08-25T05:36:27Z | 2021-08-30T20:47:11Z | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | 023d3ca2b5fb429f0b3dcc1efeed39442e232dba | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute. Part of C# 10 support | ./src/Features/LanguageServer/ProtocolUnitTests/SemanticTokens/SemanticTokensEditsTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable enable
using System.Linq;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.LanguageServer.Handler.SemanticTokens;
using Roslyn.Test.Utilities;
using Xunit;
using LSP = Microsoft.VisualStudio.LanguageServer.Protocol;
namespace Microsoft.CodeAnalysis.LanguageServer.UnitTests.SemanticTokens
{
public class SemanticTokensEditsTests : AbstractSemanticTokensTests
{
/*
* Markup for basic test case:
* // Comment
* static class C { }
*/
private static readonly string s_standardCase = @"{|caret:|}// Comment
static class C { }";
/*
* Markup for single line test case:
* // Comment
*/
private static readonly string s_singleLineCase = @"{|caret:|}// Comment";
[Fact]
public async Task TestInsertingNewLineInMiddleOfFile()
{
var updatedText = @"// Comment
static class C { }";
using var testLspServer = CreateTestLspServer(s_standardCase, out var locations);
var caretLocation = locations["caret"].First();
await RunGetSemanticTokensAsync(testLspServer, caretLocation);
UpdateDocumentText(updatedText, testLspServer.TestWorkspace);
var results = await RunGetSemanticTokensEditsAsync(testLspServer, caretLocation, previousResultId: "1");
var expectedEdit = new LSP.SemanticTokensEdit { Start = 5, DeleteCount = 1, Data = new int[] { 2 } };
Assert.Equal(expectedEdit, ((LSP.SemanticTokensDelta)results).Edits.First());
Assert.Equal("2", ((LSP.SemanticTokensDelta)results).ResultId);
}
/// <summary>
/// Tests making a deletion from the end of the file.
/// </summary>
[Fact]
public async Task TestGetSemanticTokensEdits_EndDeletionAsync()
{
var updatedText =
@"// Comment";
using var testLspServer = CreateTestLspServer(s_standardCase, out var locations);
var caretLocation = locations["caret"].First();
await RunGetSemanticTokensAsync(testLspServer, caretLocation);
UpdateDocumentText(updatedText, testLspServer.TestWorkspace);
var results = await RunGetSemanticTokensEditsAsync(testLspServer, caretLocation, previousResultId: "1");
var expectedEdit = new LSP.SemanticTokensEdit { Start = 5, DeleteCount = 25, Data = System.Array.Empty<int>() };
Assert.Equal(expectedEdit, ((LSP.SemanticTokensDelta)results).Edits.First());
Assert.Equal("2", ((LSP.SemanticTokensDelta)results).ResultId);
}
/// <summary>
/// Tests making an insertion at the end of the file.
/// </summary>
[Fact]
public async Task TestGetSemanticTokensEdits_EndInsertionAsync()
{
var updatedText =
@"// Comment
static class C { }
// Comment";
using var testLspServer = CreateTestLspServer(s_standardCase, out var locations);
var caretLocation = locations["caret"].First();
await RunGetSemanticTokensAsync(testLspServer, caretLocation);
UpdateDocumentText(updatedText, testLspServer.TestWorkspace);
var results = await RunGetSemanticTokensEditsAsync(testLspServer, caretLocation, previousResultId: "1");
var expectedEdit = new LSP.SemanticTokensEdit
{
Start = 30,
DeleteCount = 0,
Data = new int[] { 1, 0, 10, SemanticTokensCache.TokenTypeToIndex[LSP.SemanticTokenTypes.Comment], 0 }
};
Assert.Equal(expectedEdit, ((LSP.SemanticTokensDelta)results).Edits.First());
Assert.Equal("2", ((LSP.SemanticTokensDelta)results).ResultId);
}
/// <summary>
/// Tests to make sure we return a minimal number of edits.
/// </summary>
[Fact]
public async Task TestGetSemanticTokensEdits_ReturnMinimalEdits()
{
var updatedText =
@"class
// Comment";
using var testLspServer = CreateTestLspServer(s_singleLineCase, out var locations);
var caretLocation = locations["caret"].First();
await RunGetSemanticTokensAsync(testLspServer, caretLocation);
// Edit text
UpdateDocumentText(updatedText, testLspServer.TestWorkspace);
var results = await RunGetSemanticTokensEditsAsync(testLspServer, caretLocation, previousResultId: "1");
// 1. Updates length of token (10 to 5) and updates token type (comment to keyword)
// 2. Creates new token for '// Comment'
var expectedEdit = new LSP.SemanticTokensEdit
{
Start = 2,
DeleteCount = 0,
Data = new int[]
{
// 'class'
/* 0, 0, */ 5, SemanticTokensCache.TokenTypeToIndex[LSP.SemanticTokenTypes.Keyword], 0,
// '// Comment'
1, 0, /* 10, SemanticTokensCache.TokenTypeToIndex[LSP.SemanticTokenTypes.Comment], 0 */
}
};
Assert.Equal(expectedEdit, ((LSP.SemanticTokensDelta)results).Edits?[0]);
Assert.Equal("2", ((LSP.SemanticTokensDelta)results).ResultId);
}
/// <summary>
/// Tests to make sure that if we don't have a matching semantic token set for the document in the cache,
/// we return the full set of semantic tokens.
/// </summary>
[Fact]
public async Task TestGetSemanticTokensEditsNoCacheAsync()
{
var updatedText =
@"// Comment
static class C { }";
using var testLspServer = CreateTestLspServer(s_standardCase, out var locations);
var caretLocation = locations["caret"].First();
await RunGetSemanticTokensAsync(testLspServer, caretLocation);
UpdateDocumentText(updatedText, testLspServer.TestWorkspace);
var results = await RunGetSemanticTokensEditsAsync(testLspServer, caretLocation, previousResultId: "10");
// Make sure we're returned SemanticTokens instead of SemanticTokensEdits.
Assert.True(results.Value is LSP.SemanticTokens);
// The returned result should now be in the cache and should be of the LSP.SemanticTokensDelta type.
var cachedResults = await RunGetSemanticTokensEditsAsync(
testLspServer, caretLocation, previousResultId: ((LSP.SemanticTokens)results).ResultId!);
Assert.True(cachedResults.Value is LSP.SemanticTokensDelta);
}
[Fact]
public async Task TestConvertSemanticTokenEditsIntoSemanticTokens_InsertNewlineInMiddleOfFile()
{
var updatedText =
@"// Comment
static class C { }";
using var testLspServer = CreateTestLspServer(s_standardCase, out var locations);
var caretLocation = locations["caret"].First();
var originalTokens = await RunGetSemanticTokensAsync(testLspServer, caretLocation);
UpdateDocumentText(updatedText, testLspServer.TestWorkspace);
// Edits to tokens conversion
var edits = await RunGetSemanticTokensEditsAsync(testLspServer, caretLocation, previousResultId: "1");
var editsToTokens = ApplySemanticTokensEdits(originalTokens.Data, (LSP.SemanticTokensDelta)edits);
// Raw tokens
var rawTokens = await RunGetSemanticTokensAsync(testLspServer, locations["caret"].First());
Assert.True(Enumerable.SequenceEqual(rawTokens.Data, editsToTokens));
}
[Fact]
public async Task TestConvertSemanticTokenEditsIntoSemanticTokens_ReplacementEdit()
{
var updatedText =
@"// Comment
internal struct S { }";
using var testLspServer = CreateTestLspServer(s_standardCase, out var locations);
var caretLocation = locations["caret"].First();
var originalTokens = await RunGetSemanticTokensAsync(testLspServer, caretLocation);
UpdateDocumentText(updatedText, testLspServer.TestWorkspace);
// Edits to tokens conversion
var edits = await RunGetSemanticTokensEditsAsync(testLspServer, caretLocation, previousResultId: "1");
var editsToTokens = ApplySemanticTokensEdits(originalTokens.Data, (LSP.SemanticTokensDelta)edits);
// Raw tokens
var rawTokens = await RunGetSemanticTokensAsync(testLspServer, locations["caret"].First());
Assert.True(Enumerable.SequenceEqual(rawTokens.Data, editsToTokens));
}
[Fact]
public async Task TestConvertSemanticTokenEditsIntoSemanticTokens_ManyEdits()
{
var updatedText =
@"
// Comment
class C
{
static void M(int x)
{
var v = 1;
}
}";
using var testLspServer = CreateTestLspServer(s_standardCase, out var locations);
var caretLocation = locations["caret"].First();
var originalTokens = await RunGetSemanticTokensAsync(testLspServer, caretLocation);
UpdateDocumentText(updatedText, testLspServer.TestWorkspace);
// Edits to tokens conversion
var edits = await RunGetSemanticTokensEditsAsync(testLspServer, caretLocation, previousResultId: "1");
var editsToTokens = ApplySemanticTokensEdits(originalTokens.Data, (LSP.SemanticTokensDelta)edits);
// Raw tokens
var rawTokens = await RunGetSemanticTokensAsync(testLspServer, locations["caret"].First());
Assert.True(Enumerable.SequenceEqual(rawTokens.Data, editsToTokens));
}
[Fact, WorkItem(54671, "https://github.com/dotnet/roslyn/issues/54671")]
public async Task TestConvertSemanticTokenEditsIntoSemanticTokens_FragmentedTokens()
{
var originalText =
@"fo {|caret:|}r (int i = 0;/*c*/; i++)
{
}";
var updatedText =
@"for (int i = 0;/*c*/; i++)
{
}";
using var testLspServer = CreateTestLspServer(originalText, out var locations);
var caretLocation = locations["caret"].First();
var originalTokens = await RunGetSemanticTokensAsync(testLspServer, caretLocation);
UpdateDocumentText(updatedText, testLspServer.TestWorkspace);
// Edits to tokens conversion
var edits = await RunGetSemanticTokensEditsAsync(testLspServer, caretLocation, previousResultId: "1");
var editsToTokens = ApplySemanticTokensEdits(originalTokens.Data, (LSP.SemanticTokensDelta)edits);
// Raw tokens
var rawTokens = await RunGetSemanticTokensAsync(testLspServer, locations["caret"].First());
Assert.True(Enumerable.SequenceEqual(rawTokens.Data, editsToTokens));
}
private static int[] ApplySemanticTokensEdits(int[]? originalTokens, LSP.SemanticTokensDelta edits)
{
var data = originalTokens.ToList();
if (edits.Edits != null)
{
foreach (var edit in edits.Edits.Reverse())
{
data.RemoveRange(edit.Start, edit.DeleteCount);
if (edit.Data is not null)
{
data.InsertRange(edit.Start, edit.Data);
}
}
}
return data.ToArray();
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable enable
using System.Linq;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.LanguageServer.Handler.SemanticTokens;
using Roslyn.Test.Utilities;
using Xunit;
using LSP = Microsoft.VisualStudio.LanguageServer.Protocol;
namespace Microsoft.CodeAnalysis.LanguageServer.UnitTests.SemanticTokens
{
public class SemanticTokensEditsTests : AbstractSemanticTokensTests
{
/*
* Markup for basic test case:
* // Comment
* static class C { }
*/
private static readonly string s_standardCase = @"{|caret:|}// Comment
static class C { }";
/*
* Markup for single line test case:
* // Comment
*/
private static readonly string s_singleLineCase = @"{|caret:|}// Comment";
[Fact]
public async Task TestInsertingNewLineInMiddleOfFile()
{
var updatedText = @"// Comment
static class C { }";
using var testLspServer = CreateTestLspServer(s_standardCase, out var locations);
var caretLocation = locations["caret"].First();
await RunGetSemanticTokensAsync(testLspServer, caretLocation);
UpdateDocumentText(updatedText, testLspServer.TestWorkspace);
var results = await RunGetSemanticTokensEditsAsync(testLspServer, caretLocation, previousResultId: "1");
var expectedEdit = new LSP.SemanticTokensEdit { Start = 5, DeleteCount = 1, Data = new int[] { 2 } };
Assert.Equal(expectedEdit, ((LSP.SemanticTokensDelta)results).Edits.First());
Assert.Equal("2", ((LSP.SemanticTokensDelta)results).ResultId);
}
/// <summary>
/// Tests making a deletion from the end of the file.
/// </summary>
[Fact]
public async Task TestGetSemanticTokensEdits_EndDeletionAsync()
{
var updatedText =
@"// Comment";
using var testLspServer = CreateTestLspServer(s_standardCase, out var locations);
var caretLocation = locations["caret"].First();
await RunGetSemanticTokensAsync(testLspServer, caretLocation);
UpdateDocumentText(updatedText, testLspServer.TestWorkspace);
var results = await RunGetSemanticTokensEditsAsync(testLspServer, caretLocation, previousResultId: "1");
var expectedEdit = new LSP.SemanticTokensEdit { Start = 5, DeleteCount = 25, Data = System.Array.Empty<int>() };
Assert.Equal(expectedEdit, ((LSP.SemanticTokensDelta)results).Edits.First());
Assert.Equal("2", ((LSP.SemanticTokensDelta)results).ResultId);
}
/// <summary>
/// Tests making an insertion at the end of the file.
/// </summary>
[Fact]
public async Task TestGetSemanticTokensEdits_EndInsertionAsync()
{
var updatedText =
@"// Comment
static class C { }
// Comment";
using var testLspServer = CreateTestLspServer(s_standardCase, out var locations);
var caretLocation = locations["caret"].First();
await RunGetSemanticTokensAsync(testLspServer, caretLocation);
UpdateDocumentText(updatedText, testLspServer.TestWorkspace);
var results = await RunGetSemanticTokensEditsAsync(testLspServer, caretLocation, previousResultId: "1");
var expectedEdit = new LSP.SemanticTokensEdit
{
Start = 30,
DeleteCount = 0,
Data = new int[] { 1, 0, 10, SemanticTokensCache.TokenTypeToIndex[LSP.SemanticTokenTypes.Comment], 0 }
};
Assert.Equal(expectedEdit, ((LSP.SemanticTokensDelta)results).Edits.First());
Assert.Equal("2", ((LSP.SemanticTokensDelta)results).ResultId);
}
/// <summary>
/// Tests to make sure we return a minimal number of edits.
/// </summary>
[Fact]
public async Task TestGetSemanticTokensEdits_ReturnMinimalEdits()
{
var updatedText =
@"class
// Comment";
using var testLspServer = CreateTestLspServer(s_singleLineCase, out var locations);
var caretLocation = locations["caret"].First();
await RunGetSemanticTokensAsync(testLspServer, caretLocation);
// Edit text
UpdateDocumentText(updatedText, testLspServer.TestWorkspace);
var results = await RunGetSemanticTokensEditsAsync(testLspServer, caretLocation, previousResultId: "1");
// 1. Updates length of token (10 to 5) and updates token type (comment to keyword)
// 2. Creates new token for '// Comment'
var expectedEdit = new LSP.SemanticTokensEdit
{
Start = 2,
DeleteCount = 0,
Data = new int[]
{
// 'class'
/* 0, 0, */ 5, SemanticTokensCache.TokenTypeToIndex[LSP.SemanticTokenTypes.Keyword], 0,
// '// Comment'
1, 0, /* 10, SemanticTokensCache.TokenTypeToIndex[LSP.SemanticTokenTypes.Comment], 0 */
}
};
Assert.Equal(expectedEdit, ((LSP.SemanticTokensDelta)results).Edits?[0]);
Assert.Equal("2", ((LSP.SemanticTokensDelta)results).ResultId);
}
/// <summary>
/// Tests to make sure that if we don't have a matching semantic token set for the document in the cache,
/// we return the full set of semantic tokens.
/// </summary>
[Fact]
public async Task TestGetSemanticTokensEditsNoCacheAsync()
{
var updatedText =
@"// Comment
static class C { }";
using var testLspServer = CreateTestLspServer(s_standardCase, out var locations);
var caretLocation = locations["caret"].First();
await RunGetSemanticTokensAsync(testLspServer, caretLocation);
UpdateDocumentText(updatedText, testLspServer.TestWorkspace);
var results = await RunGetSemanticTokensEditsAsync(testLspServer, caretLocation, previousResultId: "10");
// Make sure we're returned SemanticTokens instead of SemanticTokensEdits.
Assert.True(results.Value is LSP.SemanticTokens);
// The returned result should now be in the cache and should be of the LSP.SemanticTokensDelta type.
var cachedResults = await RunGetSemanticTokensEditsAsync(
testLspServer, caretLocation, previousResultId: ((LSP.SemanticTokens)results).ResultId!);
Assert.True(cachedResults.Value is LSP.SemanticTokensDelta);
}
[Fact]
public async Task TestConvertSemanticTokenEditsIntoSemanticTokens_InsertNewlineInMiddleOfFile()
{
var updatedText =
@"// Comment
static class C { }";
using var testLspServer = CreateTestLspServer(s_standardCase, out var locations);
var caretLocation = locations["caret"].First();
var originalTokens = await RunGetSemanticTokensAsync(testLspServer, caretLocation);
UpdateDocumentText(updatedText, testLspServer.TestWorkspace);
// Edits to tokens conversion
var edits = await RunGetSemanticTokensEditsAsync(testLspServer, caretLocation, previousResultId: "1");
var editsToTokens = ApplySemanticTokensEdits(originalTokens.Data, (LSP.SemanticTokensDelta)edits);
// Raw tokens
var rawTokens = await RunGetSemanticTokensAsync(testLspServer, locations["caret"].First());
Assert.True(Enumerable.SequenceEqual(rawTokens.Data, editsToTokens));
}
[Fact]
public async Task TestConvertSemanticTokenEditsIntoSemanticTokens_ReplacementEdit()
{
var updatedText =
@"// Comment
internal struct S { }";
using var testLspServer = CreateTestLspServer(s_standardCase, out var locations);
var caretLocation = locations["caret"].First();
var originalTokens = await RunGetSemanticTokensAsync(testLspServer, caretLocation);
UpdateDocumentText(updatedText, testLspServer.TestWorkspace);
// Edits to tokens conversion
var edits = await RunGetSemanticTokensEditsAsync(testLspServer, caretLocation, previousResultId: "1");
var editsToTokens = ApplySemanticTokensEdits(originalTokens.Data, (LSP.SemanticTokensDelta)edits);
// Raw tokens
var rawTokens = await RunGetSemanticTokensAsync(testLspServer, locations["caret"].First());
Assert.True(Enumerable.SequenceEqual(rawTokens.Data, editsToTokens));
}
[Fact]
public async Task TestConvertSemanticTokenEditsIntoSemanticTokens_ManyEdits()
{
var updatedText =
@"
// Comment
class C
{
static void M(int x)
{
var v = 1;
}
}";
using var testLspServer = CreateTestLspServer(s_standardCase, out var locations);
var caretLocation = locations["caret"].First();
var originalTokens = await RunGetSemanticTokensAsync(testLspServer, caretLocation);
UpdateDocumentText(updatedText, testLspServer.TestWorkspace);
// Edits to tokens conversion
var edits = await RunGetSemanticTokensEditsAsync(testLspServer, caretLocation, previousResultId: "1");
var editsToTokens = ApplySemanticTokensEdits(originalTokens.Data, (LSP.SemanticTokensDelta)edits);
// Raw tokens
var rawTokens = await RunGetSemanticTokensAsync(testLspServer, locations["caret"].First());
Assert.True(Enumerable.SequenceEqual(rawTokens.Data, editsToTokens));
}
[Fact, WorkItem(54671, "https://github.com/dotnet/roslyn/issues/54671")]
public async Task TestConvertSemanticTokenEditsIntoSemanticTokens_FragmentedTokens()
{
var originalText =
@"fo {|caret:|}r (int i = 0;/*c*/; i++)
{
}";
var updatedText =
@"for (int i = 0;/*c*/; i++)
{
}";
using var testLspServer = CreateTestLspServer(originalText, out var locations);
var caretLocation = locations["caret"].First();
var originalTokens = await RunGetSemanticTokensAsync(testLspServer, caretLocation);
UpdateDocumentText(updatedText, testLspServer.TestWorkspace);
// Edits to tokens conversion
var edits = await RunGetSemanticTokensEditsAsync(testLspServer, caretLocation, previousResultId: "1");
var editsToTokens = ApplySemanticTokensEdits(originalTokens.Data, (LSP.SemanticTokensDelta)edits);
// Raw tokens
var rawTokens = await RunGetSemanticTokensAsync(testLspServer, locations["caret"].First());
Assert.True(Enumerable.SequenceEqual(rawTokens.Data, editsToTokens));
}
private static int[] ApplySemanticTokensEdits(int[]? originalTokens, LSP.SemanticTokensDelta edits)
{
var data = originalTokens.ToList();
if (edits.Edits != null)
{
foreach (var edit in edits.Edits.Reverse())
{
data.RemoveRange(edit.Start, edit.DeleteCount);
if (edit.Data is not null)
{
data.InsertRange(edit.Start, edit.Data);
}
}
}
return data.ToArray();
}
}
}
| -1 |
dotnet/roslyn | 55,877 | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute | Part of C# 10 support | davidwengier | 2021-08-25T05:36:27Z | 2021-08-30T20:47:11Z | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | 023d3ca2b5fb429f0b3dcc1efeed39442e232dba | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute. Part of C# 10 support | ./src/Workspaces/MSBuildTest/Resources/global.json | {
"comment": "this file is empty to ensure we get the 'standard' behavior as if no global.json was specified in the first place"
} | {
"comment": "this file is empty to ensure we get the 'standard' behavior as if no global.json was specified in the first place"
} | -1 |
dotnet/roslyn | 55,877 | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute | Part of C# 10 support | davidwengier | 2021-08-25T05:36:27Z | 2021-08-30T20:47:11Z | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | 023d3ca2b5fb429f0b3dcc1efeed39442e232dba | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute. Part of C# 10 support | ./src/VisualStudio/IntegrationTest/TestSetup/source.extension.vsixmanifest | <?xml version="1.0" encoding="utf-8"?>
<!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. -->
<PackageManifest Version="2.0.0" xmlns="http://schemas.microsoft.com/developer/vsx-schema/2011" xmlns:d="http://schemas.microsoft.com/developer/vsx-schema-design/2011">
<Metadata>
<Identity Id="d0122878-51f1-4b36-95ec-dec2079a2a84" Version="|%CurrentProject%;GetVsixVersion|" Language="en-US" Publisher="Microsoft" />
<DisplayName>Visual Studio Integration Test Support</DisplayName>
<Description xml:space="preserve">Support for running Visual Studio integration tests.</Description>
<License>EULA.rtf</License>
</Metadata>
<Installation Experimental="true">
<InstallationTarget Id="Microsoft.VisualStudio.Community" Version="[17.0,]">
<ProductArchitecture>x86</ProductArchitecture>
</InstallationTarget>
<InstallationTarget Id="Microsoft.VisualStudio.Community" Version="[17.0,]">
<ProductArchitecture>amd64</ProductArchitecture>
</InstallationTarget>
</Installation>
<Dependencies>
<Dependency Id="0b5e8ddb-f12d-4131-a71d-77acc26a798f" DisplayName="Roslyn Language Services" d:Source="Project" Version="[|VisualStudioSetup;GetVsixVersion|,]" d:ProjectName="VisualStudioSetup" />
</Dependencies>
<Assets>
<Asset Type="Microsoft.VisualStudio.VsPackage" d:Source="Project" d:ProjectName="%CurrentProject%" Path="|%CurrentProject%;PkgdefProjectOutputGroup|" />
<Asset Type="Microsoft.VisualStudio.MefComponent" d:Source="Project" d:ProjectName="%CurrentProject%" Path="|%CurrentProject%|" />
<Asset Type="Microsoft.VisualStudio.MefComponent" d:Source="Project" d:ProjectName="Diagnostics" Path="|Diagnostics|" AssemblyName="|Diagnostics;AssemblyName|" />
</Assets>
<Prerequisites>
<Prerequisite Id="Microsoft.VisualStudio.Component.CoreEditor" Version="[17.0,18.0)" DisplayName="Visual Studio Core Editor" />
</Prerequisites>
</PackageManifest>
| <?xml version="1.0" encoding="utf-8"?>
<!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. -->
<PackageManifest Version="2.0.0" xmlns="http://schemas.microsoft.com/developer/vsx-schema/2011" xmlns:d="http://schemas.microsoft.com/developer/vsx-schema-design/2011">
<Metadata>
<Identity Id="d0122878-51f1-4b36-95ec-dec2079a2a84" Version="|%CurrentProject%;GetVsixVersion|" Language="en-US" Publisher="Microsoft" />
<DisplayName>Visual Studio Integration Test Support</DisplayName>
<Description xml:space="preserve">Support for running Visual Studio integration tests.</Description>
<License>EULA.rtf</License>
</Metadata>
<Installation Experimental="true">
<InstallationTarget Id="Microsoft.VisualStudio.Community" Version="[17.0,]">
<ProductArchitecture>x86</ProductArchitecture>
</InstallationTarget>
<InstallationTarget Id="Microsoft.VisualStudio.Community" Version="[17.0,]">
<ProductArchitecture>amd64</ProductArchitecture>
</InstallationTarget>
</Installation>
<Dependencies>
<Dependency Id="0b5e8ddb-f12d-4131-a71d-77acc26a798f" DisplayName="Roslyn Language Services" d:Source="Project" Version="[|VisualStudioSetup;GetVsixVersion|,]" d:ProjectName="VisualStudioSetup" />
</Dependencies>
<Assets>
<Asset Type="Microsoft.VisualStudio.VsPackage" d:Source="Project" d:ProjectName="%CurrentProject%" Path="|%CurrentProject%;PkgdefProjectOutputGroup|" />
<Asset Type="Microsoft.VisualStudio.MefComponent" d:Source="Project" d:ProjectName="%CurrentProject%" Path="|%CurrentProject%|" />
<Asset Type="Microsoft.VisualStudio.MefComponent" d:Source="Project" d:ProjectName="Diagnostics" Path="|Diagnostics|" AssemblyName="|Diagnostics;AssemblyName|" />
</Assets>
<Prerequisites>
<Prerequisite Id="Microsoft.VisualStudio.Component.CoreEditor" Version="[17.0,18.0)" DisplayName="Visual Studio Core Editor" />
</Prerequisites>
</PackageManifest>
| -1 |
dotnet/roslyn | 55,877 | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute | Part of C# 10 support | davidwengier | 2021-08-25T05:36:27Z | 2021-08-30T20:47:11Z | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | 023d3ca2b5fb429f0b3dcc1efeed39442e232dba | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute. Part of C# 10 support | ./src/Compilers/Core/Portable/Emit/NoPia/CommonEmbeddedMember.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Collections.Immutable;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Emit.NoPia
{
internal abstract partial class EmbeddedTypesManager<
TPEModuleBuilder,
TModuleCompilationState,
TEmbeddedTypesManager,
TSyntaxNode,
TAttributeData,
TSymbol,
TAssemblySymbol,
TNamedTypeSymbol,
TFieldSymbol,
TMethodSymbol,
TEventSymbol,
TPropertySymbol,
TParameterSymbol,
TTypeParameterSymbol,
TEmbeddedType,
TEmbeddedField,
TEmbeddedMethod,
TEmbeddedEvent,
TEmbeddedProperty,
TEmbeddedParameter,
TEmbeddedTypeParameter>
{
internal abstract class CommonEmbeddedMember
{
internal abstract TEmbeddedTypesManager TypeManager { get; }
}
internal abstract class CommonEmbeddedMember<TMember> : CommonEmbeddedMember, Cci.IReference
where TMember : TSymbol, Cci.ITypeMemberReference
{
protected readonly TMember UnderlyingSymbol;
private ImmutableArray<TAttributeData> _lazyAttributes;
protected CommonEmbeddedMember(TMember underlyingSymbol)
{
this.UnderlyingSymbol = underlyingSymbol;
}
protected abstract IEnumerable<TAttributeData> GetCustomAttributesToEmit(TPEModuleBuilder moduleBuilder);
protected virtual TAttributeData PortAttributeIfNeedTo(TAttributeData attrData, TSyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics)
{
return null;
}
private ImmutableArray<TAttributeData> GetAttributes(TPEModuleBuilder moduleBuilder, TSyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics)
{
var builder = ArrayBuilder<TAttributeData>.GetInstance();
// Copy some of the attributes.
// Note, when porting attributes, we are not using constructors from original symbol.
// The constructors might be missing (for example, in metadata case) and doing lookup
// will ensure that we report appropriate errors.
foreach (var attrData in GetCustomAttributesToEmit(moduleBuilder))
{
if (TypeManager.IsTargetAttribute(UnderlyingSymbol, attrData, AttributeDescription.DispIdAttribute))
{
if (attrData.CommonConstructorArguments.Length == 1)
{
builder.AddOptional(TypeManager.CreateSynthesizedAttribute(WellKnownMember.System_Runtime_InteropServices_DispIdAttribute__ctor, attrData, syntaxNodeOpt, diagnostics));
}
}
else
{
builder.AddOptional(PortAttributeIfNeedTo(attrData, syntaxNodeOpt, diagnostics));
}
}
return builder.ToImmutableAndFree();
}
IEnumerable<Cci.ICustomAttribute> Cci.IReference.GetAttributes(EmitContext context)
{
if (_lazyAttributes.IsDefault)
{
var diagnostics = DiagnosticBag.GetInstance();
var attributes = GetAttributes((TPEModuleBuilder)context.Module, (TSyntaxNode)context.SyntaxNode, diagnostics);
if (ImmutableInterlocked.InterlockedInitialize(ref _lazyAttributes, attributes))
{
// Save any diagnostics that we encountered.
context.Diagnostics.AddRange(diagnostics);
}
diagnostics.Free();
}
return _lazyAttributes;
}
void Cci.IReference.Dispatch(Cci.MetadataVisitor visitor)
{
throw ExceptionUtilities.Unreachable;
}
Cci.IDefinition Cci.IReference.AsDefinition(EmitContext context)
{
throw ExceptionUtilities.Unreachable;
}
Symbols.ISymbolInternal Cci.IReference.GetInternalSymbol() => null;
public sealed override bool Equals(object obj)
{
// It is not supported to rely on default equality of these Cci objects, an explicit way to compare and hash them should be used.
throw Roslyn.Utilities.ExceptionUtilities.Unreachable;
}
public sealed override int GetHashCode()
{
// It is not supported to rely on default equality of these Cci objects, an explicit way to compare and hash them should be used.
throw Roslyn.Utilities.ExceptionUtilities.Unreachable;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Collections.Immutable;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Emit.NoPia
{
internal abstract partial class EmbeddedTypesManager<
TPEModuleBuilder,
TModuleCompilationState,
TEmbeddedTypesManager,
TSyntaxNode,
TAttributeData,
TSymbol,
TAssemblySymbol,
TNamedTypeSymbol,
TFieldSymbol,
TMethodSymbol,
TEventSymbol,
TPropertySymbol,
TParameterSymbol,
TTypeParameterSymbol,
TEmbeddedType,
TEmbeddedField,
TEmbeddedMethod,
TEmbeddedEvent,
TEmbeddedProperty,
TEmbeddedParameter,
TEmbeddedTypeParameter>
{
internal abstract class CommonEmbeddedMember
{
internal abstract TEmbeddedTypesManager TypeManager { get; }
}
internal abstract class CommonEmbeddedMember<TMember> : CommonEmbeddedMember, Cci.IReference
where TMember : TSymbol, Cci.ITypeMemberReference
{
protected readonly TMember UnderlyingSymbol;
private ImmutableArray<TAttributeData> _lazyAttributes;
protected CommonEmbeddedMember(TMember underlyingSymbol)
{
this.UnderlyingSymbol = underlyingSymbol;
}
protected abstract IEnumerable<TAttributeData> GetCustomAttributesToEmit(TPEModuleBuilder moduleBuilder);
protected virtual TAttributeData PortAttributeIfNeedTo(TAttributeData attrData, TSyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics)
{
return null;
}
private ImmutableArray<TAttributeData> GetAttributes(TPEModuleBuilder moduleBuilder, TSyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics)
{
var builder = ArrayBuilder<TAttributeData>.GetInstance();
// Copy some of the attributes.
// Note, when porting attributes, we are not using constructors from original symbol.
// The constructors might be missing (for example, in metadata case) and doing lookup
// will ensure that we report appropriate errors.
foreach (var attrData in GetCustomAttributesToEmit(moduleBuilder))
{
if (TypeManager.IsTargetAttribute(UnderlyingSymbol, attrData, AttributeDescription.DispIdAttribute))
{
if (attrData.CommonConstructorArguments.Length == 1)
{
builder.AddOptional(TypeManager.CreateSynthesizedAttribute(WellKnownMember.System_Runtime_InteropServices_DispIdAttribute__ctor, attrData, syntaxNodeOpt, diagnostics));
}
}
else
{
builder.AddOptional(PortAttributeIfNeedTo(attrData, syntaxNodeOpt, diagnostics));
}
}
return builder.ToImmutableAndFree();
}
IEnumerable<Cci.ICustomAttribute> Cci.IReference.GetAttributes(EmitContext context)
{
if (_lazyAttributes.IsDefault)
{
var diagnostics = DiagnosticBag.GetInstance();
var attributes = GetAttributes((TPEModuleBuilder)context.Module, (TSyntaxNode)context.SyntaxNode, diagnostics);
if (ImmutableInterlocked.InterlockedInitialize(ref _lazyAttributes, attributes))
{
// Save any diagnostics that we encountered.
context.Diagnostics.AddRange(diagnostics);
}
diagnostics.Free();
}
return _lazyAttributes;
}
void Cci.IReference.Dispatch(Cci.MetadataVisitor visitor)
{
throw ExceptionUtilities.Unreachable;
}
Cci.IDefinition Cci.IReference.AsDefinition(EmitContext context)
{
throw ExceptionUtilities.Unreachable;
}
Symbols.ISymbolInternal Cci.IReference.GetInternalSymbol() => null;
public sealed override bool Equals(object obj)
{
// It is not supported to rely on default equality of these Cci objects, an explicit way to compare and hash them should be used.
throw Roslyn.Utilities.ExceptionUtilities.Unreachable;
}
public sealed override int GetHashCode()
{
// It is not supported to rely on default equality of these Cci objects, an explicit way to compare and hash them should be used.
throw Roslyn.Utilities.ExceptionUtilities.Unreachable;
}
}
}
}
| -1 |
dotnet/roslyn | 55,877 | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute | Part of C# 10 support | davidwengier | 2021-08-25T05:36:27Z | 2021-08-30T20:47:11Z | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | 023d3ca2b5fb429f0b3dcc1efeed39442e232dba | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute. Part of C# 10 support | ./src/VisualStudio/Core/Test/Venus/ContainedDocumentTests_AdjustIndentation.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
#If False Then
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.VisualStudio.LanguageServices.Implementation.Venus
Imports Microsoft.VisualStudio.Text
Imports Moq
Imports Roslyn.Test.Utilities
Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.Venus
Public Class ContainedDocumentTests_AdjustIndentation
Inherits AbstractContainedDocumentTests
<WpfFact, Trait(Traits.Feature, Traits.Features.Venus)>
Public Sub NoNewLines()
Dim subjectBuffer =
<Text>
public class Default
{
void PreRender()
{
{|S1:[|int x = 1;|]|}
}
}
</Text>.NormalizedValue
Dim spansToAdjust = {0}
Dim baseIndentations = {3}
Dim startOfIndent = subjectBuffer.IndexOf("{|S1")
AssertAdjustIndentation(HtmlMarkup, subjectBuffer, spansToAdjust, baseIndentations, Enumerable.Empty(Of TextChange)(), LanguageNames.CSharp)
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.Venus)>
Public Sub OnSingleLine()
Dim subjectBuffer =
<Text>
public class Default
{
void PreRender()
{
#line "Goo.aspx", 1{|S1:[|
int x = 1;
|]|}#line hidden
#line default
}
}
</Text>.NormalizedValue
Dim spansToAdjust = {0}
Dim baseIndentations = {3}
Dim startOfIndent = subjectBuffer.IndexOf("{|S1") + vbCrLf.Length
AssertAdjustIndentation(HtmlMarkup, subjectBuffer, spansToAdjust, baseIndentations, {New TextChange(New TextSpan(startOfIndent, 0), " ")}, LanguageNames.CSharp)
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.Venus)>
Public Sub OnMultipleLines()
Dim subjectBuffer =
<Text>
public class Default
{
void PreRender()
{
#line "Goo.aspx", 1{|S1:[|
if(true)
{
}
|]|}#line hidden
#line default
}
}
</Text>.NormalizedValue
Dim spansToAdjust = {0}
Dim baseIndentations = {3}
' Span start computation explained:
' ---------------------------------
' Although this span start computation is ugly to look at,
' this is far better than just saying xx and is more readable.
Dim startOfLine1Indent = subjectBuffer.IndexOf("{|S1:") + vbCrLf.Length
Dim startOfLine2Indent = subjectBuffer.IndexOf("true)") - "{|S1:[|".Length + "true)".Length + vbCrLf.Length
Dim startOfLine3Indent = startOfLine2Indent + vbCrLf.Length + "{".Length
' Span length computation explained:
' ----------------------------------
' The length of the span being edited (replaced) is the indentation on the line.
' By outdenting all lines under test, we could just say 0 for span length.
' The edit for all lines except the very first line would also replace the previous newline
' So, the length of the span being replaced should be 0 for line 1 and 1 for everything else.
' Verify that all statements align with base.
AssertAdjustIndentation(HtmlMarkup,
subjectBuffer,
spansToAdjust,
baseIndentations,
{New TextChange(New TextSpan(startOfLine1Indent, 0), " "),
New TextChange(New TextSpan(startOfLine2Indent, 0), " "),
New TextChange(New TextSpan(startOfLine3Indent, 0), " ")},
LanguageNames.CSharp)
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.Venus)>
Public Sub IndentationInNestedStatements()
Dim subjectBuffer =
<Text>
public class Default
{
void PreRender()
{
#line "Goo.aspx", 1{|S1:[|
if(true)
{
Console.WriteLine(5);
}
|]|}#line hidden
#line default
}
}
</Text>.NormalizedValue
Dim spansToAdjust = {0}
Dim baseIndentations = {3}
Dim startOfLine1Indent = subjectBuffer.IndexOf("{|S1:") + vbCrLf.Length
Dim startOfLine2Indent = subjectBuffer.IndexOf("(true)") - "{|S1:[|".Length + "(true)".Length + vbCrLf.Length
Dim startOfLine3Indent = startOfLine2Indent + vbCrLf.Length + "{".Length
Dim startOfLine4Indent = subjectBuffer.IndexOf(");") - "{|S1:[|".Length + ");".Length + vbCrLf.Length
' Assert that the statement inside the if block is indented 4 spaces from the base which is at column 3.
' the default indentation is 4 spaces and this test isn't changing that.
AssertAdjustIndentation(HtmlMarkup,
subjectBuffer,
spansToAdjust,
baseIndentations,
{New TextChange(New TextSpan(startOfLine1Indent, 0), " "),
New TextChange(New TextSpan(startOfLine2Indent, 0), " "),
New TextChange(New TextSpan(startOfLine3Indent, 0), " "),
New TextChange(New TextSpan(startOfLine4Indent, 0), " ")},
LanguageNames.CSharp)
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.Venus)>
Public Sub InQuery()
Dim subjectBuffer =
<Text>
public class Default
{
void PreRender()
{
#line "Goo.aspx", 1{|S1:[|
int[] numbers = { 5, 4, 1 };
var even = from n in numbers
where n % 2 == 0
select n;
|]|}#line hidden
#line default
}
}
</Text>.NormalizedValue
Dim spansToAdjust = {0}
Dim baseIndentations = {3}
Dim startOfLine1Indent = subjectBuffer.IndexOf("{|S1:") + vbCrLf.Length
Dim startOfLine2Indent = subjectBuffer.IndexOf("};") - "{|S1:[|".Length + "};".Length + vbCrLf.Length
Dim startOfLine3Indent = subjectBuffer.IndexOf("where") - "{|S1:[|".Length
Dim startOfLine4Indent = subjectBuffer.IndexOf("== 0") - "{|S1:[|".Length + "== 0".Length + vbCrLf.Length
' The where and select clauses should be right under from after applying a base indent of 3 to all of those.
' var even = from n in numbers
' where n % 2 == 0
' select n;
AssertAdjustIndentation(HtmlMarkup,
subjectBuffer,
spansToAdjust,
baseIndentations,
{New TextChange(New TextSpan(startOfLine1Indent, 0), " "),
New TextChange(New TextSpan(startOfLine2Indent, 0), " "),
New TextChange(New TextSpan(startOfLine3Indent, 0), " "),
New TextChange(New TextSpan(startOfLine4Indent, 0), " ")},
LanguageNames.CSharp)
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.Venus)>
Public Sub AtEndOfSpan()
Dim subjectBuffer =
<Text>
public class Default
{
void PreRender()
{{|S1:[|
int x = 1;
|]|}
}
}
</Text>.NormalizedValue
Dim spansToAdjust = {0}
Dim baseIndentations = {3}
Dim expected As TextChange = New TextChange(New TextSpan(66, 0), " ")
AssertAdjustIndentation(HtmlMarkup, subjectBuffer, spansToAdjust, baseIndentations, {expected}, LanguageNames.CSharp)
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.Venus), WorkItem(529885)>
Public Sub EndInSpan()
Dim subjectBuffer =
<Text>
public class Default
{
void PreRender()
{ {|S1:[|
int x = 1;
|]|}
}
}
</Text>.NormalizedValue
Dim spansToAdjust = {0}
Dim baseIndentations = {3}
Dim expected = New TextChange(TextSpan.FromBounds(60, 68), " ")
AssertAdjustIndentation(HtmlMarkup, subjectBuffer, spansToAdjust, baseIndentations, {expected}, LanguageNames.CSharp)
End Sub
Private Sub AssertAdjustIndentation(
surfaceBufferMarkup As String,
subjectBufferMarkup As String,
spansToAdjust As IEnumerable(Of Integer),
baseIndentations As IEnumerable(Of Integer),
expectedEdits As IEnumerable(Of TextChange),
language As String)
Assert.Equal(spansToAdjust.Count, baseIndentations.Count)
Using Workspace = GetWorkspace(subjectBufferMarkup, language)
Dim projectedDocument = Workspace.CreateProjectionBufferDocument(surfaceBufferMarkup, Workspace.Documents, language)
Dim hostDocument = Workspace.Documents.Single()
Dim spans = hostDocument.SelectedSpans
Dim actualEdits As New List(Of TextChange)
Dim textEdit As New Mock(Of ITextEdit)
textEdit.
Setup(Function(e) e.Replace(It.IsAny(Of Span)(), It.IsAny(Of String)())).
Callback(Sub(span As Span, text As String) actualEdits.Add(New TextChange(New TextSpan(span.Start, span.Length), text)))
For Each index In spansToAdjust
ContainedDocument.AdjustIndentationForSpan(GetDocument(Workspace),
hostDocument.GetTextBuffer().CurrentSnapshot,
textEdit.Object,
spans.Item(index),
baseIndentations.ElementAt(index))
Next
AssertEx.Equal(expectedEdits, actualEdits)
End Using
End Sub
End Class
End Namespace
#End If
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
#If False Then
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.VisualStudio.LanguageServices.Implementation.Venus
Imports Microsoft.VisualStudio.Text
Imports Moq
Imports Roslyn.Test.Utilities
Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.Venus
Public Class ContainedDocumentTests_AdjustIndentation
Inherits AbstractContainedDocumentTests
<WpfFact, Trait(Traits.Feature, Traits.Features.Venus)>
Public Sub NoNewLines()
Dim subjectBuffer =
<Text>
public class Default
{
void PreRender()
{
{|S1:[|int x = 1;|]|}
}
}
</Text>.NormalizedValue
Dim spansToAdjust = {0}
Dim baseIndentations = {3}
Dim startOfIndent = subjectBuffer.IndexOf("{|S1")
AssertAdjustIndentation(HtmlMarkup, subjectBuffer, spansToAdjust, baseIndentations, Enumerable.Empty(Of TextChange)(), LanguageNames.CSharp)
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.Venus)>
Public Sub OnSingleLine()
Dim subjectBuffer =
<Text>
public class Default
{
void PreRender()
{
#line "Goo.aspx", 1{|S1:[|
int x = 1;
|]|}#line hidden
#line default
}
}
</Text>.NormalizedValue
Dim spansToAdjust = {0}
Dim baseIndentations = {3}
Dim startOfIndent = subjectBuffer.IndexOf("{|S1") + vbCrLf.Length
AssertAdjustIndentation(HtmlMarkup, subjectBuffer, spansToAdjust, baseIndentations, {New TextChange(New TextSpan(startOfIndent, 0), " ")}, LanguageNames.CSharp)
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.Venus)>
Public Sub OnMultipleLines()
Dim subjectBuffer =
<Text>
public class Default
{
void PreRender()
{
#line "Goo.aspx", 1{|S1:[|
if(true)
{
}
|]|}#line hidden
#line default
}
}
</Text>.NormalizedValue
Dim spansToAdjust = {0}
Dim baseIndentations = {3}
' Span start computation explained:
' ---------------------------------
' Although this span start computation is ugly to look at,
' this is far better than just saying xx and is more readable.
Dim startOfLine1Indent = subjectBuffer.IndexOf("{|S1:") + vbCrLf.Length
Dim startOfLine2Indent = subjectBuffer.IndexOf("true)") - "{|S1:[|".Length + "true)".Length + vbCrLf.Length
Dim startOfLine3Indent = startOfLine2Indent + vbCrLf.Length + "{".Length
' Span length computation explained:
' ----------------------------------
' The length of the span being edited (replaced) is the indentation on the line.
' By outdenting all lines under test, we could just say 0 for span length.
' The edit for all lines except the very first line would also replace the previous newline
' So, the length of the span being replaced should be 0 for line 1 and 1 for everything else.
' Verify that all statements align with base.
AssertAdjustIndentation(HtmlMarkup,
subjectBuffer,
spansToAdjust,
baseIndentations,
{New TextChange(New TextSpan(startOfLine1Indent, 0), " "),
New TextChange(New TextSpan(startOfLine2Indent, 0), " "),
New TextChange(New TextSpan(startOfLine3Indent, 0), " ")},
LanguageNames.CSharp)
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.Venus)>
Public Sub IndentationInNestedStatements()
Dim subjectBuffer =
<Text>
public class Default
{
void PreRender()
{
#line "Goo.aspx", 1{|S1:[|
if(true)
{
Console.WriteLine(5);
}
|]|}#line hidden
#line default
}
}
</Text>.NormalizedValue
Dim spansToAdjust = {0}
Dim baseIndentations = {3}
Dim startOfLine1Indent = subjectBuffer.IndexOf("{|S1:") + vbCrLf.Length
Dim startOfLine2Indent = subjectBuffer.IndexOf("(true)") - "{|S1:[|".Length + "(true)".Length + vbCrLf.Length
Dim startOfLine3Indent = startOfLine2Indent + vbCrLf.Length + "{".Length
Dim startOfLine4Indent = subjectBuffer.IndexOf(");") - "{|S1:[|".Length + ");".Length + vbCrLf.Length
' Assert that the statement inside the if block is indented 4 spaces from the base which is at column 3.
' the default indentation is 4 spaces and this test isn't changing that.
AssertAdjustIndentation(HtmlMarkup,
subjectBuffer,
spansToAdjust,
baseIndentations,
{New TextChange(New TextSpan(startOfLine1Indent, 0), " "),
New TextChange(New TextSpan(startOfLine2Indent, 0), " "),
New TextChange(New TextSpan(startOfLine3Indent, 0), " "),
New TextChange(New TextSpan(startOfLine4Indent, 0), " ")},
LanguageNames.CSharp)
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.Venus)>
Public Sub InQuery()
Dim subjectBuffer =
<Text>
public class Default
{
void PreRender()
{
#line "Goo.aspx", 1{|S1:[|
int[] numbers = { 5, 4, 1 };
var even = from n in numbers
where n % 2 == 0
select n;
|]|}#line hidden
#line default
}
}
</Text>.NormalizedValue
Dim spansToAdjust = {0}
Dim baseIndentations = {3}
Dim startOfLine1Indent = subjectBuffer.IndexOf("{|S1:") + vbCrLf.Length
Dim startOfLine2Indent = subjectBuffer.IndexOf("};") - "{|S1:[|".Length + "};".Length + vbCrLf.Length
Dim startOfLine3Indent = subjectBuffer.IndexOf("where") - "{|S1:[|".Length
Dim startOfLine4Indent = subjectBuffer.IndexOf("== 0") - "{|S1:[|".Length + "== 0".Length + vbCrLf.Length
' The where and select clauses should be right under from after applying a base indent of 3 to all of those.
' var even = from n in numbers
' where n % 2 == 0
' select n;
AssertAdjustIndentation(HtmlMarkup,
subjectBuffer,
spansToAdjust,
baseIndentations,
{New TextChange(New TextSpan(startOfLine1Indent, 0), " "),
New TextChange(New TextSpan(startOfLine2Indent, 0), " "),
New TextChange(New TextSpan(startOfLine3Indent, 0), " "),
New TextChange(New TextSpan(startOfLine4Indent, 0), " ")},
LanguageNames.CSharp)
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.Venus)>
Public Sub AtEndOfSpan()
Dim subjectBuffer =
<Text>
public class Default
{
void PreRender()
{{|S1:[|
int x = 1;
|]|}
}
}
</Text>.NormalizedValue
Dim spansToAdjust = {0}
Dim baseIndentations = {3}
Dim expected As TextChange = New TextChange(New TextSpan(66, 0), " ")
AssertAdjustIndentation(HtmlMarkup, subjectBuffer, spansToAdjust, baseIndentations, {expected}, LanguageNames.CSharp)
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.Venus), WorkItem(529885)>
Public Sub EndInSpan()
Dim subjectBuffer =
<Text>
public class Default
{
void PreRender()
{ {|S1:[|
int x = 1;
|]|}
}
}
</Text>.NormalizedValue
Dim spansToAdjust = {0}
Dim baseIndentations = {3}
Dim expected = New TextChange(TextSpan.FromBounds(60, 68), " ")
AssertAdjustIndentation(HtmlMarkup, subjectBuffer, spansToAdjust, baseIndentations, {expected}, LanguageNames.CSharp)
End Sub
Private Sub AssertAdjustIndentation(
surfaceBufferMarkup As String,
subjectBufferMarkup As String,
spansToAdjust As IEnumerable(Of Integer),
baseIndentations As IEnumerable(Of Integer),
expectedEdits As IEnumerable(Of TextChange),
language As String)
Assert.Equal(spansToAdjust.Count, baseIndentations.Count)
Using Workspace = GetWorkspace(subjectBufferMarkup, language)
Dim projectedDocument = Workspace.CreateProjectionBufferDocument(surfaceBufferMarkup, Workspace.Documents, language)
Dim hostDocument = Workspace.Documents.Single()
Dim spans = hostDocument.SelectedSpans
Dim actualEdits As New List(Of TextChange)
Dim textEdit As New Mock(Of ITextEdit)
textEdit.
Setup(Function(e) e.Replace(It.IsAny(Of Span)(), It.IsAny(Of String)())).
Callback(Sub(span As Span, text As String) actualEdits.Add(New TextChange(New TextSpan(span.Start, span.Length), text)))
For Each index In spansToAdjust
ContainedDocument.AdjustIndentationForSpan(GetDocument(Workspace),
hostDocument.GetTextBuffer().CurrentSnapshot,
textEdit.Object,
spans.Item(index),
baseIndentations.ElementAt(index))
Next
AssertEx.Equal(expectedEdits, actualEdits)
End Using
End Sub
End Class
End Namespace
#End If
| -1 |
dotnet/roslyn | 55,877 | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute | Part of C# 10 support | davidwengier | 2021-08-25T05:36:27Z | 2021-08-30T20:47:11Z | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | 023d3ca2b5fb429f0b3dcc1efeed39442e232dba | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute. Part of C# 10 support | ./src/Compilers/VisualBasic/Portable/Symbols/PreprocessingSymbol.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols
''' <summary>
''' Represents a preprocessing conditional compilation symbol.
''' </summary>
Friend NotInheritable Class PreprocessingSymbol
Inherits Symbol
Implements IPreprocessingSymbol
Private ReadOnly _name As String
Friend Sub New(name As String)
MyBase.New()
_name = name
End Sub
Public Overrides ReadOnly Property Name As String
Get
Return _name
End Get
End Property
Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location)
Get
Return ImmutableArray(Of Location).Empty
End Get
End Property
Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference)
Get
Return GetDeclaringSyntaxReferenceHelper(Of VisualBasicSyntaxNode)(Locations)
End Get
End Property
Public Overrides ReadOnly Property Kind As SymbolKind
Get
Return SymbolKind.Preprocessing
End Get
End Property
Public Overrides ReadOnly Property ContainingSymbol As Symbol
Get
Return Nothing
End Get
End Property
Public Overrides ReadOnly Property DeclaredAccessibility As Accessibility
Get
Return Accessibility.NotApplicable
End Get
End Property
Public Overrides ReadOnly Property IsMustOverride As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property IsNotOverridable As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property IsOverridable As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property IsOverrides As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property IsShared As Boolean
Get
Return False
End Get
End Property
Friend Overrides ReadOnly Property ObsoleteAttributeData As ObsoleteAttributeData
Get
Return Nothing
End Get
End Property
Public Overrides Function Equals(obj As Object) As Boolean
If obj Is Me Then
Return True
ElseIf obj Is Nothing Then
Return False
End If
Dim other As PreprocessingSymbol = TryCast(obj, PreprocessingSymbol)
Return other IsNot Nothing AndAlso
IdentifierComparison.Equals(Me.Name, other.Name)
End Function
Public Overrides Function GetHashCode() As Integer
Return Me.Name.GetHashCode()
End Function
Public Overloads Overrides Sub Accept(visitor As SymbolVisitor)
Throw New NotSupportedException()
End Sub
Public Overloads Overrides Sub Accept(visitor As VisualBasicSymbolVisitor)
Throw New NotSupportedException()
End Sub
Public Overloads Overrides Function Accept(Of TResult)(visitor As SymbolVisitor(Of TResult)) As TResult
Throw New NotSupportedException()
End Function
Public Overloads Overrides Function Accept(Of TResult)(visitor As VisualBasicSymbolVisitor(Of TResult)) As TResult
Throw New NotSupportedException()
End Function
Friend Overloads Overrides Function Accept(Of TArgument, TResult)(visitor As VisualBasicSymbolVisitor(Of TArgument, TResult), arg As TArgument) As TResult
Throw New NotSupportedException()
End Function
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols
''' <summary>
''' Represents a preprocessing conditional compilation symbol.
''' </summary>
Friend NotInheritable Class PreprocessingSymbol
Inherits Symbol
Implements IPreprocessingSymbol
Private ReadOnly _name As String
Friend Sub New(name As String)
MyBase.New()
_name = name
End Sub
Public Overrides ReadOnly Property Name As String
Get
Return _name
End Get
End Property
Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location)
Get
Return ImmutableArray(Of Location).Empty
End Get
End Property
Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference)
Get
Return GetDeclaringSyntaxReferenceHelper(Of VisualBasicSyntaxNode)(Locations)
End Get
End Property
Public Overrides ReadOnly Property Kind As SymbolKind
Get
Return SymbolKind.Preprocessing
End Get
End Property
Public Overrides ReadOnly Property ContainingSymbol As Symbol
Get
Return Nothing
End Get
End Property
Public Overrides ReadOnly Property DeclaredAccessibility As Accessibility
Get
Return Accessibility.NotApplicable
End Get
End Property
Public Overrides ReadOnly Property IsMustOverride As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property IsNotOverridable As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property IsOverridable As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property IsOverrides As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property IsShared As Boolean
Get
Return False
End Get
End Property
Friend Overrides ReadOnly Property ObsoleteAttributeData As ObsoleteAttributeData
Get
Return Nothing
End Get
End Property
Public Overrides Function Equals(obj As Object) As Boolean
If obj Is Me Then
Return True
ElseIf obj Is Nothing Then
Return False
End If
Dim other As PreprocessingSymbol = TryCast(obj, PreprocessingSymbol)
Return other IsNot Nothing AndAlso
IdentifierComparison.Equals(Me.Name, other.Name)
End Function
Public Overrides Function GetHashCode() As Integer
Return Me.Name.GetHashCode()
End Function
Public Overloads Overrides Sub Accept(visitor As SymbolVisitor)
Throw New NotSupportedException()
End Sub
Public Overloads Overrides Sub Accept(visitor As VisualBasicSymbolVisitor)
Throw New NotSupportedException()
End Sub
Public Overloads Overrides Function Accept(Of TResult)(visitor As SymbolVisitor(Of TResult)) As TResult
Throw New NotSupportedException()
End Function
Public Overloads Overrides Function Accept(Of TResult)(visitor As VisualBasicSymbolVisitor(Of TResult)) As TResult
Throw New NotSupportedException()
End Function
Friend Overloads Overrides Function Accept(Of TArgument, TResult)(visitor As VisualBasicSymbolVisitor(Of TArgument, TResult), arg As TArgument) As TResult
Throw New NotSupportedException()
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,877 | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute | Part of C# 10 support | davidwengier | 2021-08-25T05:36:27Z | 2021-08-30T20:47:11Z | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | 023d3ca2b5fb429f0b3dcc1efeed39442e232dba | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute. Part of C# 10 support | ./src/Compilers/VisualBasic/Portable/Symbols/SymbolExtensions.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports System.Runtime.CompilerServices
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols
Friend Module SymbolExtensions
Friend Const NamespaceKindNamespaceGroup As NamespaceKind = Nothing
''' <summary>
''' Does the compilation this symbol belongs to output to a winmdobj?
''' </summary>
<Extension()>
Friend Function IsCompilationOutputWinMdObj(symbol As Symbol) As Boolean
Dim comp = symbol.DeclaringCompilation
Return comp IsNot Nothing And comp.Options.OutputKind = OutputKind.WindowsRuntimeMetadata
End Function
''' <summary>
''' String such as 'class', 'interface' etc that can be used in error messages.
''' </summary>
<Extension()>
Friend Function GetKindText(target As Symbol) As String
Select Case target.Kind
Case SymbolKind.Namespace
Return "namespace"
Case SymbolKind.NamedType
Select Case DirectCast(target, TypeSymbol).TypeKind
Case TypeKind.Class
Return "class"
Case TypeKind.Enum
Return "enum"
Case TypeKind.Interface
Return "interface"
Case TypeKind.Structure
Return "structure"
Case TypeKind.Module
Return "module"
Case TypeKind.Delegate
' Dev10 error message format "... delegate Class goo ..." instead of "... delegate goo ..."
Return "delegate Class"
Case Else
'TODO: do we need string s for ByRef, Array, TypeParameter etc?
Return "type"
End Select
Case SymbolKind.Field, SymbolKind.Local, SymbolKind.Parameter, SymbolKind.RangeVariable
Return "variable"
Case SymbolKind.Method
Dim methodSymbol = DirectCast(target, MethodSymbol)
Select Case methodSymbol.MethodKind
Case MethodKind.Conversion, MethodKind.UserDefinedOperator, MethodKind.BuiltinOperator
Return "operator"
Case Else
If methodSymbol.IsSub Then
Return "sub"
Else
Return "function"
End If
End Select
Case SymbolKind.Property
If DirectCast(target, PropertySymbol).IsWithEvents Then
Return "WithEvents variable"
Else
Return "property"
End If
Case SymbolKind.Event
Return "event"
Case Else
Throw ExceptionUtilities.UnexpectedValue(target.Kind)
End Select
End Function
''' <summary>
''' String "ReadOnly", "WriteOnly", or "" describing the kind of property.
''' </summary>
<Extension()>
Friend Function GetPropertyKindText(target As PropertySymbol) As String
If target.IsWriteOnly Then
Return SyntaxFacts.GetText(SyntaxKind.WriteOnlyKeyword)
ElseIf target.IsReadOnly Then
Return SyntaxFacts.GetText(SyntaxKind.ReadOnlyKeyword)
Else
Return ""
End If
End Function
<Extension()>
Friend Function ToErrorMessageArgument(target As Symbol, Optional errorCode As ERRID = ERRID.ERR_None) As Object
If target.Kind = SymbolKind.Namespace Then
Dim ns As NamespaceSymbol = DirectCast(target, NamespaceSymbol)
If ns.IsGlobalNamespace Then
Return StringConstants.UnnamedNamespaceErrName
End If
End If
If errorCode = ERRID.ERR_TypeConflict6 Then
Return CustomSymbolDisplayFormatter.DefaultErrorFormat(target)
End If
Return target
End Function
''' <summary>
''' Checks if there is a name match with any type parameter.
''' </summary>
''' <param name="this"></param>
''' <param name="name"></param>
''' <returns></returns>
''' <remarks></remarks>
<Extension()>
Friend Function MatchesAnyName(this As ImmutableArray(Of TypeParameterSymbol), name As String) As Boolean
For Each tp In this
If IdentifierComparison.Comparer.Compare(name, tp.Name) = 0 Then
Return True
End If
Next
Return False
End Function
''' <summary>
''' Returns true if this symbols can overload another of the same kind.
''' </summary>
<Extension()>
Public Function IsOverloadable(symbol As Symbol) As Boolean
Dim kind = symbol.Kind
If kind = SymbolKind.Method Then
Return True
ElseIf kind <> SymbolKind.Property Then
Return False
End If
' uncommon case - WithEvents property do not overload. They behave like fields when OHI is concerned.
Return DirectCast(symbol, PropertySymbol).IsOverloadable
End Function
''' <summary>
''' Returns true if this property can overload another.
''' </summary>
<Extension()>
Public Function IsOverloadable(propertySymbol As PropertySymbol) As Boolean
Return Not propertySymbol.IsWithEvents
End Function
''' <summary>
''' Helper that tells if symbol has Overloads (hidebysig) on it
''' </summary>
<Extension()>
Friend Function IsOverloads(sym As Symbol) As Boolean
Debug.Assert(sym IsNot Nothing)
' methods and properties can overload.
Select Case sym.Kind
Case SymbolKind.Method
Dim method = DirectCast(sym, MethodSymbol)
If method.IsOverloads Then
Return True
End If
Case SymbolKind.Property
Dim prop = DirectCast(sym, PropertySymbol)
If prop.IsOverloads Then
Return True
End If
End Select
Return False
End Function
''' <summary>
''' Member that does not have Overloads, is considered Shadows (hidebyname)
''' </summary>
<Extension()>
Friend Function IsShadows(sym As Symbol) As Boolean
' everything that does not overload, shadows
Return Not sym.IsOverloads
End Function
''' <summary>
''' Is the symbol an instance member (i.e. access requires a receiver)
''' </summary>
<Extension()>
Friend Function IsInstanceMember(sym As Symbol) As Boolean
Select Case sym.Kind
Case SymbolKind.Field, SymbolKind.Property, SymbolKind.Method, SymbolKind.Event
Return Not sym.IsShared
Case Else
Return False
End Select
End Function
''' <summary>
''' Is this a member of a interface that requires implementation?
''' </summary>
<Extension()>
Friend Function RequiresImplementation(sym As Symbol) As Boolean
Select Case sym.Kind
Case SymbolKind.Method, SymbolKind.Property, SymbolKind.Event
' Note that in metadata, you can encounter methods that are static (shared) or non-virtual
' (for example TLBIMP VtblGap members), even though you can't define those in source.
Return sym.ContainingType.IsInterfaceType() AndAlso
Not sym.IsShared AndAlso Not sym.IsNotOverridable AndAlso
(sym.IsMustOverride OrElse sym.IsOverridable)
Case Else
Return False
End Select
End Function
<Extension()>
Friend Function IsMetadataVirtual(method As MethodSymbol) As Boolean
If method.IsOverridable OrElse
method.IsOverrides OrElse
method.IsMustOverride OrElse
Not method.ExplicitInterfaceImplementations.IsEmpty Then
Return True
End If
Dim definition As MethodSymbol = method.OriginalDefinition
Dim containingSourceType = TryCast(definition.ContainingSymbol, SourceNamedTypeSymbol)
Return containingSourceType IsNot Nothing AndAlso
containingSourceType.GetCorrespondingComClassInterfaceMethod(definition) IsNot Nothing
End Function
<Extension()>
Public Function IsAccessor(methodSymbol As MethodSymbol) As Boolean
Return methodSymbol.AssociatedSymbol IsNot Nothing
End Function
<Extension()>
Public Function IsAccessor(symbol As Symbol) As Boolean
Return symbol.Kind = SymbolKind.Method AndAlso IsAccessor(DirectCast(symbol, MethodSymbol))
End Function
<Extension()>
Public Function IsWithEventsProperty(symbol As Symbol) As Boolean
Return symbol.Kind = SymbolKind.Property AndAlso DirectCast(symbol, PropertySymbol).IsWithEvents
End Function
''' <summary>
''' Returns True for "regular" properties (those that are not WithEvents.
''' Typically used for OHI diagnostics where WithEvents properties are treated as variables.
''' </summary>
<Extension()>
Public Function IsPropertyAndNotWithEvents(symbol As Symbol) As Boolean
Return symbol.Kind = SymbolKind.Property AndAlso Not DirectCast(symbol, PropertySymbol).IsWithEvents
End Function
<Extension()>
Friend Function IsAnyConstructor(method As MethodSymbol) As Boolean
Dim kind = method.MethodKind
Return kind = MethodKind.Constructor OrElse kind = MethodKind.SharedConstructor
End Function
''' <summary>
''' default zero-init constructor symbol is added to a struct when it does not define
''' its own parameterless public constructor.
''' We do not emit this constructor and do not call it
''' </summary>
<Extension()>
Friend Function IsDefaultValueTypeConstructor(method As MethodSymbol) As Boolean
Return method.IsImplicitlyDeclared AndAlso
method.ContainingType.IsValueType AndAlso
method.IsParameterlessConstructor()
End Function
<Extension()>
Friend Function IsReducedExtensionMethod(this As Symbol) As Boolean
Return this.Kind = SymbolKind.Method AndAlso DirectCast(this, MethodSymbol).IsReducedExtensionMethod
End Function
''' <summary>
''' Return the overridden symbol for either a method or property.
''' </summary>
<Extension()>
Friend Function OverriddenMember(sym As Symbol) As Symbol
Select Case sym.Kind
Case SymbolKind.Method
Return DirectCast(sym, MethodSymbol).OverriddenMethod
Case SymbolKind.Property
Return DirectCast(sym, PropertySymbol).OverriddenProperty
Case SymbolKind.Event
Return DirectCast(sym, EventSymbol).OverriddenEvent
Case Else
Return Nothing
End Select
End Function
''' <summary>
''' Return the arity of a member.
''' </summary>
<Extension()>
Friend Function GetArity(symbol As Symbol) As Integer
Select Case symbol.Kind
Case SymbolKind.Method
Return (DirectCast(symbol, MethodSymbol)).Arity
Case SymbolKind.NamedType, SymbolKind.ErrorType
Return (DirectCast(symbol, NamedTypeSymbol)).Arity
Case Else
Return 0
End Select
End Function
''' <summary>
''' Returns the Me symbol associated with a member.
''' sym must be a member (method, field or property)
''' </summary>
<Extension()>
Friend Function GetMeParameter(sym As Symbol) As ParameterSymbol
Select Case sym.Kind
Case SymbolKind.Method
Return DirectCast(sym, MethodSymbol).MeParameter
Case SymbolKind.Field
Return DirectCast(sym, FieldSymbol).MeParameter
Case SymbolKind.Property
Return DirectCast(sym, PropertySymbol).MeParameter
Case SymbolKind.Parameter
Return Nothing
Case Else
Throw ExceptionUtilities.UnexpectedValue(sym.Kind)
End Select
End Function
''' <summary>
''' Returns the parameters of a given method or property.
''' </summary>
<Extension()>
Friend Function GetParameters(sym As Symbol) As ImmutableArray(Of ParameterSymbol)
Select Case sym.Kind
Case SymbolKind.Method
Return DirectCast(sym, MethodSymbol).Parameters
Case SymbolKind.Property
Return DirectCast(sym, PropertySymbol).Parameters
Case Else
Return ImmutableArray(Of ParameterSymbol).Empty
End Select
End Function
<Extension()>
Friend Function OfMinimalArity(symbols As IEnumerable(Of NamespaceOrTypeSymbol)) As NamespaceOrTypeSymbol
Dim minAritySymbol As NamespaceOrTypeSymbol = Nothing
Dim minArity As Integer = Int32.MaxValue
For Each symbol In symbols
Dim arity As Integer = GetArity(symbol)
If arity < minArity Then
minArity = arity
minAritySymbol = symbol
End If
Next
Return minAritySymbol
End Function
<Extension()>
Friend Function UnwrapAlias(symbol As Symbol) As Symbol
Dim aliasSym = TryCast(symbol, AliasSymbol)
Return If(aliasSym Is Nothing, symbol, aliasSym.Target)
End Function
''' <summary>
''' Is symbol a user-defined operator method.
''' </summary>
<Extension()>
Friend Function IsUserDefinedOperator(symbol As Symbol) As Boolean
Return symbol.Kind = SymbolKind.Method AndAlso DirectCast(symbol, MethodSymbol).IsUserDefinedOperator()
End Function
''' <summary>
''' Does symbol or its containing type have Microsoft.CodeAnalysis.Embedded() attribute
''' </summary>
<Extension()>
Friend Function IsHiddenByCodeAnalysisEmbeddedAttribute(symbol As Symbol) As Boolean
' Only upper-level types should be checked
Dim upperLevelType = GetUpperLevelNamedTypeSymbol(symbol)
Return upperLevelType IsNot Nothing AndAlso upperLevelType.HasCodeAnalysisEmbeddedAttribute
End Function
''' <summary>
''' Does symbol or its containing type have Microsoft.VisualBasic.Embedded() attribute
''' </summary>
<Extension()>
Friend Function IsHiddenByVisualBasicEmbeddedAttribute(symbol As Symbol) As Boolean
' Only upper-level types should be checked
Dim upperLevelType = GetUpperLevelNamedTypeSymbol(symbol)
Return upperLevelType IsNot Nothing AndAlso upperLevelType.HasVisualBasicEmbeddedAttribute
End Function
''' <summary>
''' Gets the upper-level named type symbol, or returns Nothing if it does not exist.
''' </summary>
<Extension()>
Friend Function GetUpperLevelNamedTypeSymbol(symbol As Symbol) As NamedTypeSymbol
Dim upperLevelType = If(symbol.Kind = SymbolKind.NamedType, DirectCast(symbol, NamedTypeSymbol), symbol.ContainingType)
If upperLevelType Is Nothing Then
Return Nothing
End If
While upperLevelType.ContainingType IsNot Nothing
upperLevelType = upperLevelType.ContainingType
End While
Return upperLevelType
End Function
<Extension>
Friend Function GetDeclaringSyntaxNode(Of T As VisualBasicSyntaxNode)(this As Symbol) As T
For Each node In this.DeclaringSyntaxReferences.Select(Function(d) d.GetSyntax())
Dim node_T = TryCast(node, T)
If node_T IsNot Nothing Then
Return node_T
End If
Next
Debug.Assert(this.IsImplicitlyDeclared)
Return DirectCast(Symbol.GetDeclaringSyntaxNodeHelper(Of T)(this.Locations).FirstOrDefault, T)
End Function
<Extension>
Friend Function AsMember(Of T As Symbol)(origMember As T, type As NamedTypeSymbol) As T
Debug.Assert(origMember.IsDefinition)
' ContainingType is always a definition here which is a type definition so we can use "Is"
If type Is origMember.ContainingType Then
Return origMember
End If
Dim substituted = DirectCast(type, SubstitutedNamedType)
Return DirectCast(substituted.GetMemberForDefinition(origMember), T)
End Function
<Extension>
Friend Function EnsureVbSymbolOrNothing(Of TSource As ISymbol, TDestination As {Symbol, TSource})(symbol As TSource, paramName As String) As TDestination
Dim vbSymbol = TryCast(symbol, TDestination)
If vbSymbol Is Nothing AndAlso symbol IsNot Nothing Then
Throw New ArgumentException(VBResources.NotAVbSymbol, paramName)
End If
Return vbSymbol
End Function
<Extension>
Friend Function ContainingNonLambdaMember(member As Symbol) As Symbol
While If(member?.Kind = SymbolKind.Method, False) AndAlso DirectCast(member, MethodSymbol).MethodKind = MethodKind.AnonymousFunction
member = member.ContainingSymbol
End While
Return member
End Function
<Extension>
Friend Function ContainsTupleNames(member As Symbol) As Boolean
Select Case member.Kind
Case SymbolKind.Method
Dim method = DirectCast(member, MethodSymbol)
Return method.ReturnType.ContainsTupleNames() OrElse ContainsTupleNames(method.Parameters)
Case SymbolKind.Property
Dim [property] = DirectCast(member, PropertySymbol)
Return [property].Type.ContainsTupleNames() OrElse ContainsTupleNames([property].Parameters)
Case SymbolKind.Event
' We don't check the event Type directly because materializing it requires checking the tuple names in the type (to validate interface implementations)
Return ContainsTupleNames(DirectCast(member, EventSymbol).DelegateParameters)
Case Else
' We currently don't need to use this method for other kinds of symbols
Throw ExceptionUtilities.UnexpectedValue(member.Kind)
End Select
End Function
Private Function ContainsTupleNames(parameters As ImmutableArray(Of ParameterSymbol)) As Boolean
Return parameters.Any(Function(p) p.Type.ContainsTupleNames())
End Function
End Module
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports System.Runtime.CompilerServices
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols
Friend Module SymbolExtensions
Friend Const NamespaceKindNamespaceGroup As NamespaceKind = Nothing
''' <summary>
''' Does the compilation this symbol belongs to output to a winmdobj?
''' </summary>
<Extension()>
Friend Function IsCompilationOutputWinMdObj(symbol As Symbol) As Boolean
Dim comp = symbol.DeclaringCompilation
Return comp IsNot Nothing And comp.Options.OutputKind = OutputKind.WindowsRuntimeMetadata
End Function
''' <summary>
''' String such as 'class', 'interface' etc that can be used in error messages.
''' </summary>
<Extension()>
Friend Function GetKindText(target As Symbol) As String
Select Case target.Kind
Case SymbolKind.Namespace
Return "namespace"
Case SymbolKind.NamedType
Select Case DirectCast(target, TypeSymbol).TypeKind
Case TypeKind.Class
Return "class"
Case TypeKind.Enum
Return "enum"
Case TypeKind.Interface
Return "interface"
Case TypeKind.Structure
Return "structure"
Case TypeKind.Module
Return "module"
Case TypeKind.Delegate
' Dev10 error message format "... delegate Class goo ..." instead of "... delegate goo ..."
Return "delegate Class"
Case Else
'TODO: do we need string s for ByRef, Array, TypeParameter etc?
Return "type"
End Select
Case SymbolKind.Field, SymbolKind.Local, SymbolKind.Parameter, SymbolKind.RangeVariable
Return "variable"
Case SymbolKind.Method
Dim methodSymbol = DirectCast(target, MethodSymbol)
Select Case methodSymbol.MethodKind
Case MethodKind.Conversion, MethodKind.UserDefinedOperator, MethodKind.BuiltinOperator
Return "operator"
Case Else
If methodSymbol.IsSub Then
Return "sub"
Else
Return "function"
End If
End Select
Case SymbolKind.Property
If DirectCast(target, PropertySymbol).IsWithEvents Then
Return "WithEvents variable"
Else
Return "property"
End If
Case SymbolKind.Event
Return "event"
Case Else
Throw ExceptionUtilities.UnexpectedValue(target.Kind)
End Select
End Function
''' <summary>
''' String "ReadOnly", "WriteOnly", or "" describing the kind of property.
''' </summary>
<Extension()>
Friend Function GetPropertyKindText(target As PropertySymbol) As String
If target.IsWriteOnly Then
Return SyntaxFacts.GetText(SyntaxKind.WriteOnlyKeyword)
ElseIf target.IsReadOnly Then
Return SyntaxFacts.GetText(SyntaxKind.ReadOnlyKeyword)
Else
Return ""
End If
End Function
<Extension()>
Friend Function ToErrorMessageArgument(target As Symbol, Optional errorCode As ERRID = ERRID.ERR_None) As Object
If target.Kind = SymbolKind.Namespace Then
Dim ns As NamespaceSymbol = DirectCast(target, NamespaceSymbol)
If ns.IsGlobalNamespace Then
Return StringConstants.UnnamedNamespaceErrName
End If
End If
If errorCode = ERRID.ERR_TypeConflict6 Then
Return CustomSymbolDisplayFormatter.DefaultErrorFormat(target)
End If
Return target
End Function
''' <summary>
''' Checks if there is a name match with any type parameter.
''' </summary>
''' <param name="this"></param>
''' <param name="name"></param>
''' <returns></returns>
''' <remarks></remarks>
<Extension()>
Friend Function MatchesAnyName(this As ImmutableArray(Of TypeParameterSymbol), name As String) As Boolean
For Each tp In this
If IdentifierComparison.Comparer.Compare(name, tp.Name) = 0 Then
Return True
End If
Next
Return False
End Function
''' <summary>
''' Returns true if this symbols can overload another of the same kind.
''' </summary>
<Extension()>
Public Function IsOverloadable(symbol As Symbol) As Boolean
Dim kind = symbol.Kind
If kind = SymbolKind.Method Then
Return True
ElseIf kind <> SymbolKind.Property Then
Return False
End If
' uncommon case - WithEvents property do not overload. They behave like fields when OHI is concerned.
Return DirectCast(symbol, PropertySymbol).IsOverloadable
End Function
''' <summary>
''' Returns true if this property can overload another.
''' </summary>
<Extension()>
Public Function IsOverloadable(propertySymbol As PropertySymbol) As Boolean
Return Not propertySymbol.IsWithEvents
End Function
''' <summary>
''' Helper that tells if symbol has Overloads (hidebysig) on it
''' </summary>
<Extension()>
Friend Function IsOverloads(sym As Symbol) As Boolean
Debug.Assert(sym IsNot Nothing)
' methods and properties can overload.
Select Case sym.Kind
Case SymbolKind.Method
Dim method = DirectCast(sym, MethodSymbol)
If method.IsOverloads Then
Return True
End If
Case SymbolKind.Property
Dim prop = DirectCast(sym, PropertySymbol)
If prop.IsOverloads Then
Return True
End If
End Select
Return False
End Function
''' <summary>
''' Member that does not have Overloads, is considered Shadows (hidebyname)
''' </summary>
<Extension()>
Friend Function IsShadows(sym As Symbol) As Boolean
' everything that does not overload, shadows
Return Not sym.IsOverloads
End Function
''' <summary>
''' Is the symbol an instance member (i.e. access requires a receiver)
''' </summary>
<Extension()>
Friend Function IsInstanceMember(sym As Symbol) As Boolean
Select Case sym.Kind
Case SymbolKind.Field, SymbolKind.Property, SymbolKind.Method, SymbolKind.Event
Return Not sym.IsShared
Case Else
Return False
End Select
End Function
''' <summary>
''' Is this a member of a interface that requires implementation?
''' </summary>
<Extension()>
Friend Function RequiresImplementation(sym As Symbol) As Boolean
Select Case sym.Kind
Case SymbolKind.Method, SymbolKind.Property, SymbolKind.Event
' Note that in metadata, you can encounter methods that are static (shared) or non-virtual
' (for example TLBIMP VtblGap members), even though you can't define those in source.
Return sym.ContainingType.IsInterfaceType() AndAlso
Not sym.IsShared AndAlso Not sym.IsNotOverridable AndAlso
(sym.IsMustOverride OrElse sym.IsOverridable)
Case Else
Return False
End Select
End Function
<Extension()>
Friend Function IsMetadataVirtual(method As MethodSymbol) As Boolean
If method.IsOverridable OrElse
method.IsOverrides OrElse
method.IsMustOverride OrElse
Not method.ExplicitInterfaceImplementations.IsEmpty Then
Return True
End If
Dim definition As MethodSymbol = method.OriginalDefinition
Dim containingSourceType = TryCast(definition.ContainingSymbol, SourceNamedTypeSymbol)
Return containingSourceType IsNot Nothing AndAlso
containingSourceType.GetCorrespondingComClassInterfaceMethod(definition) IsNot Nothing
End Function
<Extension()>
Public Function IsAccessor(methodSymbol As MethodSymbol) As Boolean
Return methodSymbol.AssociatedSymbol IsNot Nothing
End Function
<Extension()>
Public Function IsAccessor(symbol As Symbol) As Boolean
Return symbol.Kind = SymbolKind.Method AndAlso IsAccessor(DirectCast(symbol, MethodSymbol))
End Function
<Extension()>
Public Function IsWithEventsProperty(symbol As Symbol) As Boolean
Return symbol.Kind = SymbolKind.Property AndAlso DirectCast(symbol, PropertySymbol).IsWithEvents
End Function
''' <summary>
''' Returns True for "regular" properties (those that are not WithEvents.
''' Typically used for OHI diagnostics where WithEvents properties are treated as variables.
''' </summary>
<Extension()>
Public Function IsPropertyAndNotWithEvents(symbol As Symbol) As Boolean
Return symbol.Kind = SymbolKind.Property AndAlso Not DirectCast(symbol, PropertySymbol).IsWithEvents
End Function
<Extension()>
Friend Function IsAnyConstructor(method As MethodSymbol) As Boolean
Dim kind = method.MethodKind
Return kind = MethodKind.Constructor OrElse kind = MethodKind.SharedConstructor
End Function
''' <summary>
''' default zero-init constructor symbol is added to a struct when it does not define
''' its own parameterless public constructor.
''' We do not emit this constructor and do not call it
''' </summary>
<Extension()>
Friend Function IsDefaultValueTypeConstructor(method As MethodSymbol) As Boolean
Return method.IsImplicitlyDeclared AndAlso
method.ContainingType.IsValueType AndAlso
method.IsParameterlessConstructor()
End Function
<Extension()>
Friend Function IsReducedExtensionMethod(this As Symbol) As Boolean
Return this.Kind = SymbolKind.Method AndAlso DirectCast(this, MethodSymbol).IsReducedExtensionMethod
End Function
''' <summary>
''' Return the overridden symbol for either a method or property.
''' </summary>
<Extension()>
Friend Function OverriddenMember(sym As Symbol) As Symbol
Select Case sym.Kind
Case SymbolKind.Method
Return DirectCast(sym, MethodSymbol).OverriddenMethod
Case SymbolKind.Property
Return DirectCast(sym, PropertySymbol).OverriddenProperty
Case SymbolKind.Event
Return DirectCast(sym, EventSymbol).OverriddenEvent
Case Else
Return Nothing
End Select
End Function
''' <summary>
''' Return the arity of a member.
''' </summary>
<Extension()>
Friend Function GetArity(symbol As Symbol) As Integer
Select Case symbol.Kind
Case SymbolKind.Method
Return (DirectCast(symbol, MethodSymbol)).Arity
Case SymbolKind.NamedType, SymbolKind.ErrorType
Return (DirectCast(symbol, NamedTypeSymbol)).Arity
Case Else
Return 0
End Select
End Function
''' <summary>
''' Returns the Me symbol associated with a member.
''' sym must be a member (method, field or property)
''' </summary>
<Extension()>
Friend Function GetMeParameter(sym As Symbol) As ParameterSymbol
Select Case sym.Kind
Case SymbolKind.Method
Return DirectCast(sym, MethodSymbol).MeParameter
Case SymbolKind.Field
Return DirectCast(sym, FieldSymbol).MeParameter
Case SymbolKind.Property
Return DirectCast(sym, PropertySymbol).MeParameter
Case SymbolKind.Parameter
Return Nothing
Case Else
Throw ExceptionUtilities.UnexpectedValue(sym.Kind)
End Select
End Function
''' <summary>
''' Returns the parameters of a given method or property.
''' </summary>
<Extension()>
Friend Function GetParameters(sym As Symbol) As ImmutableArray(Of ParameterSymbol)
Select Case sym.Kind
Case SymbolKind.Method
Return DirectCast(sym, MethodSymbol).Parameters
Case SymbolKind.Property
Return DirectCast(sym, PropertySymbol).Parameters
Case Else
Return ImmutableArray(Of ParameterSymbol).Empty
End Select
End Function
<Extension()>
Friend Function OfMinimalArity(symbols As IEnumerable(Of NamespaceOrTypeSymbol)) As NamespaceOrTypeSymbol
Dim minAritySymbol As NamespaceOrTypeSymbol = Nothing
Dim minArity As Integer = Int32.MaxValue
For Each symbol In symbols
Dim arity As Integer = GetArity(symbol)
If arity < minArity Then
minArity = arity
minAritySymbol = symbol
End If
Next
Return minAritySymbol
End Function
<Extension()>
Friend Function UnwrapAlias(symbol As Symbol) As Symbol
Dim aliasSym = TryCast(symbol, AliasSymbol)
Return If(aliasSym Is Nothing, symbol, aliasSym.Target)
End Function
''' <summary>
''' Is symbol a user-defined operator method.
''' </summary>
<Extension()>
Friend Function IsUserDefinedOperator(symbol As Symbol) As Boolean
Return symbol.Kind = SymbolKind.Method AndAlso DirectCast(symbol, MethodSymbol).IsUserDefinedOperator()
End Function
''' <summary>
''' Does symbol or its containing type have Microsoft.CodeAnalysis.Embedded() attribute
''' </summary>
<Extension()>
Friend Function IsHiddenByCodeAnalysisEmbeddedAttribute(symbol As Symbol) As Boolean
' Only upper-level types should be checked
Dim upperLevelType = GetUpperLevelNamedTypeSymbol(symbol)
Return upperLevelType IsNot Nothing AndAlso upperLevelType.HasCodeAnalysisEmbeddedAttribute
End Function
''' <summary>
''' Does symbol or its containing type have Microsoft.VisualBasic.Embedded() attribute
''' </summary>
<Extension()>
Friend Function IsHiddenByVisualBasicEmbeddedAttribute(symbol As Symbol) As Boolean
' Only upper-level types should be checked
Dim upperLevelType = GetUpperLevelNamedTypeSymbol(symbol)
Return upperLevelType IsNot Nothing AndAlso upperLevelType.HasVisualBasicEmbeddedAttribute
End Function
''' <summary>
''' Gets the upper-level named type symbol, or returns Nothing if it does not exist.
''' </summary>
<Extension()>
Friend Function GetUpperLevelNamedTypeSymbol(symbol As Symbol) As NamedTypeSymbol
Dim upperLevelType = If(symbol.Kind = SymbolKind.NamedType, DirectCast(symbol, NamedTypeSymbol), symbol.ContainingType)
If upperLevelType Is Nothing Then
Return Nothing
End If
While upperLevelType.ContainingType IsNot Nothing
upperLevelType = upperLevelType.ContainingType
End While
Return upperLevelType
End Function
<Extension>
Friend Function GetDeclaringSyntaxNode(Of T As VisualBasicSyntaxNode)(this As Symbol) As T
For Each node In this.DeclaringSyntaxReferences.Select(Function(d) d.GetSyntax())
Dim node_T = TryCast(node, T)
If node_T IsNot Nothing Then
Return node_T
End If
Next
Debug.Assert(this.IsImplicitlyDeclared)
Return DirectCast(Symbol.GetDeclaringSyntaxNodeHelper(Of T)(this.Locations).FirstOrDefault, T)
End Function
<Extension>
Friend Function AsMember(Of T As Symbol)(origMember As T, type As NamedTypeSymbol) As T
Debug.Assert(origMember.IsDefinition)
' ContainingType is always a definition here which is a type definition so we can use "Is"
If type Is origMember.ContainingType Then
Return origMember
End If
Dim substituted = DirectCast(type, SubstitutedNamedType)
Return DirectCast(substituted.GetMemberForDefinition(origMember), T)
End Function
<Extension>
Friend Function EnsureVbSymbolOrNothing(Of TSource As ISymbol, TDestination As {Symbol, TSource})(symbol As TSource, paramName As String) As TDestination
Dim vbSymbol = TryCast(symbol, TDestination)
If vbSymbol Is Nothing AndAlso symbol IsNot Nothing Then
Throw New ArgumentException(VBResources.NotAVbSymbol, paramName)
End If
Return vbSymbol
End Function
<Extension>
Friend Function ContainingNonLambdaMember(member As Symbol) As Symbol
While If(member?.Kind = SymbolKind.Method, False) AndAlso DirectCast(member, MethodSymbol).MethodKind = MethodKind.AnonymousFunction
member = member.ContainingSymbol
End While
Return member
End Function
<Extension>
Friend Function ContainsTupleNames(member As Symbol) As Boolean
Select Case member.Kind
Case SymbolKind.Method
Dim method = DirectCast(member, MethodSymbol)
Return method.ReturnType.ContainsTupleNames() OrElse ContainsTupleNames(method.Parameters)
Case SymbolKind.Property
Dim [property] = DirectCast(member, PropertySymbol)
Return [property].Type.ContainsTupleNames() OrElse ContainsTupleNames([property].Parameters)
Case SymbolKind.Event
' We don't check the event Type directly because materializing it requires checking the tuple names in the type (to validate interface implementations)
Return ContainsTupleNames(DirectCast(member, EventSymbol).DelegateParameters)
Case Else
' We currently don't need to use this method for other kinds of symbols
Throw ExceptionUtilities.UnexpectedValue(member.Kind)
End Select
End Function
Private Function ContainsTupleNames(parameters As ImmutableArray(Of ParameterSymbol)) As Boolean
Return parameters.Any(Function(p) p.Type.ContainsTupleNames())
End Function
End Module
End Namespace
| -1 |
dotnet/roslyn | 55,877 | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute | Part of C# 10 support | davidwengier | 2021-08-25T05:36:27Z | 2021-08-30T20:47:11Z | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | 023d3ca2b5fb429f0b3dcc1efeed39442e232dba | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute. Part of C# 10 support | ./src/Features/LanguageServer/Protocol/Handler/DocumentChanges/DidCloseHandler.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Composition;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Host.Mef;
using Roslyn.Utilities;
using LSP = Microsoft.VisualStudio.LanguageServer.Protocol;
namespace Microsoft.CodeAnalysis.LanguageServer.Handler.DocumentChanges
{
[ExportRoslynLanguagesLspRequestHandlerProvider, Shared]
[ProvidesMethod(LSP.Methods.TextDocumentDidCloseName)]
internal class DidCloseHandler : AbstractStatelessRequestHandler<LSP.DidCloseTextDocumentParams, object?>
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public DidCloseHandler()
{
}
public override string Method => LSP.Methods.TextDocumentDidCloseName;
public override bool MutatesSolutionState => true;
public override bool RequiresLSPSolution => false;
public override LSP.TextDocumentIdentifier? GetTextDocumentIdentifier(LSP.DidCloseTextDocumentParams request) => request.TextDocument;
public override Task<object?> HandleRequestAsync(LSP.DidCloseTextDocumentParams request, RequestContext context, CancellationToken cancellationToken)
{
// GetTextDocumentIdentifier returns null to avoid creating the solution, so the queue is not able to log the uri.
context.TraceInformation($"didClose for {request.TextDocument.Uri}");
context.StopTracking(request.TextDocument.Uri);
return SpecializedTasks.Default<object>();
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Composition;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Host.Mef;
using Roslyn.Utilities;
using LSP = Microsoft.VisualStudio.LanguageServer.Protocol;
namespace Microsoft.CodeAnalysis.LanguageServer.Handler.DocumentChanges
{
[ExportRoslynLanguagesLspRequestHandlerProvider, Shared]
[ProvidesMethod(LSP.Methods.TextDocumentDidCloseName)]
internal class DidCloseHandler : AbstractStatelessRequestHandler<LSP.DidCloseTextDocumentParams, object?>
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public DidCloseHandler()
{
}
public override string Method => LSP.Methods.TextDocumentDidCloseName;
public override bool MutatesSolutionState => true;
public override bool RequiresLSPSolution => false;
public override LSP.TextDocumentIdentifier? GetTextDocumentIdentifier(LSP.DidCloseTextDocumentParams request) => request.TextDocument;
public override Task<object?> HandleRequestAsync(LSP.DidCloseTextDocumentParams request, RequestContext context, CancellationToken cancellationToken)
{
// GetTextDocumentIdentifier returns null to avoid creating the solution, so the queue is not able to log the uri.
context.TraceInformation($"didClose for {request.TextDocument.Uri}");
context.StopTracking(request.TextDocument.Uri);
return SpecializedTasks.Default<object>();
}
}
}
| -1 |
dotnet/roslyn | 55,877 | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute | Part of C# 10 support | davidwengier | 2021-08-25T05:36:27Z | 2021-08-30T20:47:11Z | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | 023d3ca2b5fb429f0b3dcc1efeed39442e232dba | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute. Part of C# 10 support | ./src/Analyzers/VisualBasic/Tests/RemoveRedundantEquality/RemoveRedundantEqualityTests.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports VerifyVB = Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions.VisualBasicCodeFixVerifier(Of
Microsoft.CodeAnalysis.VisualBasic.RemoveRedundantEquality.VisualBasicRemoveRedundantEqualityDiagnosticAnalyzer,
Microsoft.CodeAnalysis.RemoveRedundantEquality.RemoveRedundantEqualityCodeFixProvider)
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.RemoveRedundantEquality
Public Class RemoveRedundantEqualityTests
<Fact>
Public Async Function TestSimpleCaseForEqualsTrue() As Task
Dim code = "
Public Module Module1
Public Function M1(x As Boolean) As Boolean
Return x [|=|] True
End Function
End Module
"
Dim fixedCode = "
Public Module Module1
Public Function M1(x As Boolean) As Boolean
Return x
End Function
End Module
"
Await VerifyVB.VerifyCodeFixAsync(code, fixedCode)
End Function
<Fact>
Public Async Function TestSimpleCaseForEqualsFalse_NoDiagnostics() As Task
Dim code = "
Public Module Module1
Public Function M1(x As Boolean) As Boolean
Return x = False
End Function
End Module
"
Await VerifyVB.VerifyAnalyzerAsync(code)
End Function
<Fact>
Public Async Function TestSimpleCaseForNotEqualsFalse() As Task
Dim code = "
Public Module Module1
Public Function M1(x As Boolean) As Boolean
Return x [|<>|] False
End Function
End Module
"
Dim fixedCode = "
Public Module Module1
Public Function M1(x As Boolean) As Boolean
Return x
End Function
End Module
"
Await VerifyVB.VerifyCodeFixAsync(code, fixedCode)
End Function
<Fact>
Public Async Function TestSimpleCaseForNotEqualsTrue_NoDiagnostics() As Task
Dim code = "
Public Module Module1
Public Function M1(x As Boolean) As Boolean
Return x <> True
End Function
End Module
"
Await VerifyVB.VerifyAnalyzerAsync(code)
End Function
<Fact>
Public Async Function TestNullable_NoDiagnostics() As Task
Dim code = "
Public Module Module1
public Function M1(x As Boolean?) As Boolean
Return x = True
End Function
End Module
"
Await VerifyVB.VerifyAnalyzerAsync(code)
End Function
<Fact>
Public Async Function TestWhenConstant_NoDiagnostics() As Task
Dim code = "
Public Class C
Public Const MyTrueConstant As Boolean = True
Public Function M1(x As Boolean) As Boolean
Return x = MyTrueConstant
End Function
End Class
"
Await VerifyVB.VerifyAnalyzerAsync(code)
End Function
<Fact>
Public Async Function TestOverloadedOperator_NoDiagnostics() As Task
Dim code = "
Public Class C
Public Shared Operator =(a As C, b As Boolean) As Boolean
Return False
End Operator
Public Shared Operator <>(a As C, b As Boolean) As Boolean
Return True
End Operator
Public Function M1(x As C) As Boolean
Return x = True
End Function
End Class
"
Await VerifyVB.VerifyAnalyzerAsync(code)
End Function
<Fact>
Public Async Function TestOnLeftHandSide() As Task
Dim code = "
Public Module Module1
Public Function M1(x As Boolean) As Boolean
Return True [|=|] x
End Function
End Module
"
Dim fixedCode = "
Public Module Module1
Public Function M1(x As Boolean) As Boolean
Return x
End Function
End Module
"
Await VerifyVB.VerifyCodeFixAsync(code, fixedCode)
End Function
<Fact>
Public Async Function TestInArgument() As Task
Dim code = "
Public Module Module1
Public Function M1(x As Boolean) As Boolean
Return M1(x [|=|] True)
End Function
End Module
"
Dim fixedCode = "
Public Module Module1
Public Function M1(x As Boolean) As Boolean
Return M1(x)
End Function
End Module
"
Await VerifyVB.VerifyCodeFixAsync(code, fixedCode)
End Function
<Fact>
Public Async Function TestFixAll() As Task
Dim code = "
Public Module Module1
Public Function M1(x As Boolean) As Boolean
Return True [|=|] x
End Function
Public Function M2(x As Boolean) As Boolean
Return x [|<>|] False
End Function
Public Function M3(x As Boolean) As Boolean
Return x [|=|] True [|=|] True
End Function
End Module
"
Dim fixedCode = "
Public Module Module1
Public Function M1(x As Boolean) As Boolean
Return x
End Function
Public Function M2(x As Boolean) As Boolean
Return x
End Function
Public Function M3(x As Boolean) As Boolean
Return x
End Function
End Module
"
Await VerifyVB.VerifyCodeFixAsync(code, fixedCode)
End Function
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports VerifyVB = Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions.VisualBasicCodeFixVerifier(Of
Microsoft.CodeAnalysis.VisualBasic.RemoveRedundantEquality.VisualBasicRemoveRedundantEqualityDiagnosticAnalyzer,
Microsoft.CodeAnalysis.RemoveRedundantEquality.RemoveRedundantEqualityCodeFixProvider)
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.RemoveRedundantEquality
Public Class RemoveRedundantEqualityTests
<Fact>
Public Async Function TestSimpleCaseForEqualsTrue() As Task
Dim code = "
Public Module Module1
Public Function M1(x As Boolean) As Boolean
Return x [|=|] True
End Function
End Module
"
Dim fixedCode = "
Public Module Module1
Public Function M1(x As Boolean) As Boolean
Return x
End Function
End Module
"
Await VerifyVB.VerifyCodeFixAsync(code, fixedCode)
End Function
<Fact>
Public Async Function TestSimpleCaseForEqualsFalse_NoDiagnostics() As Task
Dim code = "
Public Module Module1
Public Function M1(x As Boolean) As Boolean
Return x = False
End Function
End Module
"
Await VerifyVB.VerifyAnalyzerAsync(code)
End Function
<Fact>
Public Async Function TestSimpleCaseForNotEqualsFalse() As Task
Dim code = "
Public Module Module1
Public Function M1(x As Boolean) As Boolean
Return x [|<>|] False
End Function
End Module
"
Dim fixedCode = "
Public Module Module1
Public Function M1(x As Boolean) As Boolean
Return x
End Function
End Module
"
Await VerifyVB.VerifyCodeFixAsync(code, fixedCode)
End Function
<Fact>
Public Async Function TestSimpleCaseForNotEqualsTrue_NoDiagnostics() As Task
Dim code = "
Public Module Module1
Public Function M1(x As Boolean) As Boolean
Return x <> True
End Function
End Module
"
Await VerifyVB.VerifyAnalyzerAsync(code)
End Function
<Fact>
Public Async Function TestNullable_NoDiagnostics() As Task
Dim code = "
Public Module Module1
public Function M1(x As Boolean?) As Boolean
Return x = True
End Function
End Module
"
Await VerifyVB.VerifyAnalyzerAsync(code)
End Function
<Fact>
Public Async Function TestWhenConstant_NoDiagnostics() As Task
Dim code = "
Public Class C
Public Const MyTrueConstant As Boolean = True
Public Function M1(x As Boolean) As Boolean
Return x = MyTrueConstant
End Function
End Class
"
Await VerifyVB.VerifyAnalyzerAsync(code)
End Function
<Fact>
Public Async Function TestOverloadedOperator_NoDiagnostics() As Task
Dim code = "
Public Class C
Public Shared Operator =(a As C, b As Boolean) As Boolean
Return False
End Operator
Public Shared Operator <>(a As C, b As Boolean) As Boolean
Return True
End Operator
Public Function M1(x As C) As Boolean
Return x = True
End Function
End Class
"
Await VerifyVB.VerifyAnalyzerAsync(code)
End Function
<Fact>
Public Async Function TestOnLeftHandSide() As Task
Dim code = "
Public Module Module1
Public Function M1(x As Boolean) As Boolean
Return True [|=|] x
End Function
End Module
"
Dim fixedCode = "
Public Module Module1
Public Function M1(x As Boolean) As Boolean
Return x
End Function
End Module
"
Await VerifyVB.VerifyCodeFixAsync(code, fixedCode)
End Function
<Fact>
Public Async Function TestInArgument() As Task
Dim code = "
Public Module Module1
Public Function M1(x As Boolean) As Boolean
Return M1(x [|=|] True)
End Function
End Module
"
Dim fixedCode = "
Public Module Module1
Public Function M1(x As Boolean) As Boolean
Return M1(x)
End Function
End Module
"
Await VerifyVB.VerifyCodeFixAsync(code, fixedCode)
End Function
<Fact>
Public Async Function TestFixAll() As Task
Dim code = "
Public Module Module1
Public Function M1(x As Boolean) As Boolean
Return True [|=|] x
End Function
Public Function M2(x As Boolean) As Boolean
Return x [|<>|] False
End Function
Public Function M3(x As Boolean) As Boolean
Return x [|=|] True [|=|] True
End Function
End Module
"
Dim fixedCode = "
Public Module Module1
Public Function M1(x As Boolean) As Boolean
Return x
End Function
Public Function M2(x As Boolean) As Boolean
Return x
End Function
Public Function M3(x As Boolean) As Boolean
Return x
End Function
End Module
"
Await VerifyVB.VerifyCodeFixAsync(code, fixedCode)
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,877 | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute | Part of C# 10 support | davidwengier | 2021-08-25T05:36:27Z | 2021-08-30T20:47:11Z | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | 023d3ca2b5fb429f0b3dcc1efeed39442e232dba | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute. Part of C# 10 support | ./src/Features/VisualBasic/Portable/Completion/KeywordRecommenders/Declarations/DelegateKeywordRecommender.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports System.Threading
Imports Microsoft.CodeAnalysis.Completion.Providers
Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery
Imports Microsoft.CodeAnalysis.VisualBasic.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders.Declarations
''' <summary>
''' Recommends the "Delegate" keyword in member declaration contexts
''' </summary>
Friend Class DelegateKeywordRecommender
Inherits AbstractKeywordRecommender
Private Shared ReadOnly s_keywords As ImmutableArray(Of RecommendedKeyword) =
ImmutableArray.Create(New RecommendedKeyword("Delegate", VBFeaturesResources.Used_to_declare_a_delegate_A_delegate_is_a_reference_type_that_refers_to_a_shared_method_of_a_type_or_to_an_instance_method_of_an_object_Any_procedure_that_is_convertible_or_that_has_matching_parameter_types_and_return_type_may_be_used_to_create_an_instance_of_this_delegate_class))
Protected Overrides Function RecommendKeywords(context As VisualBasicSyntaxContext, cancellationToken As CancellationToken) As ImmutableArray(Of RecommendedKeyword)
If context.IsTypeDeclarationKeywordContext Then
Dim modifiers = context.ModifierCollectionFacts
If modifiers.CouldApplyToOneOf(PossibleDeclarationTypes.Delegate) Then
Return s_keywords
End If
End If
Return ImmutableArray(Of RecommendedKeyword).Empty
End Function
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports System.Threading
Imports Microsoft.CodeAnalysis.Completion.Providers
Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery
Imports Microsoft.CodeAnalysis.VisualBasic.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders.Declarations
''' <summary>
''' Recommends the "Delegate" keyword in member declaration contexts
''' </summary>
Friend Class DelegateKeywordRecommender
Inherits AbstractKeywordRecommender
Private Shared ReadOnly s_keywords As ImmutableArray(Of RecommendedKeyword) =
ImmutableArray.Create(New RecommendedKeyword("Delegate", VBFeaturesResources.Used_to_declare_a_delegate_A_delegate_is_a_reference_type_that_refers_to_a_shared_method_of_a_type_or_to_an_instance_method_of_an_object_Any_procedure_that_is_convertible_or_that_has_matching_parameter_types_and_return_type_may_be_used_to_create_an_instance_of_this_delegate_class))
Protected Overrides Function RecommendKeywords(context As VisualBasicSyntaxContext, cancellationToken As CancellationToken) As ImmutableArray(Of RecommendedKeyword)
If context.IsTypeDeclarationKeywordContext Then
Dim modifiers = context.ModifierCollectionFacts
If modifiers.CouldApplyToOneOf(PossibleDeclarationTypes.Delegate) Then
Return s_keywords
End If
End If
Return ImmutableArray(Of RecommendedKeyword).Empty
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,877 | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute | Part of C# 10 support | davidwengier | 2021-08-25T05:36:27Z | 2021-08-30T20:47:11Z | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | 023d3ca2b5fb429f0b3dcc1efeed39442e232dba | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute. Part of C# 10 support | ./src/Workspaces/Core/Portable/Options/IDocumentOptionsProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Threading;
using System.Threading.Tasks;
namespace Microsoft.CodeAnalysis.Options
{
/// <summary>
/// Implemented to provide options that apply to specific documents, like from .editorconfig files.
/// </summary>
/// <remarks>
/// This is passed to <see cref="IOptionService.RegisterDocumentOptionsProvider(IDocumentOptionsProvider)"/> to activate it
/// for a workspace. This instance then lives around for the lifetime of the workspace.
/// </remarks>
internal interface IDocumentOptionsProvider
{
/// <summary>
/// Fetches a <see cref="IDocumentOptions"/> for the given document. Any asynchronous work (looking for config files, etc.)
/// should be done here. Can return a null-valued task to mean there is no options being provided for this document.
/// </summary>
Task<IDocumentOptions?> GetOptionsForDocumentAsync(Document document, CancellationToken cancellationToken);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Threading;
using System.Threading.Tasks;
namespace Microsoft.CodeAnalysis.Options
{
/// <summary>
/// Implemented to provide options that apply to specific documents, like from .editorconfig files.
/// </summary>
/// <remarks>
/// This is passed to <see cref="IOptionService.RegisterDocumentOptionsProvider(IDocumentOptionsProvider)"/> to activate it
/// for a workspace. This instance then lives around for the lifetime of the workspace.
/// </remarks>
internal interface IDocumentOptionsProvider
{
/// <summary>
/// Fetches a <see cref="IDocumentOptions"/> for the given document. Any asynchronous work (looking for config files, etc.)
/// should be done here. Can return a null-valued task to mean there is no options being provided for this document.
/// </summary>
Task<IDocumentOptions?> GetOptionsForDocumentAsync(Document document, CancellationToken cancellationToken);
}
}
| -1 |
dotnet/roslyn | 55,877 | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute | Part of C# 10 support | davidwengier | 2021-08-25T05:36:27Z | 2021-08-30T20:47:11Z | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | 023d3ca2b5fb429f0b3dcc1efeed39442e232dba | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute. Part of C# 10 support | ./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/VisualBasic/Utilities/SyntaxKindSet.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Namespace Microsoft.CodeAnalysis.VisualBasic.Utilities
Friend Module SyntaxKindSet
Public ReadOnly AllOperators As ISet(Of SyntaxKind) = New HashSet(Of SyntaxKind)(SyntaxFacts.EqualityComparer) From
{
SyntaxKind.ExclamationToken,
SyntaxKind.AtToken,
SyntaxKind.AmpersandToken,
SyntaxKind.SingleQuoteToken,
SyntaxKind.SemicolonToken,
SyntaxKind.AsteriskToken,
SyntaxKind.PlusToken,
SyntaxKind.MinusToken,
SyntaxKind.DotToken,
SyntaxKind.SlashToken,
SyntaxKind.LessThanToken,
SyntaxKind.LessThanEqualsToken,
SyntaxKind.LessThanGreaterThanToken,
SyntaxKind.EqualsToken,
SyntaxKind.GreaterThanToken,
SyntaxKind.GreaterThanEqualsToken,
SyntaxKind.BackslashToken,
SyntaxKind.CaretToken,
SyntaxKind.ColonEqualsToken,
SyntaxKind.AmpersandEqualsToken,
SyntaxKind.AsteriskEqualsToken,
SyntaxKind.PlusEqualsToken,
SyntaxKind.MinusEqualsToken,
SyntaxKind.SlashEqualsToken,
SyntaxKind.BackslashEqualsToken,
SyntaxKind.CaretEqualsToken,
SyntaxKind.LessThanLessThanToken,
SyntaxKind.GreaterThanGreaterThanToken,
SyntaxKind.LessThanLessThanEqualsToken,
SyntaxKind.GreaterThanGreaterThanEqualsToken
}
End Module
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Namespace Microsoft.CodeAnalysis.VisualBasic.Utilities
Friend Module SyntaxKindSet
Public ReadOnly AllOperators As ISet(Of SyntaxKind) = New HashSet(Of SyntaxKind)(SyntaxFacts.EqualityComparer) From
{
SyntaxKind.ExclamationToken,
SyntaxKind.AtToken,
SyntaxKind.AmpersandToken,
SyntaxKind.SingleQuoteToken,
SyntaxKind.SemicolonToken,
SyntaxKind.AsteriskToken,
SyntaxKind.PlusToken,
SyntaxKind.MinusToken,
SyntaxKind.DotToken,
SyntaxKind.SlashToken,
SyntaxKind.LessThanToken,
SyntaxKind.LessThanEqualsToken,
SyntaxKind.LessThanGreaterThanToken,
SyntaxKind.EqualsToken,
SyntaxKind.GreaterThanToken,
SyntaxKind.GreaterThanEqualsToken,
SyntaxKind.BackslashToken,
SyntaxKind.CaretToken,
SyntaxKind.ColonEqualsToken,
SyntaxKind.AmpersandEqualsToken,
SyntaxKind.AsteriskEqualsToken,
SyntaxKind.PlusEqualsToken,
SyntaxKind.MinusEqualsToken,
SyntaxKind.SlashEqualsToken,
SyntaxKind.BackslashEqualsToken,
SyntaxKind.CaretEqualsToken,
SyntaxKind.LessThanLessThanToken,
SyntaxKind.GreaterThanGreaterThanToken,
SyntaxKind.LessThanLessThanEqualsToken,
SyntaxKind.GreaterThanGreaterThanEqualsToken
}
End Module
End Namespace
| -1 |
dotnet/roslyn | 55,877 | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute | Part of C# 10 support | davidwengier | 2021-08-25T05:36:27Z | 2021-08-30T20:47:11Z | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | 023d3ca2b5fb429f0b3dcc1efeed39442e232dba | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute. Part of C# 10 support | ./src/Dependencies/Collections/Internal/RoslynUnsafe.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Runtime.CompilerServices;
namespace Microsoft.CodeAnalysis.Collections.Internal
{
internal static unsafe class RoslynUnsafe
{
/// <summary>
/// Returns a by-ref to type <typeparamref name="T"/> that is a null reference.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ref T NullRef<T>()
=> ref Unsafe.AsRef<T>(null);
/// <summary>
/// Returns if a given by-ref to type <typeparamref name="T"/> is a null reference.
/// </summary>
/// <remarks>
/// This check is conceptually similar to <c>(void*)(&source) == nullptr</c>.
/// </remarks>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool IsNullRef<T>(ref T source)
=> Unsafe.AsPointer(ref source) == null;
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Runtime.CompilerServices;
namespace Microsoft.CodeAnalysis.Collections.Internal
{
internal static unsafe class RoslynUnsafe
{
/// <summary>
/// Returns a by-ref to type <typeparamref name="T"/> that is a null reference.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ref T NullRef<T>()
=> ref Unsafe.AsRef<T>(null);
/// <summary>
/// Returns if a given by-ref to type <typeparamref name="T"/> is a null reference.
/// </summary>
/// <remarks>
/// This check is conceptually similar to <c>(void*)(&source) == nullptr</c>.
/// </remarks>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool IsNullRef<T>(ref T source)
=> Unsafe.AsPointer(ref source) == null;
}
}
| -1 |
dotnet/roslyn | 55,877 | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute | Part of C# 10 support | davidwengier | 2021-08-25T05:36:27Z | 2021-08-30T20:47:11Z | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | 023d3ca2b5fb429f0b3dcc1efeed39442e232dba | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute. Part of C# 10 support | ./src/EditorFeatures/Core/ExternalAccess/VSTypeScript/Api/IVSTypeScriptFormattingInteractionService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript.Api
{
internal interface IVSTypeScriptFormattingInteractionService
{
bool SupportsFormatDocument { get; }
bool SupportsFormatSelection { get; }
bool SupportsFormatOnPaste { get; }
bool SupportsFormatOnReturn { get; }
/// <summary>
/// True if this service would like to format the document based on the user typing the
/// provided character.
/// </summary>
bool SupportsFormattingOnTypedCharacter(Document document, char ch);
/// <summary>
/// Returns the text changes necessary to format the document. If "textSpan" is provided,
/// only the text changes necessary to format that span are needed.
/// </summary>
Task<ImmutableArray<TextChange>> GetFormattingChangesAsync(Document document, TextSpan? textSpan, DocumentOptionSet? documentOptions, CancellationToken cancellationToken);
/// <summary>
/// Returns the text changes necessary to format the document on paste operation.
/// </summary>
Task<ImmutableArray<TextChange>> GetFormattingChangesOnPasteAsync(Document document, TextSpan textSpan, DocumentOptionSet? documentOptions, CancellationToken cancellationToken);
/// <summary>
/// Returns the text changes necessary to format the document after the user enters a
/// character. The position provided is the position of the caret in the document after
/// the character been inserted into the document.
/// </summary>
Task<ImmutableArray<TextChange>> GetFormattingChangesAsync(Document document, char typedChar, int position, DocumentOptionSet? documentOptions, CancellationToken cancellationToken);
/// <summary>
/// Returns the text changes necessary to format the document after the user enters a Return
/// The position provided is the position of the caret in the document after Return.</summary>
Task<ImmutableArray<TextChange>> GetFormattingChangesOnReturnAsync(Document document, int position, DocumentOptionSet? documentOptions, CancellationToken cancellationToken);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript.Api
{
internal interface IVSTypeScriptFormattingInteractionService
{
bool SupportsFormatDocument { get; }
bool SupportsFormatSelection { get; }
bool SupportsFormatOnPaste { get; }
bool SupportsFormatOnReturn { get; }
/// <summary>
/// True if this service would like to format the document based on the user typing the
/// provided character.
/// </summary>
bool SupportsFormattingOnTypedCharacter(Document document, char ch);
/// <summary>
/// Returns the text changes necessary to format the document. If "textSpan" is provided,
/// only the text changes necessary to format that span are needed.
/// </summary>
Task<ImmutableArray<TextChange>> GetFormattingChangesAsync(Document document, TextSpan? textSpan, DocumentOptionSet? documentOptions, CancellationToken cancellationToken);
/// <summary>
/// Returns the text changes necessary to format the document on paste operation.
/// </summary>
Task<ImmutableArray<TextChange>> GetFormattingChangesOnPasteAsync(Document document, TextSpan textSpan, DocumentOptionSet? documentOptions, CancellationToken cancellationToken);
/// <summary>
/// Returns the text changes necessary to format the document after the user enters a
/// character. The position provided is the position of the caret in the document after
/// the character been inserted into the document.
/// </summary>
Task<ImmutableArray<TextChange>> GetFormattingChangesAsync(Document document, char typedChar, int position, DocumentOptionSet? documentOptions, CancellationToken cancellationToken);
/// <summary>
/// Returns the text changes necessary to format the document after the user enters a Return
/// The position provided is the position of the caret in the document after Return.</summary>
Task<ImmutableArray<TextChange>> GetFormattingChangesOnReturnAsync(Document document, int position, DocumentOptionSet? documentOptions, CancellationToken cancellationToken);
}
}
| -1 |
dotnet/roslyn | 55,877 | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute | Part of C# 10 support | davidwengier | 2021-08-25T05:36:27Z | 2021-08-30T20:47:11Z | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | 023d3ca2b5fb429f0b3dcc1efeed39442e232dba | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute. Part of C# 10 support | ./src/Compilers/Core/Portable/Symbols/ManagedKind.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// Enumeration of the possible "degrees of managed" for a type.
/// </summary>
[Flags]
internal enum ManagedKind : byte
{
Unknown = 0,
Unmanaged = 1,
UnmanagedWithGenerics = 2, // considered "managed" in C# 7.3 and earlier
Managed = 3,
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// Enumeration of the possible "degrees of managed" for a type.
/// </summary>
[Flags]
internal enum ManagedKind : byte
{
Unknown = 0,
Unmanaged = 1,
UnmanagedWithGenerics = 2, // considered "managed" in C# 7.3 and earlier
Managed = 3,
}
}
| -1 |
dotnet/roslyn | 55,877 | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute | Part of C# 10 support | davidwengier | 2021-08-25T05:36:27Z | 2021-08-30T20:47:11Z | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | 023d3ca2b5fb429f0b3dcc1efeed39442e232dba | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute. Part of C# 10 support | ./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Options/EditorConfig/EditorConfigStorageLocationExtensions.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using Microsoft.CodeAnalysis.Diagnostics;
namespace Microsoft.CodeAnalysis.Options
{
internal static class EditorConfigStorageLocationExtensions
{
public static bool TryGetOption(this IEditorConfigStorageLocation editorConfigStorageLocation, AnalyzerConfigOptions analyzerConfigOptions, Type type, out object value)
{
// This is a workaround until we have an API for enumeratings AnalyzerConfigOptions. See https://github.com/dotnet/roslyn/issues/41840
var backingField = analyzerConfigOptions.GetType().GetField("_backing", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
var backing = backingField?.GetValue(analyzerConfigOptions);
if (backing is IReadOnlyDictionary<string, string> backingDictionary)
{
return editorConfigStorageLocation.TryGetOption(backingDictionary, type, out value);
}
value = null;
return false;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using Microsoft.CodeAnalysis.Diagnostics;
namespace Microsoft.CodeAnalysis.Options
{
internal static class EditorConfigStorageLocationExtensions
{
public static bool TryGetOption(this IEditorConfigStorageLocation editorConfigStorageLocation, AnalyzerConfigOptions analyzerConfigOptions, Type type, out object value)
{
// This is a workaround until we have an API for enumeratings AnalyzerConfigOptions. See https://github.com/dotnet/roslyn/issues/41840
var backingField = analyzerConfigOptions.GetType().GetField("_backing", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
var backing = backingField?.GetValue(analyzerConfigOptions);
if (backing is IReadOnlyDictionary<string, string> backingDictionary)
{
return editorConfigStorageLocation.TryGetOption(backingDictionary, type, out value);
}
value = null;
return false;
}
}
}
| -1 |
dotnet/roslyn | 55,877 | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute | Part of C# 10 support | davidwengier | 2021-08-25T05:36:27Z | 2021-08-30T20:47:11Z | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | 023d3ca2b5fb429f0b3dcc1efeed39442e232dba | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute. Part of C# 10 support | ./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/CodeStyle/CSharpCodeStyleOptions.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis.AddImports;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.Options;
namespace Microsoft.CodeAnalysis.CSharp.CodeStyle
{
internal static partial class CSharpCodeStyleOptions
{
private static readonly CodeStyleOption2<bool> s_trueWithSuggestionEnforcement = new(value: true, notification: NotificationOption2.Suggestion);
private static readonly CodeStyleOption2<bool> s_trueWithSilentEnforcement = new(value: true, notification: NotificationOption2.Silent);
private static readonly ImmutableArray<IOption2>.Builder s_allOptionsBuilder = ImmutableArray.CreateBuilder<IOption2>();
internal static ImmutableArray<IOption2> AllOptions { get; }
private static Option2<T> CreateOption<T>(
OptionGroup group, string name, T defaultValue, OptionStorageLocation2 storageLocation)
=> CodeStyleHelpers.CreateOption(
group, nameof(CSharpCodeStyleOptions), name, defaultValue,
s_allOptionsBuilder, storageLocation);
private static Option2<T> CreateOption<T>(
OptionGroup group, string name, T defaultValue, OptionStorageLocation2 storageLocation1, OptionStorageLocation2 storageLocation2)
=> CodeStyleHelpers.CreateOption(
group, nameof(CSharpCodeStyleOptions), name, defaultValue,
s_allOptionsBuilder, storageLocation1, storageLocation2);
private static Option2<CodeStyleOption2<bool>> CreateOption(
OptionGroup group, string name, CodeStyleOption2<bool> defaultValue, string editorconfigKeyName, string roamingProfileStorageKeyName)
=> CreateOption(
group, name, defaultValue,
EditorConfigStorageLocation.ForBoolCodeStyleOption(editorconfigKeyName, defaultValue),
new RoamingProfileStorageLocation(roamingProfileStorageKeyName));
private static Option2<CodeStyleOption2<string>> CreateOption(
OptionGroup group, string name, CodeStyleOption2<string> defaultValue, string editorconfigKeyName, string roamingProfileStorageKeyName)
=> CreateOption(
group, name, defaultValue,
EditorConfigStorageLocation.ForStringCodeStyleOption(editorconfigKeyName, defaultValue),
new RoamingProfileStorageLocation(roamingProfileStorageKeyName));
public static readonly Option2<CodeStyleOption2<bool>> VarForBuiltInTypes = CreateOption(
CSharpCodeStyleOptionGroups.VarPreferences, nameof(VarForBuiltInTypes),
defaultValue: CodeStyleOption2<bool>.Default,
"csharp_style_var_for_built_in_types",
"TextEditor.CSharp.Specific.UseImplicitTypeForIntrinsicTypes");
public static readonly Option2<CodeStyleOption2<bool>> VarWhenTypeIsApparent = CreateOption(
CSharpCodeStyleOptionGroups.VarPreferences, nameof(VarWhenTypeIsApparent),
defaultValue: CodeStyleOption2<bool>.Default,
"csharp_style_var_when_type_is_apparent",
"TextEditor.CSharp.Specific.UseImplicitTypeWhereApparent");
public static readonly Option2<CodeStyleOption2<bool>> VarElsewhere = CreateOption(
CSharpCodeStyleOptionGroups.VarPreferences, nameof(VarElsewhere),
defaultValue: CodeStyleOption2<bool>.Default,
"csharp_style_var_elsewhere",
"TextEditor.CSharp.Specific.UseImplicitTypeWherePossible");
public static readonly Option2<CodeStyleOption2<bool>> PreferConditionalDelegateCall = CreateOption(
CSharpCodeStyleOptionGroups.NullCheckingPreferences, nameof(PreferConditionalDelegateCall),
defaultValue: s_trueWithSuggestionEnforcement,
"csharp_style_conditional_delegate_call",
"TextEditor.CSharp.Specific.PreferConditionalDelegateCall");
public static readonly Option2<CodeStyleOption2<bool>> PreferSwitchExpression = CreateOption(
CSharpCodeStyleOptionGroups.PatternMatching, nameof(PreferSwitchExpression),
defaultValue: s_trueWithSuggestionEnforcement,
"csharp_style_prefer_switch_expression",
$"TextEditor.CSharp.Specific.{nameof(PreferSwitchExpression)}");
public static readonly Option2<CodeStyleOption2<bool>> PreferPatternMatching = CreateOption(
CSharpCodeStyleOptionGroups.PatternMatching, nameof(PreferPatternMatching),
defaultValue: s_trueWithSilentEnforcement,
"csharp_style_prefer_pattern_matching",
$"TextEditor.CSharp.Specific.{nameof(PreferPatternMatching)}");
public static readonly Option2<CodeStyleOption2<bool>> PreferPatternMatchingOverAsWithNullCheck = CreateOption(
CSharpCodeStyleOptionGroups.PatternMatching, nameof(PreferPatternMatchingOverAsWithNullCheck),
defaultValue: s_trueWithSuggestionEnforcement,
"csharp_style_pattern_matching_over_as_with_null_check",
$"TextEditor.CSharp.Specific.{nameof(PreferPatternMatchingOverAsWithNullCheck)}");
public static readonly Option2<CodeStyleOption2<bool>> PreferPatternMatchingOverIsWithCastCheck = CreateOption(
CSharpCodeStyleOptionGroups.PatternMatching, nameof(PreferPatternMatchingOverIsWithCastCheck),
defaultValue: s_trueWithSuggestionEnforcement,
"csharp_style_pattern_matching_over_is_with_cast_check",
$"TextEditor.CSharp.Specific.{nameof(PreferPatternMatchingOverIsWithCastCheck)}");
public static readonly Option2<CodeStyleOption2<bool>> PreferNotPattern = CreateOption(
CSharpCodeStyleOptionGroups.PatternMatching, nameof(PreferNotPattern),
defaultValue: s_trueWithSuggestionEnforcement,
"csharp_style_prefer_not_pattern",
$"TextEditor.CSharp.Specific.{nameof(PreferNotPattern)}");
public static readonly Option2<CodeStyleOption2<bool>> PreferThrowExpression = CreateOption(
CSharpCodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferThrowExpression),
defaultValue: s_trueWithSuggestionEnforcement,
"csharp_style_throw_expression",
"TextEditor.CSharp.Specific.PreferThrowExpression");
public static readonly Option2<CodeStyleOption2<bool>> PreferInlinedVariableDeclaration = CreateOption(
CSharpCodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferInlinedVariableDeclaration),
defaultValue: s_trueWithSuggestionEnforcement,
"csharp_style_inlined_variable_declaration",
"TextEditor.CSharp.Specific.PreferInlinedVariableDeclaration");
public static readonly Option2<CodeStyleOption2<bool>> PreferDeconstructedVariableDeclaration = CreateOption(
CSharpCodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferDeconstructedVariableDeclaration),
defaultValue: s_trueWithSuggestionEnforcement,
"csharp_style_deconstructed_variable_declaration",
$"TextEditor.CSharp.Specific.{nameof(PreferDeconstructedVariableDeclaration)}");
public static readonly Option2<CodeStyleOption2<bool>> PreferIndexOperator = CreateOption(
CSharpCodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferIndexOperator),
defaultValue: s_trueWithSuggestionEnforcement,
"csharp_style_prefer_index_operator",
"TextEditor.CSharp.Specific.PreferIndexOperator");
public static readonly Option2<CodeStyleOption2<bool>> PreferRangeOperator = CreateOption(
CSharpCodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferRangeOperator),
defaultValue: s_trueWithSuggestionEnforcement,
"csharp_style_prefer_range_operator",
"TextEditor.CSharp.Specific.PreferRangeOperator");
public static readonly CodeStyleOption2<ExpressionBodyPreference> NeverWithSilentEnforcement =
new(ExpressionBodyPreference.Never, NotificationOption2.Silent);
public static readonly CodeStyleOption2<ExpressionBodyPreference> NeverWithSuggestionEnforcement =
new(ExpressionBodyPreference.Never, NotificationOption2.Suggestion);
public static readonly CodeStyleOption2<ExpressionBodyPreference> WhenPossibleWithSilentEnforcement =
new(ExpressionBodyPreference.WhenPossible, NotificationOption2.Silent);
public static readonly CodeStyleOption2<ExpressionBodyPreference> WhenPossibleWithSuggestionEnforcement =
new(ExpressionBodyPreference.WhenPossible, NotificationOption2.Suggestion);
public static readonly CodeStyleOption2<ExpressionBodyPreference> WhenOnSingleLineWithSilentEnforcement =
new(ExpressionBodyPreference.WhenOnSingleLine, NotificationOption2.Silent);
public static readonly CodeStyleOption2<PreferBracesPreference> UseBracesWithSilentEnforcement =
new(PreferBracesPreference.Always, NotificationOption2.Silent);
private static Option2<CodeStyleOption2<ExpressionBodyPreference>> CreatePreferExpressionBodyOption(
string optionName,
CodeStyleOption2<ExpressionBodyPreference> defaultValue,
string editorconfigKeyName)
=> CreateOption(
CSharpCodeStyleOptionGroups.ExpressionBodiedMembers, optionName,
defaultValue,
new EditorConfigStorageLocation<CodeStyleOption2<ExpressionBodyPreference>>(
editorconfigKeyName,
s => ParseExpressionBodyPreference(s, defaultValue),
v => GetExpressionBodyPreferenceEditorConfigString(v, defaultValue)),
new RoamingProfileStorageLocation($"TextEditor.CSharp.Specific.{optionName}"));
public static readonly Option2<CodeStyleOption2<ExpressionBodyPreference>> PreferExpressionBodiedConstructors = CreatePreferExpressionBodyOption(
nameof(PreferExpressionBodiedConstructors), defaultValue: NeverWithSilentEnforcement, "csharp_style_expression_bodied_constructors");
public static readonly Option2<CodeStyleOption2<ExpressionBodyPreference>> PreferExpressionBodiedMethods = CreatePreferExpressionBodyOption(
nameof(PreferExpressionBodiedMethods), defaultValue: NeverWithSilentEnforcement, "csharp_style_expression_bodied_methods");
public static readonly Option2<CodeStyleOption2<ExpressionBodyPreference>> PreferExpressionBodiedOperators = CreatePreferExpressionBodyOption(
nameof(PreferExpressionBodiedOperators), defaultValue: NeverWithSilentEnforcement, "csharp_style_expression_bodied_operators");
public static readonly Option2<CodeStyleOption2<ExpressionBodyPreference>> PreferExpressionBodiedProperties = CreatePreferExpressionBodyOption(
nameof(PreferExpressionBodiedProperties), defaultValue: WhenPossibleWithSilentEnforcement, "csharp_style_expression_bodied_properties");
public static readonly Option2<CodeStyleOption2<ExpressionBodyPreference>> PreferExpressionBodiedIndexers = CreatePreferExpressionBodyOption(
nameof(PreferExpressionBodiedIndexers), defaultValue: WhenPossibleWithSilentEnforcement, "csharp_style_expression_bodied_indexers");
public static readonly Option2<CodeStyleOption2<ExpressionBodyPreference>> PreferExpressionBodiedAccessors = CreatePreferExpressionBodyOption(
nameof(PreferExpressionBodiedAccessors), defaultValue: WhenPossibleWithSilentEnforcement, "csharp_style_expression_bodied_accessors");
public static readonly Option2<CodeStyleOption2<ExpressionBodyPreference>> PreferExpressionBodiedLambdas = CreatePreferExpressionBodyOption(
nameof(PreferExpressionBodiedLambdas), defaultValue: WhenPossibleWithSilentEnforcement, "csharp_style_expression_bodied_lambdas");
public static readonly Option2<CodeStyleOption2<ExpressionBodyPreference>> PreferExpressionBodiedLocalFunctions = CreatePreferExpressionBodyOption(
nameof(PreferExpressionBodiedLocalFunctions), defaultValue: NeverWithSilentEnforcement, "csharp_style_expression_bodied_local_functions");
private static Option2<CodeStyleOption2<PreferBracesPreference>> CreatePreferBracesOption(
string optionName,
CodeStyleOption2<PreferBracesPreference> defaultValue,
string editorconfigKeyName)
=> CreateOption(
CSharpCodeStyleOptionGroups.CodeBlockPreferences, optionName,
defaultValue,
new EditorConfigStorageLocation<CodeStyleOption2<PreferBracesPreference>>(
editorconfigKeyName,
s => ParsePreferBracesPreference(s, defaultValue),
v => GetPreferBracesPreferenceEditorConfigString(v, defaultValue)),
new RoamingProfileStorageLocation($"TextEditor.CSharp.Specific.{optionName}"));
public static readonly Option2<CodeStyleOption2<PreferBracesPreference>> PreferBraces = CreatePreferBracesOption(
nameof(PreferBraces), defaultValue: UseBracesWithSilentEnforcement, "csharp_prefer_braces");
public static readonly Option2<CodeStyleOption2<bool>> PreferSimpleDefaultExpression = CreateOption(
CSharpCodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferSimpleDefaultExpression),
defaultValue: s_trueWithSuggestionEnforcement,
"csharp_prefer_simple_default_expression",
$"TextEditor.CSharp.Specific.{nameof(PreferSimpleDefaultExpression)}");
private static readonly SyntaxKind[] s_preferredModifierOrderDefault =
{
SyntaxKind.PublicKeyword, SyntaxKind.PrivateKeyword, SyntaxKind.ProtectedKeyword, SyntaxKind.InternalKeyword,
SyntaxKind.StaticKeyword,
SyntaxKind.ExternKeyword,
SyntaxKind.NewKeyword,
SyntaxKind.VirtualKeyword, SyntaxKind.AbstractKeyword, SyntaxKind.SealedKeyword, SyntaxKind.OverrideKeyword,
SyntaxKind.ReadOnlyKeyword,
SyntaxKind.UnsafeKeyword,
SyntaxKind.VolatileKeyword,
SyntaxKind.AsyncKeyword
};
public static readonly Option2<CodeStyleOption2<string>> PreferredModifierOrder = CreateOption(
CSharpCodeStyleOptionGroups.Modifier, nameof(PreferredModifierOrder),
defaultValue: new CodeStyleOption2<string>(string.Join(",", s_preferredModifierOrderDefault.Select(SyntaxFacts.GetText)), NotificationOption2.Silent),
"csharp_preferred_modifier_order",
$"TextEditor.CSharp.Specific.{nameof(PreferredModifierOrder)}");
public static readonly Option2<CodeStyleOption2<bool>> PreferStaticLocalFunction = CreateOption(
CSharpCodeStyleOptionGroups.Modifier, nameof(PreferStaticLocalFunction),
defaultValue: s_trueWithSuggestionEnforcement,
"csharp_prefer_static_local_function",
$"TextEditor.CSharp.Specific.{nameof(PreferStaticLocalFunction)}");
public static readonly Option2<CodeStyleOption2<bool>> PreferSimpleUsingStatement = CreateOption(
CSharpCodeStyleOptionGroups.CodeBlockPreferences, nameof(PreferSimpleUsingStatement),
defaultValue: s_trueWithSuggestionEnforcement,
"csharp_prefer_simple_using_statement",
$"TextEditor.CSharp.Specific.{nameof(PreferSimpleUsingStatement)}");
public static readonly Option2<CodeStyleOption2<bool>> PreferLocalOverAnonymousFunction = CreateOption(
CSharpCodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferLocalOverAnonymousFunction),
defaultValue: s_trueWithSuggestionEnforcement,
"csharp_style_pattern_local_over_anonymous_function",
$"TextEditor.CSharp.Specific.{nameof(PreferLocalOverAnonymousFunction)}");
public static readonly CodeStyleOption2<AddImportPlacement> PreferOutsidePlacementWithSilentEnforcement =
new(AddImportPlacement.OutsideNamespace, NotificationOption2.Silent);
private static Option2<CodeStyleOption2<AddImportPlacement>> CreateUsingDirectivePlacementOption(string optionName, CodeStyleOption2<AddImportPlacement> defaultValue, string editorconfigKeyName)
=> CreateOption(
CSharpCodeStyleOptionGroups.UsingDirectivePreferences, optionName,
defaultValue,
new EditorConfigStorageLocation<CodeStyleOption2<AddImportPlacement>>(
editorconfigKeyName,
s => ParseUsingDirectivesPlacement(s, defaultValue),
v => GetUsingDirectivesPlacementEditorConfigString(v, defaultValue)),
new RoamingProfileStorageLocation($"TextEditor.CSharp.Specific.{optionName}"));
public static readonly Option2<CodeStyleOption2<AddImportPlacement>> PreferredUsingDirectivePlacement = CreateUsingDirectivePlacementOption(
nameof(PreferredUsingDirectivePlacement), defaultValue: PreferOutsidePlacementWithSilentEnforcement, "csharp_using_directive_placement");
internal static readonly Option2<CodeStyleOption2<UnusedValuePreference>> UnusedValueExpressionStatement =
CodeStyleHelpers.CreateUnusedExpressionAssignmentOption(
CSharpCodeStyleOptionGroups.ExpressionLevelPreferences,
feature: nameof(CSharpCodeStyleOptions),
name: nameof(UnusedValueExpressionStatement),
editorConfigName: "csharp_style_unused_value_expression_statement_preference",
defaultValue: new CodeStyleOption2<UnusedValuePreference>(UnusedValuePreference.DiscardVariable, NotificationOption2.Silent),
s_allOptionsBuilder);
internal static readonly Option2<CodeStyleOption2<UnusedValuePreference>> UnusedValueAssignment =
CodeStyleHelpers.CreateUnusedExpressionAssignmentOption(
CSharpCodeStyleOptionGroups.ExpressionLevelPreferences,
feature: nameof(CSharpCodeStyleOptions),
name: nameof(UnusedValueAssignment),
editorConfigName: "csharp_style_unused_value_assignment_preference",
defaultValue: new CodeStyleOption2<UnusedValuePreference>(UnusedValuePreference.DiscardVariable, NotificationOption2.Suggestion),
s_allOptionsBuilder);
public static readonly Option2<CodeStyleOption2<bool>> ImplicitObjectCreationWhenTypeIsApparent = CreateOption(
CSharpCodeStyleOptionGroups.ExpressionLevelPreferences, nameof(ImplicitObjectCreationWhenTypeIsApparent),
defaultValue: s_trueWithSuggestionEnforcement,
"csharp_style_implicit_object_creation_when_type_is_apparent",
"TextEditor.CSharp.Specific.ImplicitObjectCreationWhenTypeIsApparent");
internal static readonly Option2<CodeStyleOption2<bool>> PreferNullCheckOverTypeCheck = CreateOption(
CSharpCodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferNullCheckOverTypeCheck),
defaultValue: s_trueWithSuggestionEnforcement,
"csharp_style_prefer_null_check_over_type_check",
$"TextEditor.CSharp.Specific.{nameof(PreferNullCheckOverTypeCheck)}");
public static Option2<CodeStyleOption2<bool>> AllowEmbeddedStatementsOnSameLine { get; } = CreateOption(
CSharpCodeStyleOptionGroups.NewLinePreferences, nameof(AllowEmbeddedStatementsOnSameLine),
defaultValue: CodeStyleOptions2.TrueWithSilentEnforcement,
EditorConfigStorageLocation.ForBoolCodeStyleOption("csharp_style_allow_embedded_statements_on_same_line_experimental", CodeStyleOptions2.TrueWithSilentEnforcement),
new RoamingProfileStorageLocation($"TextEditor.CSharp.Specific.{nameof(AllowEmbeddedStatementsOnSameLine)}"));
public static Option2<CodeStyleOption2<bool>> AllowBlankLinesBetweenConsecutiveBraces { get; } = CreateOption(
CSharpCodeStyleOptionGroups.NewLinePreferences, nameof(AllowBlankLinesBetweenConsecutiveBraces),
defaultValue: CodeStyleOptions2.TrueWithSilentEnforcement,
EditorConfigStorageLocation.ForBoolCodeStyleOption("csharp_style_allow_blank_lines_between_consecutive_braces_experimental", CodeStyleOptions2.TrueWithSilentEnforcement),
new RoamingProfileStorageLocation($"TextEditor.CSharp.Specific.{nameof(AllowBlankLinesBetweenConsecutiveBraces)}"));
public static Option2<CodeStyleOption2<bool>> AllowBlankLineAfterColonInConstructorInitializer { get; } = CreateOption(
CSharpCodeStyleOptionGroups.NewLinePreferences, nameof(AllowBlankLineAfterColonInConstructorInitializer),
defaultValue: CodeStyleOptions2.TrueWithSilentEnforcement,
EditorConfigStorageLocation.ForBoolCodeStyleOption("csharp_style_allow_blank_line_after_colon_in_constructor_initializer_experimental", CodeStyleOptions2.TrueWithSilentEnforcement),
new RoamingProfileStorageLocation($"TextEditor.CSharp.Specific.{nameof(AllowBlankLineAfterColonInConstructorInitializer)}"));
private static Option2<CodeStyleOption2<NamespaceDeclarationPreference>> CreateNamespaceDeclarationOption(string optionName, CodeStyleOption2<NamespaceDeclarationPreference> defaultValue, string editorconfigKeyName)
=> CreateOption(
CSharpCodeStyleOptionGroups.CodeBlockPreferences, optionName,
defaultValue,
new EditorConfigStorageLocation<CodeStyleOption2<NamespaceDeclarationPreference>>(
editorconfigKeyName,
s => ParseNamespaceDeclaration(s, defaultValue),
v => GetNamespaceDeclarationEditorConfigString(v, defaultValue)),
new RoamingProfileStorageLocation($"TextEditor.CSharp.Specific.{optionName}"));
public static readonly Option2<CodeStyleOption2<NamespaceDeclarationPreference>> NamespaceDeclarations = CreateNamespaceDeclarationOption(
nameof(NamespaceDeclarations),
new(NamespaceDeclarationPreference.BlockScoped, NotificationOption2.Silent),
"csharp_style_namespace_declarations");
#if false
public static readonly Option2<CodeStyleOption2<bool>> VarElsewhere = CreateOption(
CSharpCodeStyleOptionGroups.VarPreferences, nameof(VarElsewhere),
defaultValue: s_trueWithSuggestionEnforcement,
"csharp_style_var_elsewhere",
"TextEditor.CSharp.Specific.UseImplicitTypeWherePossible");
#endif
static CSharpCodeStyleOptions()
{
// Note that the static constructor executes after all the static field initializers for the options have executed,
// and each field initializer adds the created option to s_allOptionsBuilder.
AllOptions = s_allOptionsBuilder.ToImmutable();
}
public static IEnumerable<Option2<CodeStyleOption2<bool>>> GetCodeStyleOptions()
{
yield return VarForBuiltInTypes;
yield return VarWhenTypeIsApparent;
yield return VarElsewhere;
yield return PreferConditionalDelegateCall;
yield return PreferSwitchExpression;
yield return PreferPatternMatching;
yield return PreferPatternMatchingOverAsWithNullCheck;
yield return PreferPatternMatchingOverIsWithCastCheck;
yield return PreferSimpleDefaultExpression;
yield return PreferLocalOverAnonymousFunction;
yield return PreferThrowExpression;
yield return PreferInlinedVariableDeclaration;
yield return PreferDeconstructedVariableDeclaration;
yield return PreferIndexOperator;
yield return PreferRangeOperator;
yield return AllowEmbeddedStatementsOnSameLine;
yield return AllowBlankLinesBetweenConsecutiveBraces;
}
public static IEnumerable<Option2<CodeStyleOption2<ExpressionBodyPreference>>> GetExpressionBodyOptions()
{
yield return PreferExpressionBodiedConstructors;
yield return PreferExpressionBodiedMethods;
yield return PreferExpressionBodiedOperators;
yield return PreferExpressionBodiedProperties;
yield return PreferExpressionBodiedIndexers;
yield return PreferExpressionBodiedAccessors;
yield return PreferExpressionBodiedLambdas;
}
}
internal static class CSharpCodeStyleOptionGroups
{
public static readonly OptionGroup VarPreferences = new(CSharpCompilerExtensionsResources.var_preferences, priority: 1);
public static readonly OptionGroup ExpressionBodiedMembers = new(CSharpCompilerExtensionsResources.Expression_bodied_members, priority: 2);
public static readonly OptionGroup PatternMatching = new(CSharpCompilerExtensionsResources.Pattern_matching_preferences, priority: 3);
public static readonly OptionGroup NullCheckingPreferences = new(CSharpCompilerExtensionsResources.Null_checking_preferences, priority: 4);
public static readonly OptionGroup Modifier = new(CompilerExtensionsResources.Modifier_preferences, priority: 5);
public static readonly OptionGroup CodeBlockPreferences = new(CSharpCompilerExtensionsResources.Code_block_preferences, priority: 6);
public static readonly OptionGroup ExpressionLevelPreferences = new(CompilerExtensionsResources.Expression_level_preferences, priority: 7);
public static readonly OptionGroup UsingDirectivePreferences = new(CSharpCompilerExtensionsResources.using_directive_preferences, priority: 8);
public static readonly OptionGroup NewLinePreferences = new(CompilerExtensionsResources.New_line_preferences, priority: 9);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis.AddImports;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.Options;
namespace Microsoft.CodeAnalysis.CSharp.CodeStyle
{
internal static partial class CSharpCodeStyleOptions
{
private static readonly CodeStyleOption2<bool> s_trueWithSuggestionEnforcement = new(value: true, notification: NotificationOption2.Suggestion);
private static readonly CodeStyleOption2<bool> s_trueWithSilentEnforcement = new(value: true, notification: NotificationOption2.Silent);
private static readonly ImmutableArray<IOption2>.Builder s_allOptionsBuilder = ImmutableArray.CreateBuilder<IOption2>();
internal static ImmutableArray<IOption2> AllOptions { get; }
private static Option2<T> CreateOption<T>(
OptionGroup group, string name, T defaultValue, OptionStorageLocation2 storageLocation)
=> CodeStyleHelpers.CreateOption(
group, nameof(CSharpCodeStyleOptions), name, defaultValue,
s_allOptionsBuilder, storageLocation);
private static Option2<T> CreateOption<T>(
OptionGroup group, string name, T defaultValue, OptionStorageLocation2 storageLocation1, OptionStorageLocation2 storageLocation2)
=> CodeStyleHelpers.CreateOption(
group, nameof(CSharpCodeStyleOptions), name, defaultValue,
s_allOptionsBuilder, storageLocation1, storageLocation2);
private static Option2<CodeStyleOption2<bool>> CreateOption(
OptionGroup group, string name, CodeStyleOption2<bool> defaultValue, string editorconfigKeyName, string roamingProfileStorageKeyName)
=> CreateOption(
group, name, defaultValue,
EditorConfigStorageLocation.ForBoolCodeStyleOption(editorconfigKeyName, defaultValue),
new RoamingProfileStorageLocation(roamingProfileStorageKeyName));
private static Option2<CodeStyleOption2<string>> CreateOption(
OptionGroup group, string name, CodeStyleOption2<string> defaultValue, string editorconfigKeyName, string roamingProfileStorageKeyName)
=> CreateOption(
group, name, defaultValue,
EditorConfigStorageLocation.ForStringCodeStyleOption(editorconfigKeyName, defaultValue),
new RoamingProfileStorageLocation(roamingProfileStorageKeyName));
public static readonly Option2<CodeStyleOption2<bool>> VarForBuiltInTypes = CreateOption(
CSharpCodeStyleOptionGroups.VarPreferences, nameof(VarForBuiltInTypes),
defaultValue: CodeStyleOption2<bool>.Default,
"csharp_style_var_for_built_in_types",
"TextEditor.CSharp.Specific.UseImplicitTypeForIntrinsicTypes");
public static readonly Option2<CodeStyleOption2<bool>> VarWhenTypeIsApparent = CreateOption(
CSharpCodeStyleOptionGroups.VarPreferences, nameof(VarWhenTypeIsApparent),
defaultValue: CodeStyleOption2<bool>.Default,
"csharp_style_var_when_type_is_apparent",
"TextEditor.CSharp.Specific.UseImplicitTypeWhereApparent");
public static readonly Option2<CodeStyleOption2<bool>> VarElsewhere = CreateOption(
CSharpCodeStyleOptionGroups.VarPreferences, nameof(VarElsewhere),
defaultValue: CodeStyleOption2<bool>.Default,
"csharp_style_var_elsewhere",
"TextEditor.CSharp.Specific.UseImplicitTypeWherePossible");
public static readonly Option2<CodeStyleOption2<bool>> PreferConditionalDelegateCall = CreateOption(
CSharpCodeStyleOptionGroups.NullCheckingPreferences, nameof(PreferConditionalDelegateCall),
defaultValue: s_trueWithSuggestionEnforcement,
"csharp_style_conditional_delegate_call",
"TextEditor.CSharp.Specific.PreferConditionalDelegateCall");
public static readonly Option2<CodeStyleOption2<bool>> PreferSwitchExpression = CreateOption(
CSharpCodeStyleOptionGroups.PatternMatching, nameof(PreferSwitchExpression),
defaultValue: s_trueWithSuggestionEnforcement,
"csharp_style_prefer_switch_expression",
$"TextEditor.CSharp.Specific.{nameof(PreferSwitchExpression)}");
public static readonly Option2<CodeStyleOption2<bool>> PreferPatternMatching = CreateOption(
CSharpCodeStyleOptionGroups.PatternMatching, nameof(PreferPatternMatching),
defaultValue: s_trueWithSilentEnforcement,
"csharp_style_prefer_pattern_matching",
$"TextEditor.CSharp.Specific.{nameof(PreferPatternMatching)}");
public static readonly Option2<CodeStyleOption2<bool>> PreferPatternMatchingOverAsWithNullCheck = CreateOption(
CSharpCodeStyleOptionGroups.PatternMatching, nameof(PreferPatternMatchingOverAsWithNullCheck),
defaultValue: s_trueWithSuggestionEnforcement,
"csharp_style_pattern_matching_over_as_with_null_check",
$"TextEditor.CSharp.Specific.{nameof(PreferPatternMatchingOverAsWithNullCheck)}");
public static readonly Option2<CodeStyleOption2<bool>> PreferPatternMatchingOverIsWithCastCheck = CreateOption(
CSharpCodeStyleOptionGroups.PatternMatching, nameof(PreferPatternMatchingOverIsWithCastCheck),
defaultValue: s_trueWithSuggestionEnforcement,
"csharp_style_pattern_matching_over_is_with_cast_check",
$"TextEditor.CSharp.Specific.{nameof(PreferPatternMatchingOverIsWithCastCheck)}");
public static readonly Option2<CodeStyleOption2<bool>> PreferNotPattern = CreateOption(
CSharpCodeStyleOptionGroups.PatternMatching, nameof(PreferNotPattern),
defaultValue: s_trueWithSuggestionEnforcement,
"csharp_style_prefer_not_pattern",
$"TextEditor.CSharp.Specific.{nameof(PreferNotPattern)}");
public static readonly Option2<CodeStyleOption2<bool>> PreferThrowExpression = CreateOption(
CSharpCodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferThrowExpression),
defaultValue: s_trueWithSuggestionEnforcement,
"csharp_style_throw_expression",
"TextEditor.CSharp.Specific.PreferThrowExpression");
public static readonly Option2<CodeStyleOption2<bool>> PreferInlinedVariableDeclaration = CreateOption(
CSharpCodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferInlinedVariableDeclaration),
defaultValue: s_trueWithSuggestionEnforcement,
"csharp_style_inlined_variable_declaration",
"TextEditor.CSharp.Specific.PreferInlinedVariableDeclaration");
public static readonly Option2<CodeStyleOption2<bool>> PreferDeconstructedVariableDeclaration = CreateOption(
CSharpCodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferDeconstructedVariableDeclaration),
defaultValue: s_trueWithSuggestionEnforcement,
"csharp_style_deconstructed_variable_declaration",
$"TextEditor.CSharp.Specific.{nameof(PreferDeconstructedVariableDeclaration)}");
public static readonly Option2<CodeStyleOption2<bool>> PreferIndexOperator = CreateOption(
CSharpCodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferIndexOperator),
defaultValue: s_trueWithSuggestionEnforcement,
"csharp_style_prefer_index_operator",
"TextEditor.CSharp.Specific.PreferIndexOperator");
public static readonly Option2<CodeStyleOption2<bool>> PreferRangeOperator = CreateOption(
CSharpCodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferRangeOperator),
defaultValue: s_trueWithSuggestionEnforcement,
"csharp_style_prefer_range_operator",
"TextEditor.CSharp.Specific.PreferRangeOperator");
public static readonly CodeStyleOption2<ExpressionBodyPreference> NeverWithSilentEnforcement =
new(ExpressionBodyPreference.Never, NotificationOption2.Silent);
public static readonly CodeStyleOption2<ExpressionBodyPreference> NeverWithSuggestionEnforcement =
new(ExpressionBodyPreference.Never, NotificationOption2.Suggestion);
public static readonly CodeStyleOption2<ExpressionBodyPreference> WhenPossibleWithSilentEnforcement =
new(ExpressionBodyPreference.WhenPossible, NotificationOption2.Silent);
public static readonly CodeStyleOption2<ExpressionBodyPreference> WhenPossibleWithSuggestionEnforcement =
new(ExpressionBodyPreference.WhenPossible, NotificationOption2.Suggestion);
public static readonly CodeStyleOption2<ExpressionBodyPreference> WhenOnSingleLineWithSilentEnforcement =
new(ExpressionBodyPreference.WhenOnSingleLine, NotificationOption2.Silent);
public static readonly CodeStyleOption2<PreferBracesPreference> UseBracesWithSilentEnforcement =
new(PreferBracesPreference.Always, NotificationOption2.Silent);
private static Option2<CodeStyleOption2<ExpressionBodyPreference>> CreatePreferExpressionBodyOption(
string optionName,
CodeStyleOption2<ExpressionBodyPreference> defaultValue,
string editorconfigKeyName)
=> CreateOption(
CSharpCodeStyleOptionGroups.ExpressionBodiedMembers, optionName,
defaultValue,
new EditorConfigStorageLocation<CodeStyleOption2<ExpressionBodyPreference>>(
editorconfigKeyName,
s => ParseExpressionBodyPreference(s, defaultValue),
v => GetExpressionBodyPreferenceEditorConfigString(v, defaultValue)),
new RoamingProfileStorageLocation($"TextEditor.CSharp.Specific.{optionName}"));
public static readonly Option2<CodeStyleOption2<ExpressionBodyPreference>> PreferExpressionBodiedConstructors = CreatePreferExpressionBodyOption(
nameof(PreferExpressionBodiedConstructors), defaultValue: NeverWithSilentEnforcement, "csharp_style_expression_bodied_constructors");
public static readonly Option2<CodeStyleOption2<ExpressionBodyPreference>> PreferExpressionBodiedMethods = CreatePreferExpressionBodyOption(
nameof(PreferExpressionBodiedMethods), defaultValue: NeverWithSilentEnforcement, "csharp_style_expression_bodied_methods");
public static readonly Option2<CodeStyleOption2<ExpressionBodyPreference>> PreferExpressionBodiedOperators = CreatePreferExpressionBodyOption(
nameof(PreferExpressionBodiedOperators), defaultValue: NeverWithSilentEnforcement, "csharp_style_expression_bodied_operators");
public static readonly Option2<CodeStyleOption2<ExpressionBodyPreference>> PreferExpressionBodiedProperties = CreatePreferExpressionBodyOption(
nameof(PreferExpressionBodiedProperties), defaultValue: WhenPossibleWithSilentEnforcement, "csharp_style_expression_bodied_properties");
public static readonly Option2<CodeStyleOption2<ExpressionBodyPreference>> PreferExpressionBodiedIndexers = CreatePreferExpressionBodyOption(
nameof(PreferExpressionBodiedIndexers), defaultValue: WhenPossibleWithSilentEnforcement, "csharp_style_expression_bodied_indexers");
public static readonly Option2<CodeStyleOption2<ExpressionBodyPreference>> PreferExpressionBodiedAccessors = CreatePreferExpressionBodyOption(
nameof(PreferExpressionBodiedAccessors), defaultValue: WhenPossibleWithSilentEnforcement, "csharp_style_expression_bodied_accessors");
public static readonly Option2<CodeStyleOption2<ExpressionBodyPreference>> PreferExpressionBodiedLambdas = CreatePreferExpressionBodyOption(
nameof(PreferExpressionBodiedLambdas), defaultValue: WhenPossibleWithSilentEnforcement, "csharp_style_expression_bodied_lambdas");
public static readonly Option2<CodeStyleOption2<ExpressionBodyPreference>> PreferExpressionBodiedLocalFunctions = CreatePreferExpressionBodyOption(
nameof(PreferExpressionBodiedLocalFunctions), defaultValue: NeverWithSilentEnforcement, "csharp_style_expression_bodied_local_functions");
private static Option2<CodeStyleOption2<PreferBracesPreference>> CreatePreferBracesOption(
string optionName,
CodeStyleOption2<PreferBracesPreference> defaultValue,
string editorconfigKeyName)
=> CreateOption(
CSharpCodeStyleOptionGroups.CodeBlockPreferences, optionName,
defaultValue,
new EditorConfigStorageLocation<CodeStyleOption2<PreferBracesPreference>>(
editorconfigKeyName,
s => ParsePreferBracesPreference(s, defaultValue),
v => GetPreferBracesPreferenceEditorConfigString(v, defaultValue)),
new RoamingProfileStorageLocation($"TextEditor.CSharp.Specific.{optionName}"));
public static readonly Option2<CodeStyleOption2<PreferBracesPreference>> PreferBraces = CreatePreferBracesOption(
nameof(PreferBraces), defaultValue: UseBracesWithSilentEnforcement, "csharp_prefer_braces");
public static readonly Option2<CodeStyleOption2<bool>> PreferSimpleDefaultExpression = CreateOption(
CSharpCodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferSimpleDefaultExpression),
defaultValue: s_trueWithSuggestionEnforcement,
"csharp_prefer_simple_default_expression",
$"TextEditor.CSharp.Specific.{nameof(PreferSimpleDefaultExpression)}");
private static readonly SyntaxKind[] s_preferredModifierOrderDefault =
{
SyntaxKind.PublicKeyword, SyntaxKind.PrivateKeyword, SyntaxKind.ProtectedKeyword, SyntaxKind.InternalKeyword,
SyntaxKind.StaticKeyword,
SyntaxKind.ExternKeyword,
SyntaxKind.NewKeyword,
SyntaxKind.VirtualKeyword, SyntaxKind.AbstractKeyword, SyntaxKind.SealedKeyword, SyntaxKind.OverrideKeyword,
SyntaxKind.ReadOnlyKeyword,
SyntaxKind.UnsafeKeyword,
SyntaxKind.VolatileKeyword,
SyntaxKind.AsyncKeyword
};
public static readonly Option2<CodeStyleOption2<string>> PreferredModifierOrder = CreateOption(
CSharpCodeStyleOptionGroups.Modifier, nameof(PreferredModifierOrder),
defaultValue: new CodeStyleOption2<string>(string.Join(",", s_preferredModifierOrderDefault.Select(SyntaxFacts.GetText)), NotificationOption2.Silent),
"csharp_preferred_modifier_order",
$"TextEditor.CSharp.Specific.{nameof(PreferredModifierOrder)}");
public static readonly Option2<CodeStyleOption2<bool>> PreferStaticLocalFunction = CreateOption(
CSharpCodeStyleOptionGroups.Modifier, nameof(PreferStaticLocalFunction),
defaultValue: s_trueWithSuggestionEnforcement,
"csharp_prefer_static_local_function",
$"TextEditor.CSharp.Specific.{nameof(PreferStaticLocalFunction)}");
public static readonly Option2<CodeStyleOption2<bool>> PreferSimpleUsingStatement = CreateOption(
CSharpCodeStyleOptionGroups.CodeBlockPreferences, nameof(PreferSimpleUsingStatement),
defaultValue: s_trueWithSuggestionEnforcement,
"csharp_prefer_simple_using_statement",
$"TextEditor.CSharp.Specific.{nameof(PreferSimpleUsingStatement)}");
public static readonly Option2<CodeStyleOption2<bool>> PreferLocalOverAnonymousFunction = CreateOption(
CSharpCodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferLocalOverAnonymousFunction),
defaultValue: s_trueWithSuggestionEnforcement,
"csharp_style_pattern_local_over_anonymous_function",
$"TextEditor.CSharp.Specific.{nameof(PreferLocalOverAnonymousFunction)}");
public static readonly CodeStyleOption2<AddImportPlacement> PreferOutsidePlacementWithSilentEnforcement =
new(AddImportPlacement.OutsideNamespace, NotificationOption2.Silent);
private static Option2<CodeStyleOption2<AddImportPlacement>> CreateUsingDirectivePlacementOption(string optionName, CodeStyleOption2<AddImportPlacement> defaultValue, string editorconfigKeyName)
=> CreateOption(
CSharpCodeStyleOptionGroups.UsingDirectivePreferences, optionName,
defaultValue,
new EditorConfigStorageLocation<CodeStyleOption2<AddImportPlacement>>(
editorconfigKeyName,
s => ParseUsingDirectivesPlacement(s, defaultValue),
v => GetUsingDirectivesPlacementEditorConfigString(v, defaultValue)),
new RoamingProfileStorageLocation($"TextEditor.CSharp.Specific.{optionName}"));
public static readonly Option2<CodeStyleOption2<AddImportPlacement>> PreferredUsingDirectivePlacement = CreateUsingDirectivePlacementOption(
nameof(PreferredUsingDirectivePlacement), defaultValue: PreferOutsidePlacementWithSilentEnforcement, "csharp_using_directive_placement");
internal static readonly Option2<CodeStyleOption2<UnusedValuePreference>> UnusedValueExpressionStatement =
CodeStyleHelpers.CreateUnusedExpressionAssignmentOption(
CSharpCodeStyleOptionGroups.ExpressionLevelPreferences,
feature: nameof(CSharpCodeStyleOptions),
name: nameof(UnusedValueExpressionStatement),
editorConfigName: "csharp_style_unused_value_expression_statement_preference",
defaultValue: new CodeStyleOption2<UnusedValuePreference>(UnusedValuePreference.DiscardVariable, NotificationOption2.Silent),
s_allOptionsBuilder);
internal static readonly Option2<CodeStyleOption2<UnusedValuePreference>> UnusedValueAssignment =
CodeStyleHelpers.CreateUnusedExpressionAssignmentOption(
CSharpCodeStyleOptionGroups.ExpressionLevelPreferences,
feature: nameof(CSharpCodeStyleOptions),
name: nameof(UnusedValueAssignment),
editorConfigName: "csharp_style_unused_value_assignment_preference",
defaultValue: new CodeStyleOption2<UnusedValuePreference>(UnusedValuePreference.DiscardVariable, NotificationOption2.Suggestion),
s_allOptionsBuilder);
public static readonly Option2<CodeStyleOption2<bool>> ImplicitObjectCreationWhenTypeIsApparent = CreateOption(
CSharpCodeStyleOptionGroups.ExpressionLevelPreferences, nameof(ImplicitObjectCreationWhenTypeIsApparent),
defaultValue: s_trueWithSuggestionEnforcement,
"csharp_style_implicit_object_creation_when_type_is_apparent",
"TextEditor.CSharp.Specific.ImplicitObjectCreationWhenTypeIsApparent");
internal static readonly Option2<CodeStyleOption2<bool>> PreferNullCheckOverTypeCheck = CreateOption(
CSharpCodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferNullCheckOverTypeCheck),
defaultValue: s_trueWithSuggestionEnforcement,
"csharp_style_prefer_null_check_over_type_check",
$"TextEditor.CSharp.Specific.{nameof(PreferNullCheckOverTypeCheck)}");
public static Option2<CodeStyleOption2<bool>> AllowEmbeddedStatementsOnSameLine { get; } = CreateOption(
CSharpCodeStyleOptionGroups.NewLinePreferences, nameof(AllowEmbeddedStatementsOnSameLine),
defaultValue: CodeStyleOptions2.TrueWithSilentEnforcement,
EditorConfigStorageLocation.ForBoolCodeStyleOption("csharp_style_allow_embedded_statements_on_same_line_experimental", CodeStyleOptions2.TrueWithSilentEnforcement),
new RoamingProfileStorageLocation($"TextEditor.CSharp.Specific.{nameof(AllowEmbeddedStatementsOnSameLine)}"));
public static Option2<CodeStyleOption2<bool>> AllowBlankLinesBetweenConsecutiveBraces { get; } = CreateOption(
CSharpCodeStyleOptionGroups.NewLinePreferences, nameof(AllowBlankLinesBetweenConsecutiveBraces),
defaultValue: CodeStyleOptions2.TrueWithSilentEnforcement,
EditorConfigStorageLocation.ForBoolCodeStyleOption("csharp_style_allow_blank_lines_between_consecutive_braces_experimental", CodeStyleOptions2.TrueWithSilentEnforcement),
new RoamingProfileStorageLocation($"TextEditor.CSharp.Specific.{nameof(AllowBlankLinesBetweenConsecutiveBraces)}"));
public static Option2<CodeStyleOption2<bool>> AllowBlankLineAfterColonInConstructorInitializer { get; } = CreateOption(
CSharpCodeStyleOptionGroups.NewLinePreferences, nameof(AllowBlankLineAfterColonInConstructorInitializer),
defaultValue: CodeStyleOptions2.TrueWithSilentEnforcement,
EditorConfigStorageLocation.ForBoolCodeStyleOption("csharp_style_allow_blank_line_after_colon_in_constructor_initializer_experimental", CodeStyleOptions2.TrueWithSilentEnforcement),
new RoamingProfileStorageLocation($"TextEditor.CSharp.Specific.{nameof(AllowBlankLineAfterColonInConstructorInitializer)}"));
private static Option2<CodeStyleOption2<NamespaceDeclarationPreference>> CreateNamespaceDeclarationOption(string optionName, CodeStyleOption2<NamespaceDeclarationPreference> defaultValue, string editorconfigKeyName)
=> CreateOption(
CSharpCodeStyleOptionGroups.CodeBlockPreferences, optionName,
defaultValue,
new EditorConfigStorageLocation<CodeStyleOption2<NamespaceDeclarationPreference>>(
editorconfigKeyName,
s => ParseNamespaceDeclaration(s, defaultValue),
v => GetNamespaceDeclarationEditorConfigString(v, defaultValue)),
new RoamingProfileStorageLocation($"TextEditor.CSharp.Specific.{optionName}"));
public static readonly Option2<CodeStyleOption2<NamespaceDeclarationPreference>> NamespaceDeclarations = CreateNamespaceDeclarationOption(
nameof(NamespaceDeclarations),
new(NamespaceDeclarationPreference.BlockScoped, NotificationOption2.Silent),
"csharp_style_namespace_declarations");
#if false
public static readonly Option2<CodeStyleOption2<bool>> VarElsewhere = CreateOption(
CSharpCodeStyleOptionGroups.VarPreferences, nameof(VarElsewhere),
defaultValue: s_trueWithSuggestionEnforcement,
"csharp_style_var_elsewhere",
"TextEditor.CSharp.Specific.UseImplicitTypeWherePossible");
#endif
static CSharpCodeStyleOptions()
{
// Note that the static constructor executes after all the static field initializers for the options have executed,
// and each field initializer adds the created option to s_allOptionsBuilder.
AllOptions = s_allOptionsBuilder.ToImmutable();
}
public static IEnumerable<Option2<CodeStyleOption2<bool>>> GetCodeStyleOptions()
{
yield return VarForBuiltInTypes;
yield return VarWhenTypeIsApparent;
yield return VarElsewhere;
yield return PreferConditionalDelegateCall;
yield return PreferSwitchExpression;
yield return PreferPatternMatching;
yield return PreferPatternMatchingOverAsWithNullCheck;
yield return PreferPatternMatchingOverIsWithCastCheck;
yield return PreferSimpleDefaultExpression;
yield return PreferLocalOverAnonymousFunction;
yield return PreferThrowExpression;
yield return PreferInlinedVariableDeclaration;
yield return PreferDeconstructedVariableDeclaration;
yield return PreferIndexOperator;
yield return PreferRangeOperator;
yield return AllowEmbeddedStatementsOnSameLine;
yield return AllowBlankLinesBetweenConsecutiveBraces;
}
public static IEnumerable<Option2<CodeStyleOption2<ExpressionBodyPreference>>> GetExpressionBodyOptions()
{
yield return PreferExpressionBodiedConstructors;
yield return PreferExpressionBodiedMethods;
yield return PreferExpressionBodiedOperators;
yield return PreferExpressionBodiedProperties;
yield return PreferExpressionBodiedIndexers;
yield return PreferExpressionBodiedAccessors;
yield return PreferExpressionBodiedLambdas;
}
}
internal static class CSharpCodeStyleOptionGroups
{
public static readonly OptionGroup VarPreferences = new(CSharpCompilerExtensionsResources.var_preferences, priority: 1);
public static readonly OptionGroup ExpressionBodiedMembers = new(CSharpCompilerExtensionsResources.Expression_bodied_members, priority: 2);
public static readonly OptionGroup PatternMatching = new(CSharpCompilerExtensionsResources.Pattern_matching_preferences, priority: 3);
public static readonly OptionGroup NullCheckingPreferences = new(CSharpCompilerExtensionsResources.Null_checking_preferences, priority: 4);
public static readonly OptionGroup Modifier = new(CompilerExtensionsResources.Modifier_preferences, priority: 5);
public static readonly OptionGroup CodeBlockPreferences = new(CSharpCompilerExtensionsResources.Code_block_preferences, priority: 6);
public static readonly OptionGroup ExpressionLevelPreferences = new(CompilerExtensionsResources.Expression_level_preferences, priority: 7);
public static readonly OptionGroup UsingDirectivePreferences = new(CSharpCompilerExtensionsResources.using_directive_preferences, priority: 8);
public static readonly OptionGroup NewLinePreferences = new(CompilerExtensionsResources.New_line_preferences, priority: 9);
}
}
| -1 |
dotnet/roslyn | 55,877 | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute | Part of C# 10 support | davidwengier | 2021-08-25T05:36:27Z | 2021-08-30T20:47:11Z | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | 023d3ca2b5fb429f0b3dcc1efeed39442e232dba | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute. Part of C# 10 support | ./src/EditorFeatures/Test2/NavigationBar/NavigationBarPresenterTests.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
Imports Microsoft.CodeAnalysis.Shared.TestHooks
Imports Microsoft.VisualStudio.Text
Namespace Microsoft.CodeAnalysis.Editor.UnitTests.NavigationBar
<[UseExportProvider]>
Public Class NavigationBarControllerTests
<WpfFact, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(544957, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544957")>
Public Async Function TestDoNotRecomputeAfterFullRecompute() As Task
Using workspace = TestWorkspace.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>class C { }</Document>
</Project>
</Workspace>)
Dim document = workspace.Documents.Single()
Dim presentItemsCalled As Boolean = False
Dim mockPresenter As New MockNavigationBarPresenter(document.GetTextView(), Sub() presentItemsCalled = True)
Dim controllerFactory = workspace.GetService(Of INavigationBarControllerFactoryService)()
Dim controller = controllerFactory.CreateController(mockPresenter, document.GetTextBuffer())
Dim listenerProvider = workspace.ExportProvider.GetExport(Of IAsynchronousOperationListenerProvider).Value
Dim workspaceWaiter = listenerProvider.GetWaiter(FeatureAttribute.Workspace)
Dim navbarWaiter = listenerProvider.GetWaiter(FeatureAttribute.NavigationBar)
Await navbarWaiter.ExpeditedWaitAsync()
' The first time this is called, we should get various calls as a part of the
' present
Assert.True(presentItemsCalled)
' After it, we should not get any calls
presentItemsCalled = False
Await navbarWaiter.ExpeditedWaitAsync()
Assert.False(presentItemsCalled, "The presenter should not have been called a second time.")
End Using
End Function
<WpfFact(Skip:="https://github.com/dotnet/roslyn/issues/24754"), Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(544957, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544957")>
Public Async Function ProjectionBuffersWork() As Task
Using workspace = TestWorkspace.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>{|Document:class C { $$ }|}</Document>
</Project>
</Workspace>, composition:=EditorTestCompositions.EditorFeatures)
Dim subjectDocument = workspace.Documents.Single()
Dim projectedDocument = workspace.CreateProjectionBufferDocument("LEADING TEXT {|Document:|} TRAILING TEXT", {subjectDocument})
Dim view = projectedDocument.GetTextView()
view.Caret.MoveTo(New SnapshotPoint(view.TextSnapshot, projectedDocument.CursorPosition.Value))
Dim presentItemsCalled As Boolean = False
Dim mockPresenter As New MockNavigationBarPresenter(view, Sub() presentItemsCalled = True)
' The first time this is called, we should get various calls as a part of the
' present
Dim controllerFactory = workspace.GetService(Of INavigationBarControllerFactoryService)()
Dim controller = controllerFactory.CreateController(mockPresenter, subjectDocument.GetTextBuffer())
Dim provider = workspace.ExportProvider.GetExportedValue(Of IAsynchronousOperationListenerProvider)
Await provider.WaitAllDispatcherOperationAndTasksAsync(workspace, FeatureAttribute.Workspace, FeatureAttribute.NavigationBar)
Assert.True(presentItemsCalled)
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.NavigationBar)>
Public Async Function TestNavigationBarInCSharpLinkedFiles() As Task
Using workspace = TestWorkspace.Create(
<Workspace>
<Project Language="C#" CommonReferences="true" AssemblyName="CSProj" PreprocessorSymbols="Proj1">
<Document FilePath="C.cs">
class C
{
#if Proj1
void M1(int x) { }
#endif
#if Proj2
void M2(int x) { }
#endif
}
</Document>
</Project>
<Project Language="C#" CommonReferences="true" PreprocessorSymbols="Proj2">
<Document IsLinkFile="true" LinkAssemblyName="CSProj" LinkFilePath="C.cs"/>
</Project>
</Workspace>, composition:=EditorTestCompositions.EditorFeatures)
Dim baseDocument = workspace.Documents.Single(Function(d) Not d.IsLinkFile)
Dim linkDocument = workspace.Documents.Single(Function(d) d.IsLinkFile)
Dim presentItemsCalled As Boolean = False
Dim memberName As String = Nothing
Dim projectGlyph As Glyph = Nothing
Dim mockPresenter As New MockNavigationBarPresenter(
baseDocument.GetTextView(),
Sub(projects As IList(Of NavigationBarProjectItem),
selectedProject As NavigationBarProjectItem,
typesWithMembers As IList(Of NavigationBarItem),
selectedType As NavigationBarItem,
selectedMember As NavigationBarItem)
memberName = typesWithMembers.Single().ChildItems.Single().Text
projectGlyph = selectedProject.Glyph
End Sub)
Dim controllerFactory = workspace.GetService(Of INavigationBarControllerFactoryService)()
Dim controller = controllerFactory.CreateController(mockPresenter, baseDocument.GetTextBuffer())
Dim listenerProvider = workspace.ExportProvider.GetExport(Of IAsynchronousOperationListenerProvider).Value
Dim workspaceWaiter = listenerProvider.GetWaiter(FeatureAttribute.Workspace)
Dim navbarWaiter = listenerProvider.GetWaiter(FeatureAttribute.NavigationBar)
Await navbarWaiter.ExpeditedWaitAsync()
Assert.Equal("M1(int x)", memberName)
Assert.Equal(projectGlyph, Glyph.CSharpProject)
workspace.SetDocumentContext(linkDocument.Id)
Await workspaceWaiter.ExpeditedWaitAsync()
Await navbarWaiter.ExpeditedWaitAsync()
Assert.Equal("M2(int x)", memberName)
Assert.Equal(projectGlyph, Glyph.CSharpProject)
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.NavigationBar)>
Public Async Function TestNavigationBarInVisualBasicLinkedFiles() As Task
Using workspace = TestWorkspace.Create(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true" AssemblyName="VBProj" PreprocessorSymbols="Proj1=True">
<Document FilePath="C.vb">
Class C
#If Proj1 Then
Sub M1()
End Sub
#End If
#If Proj2 Then
Sub M2()
End Sub
#End If
End Class
</Document>
</Project>
<Project Language="Visual Basic" CommonReferences="true" PreprocessorSymbols="Proj2=True">
<Document IsLinkFile="true" LinkAssemblyName="VBProj" LinkFilePath="C.vb"/>
</Project>
</Workspace>, composition:=EditorTestCompositions.EditorFeatures)
Dim baseDocument = workspace.Documents.Single(Function(d) Not d.IsLinkFile)
Dim linkDocument = workspace.Documents.Single(Function(d) d.IsLinkFile)
Dim presentItemsCalled As Boolean = False
Dim memberNames As IEnumerable(Of String) = Nothing
Dim projectGlyph As Glyph = Nothing
Dim mockPresenter As New MockNavigationBarPresenter(
baseDocument.GetTextView(),
Sub(projects As IList(Of NavigationBarProjectItem),
selectedProject As NavigationBarProjectItem,
typesWithMembers As IList(Of NavigationBarItem),
selectedType As NavigationBarItem,
selectedMember As NavigationBarItem)
memberNames = typesWithMembers.Single().ChildItems.Select(Function(c) c.Text)
projectGlyph = selectedProject.Glyph
End Sub)
Dim controllerFactory = workspace.GetService(Of INavigationBarControllerFactoryService)()
Dim controller = controllerFactory.CreateController(mockPresenter, baseDocument.GetTextBuffer())
Dim listenerProvider = workspace.ExportProvider.GetExport(Of IAsynchronousOperationListenerProvider).Value
Dim workspaceWaiter = listenerProvider.GetWaiter(FeatureAttribute.Workspace)
Dim navbarWaiter = listenerProvider.GetWaiter(FeatureAttribute.NavigationBar)
Await navbarWaiter.ExpeditedWaitAsync()
Assert.Contains("M1", memberNames)
Assert.DoesNotContain("M2", memberNames)
Assert.Equal(projectGlyph, Glyph.BasicProject)
workspace.SetDocumentContext(linkDocument.Id)
Await workspaceWaiter.ExpeditedWaitAsync()
Await navbarWaiter.ExpeditedWaitAsync()
Assert.Contains("M2", memberNames)
Assert.DoesNotContain("M1", memberNames)
Assert.Equal(projectGlyph, Glyph.BasicProject)
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.NavigationBar)>
Public Async Function TestProjectItemsAreSortedCSharp() As Task
Using workspace = TestWorkspace.Create(
<Workspace>
<Project Language="C#" CommonReferences="true" AssemblyName="BProj">
<Document FilePath="C.cs">
class C
{
}
</Document>
</Project>
<Project Language="C#" CommonReferences="true" AssemblyName="AProj">
<Document IsLinkFile="true" LinkAssemblyName="BProj" LinkFilePath="C.cs"/>
</Project>
<Project Language="C#" CommonReferences="true" AssemblyName="CProj">
<Document IsLinkFile="true" LinkAssemblyName="BProj" LinkFilePath="C.cs"/>
</Project>
</Workspace>, composition:=EditorTestCompositions.EditorFeatures)
Dim baseDocument = workspace.Documents.Single(Function(d) Not d.IsLinkFile)
Dim expectedProjectNames As New List(Of String) From {"AProj", "BProj", "CProj"}
Dim actualProjectNames As List(Of String) = Nothing
Dim mockPresenter As New MockNavigationBarPresenter(
baseDocument.GetTextView(),
Sub(projects As IList(Of NavigationBarProjectItem),
selectedProject As NavigationBarProjectItem,
typesWithMembers As IList(Of NavigationBarItem),
selectedType As NavigationBarItem,
selectedMember As NavigationBarItem)
actualProjectNames = projects.Select(Function(item)
Return item.Text
End Function).ToList()
End Sub)
Dim controllerFactory = workspace.GetService(Of INavigationBarControllerFactoryService)()
Dim controller = controllerFactory.CreateController(mockPresenter, baseDocument.GetTextBuffer())
Await workspace.ExportProvider.GetExportedValue(Of IAsynchronousOperationListenerProvider).GetWaiter(FeatureAttribute.NavigationBar).ExpeditedWaitAsync()
Assert.True(actualProjectNames.SequenceEqual(expectedProjectNames))
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.NavigationBar)>
Public Async Function TestProjectItemsAreSortedVisualBasic() As Task
Using workspace = TestWorkspace.Create(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true" AssemblyName="VBProj">
<Document FilePath="C.vb">
Class C
End Class
</Document>
</Project>
<Project Language="Visual Basic" CommonReferences="true" AssemblyName="VB-Proj1">
<Document IsLinkFile="true" LinkAssemblyName="VBProj" LinkFilePath="C.vb"/>
</Project>
</Workspace>, composition:=EditorTestCompositions.EditorFeatures)
Dim baseDocument = workspace.Documents.Single(Function(d) Not d.IsLinkFile)
Dim expectedProjectNames As New List(Of String) From {"VBProj", "VB-Proj1"}
Dim actualProjectNames As List(Of String) = Nothing
Dim mockPresenter As New MockNavigationBarPresenter(
baseDocument.GetTextView(),
Sub(projects As IList(Of NavigationBarProjectItem),
selectedProject As NavigationBarProjectItem,
typesWithMembers As IList(Of NavigationBarItem),
selectedType As NavigationBarItem,
selectedMember As NavigationBarItem)
actualProjectNames = projects.Select(Function(item)
Return item.Text
End Function).ToList()
End Sub)
Dim controllerFactory = workspace.GetService(Of INavigationBarControllerFactoryService)()
Dim controller = controllerFactory.CreateController(mockPresenter, baseDocument.GetTextBuffer())
Await workspace.ExportProvider.GetExportedValue(Of IAsynchronousOperationListenerProvider).GetWaiter(FeatureAttribute.NavigationBar).ExpeditedWaitAsync()
Assert.True(actualProjectNames.SequenceEqual(expectedProjectNames))
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.NavigationBar)>
Public Async Function TestNavigationBarRefreshesAfterProjectRename() As Task
Using workspace = TestWorkspace.Create(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true" AssemblyName="VBProj">
<Document FilePath="C.vb">
Class C
$$
End Class
</Document>
</Project>
</Workspace>, composition:=EditorTestCompositions.EditorFeatures)
Dim document = workspace.Documents.Single()
Dim projectName As String = Nothing
Dim mockPresenter As New MockNavigationBarPresenter(
document.GetTextView(),
Sub(projects As IList(Of NavigationBarProjectItem),
selectedProject As NavigationBarProjectItem,
typesWithMembers As IList(Of NavigationBarItem),
selectedType As NavigationBarItem,
selectedMember As NavigationBarItem)
projectName = If(selectedProject IsNot Nothing, selectedProject.Text, Nothing)
End Sub)
Dim controllerFactory = workspace.GetService(Of INavigationBarControllerFactoryService)()
Dim controller = controllerFactory.CreateController(mockPresenter, document.GetTextBuffer())
Await workspace.ExportProvider.GetExportedValue(Of IAsynchronousOperationListenerProvider).GetWaiter(FeatureAttribute.NavigationBar).ExpeditedWaitAsync()
Assert.Equal("VBProj", projectName)
workspace.OnProjectNameChanged(workspace.Projects.Single().Id, "VBProj2", "VBProj2.vbproj")
Dim listenerProvider = workspace.ExportProvider.GetExportedValue(Of AsynchronousOperationListenerProvider)()
Dim workspaceWaiter = listenerProvider.GetWaiter(FeatureAttribute.Workspace)
Dim navigationBarWaiter = listenerProvider.GetWaiter(FeatureAttribute.NavigationBar)
Await workspaceWaiter.ExpeditedWaitAsync()
Await navigationBarWaiter.ExpeditedWaitAsync()
Await listenerProvider.WaitAllDispatcherOperationAndTasksAsync(workspace, FeatureAttribute.Workspace, FeatureAttribute.NavigationBar)
Assert.Equal("VBProj2", projectName)
End Using
End Function
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
Imports Microsoft.CodeAnalysis.Shared.TestHooks
Imports Microsoft.VisualStudio.Text
Namespace Microsoft.CodeAnalysis.Editor.UnitTests.NavigationBar
<[UseExportProvider]>
Public Class NavigationBarControllerTests
<WpfFact, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(544957, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544957")>
Public Async Function TestDoNotRecomputeAfterFullRecompute() As Task
Using workspace = TestWorkspace.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>class C { }</Document>
</Project>
</Workspace>)
Dim document = workspace.Documents.Single()
Dim presentItemsCalled As Boolean = False
Dim mockPresenter As New MockNavigationBarPresenter(document.GetTextView(), Sub() presentItemsCalled = True)
Dim controllerFactory = workspace.GetService(Of INavigationBarControllerFactoryService)()
Dim controller = controllerFactory.CreateController(mockPresenter, document.GetTextBuffer())
Dim listenerProvider = workspace.ExportProvider.GetExport(Of IAsynchronousOperationListenerProvider).Value
Dim workspaceWaiter = listenerProvider.GetWaiter(FeatureAttribute.Workspace)
Dim navbarWaiter = listenerProvider.GetWaiter(FeatureAttribute.NavigationBar)
Await navbarWaiter.ExpeditedWaitAsync()
' The first time this is called, we should get various calls as a part of the
' present
Assert.True(presentItemsCalled)
' After it, we should not get any calls
presentItemsCalled = False
Await navbarWaiter.ExpeditedWaitAsync()
Assert.False(presentItemsCalled, "The presenter should not have been called a second time.")
End Using
End Function
<WpfFact(Skip:="https://github.com/dotnet/roslyn/issues/24754"), Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(544957, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544957")>
Public Async Function ProjectionBuffersWork() As Task
Using workspace = TestWorkspace.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>{|Document:class C { $$ }|}</Document>
</Project>
</Workspace>, composition:=EditorTestCompositions.EditorFeatures)
Dim subjectDocument = workspace.Documents.Single()
Dim projectedDocument = workspace.CreateProjectionBufferDocument("LEADING TEXT {|Document:|} TRAILING TEXT", {subjectDocument})
Dim view = projectedDocument.GetTextView()
view.Caret.MoveTo(New SnapshotPoint(view.TextSnapshot, projectedDocument.CursorPosition.Value))
Dim presentItemsCalled As Boolean = False
Dim mockPresenter As New MockNavigationBarPresenter(view, Sub() presentItemsCalled = True)
' The first time this is called, we should get various calls as a part of the
' present
Dim controllerFactory = workspace.GetService(Of INavigationBarControllerFactoryService)()
Dim controller = controllerFactory.CreateController(mockPresenter, subjectDocument.GetTextBuffer())
Dim provider = workspace.ExportProvider.GetExportedValue(Of IAsynchronousOperationListenerProvider)
Await provider.WaitAllDispatcherOperationAndTasksAsync(workspace, FeatureAttribute.Workspace, FeatureAttribute.NavigationBar)
Assert.True(presentItemsCalled)
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.NavigationBar)>
Public Async Function TestNavigationBarInCSharpLinkedFiles() As Task
Using workspace = TestWorkspace.Create(
<Workspace>
<Project Language="C#" CommonReferences="true" AssemblyName="CSProj" PreprocessorSymbols="Proj1">
<Document FilePath="C.cs">
class C
{
#if Proj1
void M1(int x) { }
#endif
#if Proj2
void M2(int x) { }
#endif
}
</Document>
</Project>
<Project Language="C#" CommonReferences="true" PreprocessorSymbols="Proj2">
<Document IsLinkFile="true" LinkAssemblyName="CSProj" LinkFilePath="C.cs"/>
</Project>
</Workspace>, composition:=EditorTestCompositions.EditorFeatures)
Dim baseDocument = workspace.Documents.Single(Function(d) Not d.IsLinkFile)
Dim linkDocument = workspace.Documents.Single(Function(d) d.IsLinkFile)
Dim presentItemsCalled As Boolean = False
Dim memberName As String = Nothing
Dim projectGlyph As Glyph = Nothing
Dim mockPresenter As New MockNavigationBarPresenter(
baseDocument.GetTextView(),
Sub(projects As IList(Of NavigationBarProjectItem),
selectedProject As NavigationBarProjectItem,
typesWithMembers As IList(Of NavigationBarItem),
selectedType As NavigationBarItem,
selectedMember As NavigationBarItem)
memberName = typesWithMembers.Single().ChildItems.Single().Text
projectGlyph = selectedProject.Glyph
End Sub)
Dim controllerFactory = workspace.GetService(Of INavigationBarControllerFactoryService)()
Dim controller = controllerFactory.CreateController(mockPresenter, baseDocument.GetTextBuffer())
Dim listenerProvider = workspace.ExportProvider.GetExport(Of IAsynchronousOperationListenerProvider).Value
Dim workspaceWaiter = listenerProvider.GetWaiter(FeatureAttribute.Workspace)
Dim navbarWaiter = listenerProvider.GetWaiter(FeatureAttribute.NavigationBar)
Await navbarWaiter.ExpeditedWaitAsync()
Assert.Equal("M1(int x)", memberName)
Assert.Equal(projectGlyph, Glyph.CSharpProject)
workspace.SetDocumentContext(linkDocument.Id)
Await workspaceWaiter.ExpeditedWaitAsync()
Await navbarWaiter.ExpeditedWaitAsync()
Assert.Equal("M2(int x)", memberName)
Assert.Equal(projectGlyph, Glyph.CSharpProject)
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.NavigationBar)>
Public Async Function TestNavigationBarInVisualBasicLinkedFiles() As Task
Using workspace = TestWorkspace.Create(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true" AssemblyName="VBProj" PreprocessorSymbols="Proj1=True">
<Document FilePath="C.vb">
Class C
#If Proj1 Then
Sub M1()
End Sub
#End If
#If Proj2 Then
Sub M2()
End Sub
#End If
End Class
</Document>
</Project>
<Project Language="Visual Basic" CommonReferences="true" PreprocessorSymbols="Proj2=True">
<Document IsLinkFile="true" LinkAssemblyName="VBProj" LinkFilePath="C.vb"/>
</Project>
</Workspace>, composition:=EditorTestCompositions.EditorFeatures)
Dim baseDocument = workspace.Documents.Single(Function(d) Not d.IsLinkFile)
Dim linkDocument = workspace.Documents.Single(Function(d) d.IsLinkFile)
Dim presentItemsCalled As Boolean = False
Dim memberNames As IEnumerable(Of String) = Nothing
Dim projectGlyph As Glyph = Nothing
Dim mockPresenter As New MockNavigationBarPresenter(
baseDocument.GetTextView(),
Sub(projects As IList(Of NavigationBarProjectItem),
selectedProject As NavigationBarProjectItem,
typesWithMembers As IList(Of NavigationBarItem),
selectedType As NavigationBarItem,
selectedMember As NavigationBarItem)
memberNames = typesWithMembers.Single().ChildItems.Select(Function(c) c.Text)
projectGlyph = selectedProject.Glyph
End Sub)
Dim controllerFactory = workspace.GetService(Of INavigationBarControllerFactoryService)()
Dim controller = controllerFactory.CreateController(mockPresenter, baseDocument.GetTextBuffer())
Dim listenerProvider = workspace.ExportProvider.GetExport(Of IAsynchronousOperationListenerProvider).Value
Dim workspaceWaiter = listenerProvider.GetWaiter(FeatureAttribute.Workspace)
Dim navbarWaiter = listenerProvider.GetWaiter(FeatureAttribute.NavigationBar)
Await navbarWaiter.ExpeditedWaitAsync()
Assert.Contains("M1", memberNames)
Assert.DoesNotContain("M2", memberNames)
Assert.Equal(projectGlyph, Glyph.BasicProject)
workspace.SetDocumentContext(linkDocument.Id)
Await workspaceWaiter.ExpeditedWaitAsync()
Await navbarWaiter.ExpeditedWaitAsync()
Assert.Contains("M2", memberNames)
Assert.DoesNotContain("M1", memberNames)
Assert.Equal(projectGlyph, Glyph.BasicProject)
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.NavigationBar)>
Public Async Function TestProjectItemsAreSortedCSharp() As Task
Using workspace = TestWorkspace.Create(
<Workspace>
<Project Language="C#" CommonReferences="true" AssemblyName="BProj">
<Document FilePath="C.cs">
class C
{
}
</Document>
</Project>
<Project Language="C#" CommonReferences="true" AssemblyName="AProj">
<Document IsLinkFile="true" LinkAssemblyName="BProj" LinkFilePath="C.cs"/>
</Project>
<Project Language="C#" CommonReferences="true" AssemblyName="CProj">
<Document IsLinkFile="true" LinkAssemblyName="BProj" LinkFilePath="C.cs"/>
</Project>
</Workspace>, composition:=EditorTestCompositions.EditorFeatures)
Dim baseDocument = workspace.Documents.Single(Function(d) Not d.IsLinkFile)
Dim expectedProjectNames As New List(Of String) From {"AProj", "BProj", "CProj"}
Dim actualProjectNames As List(Of String) = Nothing
Dim mockPresenter As New MockNavigationBarPresenter(
baseDocument.GetTextView(),
Sub(projects As IList(Of NavigationBarProjectItem),
selectedProject As NavigationBarProjectItem,
typesWithMembers As IList(Of NavigationBarItem),
selectedType As NavigationBarItem,
selectedMember As NavigationBarItem)
actualProjectNames = projects.Select(Function(item)
Return item.Text
End Function).ToList()
End Sub)
Dim controllerFactory = workspace.GetService(Of INavigationBarControllerFactoryService)()
Dim controller = controllerFactory.CreateController(mockPresenter, baseDocument.GetTextBuffer())
Await workspace.ExportProvider.GetExportedValue(Of IAsynchronousOperationListenerProvider).GetWaiter(FeatureAttribute.NavigationBar).ExpeditedWaitAsync()
Assert.True(actualProjectNames.SequenceEqual(expectedProjectNames))
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.NavigationBar)>
Public Async Function TestProjectItemsAreSortedVisualBasic() As Task
Using workspace = TestWorkspace.Create(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true" AssemblyName="VBProj">
<Document FilePath="C.vb">
Class C
End Class
</Document>
</Project>
<Project Language="Visual Basic" CommonReferences="true" AssemblyName="VB-Proj1">
<Document IsLinkFile="true" LinkAssemblyName="VBProj" LinkFilePath="C.vb"/>
</Project>
</Workspace>, composition:=EditorTestCompositions.EditorFeatures)
Dim baseDocument = workspace.Documents.Single(Function(d) Not d.IsLinkFile)
Dim expectedProjectNames As New List(Of String) From {"VBProj", "VB-Proj1"}
Dim actualProjectNames As List(Of String) = Nothing
Dim mockPresenter As New MockNavigationBarPresenter(
baseDocument.GetTextView(),
Sub(projects As IList(Of NavigationBarProjectItem),
selectedProject As NavigationBarProjectItem,
typesWithMembers As IList(Of NavigationBarItem),
selectedType As NavigationBarItem,
selectedMember As NavigationBarItem)
actualProjectNames = projects.Select(Function(item)
Return item.Text
End Function).ToList()
End Sub)
Dim controllerFactory = workspace.GetService(Of INavigationBarControllerFactoryService)()
Dim controller = controllerFactory.CreateController(mockPresenter, baseDocument.GetTextBuffer())
Await workspace.ExportProvider.GetExportedValue(Of IAsynchronousOperationListenerProvider).GetWaiter(FeatureAttribute.NavigationBar).ExpeditedWaitAsync()
Assert.True(actualProjectNames.SequenceEqual(expectedProjectNames))
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.NavigationBar)>
Public Async Function TestNavigationBarRefreshesAfterProjectRename() As Task
Using workspace = TestWorkspace.Create(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true" AssemblyName="VBProj">
<Document FilePath="C.vb">
Class C
$$
End Class
</Document>
</Project>
</Workspace>, composition:=EditorTestCompositions.EditorFeatures)
Dim document = workspace.Documents.Single()
Dim projectName As String = Nothing
Dim mockPresenter As New MockNavigationBarPresenter(
document.GetTextView(),
Sub(projects As IList(Of NavigationBarProjectItem),
selectedProject As NavigationBarProjectItem,
typesWithMembers As IList(Of NavigationBarItem),
selectedType As NavigationBarItem,
selectedMember As NavigationBarItem)
projectName = If(selectedProject IsNot Nothing, selectedProject.Text, Nothing)
End Sub)
Dim controllerFactory = workspace.GetService(Of INavigationBarControllerFactoryService)()
Dim controller = controllerFactory.CreateController(mockPresenter, document.GetTextBuffer())
Await workspace.ExportProvider.GetExportedValue(Of IAsynchronousOperationListenerProvider).GetWaiter(FeatureAttribute.NavigationBar).ExpeditedWaitAsync()
Assert.Equal("VBProj", projectName)
workspace.OnProjectNameChanged(workspace.Projects.Single().Id, "VBProj2", "VBProj2.vbproj")
Dim listenerProvider = workspace.ExportProvider.GetExportedValue(Of AsynchronousOperationListenerProvider)()
Dim workspaceWaiter = listenerProvider.GetWaiter(FeatureAttribute.Workspace)
Dim navigationBarWaiter = listenerProvider.GetWaiter(FeatureAttribute.NavigationBar)
Await workspaceWaiter.ExpeditedWaitAsync()
Await navigationBarWaiter.ExpeditedWaitAsync()
Await listenerProvider.WaitAllDispatcherOperationAndTasksAsync(workspace, FeatureAttribute.Workspace, FeatureAttribute.NavigationBar)
Assert.Equal("VBProj2", projectName)
End Using
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,877 | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute | Part of C# 10 support | davidwengier | 2021-08-25T05:36:27Z | 2021-08-30T20:47:11Z | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | 023d3ca2b5fb429f0b3dcc1efeed39442e232dba | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute. Part of C# 10 support | ./src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/Symbols/SynthesizedContextMethodSymbol.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Reflection;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator
{
/// <summary>
/// A synthesized instance method used for binding
/// expressions outside of a method - specifically, binding
/// DebuggerDisplayAttribute expressions.
/// </summary>
internal sealed class SynthesizedContextMethodSymbol : SynthesizedInstanceMethodSymbol
{
private readonly NamedTypeSymbol _container;
public SynthesizedContextMethodSymbol(NamedTypeSymbol container)
{
_container = container;
}
public override int Arity
{
get { return 0; }
}
public override Symbol AssociatedSymbol
{
get { return null; }
}
public override Symbol ContainingSymbol
{
get { return _container; }
}
public override Accessibility DeclaredAccessibility
{
get { return Accessibility.NotApplicable; }
}
public override ImmutableArray<MethodSymbol> ExplicitInterfaceImplementations
{
get { return ImmutableArray<MethodSymbol>.Empty; }
}
public override bool HidesBaseMethodsByName
{
get { return false; }
}
public override bool IsAbstract
{
get { return false; }
}
public override bool IsAsync
{
get { return false; }
}
public override bool IsExtensionMethod
{
get { return false; }
}
public override bool IsExtern
{
get { return false; }
}
public override bool IsOverride
{
get { return false; }
}
public override bool IsSealed
{
get { return true; }
}
public override bool IsStatic
{
get { return false; }
}
public override bool IsVararg
{
get { return false; }
}
public override bool IsVirtual
{
get { return false; }
}
public override ImmutableArray<Location> Locations
{
get { throw ExceptionUtilities.Unreachable; }
}
public override MethodKind MethodKind
{
get { return MethodKind.Ordinary; }
}
public override ImmutableArray<ParameterSymbol> Parameters
{
get { return ImmutableArray<ParameterSymbol>.Empty; }
}
public override bool ReturnsVoid
{
get { return true; }
}
public override RefKind RefKind
{
get { return RefKind.None; }
}
public override TypeWithAnnotations ReturnTypeWithAnnotations
{
get { throw ExceptionUtilities.Unreachable; }
}
public override FlowAnalysisAnnotations ReturnTypeFlowAnalysisAnnotations => FlowAnalysisAnnotations.None;
public override ImmutableHashSet<string> ReturnNotNullIfParameterNotNull => ImmutableHashSet<string>.Empty;
public override ImmutableArray<CustomModifier> RefCustomModifiers
{
get { throw ExceptionUtilities.Unreachable; }
}
public override ImmutableArray<TypeWithAnnotations> TypeArgumentsWithAnnotations
{
get { return ImmutableArray<TypeWithAnnotations>.Empty; }
}
public override ImmutableArray<TypeParameterSymbol> TypeParameters
{
get { return ImmutableArray<TypeParameterSymbol>.Empty; }
}
internal override Microsoft.Cci.CallingConvention CallingConvention
{
get { throw ExceptionUtilities.Unreachable; }
}
internal override bool GenerateDebugInfo
{
get { throw ExceptionUtilities.Unreachable; }
}
internal override bool HasDeclarativeSecurity
{
get { throw ExceptionUtilities.Unreachable; }
}
internal override bool HasSpecialName
{
get { throw ExceptionUtilities.Unreachable; }
}
internal override MethodImplAttributes ImplementationAttributes
{
get { throw ExceptionUtilities.Unreachable; }
}
internal override bool RequiresSecurityObject
{
get { throw ExceptionUtilities.Unreachable; }
}
internal override MarshalPseudoCustomAttributeData ReturnValueMarshallingInformation
{
get { throw ExceptionUtilities.Unreachable; }
}
public override DllImportData GetDllImportData()
{
throw ExceptionUtilities.Unreachable;
}
internal override ImmutableArray<string> GetAppliedConditionalSymbols()
{
throw ExceptionUtilities.Unreachable;
}
internal override IEnumerable<Microsoft.Cci.SecurityAttribute> GetSecurityInformation()
{
throw ExceptionUtilities.Unreachable;
}
internal override bool IsMetadataFinal
{
get
{
return false;
}
}
internal override bool IsMetadataNewSlot(bool ignoreInterfaceImplementationChanges = false)
{
throw ExceptionUtilities.Unreachable;
}
internal override bool IsMetadataVirtual(bool ignoreInterfaceImplementationChanges = false)
{
throw ExceptionUtilities.Unreachable;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Reflection;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator
{
/// <summary>
/// A synthesized instance method used for binding
/// expressions outside of a method - specifically, binding
/// DebuggerDisplayAttribute expressions.
/// </summary>
internal sealed class SynthesizedContextMethodSymbol : SynthesizedInstanceMethodSymbol
{
private readonly NamedTypeSymbol _container;
public SynthesizedContextMethodSymbol(NamedTypeSymbol container)
{
_container = container;
}
public override int Arity
{
get { return 0; }
}
public override Symbol AssociatedSymbol
{
get { return null; }
}
public override Symbol ContainingSymbol
{
get { return _container; }
}
public override Accessibility DeclaredAccessibility
{
get { return Accessibility.NotApplicable; }
}
public override ImmutableArray<MethodSymbol> ExplicitInterfaceImplementations
{
get { return ImmutableArray<MethodSymbol>.Empty; }
}
public override bool HidesBaseMethodsByName
{
get { return false; }
}
public override bool IsAbstract
{
get { return false; }
}
public override bool IsAsync
{
get { return false; }
}
public override bool IsExtensionMethod
{
get { return false; }
}
public override bool IsExtern
{
get { return false; }
}
public override bool IsOverride
{
get { return false; }
}
public override bool IsSealed
{
get { return true; }
}
public override bool IsStatic
{
get { return false; }
}
public override bool IsVararg
{
get { return false; }
}
public override bool IsVirtual
{
get { return false; }
}
public override ImmutableArray<Location> Locations
{
get { throw ExceptionUtilities.Unreachable; }
}
public override MethodKind MethodKind
{
get { return MethodKind.Ordinary; }
}
public override ImmutableArray<ParameterSymbol> Parameters
{
get { return ImmutableArray<ParameterSymbol>.Empty; }
}
public override bool ReturnsVoid
{
get { return true; }
}
public override RefKind RefKind
{
get { return RefKind.None; }
}
public override TypeWithAnnotations ReturnTypeWithAnnotations
{
get { throw ExceptionUtilities.Unreachable; }
}
public override FlowAnalysisAnnotations ReturnTypeFlowAnalysisAnnotations => FlowAnalysisAnnotations.None;
public override ImmutableHashSet<string> ReturnNotNullIfParameterNotNull => ImmutableHashSet<string>.Empty;
public override ImmutableArray<CustomModifier> RefCustomModifiers
{
get { throw ExceptionUtilities.Unreachable; }
}
public override ImmutableArray<TypeWithAnnotations> TypeArgumentsWithAnnotations
{
get { return ImmutableArray<TypeWithAnnotations>.Empty; }
}
public override ImmutableArray<TypeParameterSymbol> TypeParameters
{
get { return ImmutableArray<TypeParameterSymbol>.Empty; }
}
internal override Microsoft.Cci.CallingConvention CallingConvention
{
get { throw ExceptionUtilities.Unreachable; }
}
internal override bool GenerateDebugInfo
{
get { throw ExceptionUtilities.Unreachable; }
}
internal override bool HasDeclarativeSecurity
{
get { throw ExceptionUtilities.Unreachable; }
}
internal override bool HasSpecialName
{
get { throw ExceptionUtilities.Unreachable; }
}
internal override MethodImplAttributes ImplementationAttributes
{
get { throw ExceptionUtilities.Unreachable; }
}
internal override bool RequiresSecurityObject
{
get { throw ExceptionUtilities.Unreachable; }
}
internal override MarshalPseudoCustomAttributeData ReturnValueMarshallingInformation
{
get { throw ExceptionUtilities.Unreachable; }
}
public override DllImportData GetDllImportData()
{
throw ExceptionUtilities.Unreachable;
}
internal override ImmutableArray<string> GetAppliedConditionalSymbols()
{
throw ExceptionUtilities.Unreachable;
}
internal override IEnumerable<Microsoft.Cci.SecurityAttribute> GetSecurityInformation()
{
throw ExceptionUtilities.Unreachable;
}
internal override bool IsMetadataFinal
{
get
{
return false;
}
}
internal override bool IsMetadataNewSlot(bool ignoreInterfaceImplementationChanges = false)
{
throw ExceptionUtilities.Unreachable;
}
internal override bool IsMetadataVirtual(bool ignoreInterfaceImplementationChanges = false)
{
throw ExceptionUtilities.Unreachable;
}
}
}
| -1 |
dotnet/roslyn | 55,877 | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute | Part of C# 10 support | davidwengier | 2021-08-25T05:36:27Z | 2021-08-30T20:47:11Z | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | 023d3ca2b5fb429f0b3dcc1efeed39442e232dba | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute. Part of C# 10 support | ./src/EditorFeatures/Core.Wpf/Suggestions/SuggestedActions/SuggestedAction.CaretPositionRestorer.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Implementation.Suggestions
{
internal partial class SuggestedAction
{
internal class CaretPositionRestorer : IDisposable
{
// Bug 5535: By default the standard editor caret is set to have positive affinity. This
// means that if text is added right at the caret then the caret moves to the right and
// is placed after the added text. However, we don't want that. Instead, we want the
// caret to stay where it started at. So we store the caret position here and
// restore it afterwards.
private readonly EventHandler<CaretPositionChangedEventArgs> _caretPositionChangedHandler;
private readonly IList<Tuple<ITextView, IMappingPoint>> _caretPositions;
private readonly ITextBuffer _subjectBuffer;
private readonly ITextBufferAssociatedViewService _associatedViewService;
private bool _caretChanged;
public CaretPositionRestorer(ITextBuffer subjectBuffer, ITextBufferAssociatedViewService associatedViewService)
{
Contract.ThrowIfNull(associatedViewService);
_subjectBuffer = subjectBuffer;
_caretPositionChangedHandler = (s, e) => _caretChanged = true;
_associatedViewService = associatedViewService;
_caretPositions = GetCaretPositions();
}
private IList<Tuple<ITextView, IMappingPoint>> GetCaretPositions()
{
// Currently, only do this if there's a single view
var views = _associatedViewService.GetAssociatedTextViews(_subjectBuffer);
var result = new List<Tuple<ITextView, IMappingPoint>>();
foreach (var view in views)
{
view.Caret.PositionChanged += _caretPositionChangedHandler;
var point = view.GetCaretPoint(_subjectBuffer);
if (point != null)
{
result.Add(Tuple.Create(view, view.BufferGraph.CreateMappingPoint(point.Value, PointTrackingMode.Negative)));
}
}
return result;
}
private void RestoreCaretPositions()
{
if (_caretChanged)
{
return;
}
foreach (var tuple in _caretPositions)
{
var position = tuple.Item1.GetCaretPoint(_subjectBuffer);
if (position != null)
{
var view = tuple.Item1;
if (!view.IsClosed)
{
view.TryMoveCaretToAndEnsureVisible(position.Value);
}
}
}
}
public void Dispose()
{
RestoreCaretPositions();
foreach (var tuple in _caretPositions)
{
tuple.Item1.Caret.PositionChanged -= _caretPositionChangedHandler;
}
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Implementation.Suggestions
{
internal partial class SuggestedAction
{
internal class CaretPositionRestorer : IDisposable
{
// Bug 5535: By default the standard editor caret is set to have positive affinity. This
// means that if text is added right at the caret then the caret moves to the right and
// is placed after the added text. However, we don't want that. Instead, we want the
// caret to stay where it started at. So we store the caret position here and
// restore it afterwards.
private readonly EventHandler<CaretPositionChangedEventArgs> _caretPositionChangedHandler;
private readonly IList<Tuple<ITextView, IMappingPoint>> _caretPositions;
private readonly ITextBuffer _subjectBuffer;
private readonly ITextBufferAssociatedViewService _associatedViewService;
private bool _caretChanged;
public CaretPositionRestorer(ITextBuffer subjectBuffer, ITextBufferAssociatedViewService associatedViewService)
{
Contract.ThrowIfNull(associatedViewService);
_subjectBuffer = subjectBuffer;
_caretPositionChangedHandler = (s, e) => _caretChanged = true;
_associatedViewService = associatedViewService;
_caretPositions = GetCaretPositions();
}
private IList<Tuple<ITextView, IMappingPoint>> GetCaretPositions()
{
// Currently, only do this if there's a single view
var views = _associatedViewService.GetAssociatedTextViews(_subjectBuffer);
var result = new List<Tuple<ITextView, IMappingPoint>>();
foreach (var view in views)
{
view.Caret.PositionChanged += _caretPositionChangedHandler;
var point = view.GetCaretPoint(_subjectBuffer);
if (point != null)
{
result.Add(Tuple.Create(view, view.BufferGraph.CreateMappingPoint(point.Value, PointTrackingMode.Negative)));
}
}
return result;
}
private void RestoreCaretPositions()
{
if (_caretChanged)
{
return;
}
foreach (var tuple in _caretPositions)
{
var position = tuple.Item1.GetCaretPoint(_subjectBuffer);
if (position != null)
{
var view = tuple.Item1;
if (!view.IsClosed)
{
view.TryMoveCaretToAndEnsureVisible(position.Value);
}
}
}
}
public void Dispose()
{
RestoreCaretPositions();
foreach (var tuple in _caretPositions)
{
tuple.Item1.Caret.PositionChanged -= _caretPositionChangedHandler;
}
}
}
}
}
| -1 |
dotnet/roslyn | 55,877 | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute | Part of C# 10 support | davidwengier | 2021-08-25T05:36:27Z | 2021-08-30T20:47:11Z | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | 023d3ca2b5fb429f0b3dcc1efeed39442e232dba | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute. Part of C# 10 support | ./src/VisualStudio/Core/Def/Implementation/TableDataSource/DiagnosticTableControlEventProcessorProvider.AggregateDiagnosticTableControlEventProcessor.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using Microsoft.VisualStudio.Shell.TableControl;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.TableDataSource
{
internal partial class DiagnosticTableControlEventProcessorProvider
{
private class AggregateDiagnosticTableControlEventProcessor : EventProcessor
{
private readonly ImmutableArray<EventProcessor> _additionalEventProcessors;
public AggregateDiagnosticTableControlEventProcessor(params EventProcessor[] additionalEventProcessors)
=> _additionalEventProcessors = additionalEventProcessors.ToImmutableArray();
public override void PostprocessSelectionChanged(TableSelectionChangedEventArgs e)
{
base.PostprocessSelectionChanged(e);
foreach (var processor in _additionalEventProcessors)
{
processor.PostprocessSelectionChanged(e);
}
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using Microsoft.VisualStudio.Shell.TableControl;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.TableDataSource
{
internal partial class DiagnosticTableControlEventProcessorProvider
{
private class AggregateDiagnosticTableControlEventProcessor : EventProcessor
{
private readonly ImmutableArray<EventProcessor> _additionalEventProcessors;
public AggregateDiagnosticTableControlEventProcessor(params EventProcessor[] additionalEventProcessors)
=> _additionalEventProcessors = additionalEventProcessors.ToImmutableArray();
public override void PostprocessSelectionChanged(TableSelectionChangedEventArgs e)
{
base.PostprocessSelectionChanged(e);
foreach (var processor in _additionalEventProcessors)
{
processor.PostprocessSelectionChanged(e);
}
}
}
}
}
| -1 |
dotnet/roslyn | 55,877 | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute | Part of C# 10 support | davidwengier | 2021-08-25T05:36:27Z | 2021-08-30T20:47:11Z | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | 023d3ca2b5fb429f0b3dcc1efeed39442e232dba | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute. Part of C# 10 support | ./src/VisualStudio/IntegrationTest/TestUtilities/InProcess/Shell_InProc.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
namespace Microsoft.VisualStudio.IntegrationTest.Utilities.InProcess
{
internal class Shell_InProc : InProcComponent
{
public static Shell_InProc Create() => new Shell_InProc();
public string GetVersion()
{
return InvokeOnUIThread(cancellationToken =>
{
var shell = GetGlobalService<SVsShell, IVsShell>();
ErrorHandler.ThrowOnFailure(shell.GetProperty((int)__VSSPROPID5.VSSPROPID_ReleaseVersion, out var version));
return (string)version;
});
}
public string GetActiveWindowCaption()
=> InvokeOnUIThread(cancellationToken => GetDTE().ActiveWindow.Caption);
public IntPtr GetHWnd()
=> (IntPtr)GetDTE().MainWindow.HWnd;
public bool IsActiveTabProvisional()
=> InvokeOnUIThread(cancellationToken =>
{
var shellMonitorSelection = GetGlobalService<SVsShellMonitorSelection, IVsMonitorSelection>();
if (!ErrorHandler.Succeeded(shellMonitorSelection.GetCurrentElementValue((uint)VSConstants.VSSELELEMID.SEID_DocumentFrame, out var windowFrameObject)))
{
throw new InvalidOperationException("Tried to get the active document frame but no documents were open.");
}
var windowFrame = (IVsWindowFrame)windowFrameObject;
if (!ErrorHandler.Succeeded(windowFrame.GetProperty((int)VsFramePropID.IsProvisional, out var isProvisionalObject)))
{
throw new InvalidOperationException("The active window frame did not have an 'IsProvisional' property.");
}
return (bool)isProvisionalObject;
});
public bool IsUIContextActive(Guid context)
{
return UIContext.FromUIContextGuid(context).IsActive;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
namespace Microsoft.VisualStudio.IntegrationTest.Utilities.InProcess
{
internal class Shell_InProc : InProcComponent
{
public static Shell_InProc Create() => new Shell_InProc();
public string GetVersion()
{
return InvokeOnUIThread(cancellationToken =>
{
var shell = GetGlobalService<SVsShell, IVsShell>();
ErrorHandler.ThrowOnFailure(shell.GetProperty((int)__VSSPROPID5.VSSPROPID_ReleaseVersion, out var version));
return (string)version;
});
}
public string GetActiveWindowCaption()
=> InvokeOnUIThread(cancellationToken => GetDTE().ActiveWindow.Caption);
public IntPtr GetHWnd()
=> (IntPtr)GetDTE().MainWindow.HWnd;
public bool IsActiveTabProvisional()
=> InvokeOnUIThread(cancellationToken =>
{
var shellMonitorSelection = GetGlobalService<SVsShellMonitorSelection, IVsMonitorSelection>();
if (!ErrorHandler.Succeeded(shellMonitorSelection.GetCurrentElementValue((uint)VSConstants.VSSELELEMID.SEID_DocumentFrame, out var windowFrameObject)))
{
throw new InvalidOperationException("Tried to get the active document frame but no documents were open.");
}
var windowFrame = (IVsWindowFrame)windowFrameObject;
if (!ErrorHandler.Succeeded(windowFrame.GetProperty((int)VsFramePropID.IsProvisional, out var isProvisionalObject)))
{
throw new InvalidOperationException("The active window frame did not have an 'IsProvisional' property.");
}
return (bool)isProvisionalObject;
});
public bool IsUIContextActive(Guid context)
{
return UIContext.FromUIContextGuid(context).IsActive;
}
}
}
| -1 |
dotnet/roslyn | 55,877 | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute | Part of C# 10 support | davidwengier | 2021-08-25T05:36:27Z | 2021-08-30T20:47:11Z | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | 023d3ca2b5fb429f0b3dcc1efeed39442e232dba | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute. Part of C# 10 support | ./src/Analyzers/Core/Analyzers/xlf/AnalyzersResources.pt-BR.xlf | <?xml version="1.0" encoding="utf-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd">
<file datatype="xml" source-language="en" target-language="pt-BR" original="../AnalyzersResources.resx">
<body>
<trans-unit id="A_source_file_contains_a_header_that_does_not_match_the_required_text">
<source>A source file contains a header that does not match the required text</source>
<target state="translated">Um arquivo de origem contém um cabeçalho que não corresponde ao texto necessário</target>
<note />
</trans-unit>
<trans-unit id="A_source_file_is_missing_a_required_header">
<source>A source file is missing a required header.</source>
<target state="translated">Um arquivo de origem não tem um cabeçalho necessário.</target>
<note />
</trans-unit>
<trans-unit id="Accessibility_modifiers_required">
<source>Accessibility modifiers required</source>
<target state="translated">Modificadores de acessibilidade necessários</target>
<note />
</trans-unit>
<trans-unit id="Add_accessibility_modifiers">
<source>Add accessibility modifiers</source>
<target state="translated">Adicionar modificadores de acessibilidade</target>
<note />
</trans-unit>
<trans-unit id="Add_parentheses_for_clarity">
<source>Add parentheses for clarity</source>
<target state="translated">Adicionar parênteses para esclarecimento</target>
<note />
</trans-unit>
<trans-unit id="Add_readonly_modifier">
<source>Add readonly modifier</source>
<target state="translated">Adicionar modificador somente leitura</target>
<note />
</trans-unit>
<trans-unit id="Add_this_or_Me_qualification">
<source>Add 'this' or 'Me' qualification.</source>
<target state="translated">Adicionar a qualificação 'this' ou 'Me'.</target>
<note />
</trans-unit>
<trans-unit id="Avoid_legacy_format_target_0_in_SuppressMessageAttribute">
<source>Avoid legacy format target '{0}' in 'SuppressMessageAttribute'</source>
<target state="translated">Evite o destino de formato herdado '{0}' em 'SuppressMessageAttribute'</target>
<note />
</trans-unit>
<trans-unit id="Avoid_legacy_format_target_in_SuppressMessageAttribute">
<source>Avoid legacy format target in 'SuppressMessageAttribute'</source>
<target state="translated">Evite o destino de formato herdado em 'SuppressMessageAttribute'</target>
<note />
</trans-unit>
<trans-unit id="Avoid_multiple_blank_lines">
<source>Avoid multiple blank lines</source>
<target state="translated">Evite várias linhas em branco</target>
<note />
</trans-unit>
<trans-unit id="Avoid_unnecessary_value_assignments_in_your_code_as_these_likely_indicate_redundant_value_computations_If_the_value_computation_is_not_redundant_and_you_intend_to_retain_the_assignmentcomma_then_change_the_assignment_target_to_a_local_variable_whose_name_starts_with_an_underscore_and_is_optionally_followed_by_an_integercomma_such_as___comma__1_comma__2_comma_etc">
<source>Avoid unnecessary value assignments in your code, as these likely indicate redundant value computations. If the value computation is not redundant and you intend to retain the assignment, then change the assignment target to a local variable whose name starts with an underscore and is optionally followed by an integer, such as '_', '_1', '_2', etc. These are treated as special discard symbol names.</source>
<target state="translated">Evite atribuições de valor desnecessárias no código, pois isso pode indicar cálculos de valor redundantes. Se o cálculo do valor não for redundante e você pretender reter a atribuição, altere o destino da atribuição para uma variável local cujo nome comece com um sublinhado e seja seguido opcionalmente por um inteiro, como '_', '_1', '_2' etc. Esses nomes são tratados como nomes de símbolo de descarte especiais.</target>
<note />
</trans-unit>
<trans-unit id="Avoid_unused_parameters_in_your_code_If_the_parameter_cannot_be_removed_then_change_its_name_so_it_starts_with_an_underscore_and_is_optionally_followed_by_an_integer_such_as__comma__1_comma__2_etc_These_are_treated_as_special_discard_symbol_names">
<source>Avoid unused parameters in your code. If the parameter cannot be removed, then change its name so it starts with an underscore and is optionally followed by an integer, such as '_', '_1', '_2', etc. These are treated as special discard symbol names.</source>
<target state="translated">Evite parâmetros não usados no seu código. Se o parâmetro não puder ser removido, altere o nome para que ele comece com um sublinhado e seja seguido opcionalmente por um inteiro, como '_', '_1', '_2' etc. Esses nomes são tratados como nomes de símbolo de descarte especiais.</target>
<note />
</trans-unit>
<trans-unit id="Blank_line_required_between_block_and_subsequent_statement">
<source>Blank line required between block and subsequent statement</source>
<target state="translated">Linha em branco necessária entre o bloco e a próxima instrução</target>
<note />
</trans-unit>
<trans-unit id="Change_namespace_to_match_folder_structure">
<source>Change namespace to match folder structure</source>
<target state="translated">Alterar o namespace para corresponder à estrutura da pasta</target>
<note>{Locked="namespace"} "namespace" is a keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Changes_to_expression_trees_may_result_in_behavior_changes_at_runtime">
<source>Changes to expression trees may result in behavior changes at runtime</source>
<target state="translated">Alterações nas árvores de expressão podem resultar em alterações de comportamento no tempo de execução</target>
<note />
</trans-unit>
<trans-unit id="Conditional_expression_can_be_simplified">
<source>Conditional expression can be simplified</source>
<target state="translated">A expressão condicional pode ser simplificada</target>
<note />
</trans-unit>
<trans-unit id="Convert_to_conditional_expression">
<source>Convert to conditional expression</source>
<target state="translated">Converter em expressão condicional</target>
<note />
</trans-unit>
<trans-unit id="Convert_to_tuple">
<source>Convert to tuple</source>
<target state="translated">Converter a tupla</target>
<note />
</trans-unit>
<trans-unit id="Expression_value_is_never_used">
<source>Expression value is never used</source>
<target state="translated">O valor da expressão nunca é usado</target>
<note />
</trans-unit>
<trans-unit id="Collection_initialization_can_be_simplified">
<source>Collection initialization can be simplified</source>
<target state="translated">A inicialização de coleção pode ser simplificada</target>
<note />
</trans-unit>
<trans-unit id="Format_string_contains_invalid_placeholder">
<source>Format string contains invalid placeholder</source>
<target state="translated">A cadeia de formato contém espaço reservado inválido</target>
<note />
</trans-unit>
<trans-unit id="GetHashCode_implementation_can_be_simplified">
<source>'GetHashCode' implementation can be simplified</source>
<target state="translated">A implementação de 'GetHashCode' pode ser simplificada</target>
<note />
</trans-unit>
<trans-unit id="Interpolation_can_be_simplified">
<source>Interpolation can be simplified</source>
<target state="translated">A interpolação pode ser simplificada</target>
<note />
</trans-unit>
<trans-unit id="Invalid_format_string">
<source>Invalid format string</source>
<target state="translated">Cadeia de formato inválida</target>
<note />
</trans-unit>
<trans-unit id="Invalid_global_SuppressMessageAttribute">
<source>Invalid global 'SuppressMessageAttribute'</source>
<target state="translated">'SuppressMessageAttribute' global inválido</target>
<note />
</trans-unit>
<trans-unit id="Invalid_or_missing_target_for_SuppressMessageAttribute">
<source>Invalid or missing target for 'SuppressMessageAttribute'</source>
<target state="translated">Destino ausente ou inválido de 'SuppressMessageAttribute'</target>
<note />
</trans-unit>
<trans-unit id="Invalid_scope_for_SuppressMessageAttribute">
<source>Invalid scope for 'SuppressMessageAttribute'</source>
<target state="translated">Escopo inválido de 'SuppressMessageAttribute'</target>
<note />
</trans-unit>
<trans-unit id="Make_field_readonly">
<source>Make field readonly</source>
<target state="translated">Tornar campo somente leitura</target>
<note />
</trans-unit>
<trans-unit id="Member_access_should_be_qualified">
<source>Member access should be qualified.</source>
<target state="translated">O acesso de membro deve ser qualificado.</target>
<note />
</trans-unit>
<trans-unit id="Add_missing_cases">
<source>Add missing cases</source>
<target state="translated">Adicionar casos ausentes</target>
<note />
</trans-unit>
<trans-unit id="Member_name_can_be_simplified">
<source>Member name can be simplified</source>
<target state="translated">O nome do membro pode ser simplificado</target>
<note />
</trans-unit>
<trans-unit id="Modifiers_are_not_ordered">
<source>Modifiers are not ordered</source>
<target state="translated">Os modificadores não são ordenados</target>
<note />
</trans-unit>
<trans-unit id="Namespace_0_does_not_match_folder_structure_expected_1">
<source>Namespace "{0}" does not match folder structure, expected "{1}"</source>
<target state="translated">O namespace "{0}" não corresponde à estrutura da pasta. Esperava-se "{1}"</target>
<note>{Locked="namespace"} "namespace" is a keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Namespace_does_not_match_folder_structure">
<source>Namespace does not match folder structure</source>
<target state="translated">O namespace não corresponde à estrutura da pasta</target>
<note>{Locked="namespace"} "namespace" is a keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Naming_Styles">
<source>Naming Styles</source>
<target state="translated">Estilos de Nomenclatura</target>
<note />
</trans-unit>
<trans-unit id="Naming_rule_violation_0">
<source>Naming rule violation: {0}</source>
<target state="translated">Violação da regra de nomenclatura: {0}</target>
<note>{0} is the rule title, {1} is the way in which the rule was violated</note>
</trans-unit>
<trans-unit id="Null_check_can_be_simplified">
<source>Null check can be simplified</source>
<target state="translated">A seleção nula pode ser simplificada</target>
<note />
</trans-unit>
<trans-unit id="Order_modifiers">
<source>Order modifiers</source>
<target state="translated">Modificadores de ordem</target>
<note />
</trans-unit>
<trans-unit id="Parameter_0_can_be_removed_if_it_is_not_part_of_a_shipped_public_API_its_initial_value_is_never_used">
<source>Parameter '{0}' can be removed if it is not part of a shipped public API; its initial value is never used</source>
<target state="translated">O parâmetro '{0}' pode ser removido quando não faz parte de uma API pública enviada. Seu valor inicial nunca é usado</target>
<note />
</trans-unit>
<trans-unit id="Parameter_0_can_be_removed_its_initial_value_is_never_used">
<source>Parameter '{0}' can be removed; its initial value is never used</source>
<target state="translated">O parâmetro '{0}' pode ser removido. Seu valor inicial nunca é usado</target>
<note />
</trans-unit>
<trans-unit id="Object_initialization_can_be_simplified">
<source>Object initialization can be simplified</source>
<target state="translated">A inicialização do objeto pode ser simplificada</target>
<note />
</trans-unit>
<trans-unit id="Parentheses_can_be_removed">
<source>Parentheses can be removed</source>
<target state="translated">Os parênteses podem ser removidos</target>
<note />
</trans-unit>
<trans-unit id="Parentheses_should_be_added_for_clarity">
<source>Parentheses should be added for clarity</source>
<target state="translated">Os parênteses devem ser adicionados para esclarecimento</target>
<note />
</trans-unit>
<trans-unit id="Populate_switch">
<source>Populate switch</source>
<target state="translated">Popular comutador</target>
<note />
</trans-unit>
<trans-unit id="Prefer_explicitly_provided_tuple_element_name">
<source>Prefer explicitly provided tuple element name</source>
<target state="translated">Preferir o nome do elemento de tupla fornecido explicitamente</target>
<note />
</trans-unit>
<trans-unit id="Private_member_0_can_be_removed_as_the_value_assigned_to_it_is_never_read">
<source>Private member '{0}' can be removed as the value assigned to it is never read</source>
<target state="translated">O membro privado '{0}' pode ser removido, pois o valor atribuído a ele nunca é lido</target>
<note />
</trans-unit>
<trans-unit id="Private_member_0_is_unused">
<source>Private member '{0}' is unused</source>
<target state="translated">O membro privado '{0}' não é usado</target>
<note />
</trans-unit>
<trans-unit id="Private_method_0_can_be_removed_as_it_is_never_invoked">
<source>Private method '{0}' can be removed as it is never invoked.</source>
<target state="translated">O método particular '{0}' pode ser removido pois nunca é invocado.</target>
<note />
</trans-unit>
<trans-unit id="Private_property_0_can_be_converted_to_a_method_as_its_get_accessor_is_never_invoked">
<source>Private property '{0}' can be converted to a method as its get accessor is never invoked.</source>
<target state="translated">A propriedade privada '{0}' pode ser convertida em um método porque seu acessador get nunca é invocado.</target>
<note />
</trans-unit>
<trans-unit id="Remove_Unnecessary_Cast">
<source>Remove Unnecessary Cast</source>
<target state="translated">Remover Conversão Desnecessária</target>
<note />
</trans-unit>
<trans-unit id="Remove_redundant_equality">
<source>Remove redundant equality</source>
<target state="translated">Remover a igualdade redundante</target>
<note />
</trans-unit>
<trans-unit id="Remove_unnecessary_parentheses">
<source>Remove unnecessary parentheses</source>
<target state="translated">Remover os parênteses desnecessários</target>
<note />
</trans-unit>
<trans-unit id="Remove_unnecessary_suppression">
<source>Remove unnecessary suppression</source>
<target state="translated">Remover a supressão desnecessária</target>
<note />
</trans-unit>
<trans-unit id="Remove_unread_private_members">
<source>Remove unread private members</source>
<target state="translated">Remover membros particulares não lidos</target>
<note />
</trans-unit>
<trans-unit id="Remove_unused_member">
<source>Remove unused member</source>
<target state="translated">Remover membro não utilizado</target>
<note />
</trans-unit>
<trans-unit id="Remove_unused_parameter">
<source>Remove unused parameter</source>
<target state="translated">Remover o parâmetro não utilizado</target>
<note />
</trans-unit>
<trans-unit id="Remove_unused_parameter_0">
<source>Remove unused parameter '{0}'</source>
<target state="translated">Remover o parâmetro não usado '{0}'</target>
<note />
</trans-unit>
<trans-unit id="Remove_unused_parameter_0_if_it_is_not_part_of_a_shipped_public_API">
<source>Remove unused parameter '{0}' if it is not part of a shipped public API</source>
<target state="translated">Remover o parâmetro não usado '{0}' se ele não fizer parte de uma API pública enviada</target>
<note />
</trans-unit>
<trans-unit id="Remove_unused_private_members">
<source>Remove unused private members</source>
<target state="translated">Remover membros privados não utilizados</target>
<note />
</trans-unit>
<trans-unit id="Simplify_LINQ_expression">
<source>Simplify LINQ expression</source>
<target state="translated">Simplificar a expressão LINQ</target>
<note />
</trans-unit>
<trans-unit id="Simplify_collection_initialization">
<source>Simplify collection initialization</source>
<target state="translated">Simplificar a inicialização de coleção</target>
<note />
</trans-unit>
<trans-unit id="Simplify_conditional_expression">
<source>Simplify conditional expression</source>
<target state="translated">Simplificar a expressão condicional</target>
<note />
</trans-unit>
<trans-unit id="Simplify_interpolation">
<source>Simplify interpolation</source>
<target state="translated">Simplificar interpolação</target>
<note />
</trans-unit>
<trans-unit id="Simplify_object_initialization">
<source>Simplify object initialization</source>
<target state="translated">Simplificar a inicialização de objeto</target>
<note />
</trans-unit>
<trans-unit id="The_file_header_does_not_match_the_required_text">
<source>The file header does not match the required text</source>
<target state="translated">O cabeçalho do arquivo não corresponde ao texto necessário</target>
<note />
</trans-unit>
<trans-unit id="The_file_header_is_missing_or_not_located_at_the_top_of_the_file">
<source>The file header is missing or not located at the top of the file</source>
<target state="translated">O cabeçalho do arquivo está ausente ou não está localizado na parte superior do arquivo</target>
<note />
</trans-unit>
<trans-unit id="Unnecessary_assignment_of_a_value">
<source>Unnecessary assignment of a value</source>
<target state="translated">Atribuição desnecessária de um valor</target>
<note />
</trans-unit>
<trans-unit id="Unnecessary_assignment_of_a_value_to_0">
<source>Unnecessary assignment of a value to '{0}'</source>
<target state="translated">Atribuição desnecessária de um valor para '{0}'</target>
<note />
</trans-unit>
<trans-unit id="Use_System_HashCode">
<source>Use 'System.HashCode'</source>
<target state="translated">Use 'System.HashCode'</target>
<note />
</trans-unit>
<trans-unit id="Use_auto_property">
<source>Use auto property</source>
<target state="translated">Usar a propriedade auto</target>
<note />
</trans-unit>
<trans-unit id="Use_coalesce_expression">
<source>Use coalesce expression</source>
<target state="translated">Usar a expressão de união</target>
<note />
</trans-unit>
<trans-unit id="Use_compound_assignment">
<source>Use compound assignment</source>
<target state="translated">Usar a atribuição composta</target>
<note />
</trans-unit>
<trans-unit id="Use_decrement_operator">
<source>Use '--' operator</source>
<target state="translated">Usar o operador '--'</target>
<note />
</trans-unit>
<trans-unit id="Use_explicitly_provided_tuple_name">
<source>Use explicitly provided tuple name</source>
<target state="translated">Usar o nome de tupla fornecido explicitamente</target>
<note />
</trans-unit>
<trans-unit id="Use_increment_operator">
<source>Use '++' operator</source>
<target state="translated">Usar o operador '++'</target>
<note />
</trans-unit>
<trans-unit id="Use_inferred_member_name">
<source>Use inferred member name</source>
<target state="translated">Usar o nome do membro inferido</target>
<note />
</trans-unit>
<trans-unit id="Use_null_propagation">
<source>Use null propagation</source>
<target state="translated">Usar tratamento simplificado de nulo</target>
<note />
</trans-unit>
<trans-unit id="Use_throw_expression">
<source>Use 'throw' expression</source>
<target state="translated">Use a expressão 'throw'</target>
<note />
</trans-unit>
</body>
</file>
</xliff> | <?xml version="1.0" encoding="utf-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd">
<file datatype="xml" source-language="en" target-language="pt-BR" original="../AnalyzersResources.resx">
<body>
<trans-unit id="A_source_file_contains_a_header_that_does_not_match_the_required_text">
<source>A source file contains a header that does not match the required text</source>
<target state="translated">Um arquivo de origem contém um cabeçalho que não corresponde ao texto necessário</target>
<note />
</trans-unit>
<trans-unit id="A_source_file_is_missing_a_required_header">
<source>A source file is missing a required header.</source>
<target state="translated">Um arquivo de origem não tem um cabeçalho necessário.</target>
<note />
</trans-unit>
<trans-unit id="Accessibility_modifiers_required">
<source>Accessibility modifiers required</source>
<target state="translated">Modificadores de acessibilidade necessários</target>
<note />
</trans-unit>
<trans-unit id="Add_accessibility_modifiers">
<source>Add accessibility modifiers</source>
<target state="translated">Adicionar modificadores de acessibilidade</target>
<note />
</trans-unit>
<trans-unit id="Add_parentheses_for_clarity">
<source>Add parentheses for clarity</source>
<target state="translated">Adicionar parênteses para esclarecimento</target>
<note />
</trans-unit>
<trans-unit id="Add_readonly_modifier">
<source>Add readonly modifier</source>
<target state="translated">Adicionar modificador somente leitura</target>
<note />
</trans-unit>
<trans-unit id="Add_this_or_Me_qualification">
<source>Add 'this' or 'Me' qualification.</source>
<target state="translated">Adicionar a qualificação 'this' ou 'Me'.</target>
<note />
</trans-unit>
<trans-unit id="Avoid_legacy_format_target_0_in_SuppressMessageAttribute">
<source>Avoid legacy format target '{0}' in 'SuppressMessageAttribute'</source>
<target state="translated">Evite o destino de formato herdado '{0}' em 'SuppressMessageAttribute'</target>
<note />
</trans-unit>
<trans-unit id="Avoid_legacy_format_target_in_SuppressMessageAttribute">
<source>Avoid legacy format target in 'SuppressMessageAttribute'</source>
<target state="translated">Evite o destino de formato herdado em 'SuppressMessageAttribute'</target>
<note />
</trans-unit>
<trans-unit id="Avoid_multiple_blank_lines">
<source>Avoid multiple blank lines</source>
<target state="translated">Evite várias linhas em branco</target>
<note />
</trans-unit>
<trans-unit id="Avoid_unnecessary_value_assignments_in_your_code_as_these_likely_indicate_redundant_value_computations_If_the_value_computation_is_not_redundant_and_you_intend_to_retain_the_assignmentcomma_then_change_the_assignment_target_to_a_local_variable_whose_name_starts_with_an_underscore_and_is_optionally_followed_by_an_integercomma_such_as___comma__1_comma__2_comma_etc">
<source>Avoid unnecessary value assignments in your code, as these likely indicate redundant value computations. If the value computation is not redundant and you intend to retain the assignment, then change the assignment target to a local variable whose name starts with an underscore and is optionally followed by an integer, such as '_', '_1', '_2', etc. These are treated as special discard symbol names.</source>
<target state="translated">Evite atribuições de valor desnecessárias no código, pois isso pode indicar cálculos de valor redundantes. Se o cálculo do valor não for redundante e você pretender reter a atribuição, altere o destino da atribuição para uma variável local cujo nome comece com um sublinhado e seja seguido opcionalmente por um inteiro, como '_', '_1', '_2' etc. Esses nomes são tratados como nomes de símbolo de descarte especiais.</target>
<note />
</trans-unit>
<trans-unit id="Avoid_unused_parameters_in_your_code_If_the_parameter_cannot_be_removed_then_change_its_name_so_it_starts_with_an_underscore_and_is_optionally_followed_by_an_integer_such_as__comma__1_comma__2_etc_These_are_treated_as_special_discard_symbol_names">
<source>Avoid unused parameters in your code. If the parameter cannot be removed, then change its name so it starts with an underscore and is optionally followed by an integer, such as '_', '_1', '_2', etc. These are treated as special discard symbol names.</source>
<target state="translated">Evite parâmetros não usados no seu código. Se o parâmetro não puder ser removido, altere o nome para que ele comece com um sublinhado e seja seguido opcionalmente por um inteiro, como '_', '_1', '_2' etc. Esses nomes são tratados como nomes de símbolo de descarte especiais.</target>
<note />
</trans-unit>
<trans-unit id="Blank_line_required_between_block_and_subsequent_statement">
<source>Blank line required between block and subsequent statement</source>
<target state="translated">Linha em branco necessária entre o bloco e a próxima instrução</target>
<note />
</trans-unit>
<trans-unit id="Change_namespace_to_match_folder_structure">
<source>Change namespace to match folder structure</source>
<target state="translated">Alterar o namespace para corresponder à estrutura da pasta</target>
<note>{Locked="namespace"} "namespace" is a keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Changes_to_expression_trees_may_result_in_behavior_changes_at_runtime">
<source>Changes to expression trees may result in behavior changes at runtime</source>
<target state="translated">Alterações nas árvores de expressão podem resultar em alterações de comportamento no tempo de execução</target>
<note />
</trans-unit>
<trans-unit id="Conditional_expression_can_be_simplified">
<source>Conditional expression can be simplified</source>
<target state="translated">A expressão condicional pode ser simplificada</target>
<note />
</trans-unit>
<trans-unit id="Convert_to_conditional_expression">
<source>Convert to conditional expression</source>
<target state="translated">Converter em expressão condicional</target>
<note />
</trans-unit>
<trans-unit id="Convert_to_tuple">
<source>Convert to tuple</source>
<target state="translated">Converter a tupla</target>
<note />
</trans-unit>
<trans-unit id="Expression_value_is_never_used">
<source>Expression value is never used</source>
<target state="translated">O valor da expressão nunca é usado</target>
<note />
</trans-unit>
<trans-unit id="Collection_initialization_can_be_simplified">
<source>Collection initialization can be simplified</source>
<target state="translated">A inicialização de coleção pode ser simplificada</target>
<note />
</trans-unit>
<trans-unit id="Format_string_contains_invalid_placeholder">
<source>Format string contains invalid placeholder</source>
<target state="translated">A cadeia de formato contém espaço reservado inválido</target>
<note />
</trans-unit>
<trans-unit id="GetHashCode_implementation_can_be_simplified">
<source>'GetHashCode' implementation can be simplified</source>
<target state="translated">A implementação de 'GetHashCode' pode ser simplificada</target>
<note />
</trans-unit>
<trans-unit id="Interpolation_can_be_simplified">
<source>Interpolation can be simplified</source>
<target state="translated">A interpolação pode ser simplificada</target>
<note />
</trans-unit>
<trans-unit id="Invalid_format_string">
<source>Invalid format string</source>
<target state="translated">Cadeia de formato inválida</target>
<note />
</trans-unit>
<trans-unit id="Invalid_global_SuppressMessageAttribute">
<source>Invalid global 'SuppressMessageAttribute'</source>
<target state="translated">'SuppressMessageAttribute' global inválido</target>
<note />
</trans-unit>
<trans-unit id="Invalid_or_missing_target_for_SuppressMessageAttribute">
<source>Invalid or missing target for 'SuppressMessageAttribute'</source>
<target state="translated">Destino ausente ou inválido de 'SuppressMessageAttribute'</target>
<note />
</trans-unit>
<trans-unit id="Invalid_scope_for_SuppressMessageAttribute">
<source>Invalid scope for 'SuppressMessageAttribute'</source>
<target state="translated">Escopo inválido de 'SuppressMessageAttribute'</target>
<note />
</trans-unit>
<trans-unit id="Make_field_readonly">
<source>Make field readonly</source>
<target state="translated">Tornar campo somente leitura</target>
<note />
</trans-unit>
<trans-unit id="Member_access_should_be_qualified">
<source>Member access should be qualified.</source>
<target state="translated">O acesso de membro deve ser qualificado.</target>
<note />
</trans-unit>
<trans-unit id="Add_missing_cases">
<source>Add missing cases</source>
<target state="translated">Adicionar casos ausentes</target>
<note />
</trans-unit>
<trans-unit id="Member_name_can_be_simplified">
<source>Member name can be simplified</source>
<target state="translated">O nome do membro pode ser simplificado</target>
<note />
</trans-unit>
<trans-unit id="Modifiers_are_not_ordered">
<source>Modifiers are not ordered</source>
<target state="translated">Os modificadores não são ordenados</target>
<note />
</trans-unit>
<trans-unit id="Namespace_0_does_not_match_folder_structure_expected_1">
<source>Namespace "{0}" does not match folder structure, expected "{1}"</source>
<target state="translated">O namespace "{0}" não corresponde à estrutura da pasta. Esperava-se "{1}"</target>
<note>{Locked="namespace"} "namespace" is a keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Namespace_does_not_match_folder_structure">
<source>Namespace does not match folder structure</source>
<target state="translated">O namespace não corresponde à estrutura da pasta</target>
<note>{Locked="namespace"} "namespace" is a keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Naming_Styles">
<source>Naming Styles</source>
<target state="translated">Estilos de Nomenclatura</target>
<note />
</trans-unit>
<trans-unit id="Naming_rule_violation_0">
<source>Naming rule violation: {0}</source>
<target state="translated">Violação da regra de nomenclatura: {0}</target>
<note>{0} is the rule title, {1} is the way in which the rule was violated</note>
</trans-unit>
<trans-unit id="Null_check_can_be_simplified">
<source>Null check can be simplified</source>
<target state="translated">A seleção nula pode ser simplificada</target>
<note />
</trans-unit>
<trans-unit id="Order_modifiers">
<source>Order modifiers</source>
<target state="translated">Modificadores de ordem</target>
<note />
</trans-unit>
<trans-unit id="Parameter_0_can_be_removed_if_it_is_not_part_of_a_shipped_public_API_its_initial_value_is_never_used">
<source>Parameter '{0}' can be removed if it is not part of a shipped public API; its initial value is never used</source>
<target state="translated">O parâmetro '{0}' pode ser removido quando não faz parte de uma API pública enviada. Seu valor inicial nunca é usado</target>
<note />
</trans-unit>
<trans-unit id="Parameter_0_can_be_removed_its_initial_value_is_never_used">
<source>Parameter '{0}' can be removed; its initial value is never used</source>
<target state="translated">O parâmetro '{0}' pode ser removido. Seu valor inicial nunca é usado</target>
<note />
</trans-unit>
<trans-unit id="Object_initialization_can_be_simplified">
<source>Object initialization can be simplified</source>
<target state="translated">A inicialização do objeto pode ser simplificada</target>
<note />
</trans-unit>
<trans-unit id="Parentheses_can_be_removed">
<source>Parentheses can be removed</source>
<target state="translated">Os parênteses podem ser removidos</target>
<note />
</trans-unit>
<trans-unit id="Parentheses_should_be_added_for_clarity">
<source>Parentheses should be added for clarity</source>
<target state="translated">Os parênteses devem ser adicionados para esclarecimento</target>
<note />
</trans-unit>
<trans-unit id="Populate_switch">
<source>Populate switch</source>
<target state="translated">Popular comutador</target>
<note />
</trans-unit>
<trans-unit id="Prefer_explicitly_provided_tuple_element_name">
<source>Prefer explicitly provided tuple element name</source>
<target state="translated">Preferir o nome do elemento de tupla fornecido explicitamente</target>
<note />
</trans-unit>
<trans-unit id="Private_member_0_can_be_removed_as_the_value_assigned_to_it_is_never_read">
<source>Private member '{0}' can be removed as the value assigned to it is never read</source>
<target state="translated">O membro privado '{0}' pode ser removido, pois o valor atribuído a ele nunca é lido</target>
<note />
</trans-unit>
<trans-unit id="Private_member_0_is_unused">
<source>Private member '{0}' is unused</source>
<target state="translated">O membro privado '{0}' não é usado</target>
<note />
</trans-unit>
<trans-unit id="Private_method_0_can_be_removed_as_it_is_never_invoked">
<source>Private method '{0}' can be removed as it is never invoked.</source>
<target state="translated">O método particular '{0}' pode ser removido pois nunca é invocado.</target>
<note />
</trans-unit>
<trans-unit id="Private_property_0_can_be_converted_to_a_method_as_its_get_accessor_is_never_invoked">
<source>Private property '{0}' can be converted to a method as its get accessor is never invoked.</source>
<target state="translated">A propriedade privada '{0}' pode ser convertida em um método porque seu acessador get nunca é invocado.</target>
<note />
</trans-unit>
<trans-unit id="Remove_Unnecessary_Cast">
<source>Remove Unnecessary Cast</source>
<target state="translated">Remover Conversão Desnecessária</target>
<note />
</trans-unit>
<trans-unit id="Remove_redundant_equality">
<source>Remove redundant equality</source>
<target state="translated">Remover a igualdade redundante</target>
<note />
</trans-unit>
<trans-unit id="Remove_unnecessary_parentheses">
<source>Remove unnecessary parentheses</source>
<target state="translated">Remover os parênteses desnecessários</target>
<note />
</trans-unit>
<trans-unit id="Remove_unnecessary_suppression">
<source>Remove unnecessary suppression</source>
<target state="translated">Remover a supressão desnecessária</target>
<note />
</trans-unit>
<trans-unit id="Remove_unread_private_members">
<source>Remove unread private members</source>
<target state="translated">Remover membros particulares não lidos</target>
<note />
</trans-unit>
<trans-unit id="Remove_unused_member">
<source>Remove unused member</source>
<target state="translated">Remover membro não utilizado</target>
<note />
</trans-unit>
<trans-unit id="Remove_unused_parameter">
<source>Remove unused parameter</source>
<target state="translated">Remover o parâmetro não utilizado</target>
<note />
</trans-unit>
<trans-unit id="Remove_unused_parameter_0">
<source>Remove unused parameter '{0}'</source>
<target state="translated">Remover o parâmetro não usado '{0}'</target>
<note />
</trans-unit>
<trans-unit id="Remove_unused_parameter_0_if_it_is_not_part_of_a_shipped_public_API">
<source>Remove unused parameter '{0}' if it is not part of a shipped public API</source>
<target state="translated">Remover o parâmetro não usado '{0}' se ele não fizer parte de uma API pública enviada</target>
<note />
</trans-unit>
<trans-unit id="Remove_unused_private_members">
<source>Remove unused private members</source>
<target state="translated">Remover membros privados não utilizados</target>
<note />
</trans-unit>
<trans-unit id="Simplify_LINQ_expression">
<source>Simplify LINQ expression</source>
<target state="translated">Simplificar a expressão LINQ</target>
<note />
</trans-unit>
<trans-unit id="Simplify_collection_initialization">
<source>Simplify collection initialization</source>
<target state="translated">Simplificar a inicialização de coleção</target>
<note />
</trans-unit>
<trans-unit id="Simplify_conditional_expression">
<source>Simplify conditional expression</source>
<target state="translated">Simplificar a expressão condicional</target>
<note />
</trans-unit>
<trans-unit id="Simplify_interpolation">
<source>Simplify interpolation</source>
<target state="translated">Simplificar interpolação</target>
<note />
</trans-unit>
<trans-unit id="Simplify_object_initialization">
<source>Simplify object initialization</source>
<target state="translated">Simplificar a inicialização de objeto</target>
<note />
</trans-unit>
<trans-unit id="The_file_header_does_not_match_the_required_text">
<source>The file header does not match the required text</source>
<target state="translated">O cabeçalho do arquivo não corresponde ao texto necessário</target>
<note />
</trans-unit>
<trans-unit id="The_file_header_is_missing_or_not_located_at_the_top_of_the_file">
<source>The file header is missing or not located at the top of the file</source>
<target state="translated">O cabeçalho do arquivo está ausente ou não está localizado na parte superior do arquivo</target>
<note />
</trans-unit>
<trans-unit id="Unnecessary_assignment_of_a_value">
<source>Unnecessary assignment of a value</source>
<target state="translated">Atribuição desnecessária de um valor</target>
<note />
</trans-unit>
<trans-unit id="Unnecessary_assignment_of_a_value_to_0">
<source>Unnecessary assignment of a value to '{0}'</source>
<target state="translated">Atribuição desnecessária de um valor para '{0}'</target>
<note />
</trans-unit>
<trans-unit id="Use_System_HashCode">
<source>Use 'System.HashCode'</source>
<target state="translated">Use 'System.HashCode'</target>
<note />
</trans-unit>
<trans-unit id="Use_auto_property">
<source>Use auto property</source>
<target state="translated">Usar a propriedade auto</target>
<note />
</trans-unit>
<trans-unit id="Use_coalesce_expression">
<source>Use coalesce expression</source>
<target state="translated">Usar a expressão de união</target>
<note />
</trans-unit>
<trans-unit id="Use_compound_assignment">
<source>Use compound assignment</source>
<target state="translated">Usar a atribuição composta</target>
<note />
</trans-unit>
<trans-unit id="Use_decrement_operator">
<source>Use '--' operator</source>
<target state="translated">Usar o operador '--'</target>
<note />
</trans-unit>
<trans-unit id="Use_explicitly_provided_tuple_name">
<source>Use explicitly provided tuple name</source>
<target state="translated">Usar o nome de tupla fornecido explicitamente</target>
<note />
</trans-unit>
<trans-unit id="Use_increment_operator">
<source>Use '++' operator</source>
<target state="translated">Usar o operador '++'</target>
<note />
</trans-unit>
<trans-unit id="Use_inferred_member_name">
<source>Use inferred member name</source>
<target state="translated">Usar o nome do membro inferido</target>
<note />
</trans-unit>
<trans-unit id="Use_null_propagation">
<source>Use null propagation</source>
<target state="translated">Usar tratamento simplificado de nulo</target>
<note />
</trans-unit>
<trans-unit id="Use_throw_expression">
<source>Use 'throw' expression</source>
<target state="translated">Use a expressão 'throw'</target>
<note />
</trans-unit>
</body>
</file>
</xliff> | -1 |
dotnet/roslyn | 55,877 | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute | Part of C# 10 support | davidwengier | 2021-08-25T05:36:27Z | 2021-08-30T20:47:11Z | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | 023d3ca2b5fb429f0b3dcc1efeed39442e232dba | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute. Part of C# 10 support | ./src/Compilers/Core/Portable/Compilation/SyntaxTreeOptionsProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using System.Threading;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis
{
public abstract class SyntaxTreeOptionsProvider
{
/// <summary>
/// Get whether the given tree is generated.
/// </summary>
public abstract GeneratedKind IsGenerated(SyntaxTree tree, CancellationToken cancellationToken);
/// <summary>
/// Get diagnostic severity setting for a given diagnostic identifier in a given tree.
/// </summary>
public abstract bool TryGetDiagnosticValue(SyntaxTree tree, string diagnosticId, CancellationToken cancellationToken, out ReportDiagnostic severity);
/// <summary>
/// Get diagnostic severity set globally for a given diagnostic identifier
/// </summary>
public abstract bool TryGetGlobalDiagnosticValue(string diagnosticId, CancellationToken cancellationToken, out ReportDiagnostic severity);
}
internal sealed class CompilerSyntaxTreeOptionsProvider : SyntaxTreeOptionsProvider
{
private readonly struct Options
{
public readonly GeneratedKind IsGenerated;
public readonly ImmutableDictionary<string, ReportDiagnostic> DiagnosticOptions;
public Options(AnalyzerConfigOptionsResult? result)
{
if (result is AnalyzerConfigOptionsResult r)
{
DiagnosticOptions = r.TreeOptions;
IsGenerated = GeneratedCodeUtilities.GetIsGeneratedCodeFromOptions(r.AnalyzerOptions);
}
else
{
DiagnosticOptions = SyntaxTree.EmptyDiagnosticOptions;
IsGenerated = GeneratedKind.Unknown;
}
}
}
private readonly ImmutableDictionary<SyntaxTree, Options> _options;
private readonly AnalyzerConfigOptionsResult _globalOptions;
public CompilerSyntaxTreeOptionsProvider(
SyntaxTree?[] trees,
ImmutableArray<AnalyzerConfigOptionsResult> results,
AnalyzerConfigOptionsResult globalResults)
{
var builder = ImmutableDictionary.CreateBuilder<SyntaxTree, Options>();
for (int i = 0; i < trees.Length; i++)
{
if (trees[i] != null)
{
builder.Add(
trees[i]!,
new Options(results.IsDefault ? null : (AnalyzerConfigOptionsResult?)results[i]));
}
}
_options = builder.ToImmutableDictionary();
_globalOptions = globalResults;
}
public override GeneratedKind IsGenerated(SyntaxTree tree, CancellationToken _)
=> _options.TryGetValue(tree, out var value) ? value.IsGenerated : GeneratedKind.Unknown;
public override bool TryGetDiagnosticValue(SyntaxTree tree, string diagnosticId, CancellationToken _, out ReportDiagnostic severity)
{
if (_options.TryGetValue(tree, out var value))
{
return value.DiagnosticOptions.TryGetValue(diagnosticId, out severity);
}
severity = ReportDiagnostic.Default;
return false;
}
public override bool TryGetGlobalDiagnosticValue(string diagnosticId, CancellationToken _, out ReportDiagnostic severity)
{
if (_globalOptions.TreeOptions is object)
{
return _globalOptions.TreeOptions.TryGetValue(diagnosticId, out severity);
}
severity = ReportDiagnostic.Default;
return false;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using System.Threading;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis
{
public abstract class SyntaxTreeOptionsProvider
{
/// <summary>
/// Get whether the given tree is generated.
/// </summary>
public abstract GeneratedKind IsGenerated(SyntaxTree tree, CancellationToken cancellationToken);
/// <summary>
/// Get diagnostic severity setting for a given diagnostic identifier in a given tree.
/// </summary>
public abstract bool TryGetDiagnosticValue(SyntaxTree tree, string diagnosticId, CancellationToken cancellationToken, out ReportDiagnostic severity);
/// <summary>
/// Get diagnostic severity set globally for a given diagnostic identifier
/// </summary>
public abstract bool TryGetGlobalDiagnosticValue(string diagnosticId, CancellationToken cancellationToken, out ReportDiagnostic severity);
}
internal sealed class CompilerSyntaxTreeOptionsProvider : SyntaxTreeOptionsProvider
{
private readonly struct Options
{
public readonly GeneratedKind IsGenerated;
public readonly ImmutableDictionary<string, ReportDiagnostic> DiagnosticOptions;
public Options(AnalyzerConfigOptionsResult? result)
{
if (result is AnalyzerConfigOptionsResult r)
{
DiagnosticOptions = r.TreeOptions;
IsGenerated = GeneratedCodeUtilities.GetIsGeneratedCodeFromOptions(r.AnalyzerOptions);
}
else
{
DiagnosticOptions = SyntaxTree.EmptyDiagnosticOptions;
IsGenerated = GeneratedKind.Unknown;
}
}
}
private readonly ImmutableDictionary<SyntaxTree, Options> _options;
private readonly AnalyzerConfigOptionsResult _globalOptions;
public CompilerSyntaxTreeOptionsProvider(
SyntaxTree?[] trees,
ImmutableArray<AnalyzerConfigOptionsResult> results,
AnalyzerConfigOptionsResult globalResults)
{
var builder = ImmutableDictionary.CreateBuilder<SyntaxTree, Options>();
for (int i = 0; i < trees.Length; i++)
{
if (trees[i] != null)
{
builder.Add(
trees[i]!,
new Options(results.IsDefault ? null : (AnalyzerConfigOptionsResult?)results[i]));
}
}
_options = builder.ToImmutableDictionary();
_globalOptions = globalResults;
}
public override GeneratedKind IsGenerated(SyntaxTree tree, CancellationToken _)
=> _options.TryGetValue(tree, out var value) ? value.IsGenerated : GeneratedKind.Unknown;
public override bool TryGetDiagnosticValue(SyntaxTree tree, string diagnosticId, CancellationToken _, out ReportDiagnostic severity)
{
if (_options.TryGetValue(tree, out var value))
{
return value.DiagnosticOptions.TryGetValue(diagnosticId, out severity);
}
severity = ReportDiagnostic.Default;
return false;
}
public override bool TryGetGlobalDiagnosticValue(string diagnosticId, CancellationToken _, out ReportDiagnostic severity)
{
if (_globalOptions.TreeOptions is object)
{
return _globalOptions.TreeOptions.TryGetValue(diagnosticId, out severity);
}
severity = ReportDiagnostic.Default;
return false;
}
}
}
| -1 |
dotnet/roslyn | 55,877 | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute | Part of C# 10 support | davidwengier | 2021-08-25T05:36:27Z | 2021-08-30T20:47:11Z | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | 023d3ca2b5fb429f0b3dcc1efeed39442e232dba | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute. Part of C# 10 support | ./src/EditorFeatures/CSharp/xlf/CSharpEditorResources.ko.xlf | <?xml version="1.0" encoding="utf-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd">
<file datatype="xml" source-language="en" target-language="ko" original="../CSharpEditorResources.resx">
<body>
<trans-unit id="Add_Missing_Usings_on_Paste">
<source>Add Missing Usings on Paste</source>
<target state="translated">붙여넣을 때 누락된 using 추가</target>
<note>"usings" is a language specific term and should not be localized</note>
</trans-unit>
<trans-unit id="Adding_missing_usings">
<source>Adding missing usings...</source>
<target state="translated">누락된 using 추가 중...</target>
<note>Shown in a thread await dialog. "usings" is a language specific term and should not be localized</note>
</trans-unit>
<trans-unit id="Avoid_expression_statements_that_implicitly_ignore_value">
<source>Avoid expression statements that implicitly ignore value</source>
<target state="translated">암시적으로 값을 무시하는 식 문을 사용하지 마세요.</target>
<note />
</trans-unit>
<trans-unit id="Avoid_unused_value_assignments">
<source>Avoid unused value assignments</source>
<target state="translated">사용되지 않는 값 할당을 사용하지 마세요.</target>
<note />
</trans-unit>
<trans-unit id="Chosen_version_0">
<source>Chosen version: '{0}'</source>
<target state="translated">선택한 버전: '{0}'</target>
<note />
</trans-unit>
<trans-unit id="Complete_statement_on_semicolon">
<source>Complete statement on ;</source>
<target state="translated">;에서 문 완성</target>
<note />
</trans-unit>
<trans-unit id="Could_not_find_by_name_0">
<source>Could not find by name: '{0}'</source>
<target state="translated">'{0}' 이름으로 찾을 수 없습니다.</target>
<note />
</trans-unit>
<trans-unit id="Decompilation_log">
<source>Decompilation log</source>
<target state="translated">디컴파일 로그</target>
<note />
</trans-unit>
<trans-unit id="Discard">
<source>Discard</source>
<target state="translated">폐기</target>
<note />
</trans-unit>
<trans-unit id="Elsewhere">
<source>Elsewhere</source>
<target state="translated">다른 곳</target>
<note />
</trans-unit>
<trans-unit id="Fix_interpolated_verbatim_string">
<source>Fix interpolated verbatim string</source>
<target state="translated">보간된 축자 문자열 수정</target>
<note />
</trans-unit>
<trans-unit id="For_built_in_types">
<source>For built-in types</source>
<target state="translated">기본 제공 형식인 경우</target>
<note />
</trans-unit>
<trans-unit id="Found_0_assemblies_for_1">
<source>Found '{0}' assemblies for '{1}':</source>
<target state="translated">'{1}'의 어셈블리를 '{0}'개 찾았습니다.</target>
<note />
</trans-unit>
<trans-unit id="Found_exact_match_0">
<source>Found exact match: '{0}'</source>
<target state="translated">정확하게 일치하는 항목을 찾았습니다. '{0}'</target>
<note />
</trans-unit>
<trans-unit id="Found_higher_version_match_0">
<source>Found higher version match: '{0}'</source>
<target state="translated">일치하는 상위 버전을 찾았습니다. '{0}'</target>
<note />
</trans-unit>
<trans-unit id="Found_single_assembly_0">
<source>Found single assembly: '{0}'</source>
<target state="translated">단일 어셈블리를 찾았습니다. '{0}'</target>
<note />
</trans-unit>
<trans-unit id="Generate_Event_Subscription">
<source>Generate Event Subscription</source>
<target state="translated">이벤트 구독 생성</target>
<note />
</trans-unit>
<trans-unit id="Ignore_spaces_in_declaration_statements">
<source>Ignore spaces in declaration statements</source>
<target state="translated">선언문의 공백 무시</target>
<note />
</trans-unit>
<trans-unit id="Indent_block_contents">
<source>Indent block contents</source>
<target state="translated">블록 내용 들여쓰기</target>
<note />
</trans-unit>
<trans-unit id="Indent_case_contents">
<source>Indent case contents</source>
<target state="translated">case 내용 들여쓰기</target>
<note />
</trans-unit>
<trans-unit id="Indent_case_contents_when_block">
<source>Indent case contents (when block)</source>
<target state="translated">case 내용 들여쓰기(블록)</target>
<note />
</trans-unit>
<trans-unit id="Indent_case_labels">
<source>Indent case labels</source>
<target state="translated">case 레이블 들여쓰기</target>
<note />
</trans-unit>
<trans-unit id="Indent_open_and_close_braces">
<source>Indent open and close braces</source>
<target state="translated">여는 중괄호 및 닫는 중괄호 들여쓰기</target>
<note />
</trans-unit>
<trans-unit id="Insert_space_after_cast">
<source>Insert space after cast</source>
<target state="translated">캐스트 뒤에 공백 삽입</target>
<note />
</trans-unit>
<trans-unit id="Insert_space_after_colon_for_base_or_interface_in_type_declaration">
<source>Insert space after colon for base or interface in type declaration</source>
<target state="translated">형식 선언의 기본 또는 인터페이스에 대한 콜론 뒤에 공백 삽입</target>
<note />
</trans-unit>
<trans-unit id="Insert_space_after_comma">
<source>Insert space after comma</source>
<target state="translated">쉼표 뒤에 공백 삽입</target>
<note />
</trans-unit>
<trans-unit id="Insert_space_after_dot">
<source>Insert space after dot</source>
<target state="translated">점 뒤에 공백 삽입</target>
<note />
</trans-unit>
<trans-unit id="Insert_space_after_keywords_in_control_flow_statements">
<source>Insert space after keywords in control flow statements</source>
<target state="translated">제어 흐름 문의 키워드 뒤에 공백 삽입</target>
<note />
</trans-unit>
<trans-unit id="Insert_space_after_semicolon_in_for_statement">
<source>Insert space after semicolon in "for" statement</source>
<target state="translated">"for" 문의 세미콜론 뒤에 공백 삽입</target>
<note />
</trans-unit>
<trans-unit id="Insert_space_before_colon_for_base_or_interface_in_type_declaration">
<source>Insert space before colon for base or interface in type declaration</source>
<target state="translated">형식 선언의 기본 또는 인터페이스에 대한 콜론 앞에 공백 삽입</target>
<note />
</trans-unit>
<trans-unit id="Insert_space_before_comma">
<source>Insert space before comma</source>
<target state="translated">쉼표 앞에 공백 삽입</target>
<note />
</trans-unit>
<trans-unit id="Insert_space_before_dot">
<source>Insert space before dot</source>
<target state="translated">점 앞에 공백 삽입</target>
<note />
</trans-unit>
<trans-unit id="Insert_space_before_open_square_bracket">
<source>Insert space before open square bracket</source>
<target state="translated">여는 대괄호 앞에 공백 삽입</target>
<note />
</trans-unit>
<trans-unit id="Insert_space_before_semicolon_in_for_statement">
<source>Insert space before semicolon in "for" statement</source>
<target state="translated">"for" 문의 세미콜론 앞에 공백 삽입</target>
<note />
</trans-unit>
<trans-unit id="Insert_space_between_method_name_and_its_opening_parenthesis1">
<source>Insert space between method name and its opening parenthesis</source>
<target state="translated">메서드 이름과 여는 괄호 사이에 공백 삽입</target>
<note />
</trans-unit>
<trans-unit id="Insert_space_between_method_name_and_its_opening_parenthesis2">
<source>Insert space between method name and its opening parenthesis</source>
<target state="translated">메서드 이름과 여는 괄호 사이에 공백 삽입</target>
<note />
</trans-unit>
<trans-unit id="Insert_space_within_argument_list_parentheses">
<source>Insert space within argument list parentheses</source>
<target state="translated">인수 목록 괄호의 내부에 공백 삽입</target>
<note />
</trans-unit>
<trans-unit id="Insert_space_within_empty_argument_list_parentheses">
<source>Insert space within empty argument list parentheses</source>
<target state="translated">빈 인수 목록 괄호 내부에 공백 삽입</target>
<note />
</trans-unit>
<trans-unit id="Insert_space_within_empty_parameter_list_parentheses">
<source>Insert space within empty parameter list parentheses</source>
<target state="translated">빈 매개 변수 목록 괄호 내에 공백 삽입</target>
<note />
</trans-unit>
<trans-unit id="Insert_space_within_empty_square_brackets">
<source>Insert space within empty square brackets</source>
<target state="translated">빈 대괄호의 내부에 공백 삽입</target>
<note />
</trans-unit>
<trans-unit id="Insert_space_within_parameter_list_parentheses">
<source>Insert space within parameter list parentheses</source>
<target state="translated">매개 변수 목록 괄호 내에 공백 삽입</target>
<note />
</trans-unit>
<trans-unit id="Insert_space_within_parentheses_of_expressions">
<source>Insert space within parentheses of expressions</source>
<target state="translated">식의 괄호 내부에 공백 삽입</target>
<note />
</trans-unit>
<trans-unit id="Insert_space_within_parentheses_of_type_casts">
<source>Insert space within parentheses of type casts</source>
<target state="translated">형식 캐스팅의 괄호 내부에 공백 삽입</target>
<note />
</trans-unit>
<trans-unit id="Insert_spaces_within_parentheses_of_control_flow_statements">
<source>Insert spaces within parentheses of control flow statements</source>
<target state="translated">제어 흐름 문의 괄호 내부에 공백 삽입</target>
<note />
</trans-unit>
<trans-unit id="Insert_spaces_within_square_brackets">
<source>Insert spaces within square brackets</source>
<target state="translated">대괄호 내부에 공백 삽입</target>
<note />
</trans-unit>
<trans-unit id="Inside_namespace">
<source>Inside namespace</source>
<target state="translated">namespace 내부</target>
<note />
</trans-unit>
<trans-unit id="Label_Indentation">
<source>Label Indentation</source>
<target state="translated">레이블 들여쓰기</target>
<note />
</trans-unit>
<trans-unit id="Leave_block_on_single_line">
<source>Leave block on single line</source>
<target state="translated">블록을 한 줄에 유지</target>
<note />
</trans-unit>
<trans-unit id="Leave_statements_and_member_declarations_on_the_same_line">
<source>Leave statements and member declarations on the same line</source>
<target state="translated">문과 멤버 선언을 같은 줄에 유지</target>
<note />
</trans-unit>
<trans-unit id="Load_from_0">
<source>Load from: '{0}'</source>
<target state="translated">로드 위치: '{0}'</target>
<note />
</trans-unit>
<trans-unit id="Module_not_found">
<source>Module not found!</source>
<target state="translated">모듈을 찾을 수 없습니다.</target>
<note />
</trans-unit>
<trans-unit id="Never">
<source>Never</source>
<target state="translated">안 함 </target>
<note />
</trans-unit>
<trans-unit id="Outside_namespace">
<source>Outside namespace</source>
<target state="translated">외부 namespace</target>
<note />
</trans-unit>
<trans-unit id="Place_catch_on_new_line">
<source>Place "catch" on new line</source>
<target state="translated">"catch"를 새 줄에 배치</target>
<note />
</trans-unit>
<trans-unit id="Place_else_on_new_line">
<source>Place "else" on new line</source>
<target state="translated">"else"를 새 줄에 배치</target>
<note />
</trans-unit>
<trans-unit id="Place_finally_on_new_line">
<source>Place "finally" on new line</source>
<target state="translated">"finally"를 새 줄에 배치</target>
<note />
</trans-unit>
<trans-unit id="Place_members_in_anonymous_types_on_new_line">
<source>Place members in anonymous types on new line</source>
<target state="translated">익명 형식의 멤버를 새 줄에 배치</target>
<note />
</trans-unit>
<trans-unit id="Place_members_in_object_initializers_on_new_line">
<source>Place members in object initializers on new line</source>
<target state="translated">개체 이니셜라이저의 멤버를 새 줄에 배치</target>
<note />
</trans-unit>
<trans-unit id="Place_open_brace_on_new_line_for_anonymous_methods">
<source>Place open brace on new line for anonymous methods</source>
<target state="translated">무명 메서드의 여는 중괄호를 새 줄에 배치</target>
<note />
</trans-unit>
<trans-unit id="Place_open_brace_on_new_line_for_anonymous_types">
<source>Place open brace on new line for anonymous types</source>
<target state="translated">익명 형식의 여는 중괄호를 새 줄에 배치</target>
<note />
</trans-unit>
<trans-unit id="Place_open_brace_on_new_line_for_control_blocks">
<source>Place open brace on new line for control blocks</source>
<target state="translated">제어 블록의 여는 중괄호를 새 줄에 배치</target>
<note />
</trans-unit>
<trans-unit id="Place_open_brace_on_new_line_for_lambda_expression">
<source>Place open brace on new line for lambda expression</source>
<target state="translated">람다 식의 여는 중괄호를 새 줄에 배치</target>
<note />
</trans-unit>
<trans-unit id="Place_open_brace_on_new_line_for_methods_local_functions">
<source>Place open brace on new line for methods and local functions</source>
<target state="translated">메서드 및 로컬 함수의 여는 중괄호를 새 줄에 배치합니다.</target>
<note />
</trans-unit>
<trans-unit id="Place_open_brace_on_new_line_for_object_collection_array_and_with_initializers">
<source>Place open brace on new line for object, collection, array, and with initializers</source>
<target state="translated">개체, 컬렉션, 배열 및 with 이니셜라이저의 여는 중괄호를 새 줄에 배치</target>
<note />
</trans-unit>
<trans-unit id="Place_open_brace_on_new_line_for_properties_indexers_and_events">
<source>Place open brace on new line for properties, indexers, and events</source>
<target state="translated">속성, 인덱서 및 이벤트의 여는 중괄호를 새 줄에 배치합니다.</target>
<note />
</trans-unit>
<trans-unit id="Place_open_brace_on_new_line_for_property_indexer_and_event_accessors">
<source>Place open brace on new line for property, indexer, and event accessors</source>
<target state="translated">속성, 인덱서 및 이벤트 접근자의 여는 중괄호를 새 줄에 배치합니다.</target>
<note />
</trans-unit>
<trans-unit id="Place_open_brace_on_new_line_for_types">
<source>Place open brace on new line for types</source>
<target state="translated">형식의 여는 중괄호를 새 줄에 배치</target>
<note />
</trans-unit>
<trans-unit id="Place_query_expression_clauses_on_new_line">
<source>Place query expression clauses on new line</source>
<target state="translated">쿼리 식의 절을 새 줄에 배치</target>
<note />
</trans-unit>
<trans-unit id="Prefer_conditional_delegate_call">
<source>Prefer conditional delegate call</source>
<target state="translated">조건부 대리자 호출 기본 사용</target>
<note />
</trans-unit>
<trans-unit id="Prefer_deconstructed_variable_declaration">
<source>Prefer deconstructed variable declaration</source>
<target state="translated">분해된 변수 선언 사용</target>
<note />
</trans-unit>
<trans-unit id="Prefer_explicit_type">
<source>Prefer explicit type</source>
<target state="translated">명시적 형식 기본 사용</target>
<note />
</trans-unit>
<trans-unit id="Prefer_index_operator">
<source>Prefer index operator</source>
<target state="translated">인덱스 연산자 선호</target>
<note />
</trans-unit>
<trans-unit id="Prefer_inlined_variable_declaration">
<source>Prefer inlined variable declaration</source>
<target state="translated">인라인 변수 선언 사용</target>
<note />
</trans-unit>
<trans-unit id="Prefer_local_function_over_anonymous_function">
<source>Prefer local function over anonymous function</source>
<target state="translated">익명 함수보다 로컬 함수 선호</target>
<note />
</trans-unit>
<trans-unit id="Prefer_null_check_over_type_check">
<source>Prefer 'null' check over type check</source>
<target state="new">Prefer 'null' check over type check</target>
<note />
</trans-unit>
<trans-unit id="Prefer_pattern_matching">
<source>Prefer pattern matching</source>
<target state="translated">패턴 일치 선호</target>
<note />
</trans-unit>
<trans-unit id="Prefer_pattern_matching_over_as_with_null_check">
<source>Prefer pattern matching over 'as' with 'null' check</source>
<target state="translated">null' 검사에서 'as'보다 패턴 일치 기본 사용</target>
<note />
</trans-unit>
<trans-unit id="Prefer_pattern_matching_over_is_with_cast_check">
<source>Prefer pattern matching over 'is' with 'cast' check</source>
<target state="translated">캐스트' 검사에서 'is'보다 패턴 일치 기본 사용</target>
<note />
</trans-unit>
<trans-unit id="Prefer_pattern_matching_over_mixed_type_check">
<source>Prefer pattern matching over mixed type check</source>
<target state="translated">혼합 형식 검사 대신 패턴 일치 사용</target>
<note />
</trans-unit>
<trans-unit id="Prefer_range_operator">
<source>Prefer range operator</source>
<target state="translated">범위 연산자 선호</target>
<note />
</trans-unit>
<trans-unit id="Prefer_simple_default_expression">
<source>Prefer simple 'default' expression</source>
<target state="translated">간단한 'default' 식을 기본으로 사용</target>
<note />
</trans-unit>
<trans-unit id="Prefer_simple_using_statement">
<source>Prefer simple 'using' statement</source>
<target state="translated">간단한 'using' 문 선호</target>
<note />
</trans-unit>
<trans-unit id="Prefer_static_local_functions">
<source>Prefer static local functions</source>
<target state="translated">정적 로컬 함수 선호</target>
<note />
</trans-unit>
<trans-unit id="Prefer_switch_expression">
<source>Prefer switch expression</source>
<target state="translated">switch 식 선호</target>
<note />
</trans-unit>
<trans-unit id="Prefer_throw_expression">
<source>Prefer throw-expression</source>
<target state="translated">throw 식 기본 사용</target>
<note />
</trans-unit>
<trans-unit id="Prefer_var">
<source>Prefer 'var'</source>
<target state="translated">var'을 기본으로 사용합니다.</target>
<note />
</trans-unit>
<trans-unit id="Preferred_using_directive_placement">
<source>Preferred 'using' directive placement</source>
<target state="translated">선호하는 'using' 지시문 배치</target>
<note />
</trans-unit>
<trans-unit id="Press_TAB_to_insert">
<source> (Press TAB to insert)</source>
<target state="translated"> (삽입하려면 <Tab> 키 누름)</target>
<note />
</trans-unit>
<trans-unit id="Resolve_0">
<source>Resolve: '{0}'</source>
<target state="translated">확인: '{0}'</target>
<note />
</trans-unit>
<trans-unit id="Resolve_module_0_of_1">
<source>Resolve module: '{0}' of '{1}'</source>
<target state="translated">모듈 확인: '{0}'/'{1}'</target>
<note />
</trans-unit>
<trans-unit id="Set_spacing_for_operators">
<source>Set spacing for operators</source>
<target state="translated">연산자의 간격을 설정합니다.</target>
<note />
</trans-unit>
<trans-unit id="Smart_Indenting">
<source>Smart Indenting</source>
<target state="translated">스마트 들여쓰기</target>
<note />
</trans-unit>
<trans-unit id="Split_string">
<source>Split string</source>
<target state="translated">문자열 분할</target>
<note />
</trans-unit>
<trans-unit id="Unused_local">
<source>Unused local</source>
<target state="translated">사용하지 않는 로컬</target>
<note />
</trans-unit>
<trans-unit id="Use_expression_body_for_accessors">
<source>Use expression body for accessors</source>
<target state="translated">접근자에 식 본문 사용</target>
<note />
</trans-unit>
<trans-unit id="Use_expression_body_for_constructors">
<source>Use expression body for constructors</source>
<target state="translated">생성자에 식 본문 사용</target>
<note />
</trans-unit>
<trans-unit id="Use_expression_body_for_indexers">
<source>Use expression body for indexers</source>
<target state="translated">인덱서에 식 본문 사용</target>
<note />
</trans-unit>
<trans-unit id="Use_expression_body_for_lambdas">
<source>Use expression body for lambdas</source>
<target state="translated">람다에 식 본문 사용</target>
<note />
</trans-unit>
<trans-unit id="Use_expression_body_for_local_functions">
<source>Use expression body for local functions</source>
<target state="translated">로컬 함수의 식 본문 사용</target>
<note />
</trans-unit>
<trans-unit id="Use_expression_body_for_methods">
<source>Use expression body for methods</source>
<target state="translated">메서드에 식 본문 사용</target>
<note />
</trans-unit>
<trans-unit id="Use_expression_body_for_operators">
<source>Use expression body for operators</source>
<target state="translated">연산자에 식 본문 사용</target>
<note />
</trans-unit>
<trans-unit id="Use_expression_body_for_properties">
<source>Use expression body for properties</source>
<target state="translated">속성에 식 본문 사용</target>
<note />
</trans-unit>
<trans-unit id="WARN_Version_mismatch_Expected_0_Got_1">
<source>WARN: Version mismatch. Expected: '{0}', Got: '{1}'</source>
<target state="translated">WARN: 버전이 일치하지 않습니다. 예상: '{0}', 실제: '{1}'</target>
<note />
</trans-unit>
<trans-unit id="When_on_single_line">
<source>When on single line</source>
<target state="translated">한 줄에 있는 경우</target>
<note />
</trans-unit>
<trans-unit id="When_possible">
<source>When possible</source>
<target state="translated">가능한 경우</target>
<note />
</trans-unit>
<trans-unit id="When_variable_type_is_apparent">
<source>When variable type is apparent</source>
<target state="translated">변수 형식이 명백한 경우</target>
<note />
</trans-unit>
<trans-unit id="_0_items_in_cache">
<source>'{0}' items in cache</source>
<target state="translated">캐시의 '{0}'개 항목</target>
<note />
</trans-unit>
</body>
</file>
</xliff> | <?xml version="1.0" encoding="utf-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd">
<file datatype="xml" source-language="en" target-language="ko" original="../CSharpEditorResources.resx">
<body>
<trans-unit id="Add_Missing_Usings_on_Paste">
<source>Add Missing Usings on Paste</source>
<target state="translated">붙여넣을 때 누락된 using 추가</target>
<note>"usings" is a language specific term and should not be localized</note>
</trans-unit>
<trans-unit id="Adding_missing_usings">
<source>Adding missing usings...</source>
<target state="translated">누락된 using 추가 중...</target>
<note>Shown in a thread await dialog. "usings" is a language specific term and should not be localized</note>
</trans-unit>
<trans-unit id="Avoid_expression_statements_that_implicitly_ignore_value">
<source>Avoid expression statements that implicitly ignore value</source>
<target state="translated">암시적으로 값을 무시하는 식 문을 사용하지 마세요.</target>
<note />
</trans-unit>
<trans-unit id="Avoid_unused_value_assignments">
<source>Avoid unused value assignments</source>
<target state="translated">사용되지 않는 값 할당을 사용하지 마세요.</target>
<note />
</trans-unit>
<trans-unit id="Chosen_version_0">
<source>Chosen version: '{0}'</source>
<target state="translated">선택한 버전: '{0}'</target>
<note />
</trans-unit>
<trans-unit id="Complete_statement_on_semicolon">
<source>Complete statement on ;</source>
<target state="translated">;에서 문 완성</target>
<note />
</trans-unit>
<trans-unit id="Could_not_find_by_name_0">
<source>Could not find by name: '{0}'</source>
<target state="translated">'{0}' 이름으로 찾을 수 없습니다.</target>
<note />
</trans-unit>
<trans-unit id="Decompilation_log">
<source>Decompilation log</source>
<target state="translated">디컴파일 로그</target>
<note />
</trans-unit>
<trans-unit id="Discard">
<source>Discard</source>
<target state="translated">폐기</target>
<note />
</trans-unit>
<trans-unit id="Elsewhere">
<source>Elsewhere</source>
<target state="translated">다른 곳</target>
<note />
</trans-unit>
<trans-unit id="Fix_interpolated_verbatim_string">
<source>Fix interpolated verbatim string</source>
<target state="translated">보간된 축자 문자열 수정</target>
<note />
</trans-unit>
<trans-unit id="For_built_in_types">
<source>For built-in types</source>
<target state="translated">기본 제공 형식인 경우</target>
<note />
</trans-unit>
<trans-unit id="Found_0_assemblies_for_1">
<source>Found '{0}' assemblies for '{1}':</source>
<target state="translated">'{1}'의 어셈블리를 '{0}'개 찾았습니다.</target>
<note />
</trans-unit>
<trans-unit id="Found_exact_match_0">
<source>Found exact match: '{0}'</source>
<target state="translated">정확하게 일치하는 항목을 찾았습니다. '{0}'</target>
<note />
</trans-unit>
<trans-unit id="Found_higher_version_match_0">
<source>Found higher version match: '{0}'</source>
<target state="translated">일치하는 상위 버전을 찾았습니다. '{0}'</target>
<note />
</trans-unit>
<trans-unit id="Found_single_assembly_0">
<source>Found single assembly: '{0}'</source>
<target state="translated">단일 어셈블리를 찾았습니다. '{0}'</target>
<note />
</trans-unit>
<trans-unit id="Generate_Event_Subscription">
<source>Generate Event Subscription</source>
<target state="translated">이벤트 구독 생성</target>
<note />
</trans-unit>
<trans-unit id="Ignore_spaces_in_declaration_statements">
<source>Ignore spaces in declaration statements</source>
<target state="translated">선언문의 공백 무시</target>
<note />
</trans-unit>
<trans-unit id="Indent_block_contents">
<source>Indent block contents</source>
<target state="translated">블록 내용 들여쓰기</target>
<note />
</trans-unit>
<trans-unit id="Indent_case_contents">
<source>Indent case contents</source>
<target state="translated">case 내용 들여쓰기</target>
<note />
</trans-unit>
<trans-unit id="Indent_case_contents_when_block">
<source>Indent case contents (when block)</source>
<target state="translated">case 내용 들여쓰기(블록)</target>
<note />
</trans-unit>
<trans-unit id="Indent_case_labels">
<source>Indent case labels</source>
<target state="translated">case 레이블 들여쓰기</target>
<note />
</trans-unit>
<trans-unit id="Indent_open_and_close_braces">
<source>Indent open and close braces</source>
<target state="translated">여는 중괄호 및 닫는 중괄호 들여쓰기</target>
<note />
</trans-unit>
<trans-unit id="Insert_space_after_cast">
<source>Insert space after cast</source>
<target state="translated">캐스트 뒤에 공백 삽입</target>
<note />
</trans-unit>
<trans-unit id="Insert_space_after_colon_for_base_or_interface_in_type_declaration">
<source>Insert space after colon for base or interface in type declaration</source>
<target state="translated">형식 선언의 기본 또는 인터페이스에 대한 콜론 뒤에 공백 삽입</target>
<note />
</trans-unit>
<trans-unit id="Insert_space_after_comma">
<source>Insert space after comma</source>
<target state="translated">쉼표 뒤에 공백 삽입</target>
<note />
</trans-unit>
<trans-unit id="Insert_space_after_dot">
<source>Insert space after dot</source>
<target state="translated">점 뒤에 공백 삽입</target>
<note />
</trans-unit>
<trans-unit id="Insert_space_after_keywords_in_control_flow_statements">
<source>Insert space after keywords in control flow statements</source>
<target state="translated">제어 흐름 문의 키워드 뒤에 공백 삽입</target>
<note />
</trans-unit>
<trans-unit id="Insert_space_after_semicolon_in_for_statement">
<source>Insert space after semicolon in "for" statement</source>
<target state="translated">"for" 문의 세미콜론 뒤에 공백 삽입</target>
<note />
</trans-unit>
<trans-unit id="Insert_space_before_colon_for_base_or_interface_in_type_declaration">
<source>Insert space before colon for base or interface in type declaration</source>
<target state="translated">형식 선언의 기본 또는 인터페이스에 대한 콜론 앞에 공백 삽입</target>
<note />
</trans-unit>
<trans-unit id="Insert_space_before_comma">
<source>Insert space before comma</source>
<target state="translated">쉼표 앞에 공백 삽입</target>
<note />
</trans-unit>
<trans-unit id="Insert_space_before_dot">
<source>Insert space before dot</source>
<target state="translated">점 앞에 공백 삽입</target>
<note />
</trans-unit>
<trans-unit id="Insert_space_before_open_square_bracket">
<source>Insert space before open square bracket</source>
<target state="translated">여는 대괄호 앞에 공백 삽입</target>
<note />
</trans-unit>
<trans-unit id="Insert_space_before_semicolon_in_for_statement">
<source>Insert space before semicolon in "for" statement</source>
<target state="translated">"for" 문의 세미콜론 앞에 공백 삽입</target>
<note />
</trans-unit>
<trans-unit id="Insert_space_between_method_name_and_its_opening_parenthesis1">
<source>Insert space between method name and its opening parenthesis</source>
<target state="translated">메서드 이름과 여는 괄호 사이에 공백 삽입</target>
<note />
</trans-unit>
<trans-unit id="Insert_space_between_method_name_and_its_opening_parenthesis2">
<source>Insert space between method name and its opening parenthesis</source>
<target state="translated">메서드 이름과 여는 괄호 사이에 공백 삽입</target>
<note />
</trans-unit>
<trans-unit id="Insert_space_within_argument_list_parentheses">
<source>Insert space within argument list parentheses</source>
<target state="translated">인수 목록 괄호의 내부에 공백 삽입</target>
<note />
</trans-unit>
<trans-unit id="Insert_space_within_empty_argument_list_parentheses">
<source>Insert space within empty argument list parentheses</source>
<target state="translated">빈 인수 목록 괄호 내부에 공백 삽입</target>
<note />
</trans-unit>
<trans-unit id="Insert_space_within_empty_parameter_list_parentheses">
<source>Insert space within empty parameter list parentheses</source>
<target state="translated">빈 매개 변수 목록 괄호 내에 공백 삽입</target>
<note />
</trans-unit>
<trans-unit id="Insert_space_within_empty_square_brackets">
<source>Insert space within empty square brackets</source>
<target state="translated">빈 대괄호의 내부에 공백 삽입</target>
<note />
</trans-unit>
<trans-unit id="Insert_space_within_parameter_list_parentheses">
<source>Insert space within parameter list parentheses</source>
<target state="translated">매개 변수 목록 괄호 내에 공백 삽입</target>
<note />
</trans-unit>
<trans-unit id="Insert_space_within_parentheses_of_expressions">
<source>Insert space within parentheses of expressions</source>
<target state="translated">식의 괄호 내부에 공백 삽입</target>
<note />
</trans-unit>
<trans-unit id="Insert_space_within_parentheses_of_type_casts">
<source>Insert space within parentheses of type casts</source>
<target state="translated">형식 캐스팅의 괄호 내부에 공백 삽입</target>
<note />
</trans-unit>
<trans-unit id="Insert_spaces_within_parentheses_of_control_flow_statements">
<source>Insert spaces within parentheses of control flow statements</source>
<target state="translated">제어 흐름 문의 괄호 내부에 공백 삽입</target>
<note />
</trans-unit>
<trans-unit id="Insert_spaces_within_square_brackets">
<source>Insert spaces within square brackets</source>
<target state="translated">대괄호 내부에 공백 삽입</target>
<note />
</trans-unit>
<trans-unit id="Inside_namespace">
<source>Inside namespace</source>
<target state="translated">namespace 내부</target>
<note />
</trans-unit>
<trans-unit id="Label_Indentation">
<source>Label Indentation</source>
<target state="translated">레이블 들여쓰기</target>
<note />
</trans-unit>
<trans-unit id="Leave_block_on_single_line">
<source>Leave block on single line</source>
<target state="translated">블록을 한 줄에 유지</target>
<note />
</trans-unit>
<trans-unit id="Leave_statements_and_member_declarations_on_the_same_line">
<source>Leave statements and member declarations on the same line</source>
<target state="translated">문과 멤버 선언을 같은 줄에 유지</target>
<note />
</trans-unit>
<trans-unit id="Load_from_0">
<source>Load from: '{0}'</source>
<target state="translated">로드 위치: '{0}'</target>
<note />
</trans-unit>
<trans-unit id="Module_not_found">
<source>Module not found!</source>
<target state="translated">모듈을 찾을 수 없습니다.</target>
<note />
</trans-unit>
<trans-unit id="Never">
<source>Never</source>
<target state="translated">안 함 </target>
<note />
</trans-unit>
<trans-unit id="Outside_namespace">
<source>Outside namespace</source>
<target state="translated">외부 namespace</target>
<note />
</trans-unit>
<trans-unit id="Place_catch_on_new_line">
<source>Place "catch" on new line</source>
<target state="translated">"catch"를 새 줄에 배치</target>
<note />
</trans-unit>
<trans-unit id="Place_else_on_new_line">
<source>Place "else" on new line</source>
<target state="translated">"else"를 새 줄에 배치</target>
<note />
</trans-unit>
<trans-unit id="Place_finally_on_new_line">
<source>Place "finally" on new line</source>
<target state="translated">"finally"를 새 줄에 배치</target>
<note />
</trans-unit>
<trans-unit id="Place_members_in_anonymous_types_on_new_line">
<source>Place members in anonymous types on new line</source>
<target state="translated">익명 형식의 멤버를 새 줄에 배치</target>
<note />
</trans-unit>
<trans-unit id="Place_members_in_object_initializers_on_new_line">
<source>Place members in object initializers on new line</source>
<target state="translated">개체 이니셜라이저의 멤버를 새 줄에 배치</target>
<note />
</trans-unit>
<trans-unit id="Place_open_brace_on_new_line_for_anonymous_methods">
<source>Place open brace on new line for anonymous methods</source>
<target state="translated">무명 메서드의 여는 중괄호를 새 줄에 배치</target>
<note />
</trans-unit>
<trans-unit id="Place_open_brace_on_new_line_for_anonymous_types">
<source>Place open brace on new line for anonymous types</source>
<target state="translated">익명 형식의 여는 중괄호를 새 줄에 배치</target>
<note />
</trans-unit>
<trans-unit id="Place_open_brace_on_new_line_for_control_blocks">
<source>Place open brace on new line for control blocks</source>
<target state="translated">제어 블록의 여는 중괄호를 새 줄에 배치</target>
<note />
</trans-unit>
<trans-unit id="Place_open_brace_on_new_line_for_lambda_expression">
<source>Place open brace on new line for lambda expression</source>
<target state="translated">람다 식의 여는 중괄호를 새 줄에 배치</target>
<note />
</trans-unit>
<trans-unit id="Place_open_brace_on_new_line_for_methods_local_functions">
<source>Place open brace on new line for methods and local functions</source>
<target state="translated">메서드 및 로컬 함수의 여는 중괄호를 새 줄에 배치합니다.</target>
<note />
</trans-unit>
<trans-unit id="Place_open_brace_on_new_line_for_object_collection_array_and_with_initializers">
<source>Place open brace on new line for object, collection, array, and with initializers</source>
<target state="translated">개체, 컬렉션, 배열 및 with 이니셜라이저의 여는 중괄호를 새 줄에 배치</target>
<note />
</trans-unit>
<trans-unit id="Place_open_brace_on_new_line_for_properties_indexers_and_events">
<source>Place open brace on new line for properties, indexers, and events</source>
<target state="translated">속성, 인덱서 및 이벤트의 여는 중괄호를 새 줄에 배치합니다.</target>
<note />
</trans-unit>
<trans-unit id="Place_open_brace_on_new_line_for_property_indexer_and_event_accessors">
<source>Place open brace on new line for property, indexer, and event accessors</source>
<target state="translated">속성, 인덱서 및 이벤트 접근자의 여는 중괄호를 새 줄에 배치합니다.</target>
<note />
</trans-unit>
<trans-unit id="Place_open_brace_on_new_line_for_types">
<source>Place open brace on new line for types</source>
<target state="translated">형식의 여는 중괄호를 새 줄에 배치</target>
<note />
</trans-unit>
<trans-unit id="Place_query_expression_clauses_on_new_line">
<source>Place query expression clauses on new line</source>
<target state="translated">쿼리 식의 절을 새 줄에 배치</target>
<note />
</trans-unit>
<trans-unit id="Prefer_conditional_delegate_call">
<source>Prefer conditional delegate call</source>
<target state="translated">조건부 대리자 호출 기본 사용</target>
<note />
</trans-unit>
<trans-unit id="Prefer_deconstructed_variable_declaration">
<source>Prefer deconstructed variable declaration</source>
<target state="translated">분해된 변수 선언 사용</target>
<note />
</trans-unit>
<trans-unit id="Prefer_explicit_type">
<source>Prefer explicit type</source>
<target state="translated">명시적 형식 기본 사용</target>
<note />
</trans-unit>
<trans-unit id="Prefer_index_operator">
<source>Prefer index operator</source>
<target state="translated">인덱스 연산자 선호</target>
<note />
</trans-unit>
<trans-unit id="Prefer_inlined_variable_declaration">
<source>Prefer inlined variable declaration</source>
<target state="translated">인라인 변수 선언 사용</target>
<note />
</trans-unit>
<trans-unit id="Prefer_local_function_over_anonymous_function">
<source>Prefer local function over anonymous function</source>
<target state="translated">익명 함수보다 로컬 함수 선호</target>
<note />
</trans-unit>
<trans-unit id="Prefer_null_check_over_type_check">
<source>Prefer 'null' check over type check</source>
<target state="new">Prefer 'null' check over type check</target>
<note />
</trans-unit>
<trans-unit id="Prefer_pattern_matching">
<source>Prefer pattern matching</source>
<target state="translated">패턴 일치 선호</target>
<note />
</trans-unit>
<trans-unit id="Prefer_pattern_matching_over_as_with_null_check">
<source>Prefer pattern matching over 'as' with 'null' check</source>
<target state="translated">null' 검사에서 'as'보다 패턴 일치 기본 사용</target>
<note />
</trans-unit>
<trans-unit id="Prefer_pattern_matching_over_is_with_cast_check">
<source>Prefer pattern matching over 'is' with 'cast' check</source>
<target state="translated">캐스트' 검사에서 'is'보다 패턴 일치 기본 사용</target>
<note />
</trans-unit>
<trans-unit id="Prefer_pattern_matching_over_mixed_type_check">
<source>Prefer pattern matching over mixed type check</source>
<target state="translated">혼합 형식 검사 대신 패턴 일치 사용</target>
<note />
</trans-unit>
<trans-unit id="Prefer_range_operator">
<source>Prefer range operator</source>
<target state="translated">범위 연산자 선호</target>
<note />
</trans-unit>
<trans-unit id="Prefer_simple_default_expression">
<source>Prefer simple 'default' expression</source>
<target state="translated">간단한 'default' 식을 기본으로 사용</target>
<note />
</trans-unit>
<trans-unit id="Prefer_simple_using_statement">
<source>Prefer simple 'using' statement</source>
<target state="translated">간단한 'using' 문 선호</target>
<note />
</trans-unit>
<trans-unit id="Prefer_static_local_functions">
<source>Prefer static local functions</source>
<target state="translated">정적 로컬 함수 선호</target>
<note />
</trans-unit>
<trans-unit id="Prefer_switch_expression">
<source>Prefer switch expression</source>
<target state="translated">switch 식 선호</target>
<note />
</trans-unit>
<trans-unit id="Prefer_throw_expression">
<source>Prefer throw-expression</source>
<target state="translated">throw 식 기본 사용</target>
<note />
</trans-unit>
<trans-unit id="Prefer_var">
<source>Prefer 'var'</source>
<target state="translated">var'을 기본으로 사용합니다.</target>
<note />
</trans-unit>
<trans-unit id="Preferred_using_directive_placement">
<source>Preferred 'using' directive placement</source>
<target state="translated">선호하는 'using' 지시문 배치</target>
<note />
</trans-unit>
<trans-unit id="Press_TAB_to_insert">
<source> (Press TAB to insert)</source>
<target state="translated"> (삽입하려면 <Tab> 키 누름)</target>
<note />
</trans-unit>
<trans-unit id="Resolve_0">
<source>Resolve: '{0}'</source>
<target state="translated">확인: '{0}'</target>
<note />
</trans-unit>
<trans-unit id="Resolve_module_0_of_1">
<source>Resolve module: '{0}' of '{1}'</source>
<target state="translated">모듈 확인: '{0}'/'{1}'</target>
<note />
</trans-unit>
<trans-unit id="Set_spacing_for_operators">
<source>Set spacing for operators</source>
<target state="translated">연산자의 간격을 설정합니다.</target>
<note />
</trans-unit>
<trans-unit id="Smart_Indenting">
<source>Smart Indenting</source>
<target state="translated">스마트 들여쓰기</target>
<note />
</trans-unit>
<trans-unit id="Split_string">
<source>Split string</source>
<target state="translated">문자열 분할</target>
<note />
</trans-unit>
<trans-unit id="Unused_local">
<source>Unused local</source>
<target state="translated">사용하지 않는 로컬</target>
<note />
</trans-unit>
<trans-unit id="Use_expression_body_for_accessors">
<source>Use expression body for accessors</source>
<target state="translated">접근자에 식 본문 사용</target>
<note />
</trans-unit>
<trans-unit id="Use_expression_body_for_constructors">
<source>Use expression body for constructors</source>
<target state="translated">생성자에 식 본문 사용</target>
<note />
</trans-unit>
<trans-unit id="Use_expression_body_for_indexers">
<source>Use expression body for indexers</source>
<target state="translated">인덱서에 식 본문 사용</target>
<note />
</trans-unit>
<trans-unit id="Use_expression_body_for_lambdas">
<source>Use expression body for lambdas</source>
<target state="translated">람다에 식 본문 사용</target>
<note />
</trans-unit>
<trans-unit id="Use_expression_body_for_local_functions">
<source>Use expression body for local functions</source>
<target state="translated">로컬 함수의 식 본문 사용</target>
<note />
</trans-unit>
<trans-unit id="Use_expression_body_for_methods">
<source>Use expression body for methods</source>
<target state="translated">메서드에 식 본문 사용</target>
<note />
</trans-unit>
<trans-unit id="Use_expression_body_for_operators">
<source>Use expression body for operators</source>
<target state="translated">연산자에 식 본문 사용</target>
<note />
</trans-unit>
<trans-unit id="Use_expression_body_for_properties">
<source>Use expression body for properties</source>
<target state="translated">속성에 식 본문 사용</target>
<note />
</trans-unit>
<trans-unit id="WARN_Version_mismatch_Expected_0_Got_1">
<source>WARN: Version mismatch. Expected: '{0}', Got: '{1}'</source>
<target state="translated">WARN: 버전이 일치하지 않습니다. 예상: '{0}', 실제: '{1}'</target>
<note />
</trans-unit>
<trans-unit id="When_on_single_line">
<source>When on single line</source>
<target state="translated">한 줄에 있는 경우</target>
<note />
</trans-unit>
<trans-unit id="When_possible">
<source>When possible</source>
<target state="translated">가능한 경우</target>
<note />
</trans-unit>
<trans-unit id="When_variable_type_is_apparent">
<source>When variable type is apparent</source>
<target state="translated">변수 형식이 명백한 경우</target>
<note />
</trans-unit>
<trans-unit id="_0_items_in_cache">
<source>'{0}' items in cache</source>
<target state="translated">캐시의 '{0}'개 항목</target>
<note />
</trans-unit>
</body>
</file>
</xliff> | -1 |
dotnet/roslyn | 55,877 | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute | Part of C# 10 support | davidwengier | 2021-08-25T05:36:27Z | 2021-08-30T20:47:11Z | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | 023d3ca2b5fb429f0b3dcc1efeed39442e232dba | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute. Part of C# 10 support | ./src/Analyzers/Core/Analyzers/UseCollectionInitializer/AbstractObjectCreationExpressionAnalyzer.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
namespace Microsoft.CodeAnalysis.UseCollectionInitializer
{
internal abstract class AbstractObjectCreationExpressionAnalyzer<
TExpressionSyntax,
TStatementSyntax,
TObjectCreationExpressionSyntax,
TVariableDeclaratorSyntax,
TMatch>
where TExpressionSyntax : SyntaxNode
where TStatementSyntax : SyntaxNode
where TObjectCreationExpressionSyntax : TExpressionSyntax
where TVariableDeclaratorSyntax : SyntaxNode
{
protected SemanticModel _semanticModel;
protected ISyntaxFacts _syntaxFacts;
protected TObjectCreationExpressionSyntax _objectCreationExpression;
protected CancellationToken _cancellationToken;
protected TStatementSyntax _containingStatement;
private SyntaxNodeOrToken _valuePattern;
private ISymbol _initializedSymbol;
protected AbstractObjectCreationExpressionAnalyzer()
{
}
public void Initialize(
SemanticModel semanticModel,
ISyntaxFacts syntaxFacts,
TObjectCreationExpressionSyntax objectCreationExpression,
CancellationToken cancellationToken)
{
_semanticModel = semanticModel;
_syntaxFacts = syntaxFacts;
_objectCreationExpression = objectCreationExpression;
_cancellationToken = cancellationToken;
}
protected void Clear()
{
_semanticModel = null;
_syntaxFacts = null;
_objectCreationExpression = null;
_cancellationToken = default;
_containingStatement = null;
_valuePattern = default;
_initializedSymbol = null;
}
protected abstract void AddMatches(ArrayBuilder<TMatch> matches);
protected ImmutableArray<TMatch>? AnalyzeWorker()
{
if (_syntaxFacts.GetObjectCreationInitializer(_objectCreationExpression) != null)
{
// Don't bother if this already has an initializer.
return null;
}
if (!ShouldAnalyze())
{
return null;
}
_containingStatement = _objectCreationExpression.FirstAncestorOrSelf<TStatementSyntax>();
if (_containingStatement == null)
{
return null;
}
if (!TryInitializeVariableDeclarationCase() &&
!TryInitializeAssignmentCase())
{
return null;
}
using var _ = ArrayBuilder<TMatch>.GetInstance(out var matches);
AddMatches(matches);
return matches.ToImmutable();
}
private bool TryInitializeVariableDeclarationCase()
{
if (!_syntaxFacts.IsLocalDeclarationStatement(_containingStatement))
{
return false;
}
if (_objectCreationExpression.Parent.Parent is not TVariableDeclaratorSyntax containingDeclarator)
{
return false;
}
_initializedSymbol = _semanticModel.GetDeclaredSymbol(containingDeclarator, _cancellationToken);
if (_initializedSymbol is ILocalSymbol local &&
local.Type is IDynamicTypeSymbol)
{
// Not supported if we're creating a dynamic local. The object we're instantiating
// may not have the members that we're trying to access on the dynamic object.
return false;
}
if (!_syntaxFacts.IsDeclaratorOfLocalDeclarationStatement(containingDeclarator, _containingStatement))
{
return false;
}
_valuePattern = _syntaxFacts.GetIdentifierOfVariableDeclarator(containingDeclarator);
return true;
}
private bool TryInitializeAssignmentCase()
{
if (!_syntaxFacts.IsSimpleAssignmentStatement(_containingStatement))
{
return false;
}
_syntaxFacts.GetPartsOfAssignmentStatement(_containingStatement,
out var left, out var right);
if (right != _objectCreationExpression)
{
return false;
}
var typeInfo = _semanticModel.GetTypeInfo(left, _cancellationToken);
if (typeInfo.Type is IDynamicTypeSymbol || typeInfo.ConvertedType is IDynamicTypeSymbol)
{
// Not supported if we're initializing something dynamic. The object we're instantiating
// may not have the members that we're trying to access on the dynamic object.
return false;
}
_valuePattern = left;
_initializedSymbol = _semanticModel.GetSymbolInfo(left, _cancellationToken).GetAnySymbol();
return true;
}
protected bool ValuePatternMatches(TExpressionSyntax expression)
{
if (_valuePattern.IsToken)
{
return _syntaxFacts.IsIdentifierName(expression) &&
_syntaxFacts.AreEquivalent(
_valuePattern.AsToken(),
_syntaxFacts.GetIdentifierOfSimpleName(expression));
}
else
{
return _syntaxFacts.AreEquivalent(
_valuePattern.AsNode(), expression);
}
}
protected bool ExpressionContainsValuePatternOrReferencesInitializedSymbol(SyntaxNode expression)
{
foreach (var subExpression in expression.DescendantNodesAndSelf().OfType<TExpressionSyntax>())
{
if (!_syntaxFacts.IsNameOfSimpleMemberAccessExpression(subExpression) &&
!_syntaxFacts.IsNameOfMemberBindingExpression(subExpression))
{
if (ValuePatternMatches(subExpression))
{
return true;
}
}
if (_initializedSymbol != null &&
_initializedSymbol.Equals(
_semanticModel.GetSymbolInfo(subExpression, _cancellationToken).GetAnySymbol()))
{
return true;
}
}
return false;
}
protected abstract bool ShouldAnalyze();
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
namespace Microsoft.CodeAnalysis.UseCollectionInitializer
{
internal abstract class AbstractObjectCreationExpressionAnalyzer<
TExpressionSyntax,
TStatementSyntax,
TObjectCreationExpressionSyntax,
TVariableDeclaratorSyntax,
TMatch>
where TExpressionSyntax : SyntaxNode
where TStatementSyntax : SyntaxNode
where TObjectCreationExpressionSyntax : TExpressionSyntax
where TVariableDeclaratorSyntax : SyntaxNode
{
protected SemanticModel _semanticModel;
protected ISyntaxFacts _syntaxFacts;
protected TObjectCreationExpressionSyntax _objectCreationExpression;
protected CancellationToken _cancellationToken;
protected TStatementSyntax _containingStatement;
private SyntaxNodeOrToken _valuePattern;
private ISymbol _initializedSymbol;
protected AbstractObjectCreationExpressionAnalyzer()
{
}
public void Initialize(
SemanticModel semanticModel,
ISyntaxFacts syntaxFacts,
TObjectCreationExpressionSyntax objectCreationExpression,
CancellationToken cancellationToken)
{
_semanticModel = semanticModel;
_syntaxFacts = syntaxFacts;
_objectCreationExpression = objectCreationExpression;
_cancellationToken = cancellationToken;
}
protected void Clear()
{
_semanticModel = null;
_syntaxFacts = null;
_objectCreationExpression = null;
_cancellationToken = default;
_containingStatement = null;
_valuePattern = default;
_initializedSymbol = null;
}
protected abstract void AddMatches(ArrayBuilder<TMatch> matches);
protected ImmutableArray<TMatch>? AnalyzeWorker()
{
if (_syntaxFacts.GetObjectCreationInitializer(_objectCreationExpression) != null)
{
// Don't bother if this already has an initializer.
return null;
}
if (!ShouldAnalyze())
{
return null;
}
_containingStatement = _objectCreationExpression.FirstAncestorOrSelf<TStatementSyntax>();
if (_containingStatement == null)
{
return null;
}
if (!TryInitializeVariableDeclarationCase() &&
!TryInitializeAssignmentCase())
{
return null;
}
using var _ = ArrayBuilder<TMatch>.GetInstance(out var matches);
AddMatches(matches);
return matches.ToImmutable();
}
private bool TryInitializeVariableDeclarationCase()
{
if (!_syntaxFacts.IsLocalDeclarationStatement(_containingStatement))
{
return false;
}
if (_objectCreationExpression.Parent.Parent is not TVariableDeclaratorSyntax containingDeclarator)
{
return false;
}
_initializedSymbol = _semanticModel.GetDeclaredSymbol(containingDeclarator, _cancellationToken);
if (_initializedSymbol is ILocalSymbol local &&
local.Type is IDynamicTypeSymbol)
{
// Not supported if we're creating a dynamic local. The object we're instantiating
// may not have the members that we're trying to access on the dynamic object.
return false;
}
if (!_syntaxFacts.IsDeclaratorOfLocalDeclarationStatement(containingDeclarator, _containingStatement))
{
return false;
}
_valuePattern = _syntaxFacts.GetIdentifierOfVariableDeclarator(containingDeclarator);
return true;
}
private bool TryInitializeAssignmentCase()
{
if (!_syntaxFacts.IsSimpleAssignmentStatement(_containingStatement))
{
return false;
}
_syntaxFacts.GetPartsOfAssignmentStatement(_containingStatement,
out var left, out var right);
if (right != _objectCreationExpression)
{
return false;
}
var typeInfo = _semanticModel.GetTypeInfo(left, _cancellationToken);
if (typeInfo.Type is IDynamicTypeSymbol || typeInfo.ConvertedType is IDynamicTypeSymbol)
{
// Not supported if we're initializing something dynamic. The object we're instantiating
// may not have the members that we're trying to access on the dynamic object.
return false;
}
_valuePattern = left;
_initializedSymbol = _semanticModel.GetSymbolInfo(left, _cancellationToken).GetAnySymbol();
return true;
}
protected bool ValuePatternMatches(TExpressionSyntax expression)
{
if (_valuePattern.IsToken)
{
return _syntaxFacts.IsIdentifierName(expression) &&
_syntaxFacts.AreEquivalent(
_valuePattern.AsToken(),
_syntaxFacts.GetIdentifierOfSimpleName(expression));
}
else
{
return _syntaxFacts.AreEquivalent(
_valuePattern.AsNode(), expression);
}
}
protected bool ExpressionContainsValuePatternOrReferencesInitializedSymbol(SyntaxNode expression)
{
foreach (var subExpression in expression.DescendantNodesAndSelf().OfType<TExpressionSyntax>())
{
if (!_syntaxFacts.IsNameOfSimpleMemberAccessExpression(subExpression) &&
!_syntaxFacts.IsNameOfMemberBindingExpression(subExpression))
{
if (ValuePatternMatches(subExpression))
{
return true;
}
}
if (_initializedSymbol != null &&
_initializedSymbol.Equals(
_semanticModel.GetSymbolInfo(subExpression, _cancellationToken).GetAnySymbol()))
{
return true;
}
}
return false;
}
protected abstract bool ShouldAnalyze();
}
}
| -1 |
dotnet/roslyn | 55,877 | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute | Part of C# 10 support | davidwengier | 2021-08-25T05:36:27Z | 2021-08-30T20:47:11Z | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | 023d3ca2b5fb429f0b3dcc1efeed39442e232dba | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute. Part of C# 10 support | ./eng/pipelines/test-windows-job-single-machine.yml | # Test on Windows Desktop using a single machine
parameters:
- name: testRunName
type: string
default: ''
- name: jobName
type: string
default: ''
- name: buildJobName
type: string
default: ''
- name: testArtifactName
type: string
default: ''
- name: configuration
type: string
default: 'Debug'
- name: testArguments
type: string
default: ''
- name: queueName
type: string
default: 'BuildPool.Windows.10.Amd64.Open'
jobs:
- job: ${{ parameters.jobName }}
dependsOn: ${{ parameters.buildJobName }}
pool:
name: NetCorePublic-Pool
queue: ${{ parameters.queueName }}
timeoutInMinutes: 120
variables:
DOTNET_ROLL_FORWARD: LatestMajor
DOTNET_ROLL_FORWARD_TO_PRERELEASE: 1
steps:
- checkout: none
- task: DownloadPipelineArtifact@2
displayName: Download Test Payload
inputs:
artifact: ${{ parameters.testArtifactName }}
path: '$(Build.SourcesDirectory)'
- task: BatchScript@1
displayName: Rehydrate Unit Tests Environment
inputs:
filename: rehydrate-all.cmd
- task: PowerShell@2
displayName: Run Unit Tests
inputs:
filePath: eng/build.ps1
arguments: -ci -configuration ${{ parameters.configuration }} ${{ parameters.testArguments }} -collectDumps
- task: PublishTestResults@2
displayName: Publish xUnit Test Results
inputs:
testRunner: XUnit
testResultsFiles: '$(Build.SourcesDirectory)\artifacts\TestResults\${{ parameters.configuration }}\*.xml'
mergeTestResults: true
testRunTitle: '${{ parameters.testRunName }}'
condition: always()
- template: publish-logs.yml
parameters:
configuration: ${{ parameters.configuration }}
jobName: ${{ parameters.jobName }}
| # Test on Windows Desktop using a single machine
parameters:
- name: testRunName
type: string
default: ''
- name: jobName
type: string
default: ''
- name: buildJobName
type: string
default: ''
- name: testArtifactName
type: string
default: ''
- name: configuration
type: string
default: 'Debug'
- name: testArguments
type: string
default: ''
- name: queueName
type: string
default: 'BuildPool.Windows.10.Amd64.Open'
jobs:
- job: ${{ parameters.jobName }}
dependsOn: ${{ parameters.buildJobName }}
pool:
name: NetCorePublic-Pool
queue: ${{ parameters.queueName }}
timeoutInMinutes: 120
variables:
DOTNET_ROLL_FORWARD: LatestMajor
DOTNET_ROLL_FORWARD_TO_PRERELEASE: 1
steps:
- checkout: none
- task: DownloadPipelineArtifact@2
displayName: Download Test Payload
inputs:
artifact: ${{ parameters.testArtifactName }}
path: '$(Build.SourcesDirectory)'
- task: BatchScript@1
displayName: Rehydrate Unit Tests Environment
inputs:
filename: rehydrate-all.cmd
- task: PowerShell@2
displayName: Run Unit Tests
inputs:
filePath: eng/build.ps1
arguments: -ci -configuration ${{ parameters.configuration }} ${{ parameters.testArguments }} -collectDumps
- task: PublishTestResults@2
displayName: Publish xUnit Test Results
inputs:
testRunner: XUnit
testResultsFiles: '$(Build.SourcesDirectory)\artifacts\TestResults\${{ parameters.configuration }}\*.xml'
mergeTestResults: true
testRunTitle: '${{ parameters.testRunName }}'
condition: always()
- template: publish-logs.yml
parameters:
configuration: ${{ parameters.configuration }}
jobName: ${{ parameters.jobName }}
| -1 |
dotnet/roslyn | 55,877 | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute | Part of C# 10 support | davidwengier | 2021-08-25T05:36:27Z | 2021-08-30T20:47:11Z | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | 023d3ca2b5fb429f0b3dcc1efeed39442e232dba | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute. Part of C# 10 support | ./src/VisualStudio/Core/Def/Implementation/CommandBindings.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.ComponentModel.Composition;
using Microsoft.CodeAnalysis.Editor.Commanding.Commands;
using Microsoft.VisualStudio.Editor.Commanding;
using Microsoft.VisualStudio.LanguageServices;
using Microsoft.VisualStudio.LanguageServices.ValueTracking;
namespace Microsoft.VisualStudio.Editor.Implementation
{
internal sealed class CommandBindings
{
[Export]
[CommandBinding(Guids.RoslynGroupIdString, ID.RoslynCommands.GoToImplementation, typeof(GoToImplementationCommandArgs))]
internal CommandBindingDefinition gotoImplementationCommandBinding;
[Export]
[CommandBinding(Guids.CSharpGroupIdString, ID.CSharpCommands.OrganizeSortUsings, typeof(SortImportsCommandArgs))]
internal CommandBindingDefinition organizeSortCommandBinding;
[Export]
[CommandBinding(Guids.CSharpGroupIdString, ID.CSharpCommands.OrganizeRemoveAndSort, typeof(SortAndRemoveUnnecessaryImportsCommandArgs))]
internal CommandBindingDefinition organizeRemoveAndSortCommandBinding;
[Export]
[CommandBinding(Guids.CSharpGroupIdString, ID.CSharpCommands.ContextOrganizeRemoveAndSort, typeof(SortAndRemoveUnnecessaryImportsCommandArgs))]
internal CommandBindingDefinition contextOrganizeRemoveAndSortCommandBinding;
[Export]
[CommandBinding(Guids.RoslynGroupIdString, ID.RoslynCommands.GoToValueTrackingWindow, typeof(ValueTrackingEditorCommandArgs))]
internal CommandBindingDefinition gotoDataFlowToolCommandBinding;
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.ComponentModel.Composition;
using Microsoft.CodeAnalysis.Editor.Commanding.Commands;
using Microsoft.VisualStudio.Editor.Commanding;
using Microsoft.VisualStudio.LanguageServices;
using Microsoft.VisualStudio.LanguageServices.ValueTracking;
namespace Microsoft.VisualStudio.Editor.Implementation
{
internal sealed class CommandBindings
{
[Export]
[CommandBinding(Guids.RoslynGroupIdString, ID.RoslynCommands.GoToImplementation, typeof(GoToImplementationCommandArgs))]
internal CommandBindingDefinition gotoImplementationCommandBinding;
[Export]
[CommandBinding(Guids.CSharpGroupIdString, ID.CSharpCommands.OrganizeSortUsings, typeof(SortImportsCommandArgs))]
internal CommandBindingDefinition organizeSortCommandBinding;
[Export]
[CommandBinding(Guids.CSharpGroupIdString, ID.CSharpCommands.OrganizeRemoveAndSort, typeof(SortAndRemoveUnnecessaryImportsCommandArgs))]
internal CommandBindingDefinition organizeRemoveAndSortCommandBinding;
[Export]
[CommandBinding(Guids.CSharpGroupIdString, ID.CSharpCommands.ContextOrganizeRemoveAndSort, typeof(SortAndRemoveUnnecessaryImportsCommandArgs))]
internal CommandBindingDefinition contextOrganizeRemoveAndSortCommandBinding;
[Export]
[CommandBinding(Guids.RoslynGroupIdString, ID.RoslynCommands.GoToValueTrackingWindow, typeof(ValueTrackingEditorCommandArgs))]
internal CommandBindingDefinition gotoDataFlowToolCommandBinding;
}
}
| -1 |
dotnet/roslyn | 55,877 | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute | Part of C# 10 support | davidwengier | 2021-08-25T05:36:27Z | 2021-08-30T20:47:11Z | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | 023d3ca2b5fb429f0b3dcc1efeed39442e232dba | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute. Part of C# 10 support | ./src/VisualStudio/CSharp/Impl/Options/IntelliSenseOptionPageControl.xaml | <options:AbstractOptionPageControl
x:Class="Microsoft.VisualStudio.LanguageServices.CSharp.Options.IntelliSenseOptionPageControl"
x:ClassModifier="internal"
x:Uid="CSharpOptionsIntelliSenseOptionPageControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:options="clr-namespace:Microsoft.VisualStudio.LanguageServices.Implementation.Options;assembly=Microsoft.VisualStudio.LanguageServices.Implementation"
xmlns:local="clr-namespace:Microsoft.VisualStudio.LanguageServices.CSharp.Options"
mc:Ignorable="d" d:DesignHeight="350" d:DesignWidth="460">
<ScrollViewer VerticalScrollBarVisibility="Auto">
<StackPanel>
<GroupBox x:Uid="CompletionListsGroupBox"
Header="{x:Static local:IntelliSenseOptionPageStrings.Option_Completion}">
<StackPanel>
<CheckBox x:Uid="Show_completion_list_after_a_character_is_typed"
x:Name="Show_completion_list_after_a_character_is_typed"
Content="{x:Static local:IntelliSenseOptionPageStrings.Option_Show_completion_list_after_a_character_is_typed}"
Checked="Show_completion_list_after_a_character_is_typed_Checked"
Unchecked="Show_completion_list_after_a_character_is_typed_Unchecked"/>
<StackPanel Margin="15, 0, 0, 0">
<CheckBox x:Uid="Show_completion_list_after_a_character_is_deleted"
x:Name="Show_completion_list_after_a_character_is_deleted"
Content="{x:Static local:IntelliSenseOptionPageStrings.Option_Show_completion_list_after_a_character_is_deleted}"
Checked="Show_completion_list_after_a_character_is_deleted_Checked"
Unchecked="Show_completion_list_after_a_character_is_deleted_Unchecked"/>
</StackPanel>
<CheckBox x:Uid="Automatically_show_completion_list_in_argument_lists"
x:Name="Automatically_show_completion_list_in_argument_lists"
Content="{x:Static local:IntelliSenseOptionPageStrings.Automatically_show_completion_list_in_argument_lists}" />
<CheckBox x:Uid="Highlight_matching_portions_of_completion_list_items"
x:Name="Highlight_matching_portions_of_completion_list_items"
Content="{x:Static local:IntelliSenseOptionPageStrings.Option_Highlight_matching_portions_of_completion_list_items}" />
<CheckBox x:Uid="Show_completion_item_filters"
x:Name="Show_completion_item_filters"
Content="{x:Static local:IntelliSenseOptionPageStrings.Option_Show_completion_item_filters}" />
<CheckBox x:Name="Automatically_complete_statement_on_semicolon"
Content="{x:Static local:IntelliSenseOptionPageStrings.Option_Automatically_complete_statement_on_semicolon}" />
<Label Content="{x:Static local:IntelliSenseOptionPageStrings.Snippets_behavior}"/>
<StackPanel Margin="15, 0, 0, 0">
<RadioButton GroupName="Snippets_behavior"
x:Name="Never_include_snippets"
Content="{x:Static local:IntelliSenseOptionPageStrings.Option_Never_include_snippets}"/>
<RadioButton GroupName="Snippets_behavior"
x:Name="Always_include_snippets"
Content="{x:Static local:IntelliSenseOptionPageStrings.Option_Always_include_snippets}"/>
<RadioButton GroupName="Snippets_behavior"
x:Name="Include_snippets_when_question_Tab_is_typed_after_an_identifier"
Content="{x:Static local:IntelliSenseOptionPageStrings.Option_Include_snippets_when_question_Tab_is_typed_after_an_identifier}"/>
</StackPanel>
<Label Content="{x:Static local:IntelliSenseOptionPageStrings.Enter_key_behavior_Title}"/>
<StackPanel Margin="15, 0, 0, 0">
<RadioButton GroupName="InsertNewlineOnEnterRadio"
x:Name="Never_add_new_line_on_enter"
Content="{x:Static local:IntelliSenseOptionPageStrings.Option_Never_add_new_line_on_enter}"/>
<RadioButton GroupName="InsertNewlineOnEnterRadio"
x:Name="Only_add_new_line_on_enter_with_whole_word"
Content="{x:Static local:IntelliSenseOptionPageStrings.Option_Only_add_new_line_on_enter_with_whole_word}"/>
<RadioButton GroupName="InsertNewlineOnEnterRadio"
x:Name="Always_add_new_line_on_enter"
Content="{x:Static local:IntelliSenseOptionPageStrings.Option_Always_add_new_line_on_enter}"/>
</StackPanel>
<CheckBox x:Uid="Show_name_suggestions"
x:Name="Show_name_suggestions"
Content="{x:Static local:IntelliSenseOptionPageStrings.Option_Show_name_suggestions}" />
<CheckBox x:Uid="Show_items_from_unimported_namespaces"
x:Name="Show_items_from_unimported_namespaces"
Content="{x:Static local:IntelliSenseOptionPageStrings.Option_Show_items_from_unimported_namespaces}"
Checked="Show_items_from_unimported_namespaces_CheckedChanged"
Unchecked="Show_items_from_unimported_namespaces_CheckedChanged"
Indeterminate="Show_items_from_unimported_namespaces_CheckedChanged"
IsThreeState="True"/>
<CheckBox x:Uid="Tab_twice_to_insert_arguments"
x:Name="Tab_twice_to_insert_arguments"
Content="{x:Static local:IntelliSenseOptionPageStrings.Option_Tab_twice_to_insert_arguments}"
Checked="Tab_twice_to_insert_arguments_CheckedChanged"
Unchecked="Tab_twice_to_insert_arguments_CheckedChanged"
Indeterminate="Tab_twice_to_insert_arguments_CheckedChanged"
IsThreeState="True"/>
</StackPanel>
</GroupBox>
</StackPanel>
</ScrollViewer>
</options:AbstractOptionPageControl>
| <options:AbstractOptionPageControl
x:Class="Microsoft.VisualStudio.LanguageServices.CSharp.Options.IntelliSenseOptionPageControl"
x:ClassModifier="internal"
x:Uid="CSharpOptionsIntelliSenseOptionPageControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:options="clr-namespace:Microsoft.VisualStudio.LanguageServices.Implementation.Options;assembly=Microsoft.VisualStudio.LanguageServices.Implementation"
xmlns:local="clr-namespace:Microsoft.VisualStudio.LanguageServices.CSharp.Options"
mc:Ignorable="d" d:DesignHeight="350" d:DesignWidth="460">
<ScrollViewer VerticalScrollBarVisibility="Auto">
<StackPanel>
<GroupBox x:Uid="CompletionListsGroupBox"
Header="{x:Static local:IntelliSenseOptionPageStrings.Option_Completion}">
<StackPanel>
<CheckBox x:Uid="Show_completion_list_after_a_character_is_typed"
x:Name="Show_completion_list_after_a_character_is_typed"
Content="{x:Static local:IntelliSenseOptionPageStrings.Option_Show_completion_list_after_a_character_is_typed}"
Checked="Show_completion_list_after_a_character_is_typed_Checked"
Unchecked="Show_completion_list_after_a_character_is_typed_Unchecked"/>
<StackPanel Margin="15, 0, 0, 0">
<CheckBox x:Uid="Show_completion_list_after_a_character_is_deleted"
x:Name="Show_completion_list_after_a_character_is_deleted"
Content="{x:Static local:IntelliSenseOptionPageStrings.Option_Show_completion_list_after_a_character_is_deleted}"
Checked="Show_completion_list_after_a_character_is_deleted_Checked"
Unchecked="Show_completion_list_after_a_character_is_deleted_Unchecked"/>
</StackPanel>
<CheckBox x:Uid="Automatically_show_completion_list_in_argument_lists"
x:Name="Automatically_show_completion_list_in_argument_lists"
Content="{x:Static local:IntelliSenseOptionPageStrings.Automatically_show_completion_list_in_argument_lists}" />
<CheckBox x:Uid="Highlight_matching_portions_of_completion_list_items"
x:Name="Highlight_matching_portions_of_completion_list_items"
Content="{x:Static local:IntelliSenseOptionPageStrings.Option_Highlight_matching_portions_of_completion_list_items}" />
<CheckBox x:Uid="Show_completion_item_filters"
x:Name="Show_completion_item_filters"
Content="{x:Static local:IntelliSenseOptionPageStrings.Option_Show_completion_item_filters}" />
<CheckBox x:Name="Automatically_complete_statement_on_semicolon"
Content="{x:Static local:IntelliSenseOptionPageStrings.Option_Automatically_complete_statement_on_semicolon}" />
<Label Content="{x:Static local:IntelliSenseOptionPageStrings.Snippets_behavior}"/>
<StackPanel Margin="15, 0, 0, 0">
<RadioButton GroupName="Snippets_behavior"
x:Name="Never_include_snippets"
Content="{x:Static local:IntelliSenseOptionPageStrings.Option_Never_include_snippets}"/>
<RadioButton GroupName="Snippets_behavior"
x:Name="Always_include_snippets"
Content="{x:Static local:IntelliSenseOptionPageStrings.Option_Always_include_snippets}"/>
<RadioButton GroupName="Snippets_behavior"
x:Name="Include_snippets_when_question_Tab_is_typed_after_an_identifier"
Content="{x:Static local:IntelliSenseOptionPageStrings.Option_Include_snippets_when_question_Tab_is_typed_after_an_identifier}"/>
</StackPanel>
<Label Content="{x:Static local:IntelliSenseOptionPageStrings.Enter_key_behavior_Title}"/>
<StackPanel Margin="15, 0, 0, 0">
<RadioButton GroupName="InsertNewlineOnEnterRadio"
x:Name="Never_add_new_line_on_enter"
Content="{x:Static local:IntelliSenseOptionPageStrings.Option_Never_add_new_line_on_enter}"/>
<RadioButton GroupName="InsertNewlineOnEnterRadio"
x:Name="Only_add_new_line_on_enter_with_whole_word"
Content="{x:Static local:IntelliSenseOptionPageStrings.Option_Only_add_new_line_on_enter_with_whole_word}"/>
<RadioButton GroupName="InsertNewlineOnEnterRadio"
x:Name="Always_add_new_line_on_enter"
Content="{x:Static local:IntelliSenseOptionPageStrings.Option_Always_add_new_line_on_enter}"/>
</StackPanel>
<CheckBox x:Uid="Show_name_suggestions"
x:Name="Show_name_suggestions"
Content="{x:Static local:IntelliSenseOptionPageStrings.Option_Show_name_suggestions}" />
<CheckBox x:Uid="Show_items_from_unimported_namespaces"
x:Name="Show_items_from_unimported_namespaces"
Content="{x:Static local:IntelliSenseOptionPageStrings.Option_Show_items_from_unimported_namespaces}"
Checked="Show_items_from_unimported_namespaces_CheckedChanged"
Unchecked="Show_items_from_unimported_namespaces_CheckedChanged"
Indeterminate="Show_items_from_unimported_namespaces_CheckedChanged"
IsThreeState="True"/>
<CheckBox x:Uid="Tab_twice_to_insert_arguments"
x:Name="Tab_twice_to_insert_arguments"
Content="{x:Static local:IntelliSenseOptionPageStrings.Option_Tab_twice_to_insert_arguments}"
Checked="Tab_twice_to_insert_arguments_CheckedChanged"
Unchecked="Tab_twice_to_insert_arguments_CheckedChanged"
Indeterminate="Tab_twice_to_insert_arguments_CheckedChanged"
IsThreeState="True"/>
</StackPanel>
</GroupBox>
</StackPanel>
</ScrollViewer>
</options:AbstractOptionPageControl>
| -1 |
dotnet/roslyn | 55,877 | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute | Part of C# 10 support | davidwengier | 2021-08-25T05:36:27Z | 2021-08-30T20:47:11Z | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | 023d3ca2b5fb429f0b3dcc1efeed39442e232dba | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute. Part of C# 10 support | ./src/Compilers/Core/MSBuildTaskTests/TestUtilities/MSBuildUtil.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.Build.Framework;
using Moq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Microsoft.CodeAnalysis.BuildTasks.UnitTests
{
internal static class MSBuildUtil
{
public static ITaskItem[] CreateTaskItems(params string[] fileNames)
{
return fileNames.Select(CreateTaskItem).ToArray();
}
public static ITaskItem CreateTaskItem(string fileName)
{
var taskItem = new Mock<ITaskItem>(MockBehavior.Strict);
taskItem.Setup(x => x.ItemSpec).Returns(fileName);
return taskItem.Object;
}
public static ITaskItem CreateTaskItem(string fileName, Dictionary<string, string> metadata)
{
var taskItem = new Mock<ITaskItem>(MockBehavior.Strict);
taskItem.Setup(x => x.ItemSpec).Returns(fileName);
taskItem.Setup(x => x.GetMetadata(It.IsAny<string>())).Returns<string>(s => s switch
{
"FullPath" => fileName,
_ => metadata.ContainsKey(s) ? metadata[s] : string.Empty
});
return taskItem.Object;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.Build.Framework;
using Moq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Microsoft.CodeAnalysis.BuildTasks.UnitTests
{
internal static class MSBuildUtil
{
public static ITaskItem[] CreateTaskItems(params string[] fileNames)
{
return fileNames.Select(CreateTaskItem).ToArray();
}
public static ITaskItem CreateTaskItem(string fileName)
{
var taskItem = new Mock<ITaskItem>(MockBehavior.Strict);
taskItem.Setup(x => x.ItemSpec).Returns(fileName);
return taskItem.Object;
}
public static ITaskItem CreateTaskItem(string fileName, Dictionary<string, string> metadata)
{
var taskItem = new Mock<ITaskItem>(MockBehavior.Strict);
taskItem.Setup(x => x.ItemSpec).Returns(fileName);
taskItem.Setup(x => x.GetMetadata(It.IsAny<string>())).Returns<string>(s => s switch
{
"FullPath" => fileName,
_ => metadata.ContainsKey(s) ? metadata[s] : string.Empty
});
return taskItem.Object;
}
}
}
| -1 |
dotnet/roslyn | 55,877 | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute | Part of C# 10 support | davidwengier | 2021-08-25T05:36:27Z | 2021-08-30T20:47:11Z | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | 023d3ca2b5fb429f0b3dcc1efeed39442e232dba | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute. Part of C# 10 support | ./src/Compilers/CSharp/Portable/Emitter/Model/MostCommonNullableValueBuilder.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
internal struct MostCommonNullableValueBuilder
{
private int _value0;
private int _value1;
private int _value2;
internal byte? MostCommonValue
{
get
{
int max;
byte b;
if (_value1 > _value0)
{
max = _value1;
b = 1;
}
else
{
max = _value0;
b = 0;
}
if (_value2 > max)
{
return 2;
}
return max == 0 ? (byte?)null : b;
}
}
internal void AddValue(byte value)
{
switch (value)
{
case 0:
_value0++;
break;
case 1:
_value1++;
break;
case 2:
_value2++;
break;
default:
throw ExceptionUtilities.UnexpectedValue(value);
}
}
internal void AddValue(byte? value)
{
if (value != null)
{
AddValue(value.GetValueOrDefault());
}
}
internal void AddValue(TypeWithAnnotations type)
{
var builder = ArrayBuilder<byte>.GetInstance();
type.AddNullableTransforms(builder);
AddValue(GetCommonValue(builder));
builder.Free();
}
/// <summary>
/// Returns the common value if all bytes are the same value.
/// Otherwise returns null.
/// </summary>
internal static byte? GetCommonValue(ArrayBuilder<byte> builder)
{
int n = builder.Count;
if (n == 0)
{
return null;
}
byte b = builder[0];
for (int i = 1; i < n; i++)
{
if (builder[i] != b)
{
return null;
}
}
return b;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
internal struct MostCommonNullableValueBuilder
{
private int _value0;
private int _value1;
private int _value2;
internal byte? MostCommonValue
{
get
{
int max;
byte b;
if (_value1 > _value0)
{
max = _value1;
b = 1;
}
else
{
max = _value0;
b = 0;
}
if (_value2 > max)
{
return 2;
}
return max == 0 ? (byte?)null : b;
}
}
internal void AddValue(byte value)
{
switch (value)
{
case 0:
_value0++;
break;
case 1:
_value1++;
break;
case 2:
_value2++;
break;
default:
throw ExceptionUtilities.UnexpectedValue(value);
}
}
internal void AddValue(byte? value)
{
if (value != null)
{
AddValue(value.GetValueOrDefault());
}
}
internal void AddValue(TypeWithAnnotations type)
{
var builder = ArrayBuilder<byte>.GetInstance();
type.AddNullableTransforms(builder);
AddValue(GetCommonValue(builder));
builder.Free();
}
/// <summary>
/// Returns the common value if all bytes are the same value.
/// Otherwise returns null.
/// </summary>
internal static byte? GetCommonValue(ArrayBuilder<byte> builder)
{
int n = builder.Count;
if (n == 0)
{
return null;
}
byte b = builder[0];
for (int i = 1; i < n; i++)
{
if (builder[i] != b)
{
return null;
}
}
return b;
}
}
}
| -1 |
dotnet/roslyn | 55,877 | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute | Part of C# 10 support | davidwengier | 2021-08-25T05:36:27Z | 2021-08-30T20:47:11Z | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | 023d3ca2b5fb429f0b3dcc1efeed39442e232dba | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute. Part of C# 10 support | ./src/Features/LanguageServer/Protocol/Handler/Symbols/DocumentSymbolsHandler.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Composition;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.NavigationBar;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.LanguageServer.Protocol;
using Microsoft.VisualStudio.Text.Adornments;
using Roslyn.Utilities;
using LSP = Microsoft.VisualStudio.LanguageServer.Protocol;
namespace Microsoft.CodeAnalysis.LanguageServer.Handler
{
[ExportRoslynLanguagesLspRequestHandlerProvider, Shared]
[ProvidesMethod(Methods.TextDocumentDocumentSymbolName)]
internal class DocumentSymbolsHandler : AbstractStatelessRequestHandler<DocumentSymbolParams, object[]>
{
public override string Method => Methods.TextDocumentDocumentSymbolName;
public override bool MutatesSolutionState => false;
public override bool RequiresLSPSolution => true;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public DocumentSymbolsHandler()
{
}
public override TextDocumentIdentifier GetTextDocumentIdentifier(DocumentSymbolParams request) => request.TextDocument;
public override async Task<object[]> HandleRequestAsync(DocumentSymbolParams request, RequestContext context, CancellationToken cancellationToken)
{
var document = context.Document;
if (document == null)
return Array.Empty<SymbolInformation>();
var navBarService = document.Project.LanguageServices.GetRequiredService<INavigationBarItemService>();
var navBarItems = await navBarService.GetItemsAsync(document, supportsCodeGeneration: false, cancellationToken).ConfigureAwait(false);
if (navBarItems.IsEmpty)
return Array.Empty<object>();
var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);
// TODO - Return more than 2 levels of symbols.
// https://github.com/dotnet/roslyn/projects/45#card-20033869
using var _ = ArrayBuilder<object>.GetInstance(out var symbols);
if (context.ClientCapabilities?.TextDocument?.DocumentSymbol?.HierarchicalDocumentSymbolSupport == true)
{
// only top level ones
foreach (var item in navBarItems)
symbols.AddIfNotNull(GetDocumentSymbol(item, text, cancellationToken));
}
else
{
foreach (var item in navBarItems)
{
symbols.AddIfNotNull(GetSymbolInformation(item, document, text, containerName: null));
foreach (var childItem in item.ChildItems)
symbols.AddIfNotNull(GetSymbolInformation(childItem, document, text, item.Text));
}
}
var result = symbols.ToArray();
return result;
}
/// <summary>
/// Get a symbol information from a specified nav bar item.
/// </summary>
private static SymbolInformation? GetSymbolInformation(
RoslynNavigationBarItem item, Document document, SourceText text, string? containerName = null)
{
if (item is not RoslynNavigationBarItem.SymbolItem symbolItem || symbolItem.Location.InDocumentInfo == null)
return null;
return new VSSymbolInformation
{
Name = item.Text,
Location = new LSP.Location
{
Uri = document.GetURI(),
Range = ProtocolConversions.TextSpanToRange(symbolItem.Location.InDocumentInfo.Value.navigationSpan, text),
},
Kind = ProtocolConversions.GlyphToSymbolKind(item.Glyph),
ContainerName = containerName,
Icon = ProtocolConversions.GetImageIdFromGlyph(item.Glyph),
};
}
/// <summary>
/// Get a document symbol from a specified nav bar item.
/// </summary>
private static DocumentSymbol? GetDocumentSymbol(
RoslynNavigationBarItem item, SourceText text, CancellationToken cancellationToken)
{
if (item is not RoslynNavigationBarItem.SymbolItem symbolItem ||
symbolItem.Location.InDocumentInfo == null)
{
return null;
}
var inDocumentInfo = symbolItem.Location.InDocumentInfo.Value;
if (inDocumentInfo.spans.Length == 0)
return null;
return new DocumentSymbol
{
Name = symbolItem.Name,
Detail = item.Text,
Kind = ProtocolConversions.GlyphToSymbolKind(item.Glyph),
Deprecated = symbolItem.IsObsolete,
Range = ProtocolConversions.TextSpanToRange(inDocumentInfo.spans.First(), text),
SelectionRange = ProtocolConversions.TextSpanToRange(inDocumentInfo.navigationSpan, text),
Children = GetChildren(item.ChildItems, text, cancellationToken),
};
static DocumentSymbol[] GetChildren(
ImmutableArray<RoslynNavigationBarItem> items, SourceText text, CancellationToken cancellationToken)
{
using var _ = ArrayBuilder<DocumentSymbol>.GetInstance(out var list);
foreach (var item in items)
list.AddIfNotNull(GetDocumentSymbol(item, text, cancellationToken));
return list.ToArray();
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Composition;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.NavigationBar;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.LanguageServer.Protocol;
using Microsoft.VisualStudio.Text.Adornments;
using Roslyn.Utilities;
using LSP = Microsoft.VisualStudio.LanguageServer.Protocol;
namespace Microsoft.CodeAnalysis.LanguageServer.Handler
{
[ExportRoslynLanguagesLspRequestHandlerProvider, Shared]
[ProvidesMethod(Methods.TextDocumentDocumentSymbolName)]
internal class DocumentSymbolsHandler : AbstractStatelessRequestHandler<DocumentSymbolParams, object[]>
{
public override string Method => Methods.TextDocumentDocumentSymbolName;
public override bool MutatesSolutionState => false;
public override bool RequiresLSPSolution => true;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public DocumentSymbolsHandler()
{
}
public override TextDocumentIdentifier GetTextDocumentIdentifier(DocumentSymbolParams request) => request.TextDocument;
public override async Task<object[]> HandleRequestAsync(DocumentSymbolParams request, RequestContext context, CancellationToken cancellationToken)
{
var document = context.Document;
if (document == null)
return Array.Empty<SymbolInformation>();
var navBarService = document.Project.LanguageServices.GetRequiredService<INavigationBarItemService>();
var navBarItems = await navBarService.GetItemsAsync(document, supportsCodeGeneration: false, cancellationToken).ConfigureAwait(false);
if (navBarItems.IsEmpty)
return Array.Empty<object>();
var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);
// TODO - Return more than 2 levels of symbols.
// https://github.com/dotnet/roslyn/projects/45#card-20033869
using var _ = ArrayBuilder<object>.GetInstance(out var symbols);
if (context.ClientCapabilities?.TextDocument?.DocumentSymbol?.HierarchicalDocumentSymbolSupport == true)
{
// only top level ones
foreach (var item in navBarItems)
symbols.AddIfNotNull(GetDocumentSymbol(item, text, cancellationToken));
}
else
{
foreach (var item in navBarItems)
{
symbols.AddIfNotNull(GetSymbolInformation(item, document, text, containerName: null));
foreach (var childItem in item.ChildItems)
symbols.AddIfNotNull(GetSymbolInformation(childItem, document, text, item.Text));
}
}
var result = symbols.ToArray();
return result;
}
/// <summary>
/// Get a symbol information from a specified nav bar item.
/// </summary>
private static SymbolInformation? GetSymbolInformation(
RoslynNavigationBarItem item, Document document, SourceText text, string? containerName = null)
{
if (item is not RoslynNavigationBarItem.SymbolItem symbolItem || symbolItem.Location.InDocumentInfo == null)
return null;
return new VSSymbolInformation
{
Name = item.Text,
Location = new LSP.Location
{
Uri = document.GetURI(),
Range = ProtocolConversions.TextSpanToRange(symbolItem.Location.InDocumentInfo.Value.navigationSpan, text),
},
Kind = ProtocolConversions.GlyphToSymbolKind(item.Glyph),
ContainerName = containerName,
Icon = ProtocolConversions.GetImageIdFromGlyph(item.Glyph),
};
}
/// <summary>
/// Get a document symbol from a specified nav bar item.
/// </summary>
private static DocumentSymbol? GetDocumentSymbol(
RoslynNavigationBarItem item, SourceText text, CancellationToken cancellationToken)
{
if (item is not RoslynNavigationBarItem.SymbolItem symbolItem ||
symbolItem.Location.InDocumentInfo == null)
{
return null;
}
var inDocumentInfo = symbolItem.Location.InDocumentInfo.Value;
if (inDocumentInfo.spans.Length == 0)
return null;
return new DocumentSymbol
{
Name = symbolItem.Name,
Detail = item.Text,
Kind = ProtocolConversions.GlyphToSymbolKind(item.Glyph),
Deprecated = symbolItem.IsObsolete,
Range = ProtocolConversions.TextSpanToRange(inDocumentInfo.spans.First(), text),
SelectionRange = ProtocolConversions.TextSpanToRange(inDocumentInfo.navigationSpan, text),
Children = GetChildren(item.ChildItems, text, cancellationToken),
};
static DocumentSymbol[] GetChildren(
ImmutableArray<RoslynNavigationBarItem> items, SourceText text, CancellationToken cancellationToken)
{
using var _ = ArrayBuilder<DocumentSymbol>.GetInstance(out var list);
foreach (var item in items)
list.AddIfNotNull(GetDocumentSymbol(item, text, cancellationToken));
return list.ToArray();
}
}
}
}
| -1 |
dotnet/roslyn | 55,877 | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute | Part of C# 10 support | davidwengier | 2021-08-25T05:36:27Z | 2021-08-30T20:47:11Z | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | 023d3ca2b5fb429f0b3dcc1efeed39442e232dba | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute. Part of C# 10 support | ./src/Compilers/Core/MSBuildTask/xlf/ErrorString.ko.xlf | <?xml version="1.0" encoding="utf-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd">
<file datatype="xml" source-language="en" target-language="ko" original="../ErrorString.resx">
<body>
<trans-unit id="Compiler_UnexpectedException">
<source>MSB3883: Unexpected exception: </source>
<target state="translated">MSB3883: 예기치 않은 예외: </target>
<note>{StrBegin="MSB3883: "}</note>
</trans-unit>
<trans-unit id="Csc_AssemblyAliasContainsIllegalCharacters">
<source>MSB3053: The assembly alias "{1}" on reference "{0}" contains illegal characters.</source>
<target state="translated">MSB3053: "{0}" 참조의 어셈블리 별칭 "{1}"에 잘못된 문자가 포함되어 있습니다.</target>
<note>{StrBegin="MSB3053: "}</note>
</trans-unit>
<trans-unit id="Csc_InvalidParameter">
<source>MSB3051: The parameter to the compiler is invalid. {0}</source>
<target state="translated">MSB3051: 컴파일러에 대한 매개 변수가 잘못되었습니다. {0}</target>
<note>{StrBegin="MSB3051: "}</note>
</trans-unit>
<trans-unit id="Csc_InvalidParameterWarning">
<source>MSB3052: The parameter to the compiler is invalid, '{0}{1}' will be ignored.</source>
<target state="translated">MSB3052: 컴파일러에 대한 매개 변수가 잘못되었습니다. '{0}{1}'이(가) 무시됩니다.</target>
<note>{StrBegin="MSB3052: "}</note>
</trans-unit>
<trans-unit id="General_CannotConvertStringToBool">
<source>The string "{0}" cannot be converted to a boolean (true/false) value.</source>
<target state="translated">"{0}" 문자열을 부울 값(true/false)으로 변환할 수 없습니다.</target>
<note />
</trans-unit>
<trans-unit id="General_CouldNotSetHostObjectParameter">
<source>MSB3081: A problem occurred while trying to set the "{0}" parameter for the IDE's in-process compiler. {1}</source>
<target state="translated">MSB3081: IDE의 In-Process 컴파일러에 "{0}" 매개 변수를 설정하는 동안 문제가 발생했습니다. {1}</target>
<note>{StrBegin="MSB3081: "}</note>
</trans-unit>
<trans-unit id="General_DuplicateItemsNotSupported">
<source>MSB3105: The item "{0}" was specified more than once in the "{1}" parameter. Duplicate items are not supported by the "{1}" parameter.</source>
<target state="translated">MSB3105: "{0}" 항목을 "{1}" 매개 변수에 두 번 이상 지정했습니다. "{1}" 매개 변수는 중복 항목을 지원하지 않습니다.</target>
<note>{StrBegin="MSB3105: "}</note>
</trans-unit>
<trans-unit id="General_DuplicateItemsNotSupportedWithMetadata">
<source>MSB3083: The item "{0}" was specified more than once in the "{1}" parameter and both items had the same value "{2}" for the "{3}" metadata. Duplicate items are not supported by the "{1}" parameter unless they have different values for the "{3}" metadata.</source>
<target state="translated">MSB3083: "{0}" 항목이 "{1}" 매개 변수에 두 번 이상 지정되었으며 두 항목이 "{3}" 메타데이터에 대해 동일한 값 "{2}"을(를) 가지고 있습니다. "{3}" 메타데이터에 대한 값이 같으면 "{1}" 매개 변수는 중복 항목을 지원하지 않습니다.</target>
<note>{StrBegin="MSB3083: "}</note>
</trans-unit>
<trans-unit id="General_ExpectedFileMissing">
<source>Expected file "{0}" does not exist.</source>
<target state="translated">필요한 "{0}" 파일이 없습니다.</target>
<note />
</trans-unit>
<trans-unit id="CopyRefAssembly_SkippingCopy1">
<source>Reference assembly "{0}" already has latest information. Leaving it untouched.</source>
<target state="translated">참조 어셈블리 "{0}"에 이미 최신 정보가 있습니다. 그대로 유지합니다.</target>
<note />
</trans-unit>
<trans-unit id="CopyRefAssembly_SourceNotRef1">
<source>Could not extract the MVID from "{0}". Are you sure it is a reference assembly?</source>
<target state="translated">"{0}"에서 MVID를 추출할 수 없습니다. 참조 어셈블리가 맞는지 확인하세요.</target>
<note />
</trans-unit>
<trans-unit id="CopyRefAssembly_BadSource3">
<source>Failed to check the content hash of the source ref assembly '{0}': {1}
{2}</source>
<target state="translated">소스 참조 어셈블리 '{0}'의 콘텐츠 해시를 확인하지 못했습니다. {1}
{2}</target>
<note />
</trans-unit>
<trans-unit id="CopyRefAssembly_BadDestination1">
<source>Failed to check the content hash of the destination ref assembly '{0}'. It will be overwritten.</source>
<target state="translated">대상 참조 어셈블리 '{0}'의 콘텐츠 해시를 확인하지 못했으므로 이 대상 참조 어셈블리를 덮어씁니다.</target>
<note />
</trans-unit>
<trans-unit id="General_ToolFileNotFound">
<source>MSB3082: Task failed because "{0}" was not found.</source>
<target state="translated">MSB3082: "{0}"을(를) 찾을 수 없어서 작업에 실패했습니다.</target>
<note>{StrBegin="MSB3082: "}</note>
</trans-unit>
<trans-unit id="General_IncorrectHostObject">
<source>MSB3087: An incompatible host object was passed into the "{0}" task. The host object for this task must implement the "{1}" interface.</source>
<target state="translated">MSB3087: 호환되지 않는 호스트 개체가 "{0}" 작업에 전달되었습니다. 이 작업의 호스트 개체는 "{1}" 인터페이스를 구현해야 합니다.</target>
<note>{StrBegin="MSB3087: "}</note>
</trans-unit>
<trans-unit id="General_InvalidAttributeMetadata">
<source>Item "{0}" has attribute "{1}" with value "{2}" that could not be converted to "{3}".</source>
<target state="translated">"{0}" 항목에 "{3}"(으)로 변환할 수 없는 "{2}" 값이 있는 "{1}" 특성이 있습니다.</target>
<note />
</trans-unit>
<trans-unit id="General_ParameterUnsupportedOnHostCompiler">
<source>The IDE's in-process compiler does not support the specified values for the "{0}" parameter. Therefore, this task will fallback to using the command-line compiler.</source>
<target state="translated">IDE의 In-Process 컴파일러에서는 "{0}" 매개 변수에 지정한 값이 지원되지 않으므로 대신 명령줄 컴파일러에서 이 작업을 처리합니다.</target>
<note />
</trans-unit>
<trans-unit id="General_ReferenceDoesNotExist">
<source>MSB3104: The referenced assembly "{0}" was not found. If this assembly is produced by another one of your projects, please make sure to build that project before building this one.</source>
<target state="translated">MSB3104: 참조된 어셈블리 "{0}"을(를) 찾을 수 없습니다. 다른 프로젝트에서 이 어셈블리를 생성한 경우 이 어셈블리를 빌드하기 전에 해당 프로젝트를 빌드해야 합니다.</target>
<note>{StrBegin="MSB3104: "}</note>
</trans-unit>
<trans-unit id="General_UnableToReadFile">
<source>File "{0}" could not be read: {1}</source>
<target state="translated">"{0}" 파일을 읽을 수 없습니다. {1}</target>
<note />
</trans-unit>
<trans-unit id="ImplicitlySkipAnalyzersMessage">
<source>Skipping analyzers to speed up the build. You can execute 'Build' or 'Rebuild' command to run analyzers.</source>
<target state="new">Skipping analyzers to speed up the build. You can execute 'Build' or 'Rebuild' command to run analyzers.</target>
<note />
</trans-unit>
<trans-unit id="SharedCompilationFallback">
<source>Shared compilation failed; falling back to tool: {0}</source>
<target state="translated">공유 컴파일 실패, 다음 도구로 변경 중: {0}</target>
<note />
</trans-unit>
<trans-unit id="UsingSharedCompilation">
<source>Using shared compilation with compiler from directory: {0}</source>
<target state="translated">디렉터리의 컴파일러로 공유 컴파일 사용: {0}</target>
<note />
</trans-unit>
<trans-unit id="Vbc_EnumParameterHasInvalidValue">
<source>MSB3401: "{1}" is an invalid value for the "{0}" parameter. The valid values are: {2}</source>
<target state="translated">MSB3401: "{1}"은(는) "{0}" 매개 변수에 사용할 수 없는 값입니다. 유효한 값은 {2}입니다.</target>
<note>{StrBegin="MSB3401: "}</note>
</trans-unit>
<trans-unit id="Vbc_ParameterHasInvalidValue">
<source>"{1}" is an invalid value for the "{0}" parameter.</source>
<target state="translated">"{1}"은(는) "{0}" 매개 변수에 사용할 수 없는 값입니다.</target>
<note />
</trans-unit>
<trans-unit id="Vbc_RenamePDB">
<source>MSB3402: There was an error creating the pdb file "{0}". {1}</source>
<target state="translated">MSB3402: pdb 파일 "{0}"을(를) 만드는 동안 오류가 발생했습니다. {1}</target>
<note>{StrBegin="MSB3402: "}</note>
</trans-unit>
<trans-unit id="MapSourceRoots.ContainsDuplicate">
<source>{0} contains duplicate items '{1}' with conflicting metadata '{2}': '{3}' and '{4}'</source>
<target state="translated">충돌 메타데이터 '{2}'이(가) 있는 중복 항목 '{1}'이(가) {0}에 포함되어 있습니다. '{3}' 및 '{4}'</target>
<note />
</trans-unit>
<trans-unit id="MapSourceRoots.PathMustEndWithSlashOrBackslash">
<source>{0} paths are required to end with a slash or backslash: '{1}'</source>
<target state="translated">{0} 경로는 슬래시 또는 백슬래시로 끝나야 합니다. '{1}'</target>
<note />
</trans-unit>
<trans-unit id="MapSourceRoots.NoTopLevelSourceRoot">
<source>{0} items must include at least one top-level (not nested) item when {1} is true</source>
<target state="translated">{0} 항목은 {1}이(가) true인 경우 최상위(중첩되지 않은) 항목을 하나 이상 포함해야 합니다.</target>
<note />
</trans-unit>
<trans-unit id="MapSourceRoots.NoSuchTopLevelSourceRoot">
<source>The value of {0} not found in {1} items, or the corresponding item is not a top-level source root: '{2}'</source>
<target state="translated">{1} 항목에서 {0}의 값을 찾을 수 없거나 해당 항목이 최상위 소스 루트가 아닙니다. '{2}'</target>
<note />
</trans-unit>
</body>
</file>
</xliff> | <?xml version="1.0" encoding="utf-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd">
<file datatype="xml" source-language="en" target-language="ko" original="../ErrorString.resx">
<body>
<trans-unit id="Compiler_UnexpectedException">
<source>MSB3883: Unexpected exception: </source>
<target state="translated">MSB3883: 예기치 않은 예외: </target>
<note>{StrBegin="MSB3883: "}</note>
</trans-unit>
<trans-unit id="Csc_AssemblyAliasContainsIllegalCharacters">
<source>MSB3053: The assembly alias "{1}" on reference "{0}" contains illegal characters.</source>
<target state="translated">MSB3053: "{0}" 참조의 어셈블리 별칭 "{1}"에 잘못된 문자가 포함되어 있습니다.</target>
<note>{StrBegin="MSB3053: "}</note>
</trans-unit>
<trans-unit id="Csc_InvalidParameter">
<source>MSB3051: The parameter to the compiler is invalid. {0}</source>
<target state="translated">MSB3051: 컴파일러에 대한 매개 변수가 잘못되었습니다. {0}</target>
<note>{StrBegin="MSB3051: "}</note>
</trans-unit>
<trans-unit id="Csc_InvalidParameterWarning">
<source>MSB3052: The parameter to the compiler is invalid, '{0}{1}' will be ignored.</source>
<target state="translated">MSB3052: 컴파일러에 대한 매개 변수가 잘못되었습니다. '{0}{1}'이(가) 무시됩니다.</target>
<note>{StrBegin="MSB3052: "}</note>
</trans-unit>
<trans-unit id="General_CannotConvertStringToBool">
<source>The string "{0}" cannot be converted to a boolean (true/false) value.</source>
<target state="translated">"{0}" 문자열을 부울 값(true/false)으로 변환할 수 없습니다.</target>
<note />
</trans-unit>
<trans-unit id="General_CouldNotSetHostObjectParameter">
<source>MSB3081: A problem occurred while trying to set the "{0}" parameter for the IDE's in-process compiler. {1}</source>
<target state="translated">MSB3081: IDE의 In-Process 컴파일러에 "{0}" 매개 변수를 설정하는 동안 문제가 발생했습니다. {1}</target>
<note>{StrBegin="MSB3081: "}</note>
</trans-unit>
<trans-unit id="General_DuplicateItemsNotSupported">
<source>MSB3105: The item "{0}" was specified more than once in the "{1}" parameter. Duplicate items are not supported by the "{1}" parameter.</source>
<target state="translated">MSB3105: "{0}" 항목을 "{1}" 매개 변수에 두 번 이상 지정했습니다. "{1}" 매개 변수는 중복 항목을 지원하지 않습니다.</target>
<note>{StrBegin="MSB3105: "}</note>
</trans-unit>
<trans-unit id="General_DuplicateItemsNotSupportedWithMetadata">
<source>MSB3083: The item "{0}" was specified more than once in the "{1}" parameter and both items had the same value "{2}" for the "{3}" metadata. Duplicate items are not supported by the "{1}" parameter unless they have different values for the "{3}" metadata.</source>
<target state="translated">MSB3083: "{0}" 항목이 "{1}" 매개 변수에 두 번 이상 지정되었으며 두 항목이 "{3}" 메타데이터에 대해 동일한 값 "{2}"을(를) 가지고 있습니다. "{3}" 메타데이터에 대한 값이 같으면 "{1}" 매개 변수는 중복 항목을 지원하지 않습니다.</target>
<note>{StrBegin="MSB3083: "}</note>
</trans-unit>
<trans-unit id="General_ExpectedFileMissing">
<source>Expected file "{0}" does not exist.</source>
<target state="translated">필요한 "{0}" 파일이 없습니다.</target>
<note />
</trans-unit>
<trans-unit id="CopyRefAssembly_SkippingCopy1">
<source>Reference assembly "{0}" already has latest information. Leaving it untouched.</source>
<target state="translated">참조 어셈블리 "{0}"에 이미 최신 정보가 있습니다. 그대로 유지합니다.</target>
<note />
</trans-unit>
<trans-unit id="CopyRefAssembly_SourceNotRef1">
<source>Could not extract the MVID from "{0}". Are you sure it is a reference assembly?</source>
<target state="translated">"{0}"에서 MVID를 추출할 수 없습니다. 참조 어셈블리가 맞는지 확인하세요.</target>
<note />
</trans-unit>
<trans-unit id="CopyRefAssembly_BadSource3">
<source>Failed to check the content hash of the source ref assembly '{0}': {1}
{2}</source>
<target state="translated">소스 참조 어셈블리 '{0}'의 콘텐츠 해시를 확인하지 못했습니다. {1}
{2}</target>
<note />
</trans-unit>
<trans-unit id="CopyRefAssembly_BadDestination1">
<source>Failed to check the content hash of the destination ref assembly '{0}'. It will be overwritten.</source>
<target state="translated">대상 참조 어셈블리 '{0}'의 콘텐츠 해시를 확인하지 못했으므로 이 대상 참조 어셈블리를 덮어씁니다.</target>
<note />
</trans-unit>
<trans-unit id="General_ToolFileNotFound">
<source>MSB3082: Task failed because "{0}" was not found.</source>
<target state="translated">MSB3082: "{0}"을(를) 찾을 수 없어서 작업에 실패했습니다.</target>
<note>{StrBegin="MSB3082: "}</note>
</trans-unit>
<trans-unit id="General_IncorrectHostObject">
<source>MSB3087: An incompatible host object was passed into the "{0}" task. The host object for this task must implement the "{1}" interface.</source>
<target state="translated">MSB3087: 호환되지 않는 호스트 개체가 "{0}" 작업에 전달되었습니다. 이 작업의 호스트 개체는 "{1}" 인터페이스를 구현해야 합니다.</target>
<note>{StrBegin="MSB3087: "}</note>
</trans-unit>
<trans-unit id="General_InvalidAttributeMetadata">
<source>Item "{0}" has attribute "{1}" with value "{2}" that could not be converted to "{3}".</source>
<target state="translated">"{0}" 항목에 "{3}"(으)로 변환할 수 없는 "{2}" 값이 있는 "{1}" 특성이 있습니다.</target>
<note />
</trans-unit>
<trans-unit id="General_ParameterUnsupportedOnHostCompiler">
<source>The IDE's in-process compiler does not support the specified values for the "{0}" parameter. Therefore, this task will fallback to using the command-line compiler.</source>
<target state="translated">IDE의 In-Process 컴파일러에서는 "{0}" 매개 변수에 지정한 값이 지원되지 않으므로 대신 명령줄 컴파일러에서 이 작업을 처리합니다.</target>
<note />
</trans-unit>
<trans-unit id="General_ReferenceDoesNotExist">
<source>MSB3104: The referenced assembly "{0}" was not found. If this assembly is produced by another one of your projects, please make sure to build that project before building this one.</source>
<target state="translated">MSB3104: 참조된 어셈블리 "{0}"을(를) 찾을 수 없습니다. 다른 프로젝트에서 이 어셈블리를 생성한 경우 이 어셈블리를 빌드하기 전에 해당 프로젝트를 빌드해야 합니다.</target>
<note>{StrBegin="MSB3104: "}</note>
</trans-unit>
<trans-unit id="General_UnableToReadFile">
<source>File "{0}" could not be read: {1}</source>
<target state="translated">"{0}" 파일을 읽을 수 없습니다. {1}</target>
<note />
</trans-unit>
<trans-unit id="ImplicitlySkipAnalyzersMessage">
<source>Skipping analyzers to speed up the build. You can execute 'Build' or 'Rebuild' command to run analyzers.</source>
<target state="new">Skipping analyzers to speed up the build. You can execute 'Build' or 'Rebuild' command to run analyzers.</target>
<note />
</trans-unit>
<trans-unit id="SharedCompilationFallback">
<source>Shared compilation failed; falling back to tool: {0}</source>
<target state="translated">공유 컴파일 실패, 다음 도구로 변경 중: {0}</target>
<note />
</trans-unit>
<trans-unit id="UsingSharedCompilation">
<source>Using shared compilation with compiler from directory: {0}</source>
<target state="translated">디렉터리의 컴파일러로 공유 컴파일 사용: {0}</target>
<note />
</trans-unit>
<trans-unit id="Vbc_EnumParameterHasInvalidValue">
<source>MSB3401: "{1}" is an invalid value for the "{0}" parameter. The valid values are: {2}</source>
<target state="translated">MSB3401: "{1}"은(는) "{0}" 매개 변수에 사용할 수 없는 값입니다. 유효한 값은 {2}입니다.</target>
<note>{StrBegin="MSB3401: "}</note>
</trans-unit>
<trans-unit id="Vbc_ParameterHasInvalidValue">
<source>"{1}" is an invalid value for the "{0}" parameter.</source>
<target state="translated">"{1}"은(는) "{0}" 매개 변수에 사용할 수 없는 값입니다.</target>
<note />
</trans-unit>
<trans-unit id="Vbc_RenamePDB">
<source>MSB3402: There was an error creating the pdb file "{0}". {1}</source>
<target state="translated">MSB3402: pdb 파일 "{0}"을(를) 만드는 동안 오류가 발생했습니다. {1}</target>
<note>{StrBegin="MSB3402: "}</note>
</trans-unit>
<trans-unit id="MapSourceRoots.ContainsDuplicate">
<source>{0} contains duplicate items '{1}' with conflicting metadata '{2}': '{3}' and '{4}'</source>
<target state="translated">충돌 메타데이터 '{2}'이(가) 있는 중복 항목 '{1}'이(가) {0}에 포함되어 있습니다. '{3}' 및 '{4}'</target>
<note />
</trans-unit>
<trans-unit id="MapSourceRoots.PathMustEndWithSlashOrBackslash">
<source>{0} paths are required to end with a slash or backslash: '{1}'</source>
<target state="translated">{0} 경로는 슬래시 또는 백슬래시로 끝나야 합니다. '{1}'</target>
<note />
</trans-unit>
<trans-unit id="MapSourceRoots.NoTopLevelSourceRoot">
<source>{0} items must include at least one top-level (not nested) item when {1} is true</source>
<target state="translated">{0} 항목은 {1}이(가) true인 경우 최상위(중첩되지 않은) 항목을 하나 이상 포함해야 합니다.</target>
<note />
</trans-unit>
<trans-unit id="MapSourceRoots.NoSuchTopLevelSourceRoot">
<source>The value of {0} not found in {1} items, or the corresponding item is not a top-level source root: '{2}'</source>
<target state="translated">{1} 항목에서 {0}의 값을 찾을 수 없거나 해당 항목이 최상위 소스 루트가 아닙니다. '{2}'</target>
<note />
</trans-unit>
</body>
</file>
</xliff> | -1 |
dotnet/roslyn | 55,877 | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute | Part of C# 10 support | davidwengier | 2021-08-25T05:36:27Z | 2021-08-30T20:47:11Z | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | 023d3ca2b5fb429f0b3dcc1efeed39442e232dba | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute. Part of C# 10 support | ./src/VisualStudio/Core/Def/Implementation/PullMemberUp/WarningDialog/PullMemberUpWarningViewModel.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.PullMemberUp;
using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.PullMemberUp.WarningDialog
{
internal class PullMemberUpWarningViewModel : AbstractNotifyPropertyChanged
{
public ImmutableArray<string> WarningMessageContainer { get; set; }
public string ProblemsListViewAutomationText => ServicesVSResources.Review_Changes;
public PullMemberUpWarningViewModel(PullMembersUpOptions options)
=> WarningMessageContainer = GenerateMessage(options);
private ImmutableArray<string> GenerateMessage(PullMembersUpOptions options)
{
var warningMessagesBuilder = ImmutableArray.CreateBuilder<string>();
if (!options.Destination.IsAbstract &&
options.MemberAnalysisResults.Any(result => result.ChangeDestinationTypeToAbstract))
{
Logger.Log(FunctionId.PullMembersUpWarning_ChangeTargetToAbstract);
warningMessagesBuilder.Add(string.Format(ServicesVSResources._0_will_be_changed_to_abstract, options.Destination.Name));
}
foreach (var result in options.MemberAnalysisResults)
{
if (result.ChangeOriginalToPublic)
{
Logger.Log(FunctionId.PullMembersUpWarning_ChangeOriginToPublic);
warningMessagesBuilder.Add(string.Format(ServicesVSResources._0_will_be_changed_to_public, result.Member.Name));
}
if (result.ChangeOriginalToNonStatic)
{
Logger.Log(FunctionId.PullMembersUpWarning_ChangeOriginToNonStatic);
warningMessagesBuilder.Add(string.Format(ServicesVSResources._0_will_be_changed_to_non_static, result.Member.Name));
}
}
return warningMessagesBuilder.ToImmutableArray();
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.PullMemberUp;
using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.PullMemberUp.WarningDialog
{
internal class PullMemberUpWarningViewModel : AbstractNotifyPropertyChanged
{
public ImmutableArray<string> WarningMessageContainer { get; set; }
public string ProblemsListViewAutomationText => ServicesVSResources.Review_Changes;
public PullMemberUpWarningViewModel(PullMembersUpOptions options)
=> WarningMessageContainer = GenerateMessage(options);
private ImmutableArray<string> GenerateMessage(PullMembersUpOptions options)
{
var warningMessagesBuilder = ImmutableArray.CreateBuilder<string>();
if (!options.Destination.IsAbstract &&
options.MemberAnalysisResults.Any(result => result.ChangeDestinationTypeToAbstract))
{
Logger.Log(FunctionId.PullMembersUpWarning_ChangeTargetToAbstract);
warningMessagesBuilder.Add(string.Format(ServicesVSResources._0_will_be_changed_to_abstract, options.Destination.Name));
}
foreach (var result in options.MemberAnalysisResults)
{
if (result.ChangeOriginalToPublic)
{
Logger.Log(FunctionId.PullMembersUpWarning_ChangeOriginToPublic);
warningMessagesBuilder.Add(string.Format(ServicesVSResources._0_will_be_changed_to_public, result.Member.Name));
}
if (result.ChangeOriginalToNonStatic)
{
Logger.Log(FunctionId.PullMembersUpWarning_ChangeOriginToNonStatic);
warningMessagesBuilder.Add(string.Format(ServicesVSResources._0_will_be_changed_to_non_static, result.Member.Name));
}
}
return warningMessagesBuilder.ToImmutableArray();
}
}
}
| -1 |
dotnet/roslyn | 55,877 | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute | Part of C# 10 support | davidwengier | 2021-08-25T05:36:27Z | 2021-08-30T20:47:11Z | 4d99cda6e446e77dbb302e26388c1093bd3ef569 | 023d3ca2b5fb429f0b3dcc1efeed39442e232dba | EnC - Report rude edit when a user adds an AsyncMethodBuild attribute. Part of C# 10 support | ./src/Compilers/Test/Resources/Core/SymbolsTests/NoPia/NoPIAGenerics1-Asm1.dll | MZ @ !L!This program cannot be run in DOS mode.
$ PE L hSL ! * I ` @ @ \I O ` H .text ) * `.sdata ` . @ .rsrc 0 @ @.reloc 4 @ B I H % # &(
* * (
* s
s
s
s
* 0 ~ o
+ *0 ~ o
+ *0 ~ o
+ *0 ~ o
+ *0 (
(
+ * 0 (
+ *0 (
+ *0 (
+ *0 -
( +
++
+ * 0
* * (
* 0 / {
o
-( +{
o
+ * V (
s
}
* * *0
+ * *0
*
+ *0
+ * 0
+ * 0
+ * 0
+ * *0
+ * * *0
+ * 0 ? (
s.
s.
} s/
} s0
} * &(1
* 0 *
+ *"2
* &(
* &(3
* 0 ~4
+ * &(
* *0
+ * 0 *
+ * *0
~
+ * " * * *0 s.
+ * &(
* ** (
* 0 s.
+ * 0 s2
+ *f{
(7
t }
* f{
(8
t }
* &(
* &(
* *0 *
(< |