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 &amp;and Sort Namespaces</source> <target state="translated">Ri&amp;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>&amp;Sort Namespaces</source> <target state="translated">Or&amp;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 &amp;and Sort Namespaces</source> <target state="translated">Ri&amp;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>&amp;Sort Namespaces</source> <target state="translated">Or&amp;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*)(&amp;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*)(&amp;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"> (삽입하려면 &lt;Tab&gt; 키 누름)</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"> (삽입하려면 &lt;Tab&gt; 키 누름)</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. $PELhSL! *I `@ @\IO `  H.text) * `.sdata`.@.rsrc0@@.reloc 4@BIH%#&( **( *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 * (<*0 ~ +*"**(9 *^s; *&( **0* +*0 * +*0!+ +*&( **&( *0"Is< +*&+*BSJB v4.0.30319l4#~` #Strings#US#GUID#BlobW %33V<DR" E  m  3m 3 X?,p +,W "O7yff  "W7u   " B 0 Y 7t f f      " D o  f  7 7 )7:7 E7 O ]  x    " $ & ) 0 2 7 8 :5= >! D2F= GNJYAKcAObS SASW1 1-1A:1fG!Bw~5_5: 5L P c h t 5V| $V $V $V $Vo $V $P \ h   ( 85 VB!Fc$!Fh<!lX!Fqp!x!!!""fo"fx "f~4"f8"f hL"f `"ft"f "f "f "f  "f  "f#"fK"#(#1<#H#T#`#1x##?#E#J#T#g#*p#z#Jp#Rg#$J$$n,$zD$ `$ |$$$$$1$$$ $ % %#1!%7!0%7"D%#P%A,#FK2$T%$`%FK;$% $FOD%N&FT(Fb+F,N-Fh/Fq2F|3N4F6Fb:F;sssss88ivivivm m $  lt|lt|f4ch)AqQaB,o,x~h$$$ &$$#y,5<<5!1 1i9NIYaay<Y\]`d(h-l2p7 #). C.L.U.#t@3@CCI `#cci3{ 3i33k?3 3 @3@`3`333{33#c&c{ 5i#`###`####### &`##### 9=HM\\9=99,=5:c==t=yyy====="  OT3Y^LZ`kZd56   *)+,;<"?$A&C(E*G,I.K0M2O4Q6S8U:W<Yuu#*8u)IPXm1   ,,?/W/*<Module>mscorlibMicrosoft.VisualBasicMyApplicationMyMyComputerMyProjectMyWebServicesThreadSafeObjectProvider`1Interface1ImplNestedConstructsInterface1Class1Class2`1Class3InheritsMethodsTypeRefs1TypeRefs1aTypeRefs2TypeRefs3TypeRefs4TypeRefs5MyTypeAttributeTypeRefs6MyGenericClass`2Interface3OverridableClassInterface2Delegate1Delegate2Microsoft.VisualBasic.ApplicationServicesApplicationBase.ctorMicrosoft.VisualBasic.DevicesComputerSystemObject.cctorget_Computerm_ComputerObjectProviderget_Applicationm_AppObjectProviderUserget_Userm_UserObjectProviderget_WebServicesm_MyWebServicesObjectProviderApplicationWebServicesEqualsoGetHashCodeTypeGetTypeToStringCreate__Instance__TinstanceDispose__Instance__get_GetInstanceMicrosoft.VisualBasic.MyServices.InternalContextValue`1m_ContextGetInstanceValueTypeISubFuncPropAdditemClearContainsCopyToarrayarrayIndexget_Countget_IsReadOnlyRemoveSystem.Collections.GenericIEnumerator`1GetEnumeratorIndexOfInsertindexget_Itemset_ItemvalueRemoveAtSystem.CollectionsIEnumeratorGetEnumerator1CountIsReadOnlyItemList`1field1field2IList`1FooStructfield3field4NoAttributesDelegatefield5Class1FooMyStaticGetMyStaticMethod1c1FooEnumget_Property1xset_Property1_Property2get_Property2set_Property2AutoPropertyValueMethod2Method4Property1Property2op_Explicitop_ImplicitAction`1add_Event1objEvent1Eventremove_Event1Event1Method5_Property3get_Property3set_Property3Property3AttributeMethod6Nullable`1field6field7Method7IEnumerableMethod8SSetTValueFooMethod3MulticastDelegateTargetObjectTargetMethodIAsyncResultAsyncCallbackBeginInvokeDelegateCallbackDelegateAsyncStateEndInvokeDelegateAsyncResultInvokeSystem.ComponentModelEditorBrowsableAttributeEditorBrowsableStateSystem.CodeDom.CompilerGeneratedCodeAttributeSystem.DiagnosticsDebuggerNonUserCodeAttributeDebuggerHiddenAttributeMicrosoft.VisualBasic.CompilerServicesStandardModuleAttributeHideModuleNameAttributeSystem.ComponentModel.DesignHelpKeywordAttributeSystem.Runtime.CompilerServicesRuntimeHelpersGetObjectValueRuntimeTypeHandleGetTypeFromHandleActivatorCreateInstanceMyGroupCollectionAttributeget_Valueset_ValueSystem.Runtime.InteropServicesComVisibleAttributeICollection`1IEnumerable`1System.ReflectionDefaultMemberAttributeCompilerGeneratedAttributeDebuggerBrowsableAttributeDebuggerBrowsableStateDelegateCombineAttributeUsageAttributeAttributeTargets_Lambda$__1InterfaceTypeAttributeComInterfaceTypeGuidAttributeTypeIdentifierAttributeStructureDecimalNET構造メンバーFoo3Foo4yEnumvalue__Foo1__Foo2列挙識別子COMDebuggableAttributeDebuggingModesCompilationRelaxationsAttributeRuntimeCompatibilityAttributeSystem.Runtime.VersioningTargetFrameworkAttributeNoPIAGenerics1-Asm1NoPIAGenerics1-Asm1.dll |,JlFdSz\V4?_ :        0 ( p p p  !p p p p  %(((p)p)p )-t -)p--)x-p)t,p(( )| )|)p)p )p )t )|)p )p )t )p@ @)p 1)| 1)| 1)| )|9|Xt= )p  )p 1t )|  E)pI E EI )pE )p Q  MyTemplate10.0.0.0    My.Computer My.UserMy.ApplicationMy.WebServicesq  a4System.Web.Services.Protocols.SoapHttpClientProtocolCreate__Instance__Dispose__Instance__  p  p !   !pp% Item)p)p )-t )p,()p @ |System.Collections.Generic.List`1[ISubFuncProp], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089~ySystem.Collections.Generic.List`1[FooStruct], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 9|Xtt1t1t )$bd62ff24-a97c-4a9c-a43e-09a31ff8b312)$63370d76-3395-4560-92fd-b69ccfdaf4613$f9c2d51d-4f44-45f0-9eda-c9d599b58257 FooStruct>$f9c2d51d-4f44-45f0-9eda-c9d599b58257NoAttributesDelegate)$ee3c2bee-9dfb-4d1c-91de-4cd32ff133021$f9c2d51d-4f44-45f0-9eda-c9d599b58257FooEnum EI | TWrapNonExceptionThrowsG.NETFramework,Version=v4.0TFrameworkDisplayName.NET Framework 4II I_CorDllMainmscoree.dll% @hSL`.RSDS*{Hc5D:\SCHOOL\NoPIAGenerics1-ClassLibrary1_Embed.229931.22640\obj\Default\Lab Build\NoPIAGenerics1-Asm1.pdb0HXtt4VS_VERSION_INFO?DVarFileInfo$TranslationStringFileInfo000004b0,FileDescription 0FileVersion0.0.0.0PInternalNameNoPIAGenerics1-Asm1.dll(LegalCopyright XOriginalFilenameNoPIAGenerics1-Asm1.dll4ProductVersion0.0.0.08Assembly Version0.0.0.0@ 9
MZ@ !L!This program cannot be run in DOS mode. $PELhSL! *I `@ @\IO `  H.text) * `.sdata`.@.rsrc0@@.reloc 4@BIH%#&( **( *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 * (<*0 ~ +*"**(9 *^s; *&( **0* +*0 * +*0!+ +*&( **&( *0"Is< +*&+*BSJB v4.0.30319l4#~` #Strings#US#GUID#BlobW %33V<DR" E  m  3m 3 X?,p +,W "O7yff  "W7u   " B 0 Y 7t f f      " D o  f  7 7 )7:7 E7 O ]  x    " $ & ) 0 2 7 8 :5= >! D2F= GNJYAKcAObS SASW1 1-1A:1fG!Bw~5_5: 5L P c h t 5V| $V $V $V $Vo $V $P \ h   ( 85 VB!Fc$!Fh<!lX!Fqp!x!!!""fo"fx "f~4"f8"f hL"f `"ft"f "f "f "f  "f  "f#"fK"#(#1<#H#T#`#1x##?#E#J#T#g#*p#z#Jp#Rg#$J$$n,$zD$ `$ |$$$$$1$$$ $ % %#1!%7!0%7"D%#P%A,#FK2$T%$`%FK;$% $FOD%N&FT(Fb+F,N-Fh/Fq2F|3N4F6Fb:F;sssss88ivivivm m $  lt|lt|f4ch)AqQaB,o,x~h$$$ &$$#y,5<<5!1 1i9NIYaay<Y\]`d(h-l2p7 #). C.L.U.#t@3@CCI `#cci3{ 3i33k?3 3 @3@`3`333{33#c&c{ 5i#`###`####### &`##### 9=HM\\9=99,=5:c==t=yyy====="  OT3Y^LZ`kZd56   *)+,;<"?$A&C(E*G,I.K0M2O4Q6S8U:W<Yuu#*8u)IPXm1   ,,?/W/*<Module>mscorlibMicrosoft.VisualBasicMyApplicationMyMyComputerMyProjectMyWebServicesThreadSafeObjectProvider`1Interface1ImplNestedConstructsInterface1Class1Class2`1Class3InheritsMethodsTypeRefs1TypeRefs1aTypeRefs2TypeRefs3TypeRefs4TypeRefs5MyTypeAttributeTypeRefs6MyGenericClass`2Interface3OverridableClassInterface2Delegate1Delegate2Microsoft.VisualBasic.ApplicationServicesApplicationBase.ctorMicrosoft.VisualBasic.DevicesComputerSystemObject.cctorget_Computerm_ComputerObjectProviderget_Applicationm_AppObjectProviderUserget_Userm_UserObjectProviderget_WebServicesm_MyWebServicesObjectProviderApplicationWebServicesEqualsoGetHashCodeTypeGetTypeToStringCreate__Instance__TinstanceDispose__Instance__get_GetInstanceMicrosoft.VisualBasic.MyServices.InternalContextValue`1m_ContextGetInstanceValueTypeISubFuncPropAdditemClearContainsCopyToarrayarrayIndexget_Countget_IsReadOnlyRemoveSystem.Collections.GenericIEnumerator`1GetEnumeratorIndexOfInsertindexget_Itemset_ItemvalueRemoveAtSystem.CollectionsIEnumeratorGetEnumerator1CountIsReadOnlyItemList`1field1field2IList`1FooStructfield3field4NoAttributesDelegatefield5Class1FooMyStaticGetMyStaticMethod1c1FooEnumget_Property1xset_Property1_Property2get_Property2set_Property2AutoPropertyValueMethod2Method4Property1Property2op_Explicitop_ImplicitAction`1add_Event1objEvent1Eventremove_Event1Event1Method5_Property3get_Property3set_Property3Property3AttributeMethod6Nullable`1field6field7Method7IEnumerableMethod8SSetTValueFooMethod3MulticastDelegateTargetObjectTargetMethodIAsyncResultAsyncCallbackBeginInvokeDelegateCallbackDelegateAsyncStateEndInvokeDelegateAsyncResultInvokeSystem.ComponentModelEditorBrowsableAttributeEditorBrowsableStateSystem.CodeDom.CompilerGeneratedCodeAttributeSystem.DiagnosticsDebuggerNonUserCodeAttributeDebuggerHiddenAttributeMicrosoft.VisualBasic.CompilerServicesStandardModuleAttributeHideModuleNameAttributeSystem.ComponentModel.DesignHelpKeywordAttributeSystem.Runtime.CompilerServicesRuntimeHelpersGetObjectValueRuntimeTypeHandleGetTypeFromHandleActivatorCreateInstanceMyGroupCollectionAttributeget_Valueset_ValueSystem.Runtime.InteropServicesComVisibleAttributeICollection`1IEnumerable`1System.ReflectionDefaultMemberAttributeCompilerGeneratedAttributeDebuggerBrowsableAttributeDebuggerBrowsableStateDelegateCombineAttributeUsageAttributeAttributeTargets_Lambda$__1InterfaceTypeAttributeComInterfaceTypeGuidAttributeTypeIdentifierAttributeStructureDecimalNET構造メンバーFoo3Foo4yEnumvalue__Foo1__Foo2列挙識別子COMDebuggableAttributeDebuggingModesCompilationRelaxationsAttributeRuntimeCompatibilityAttributeSystem.Runtime.VersioningTargetFrameworkAttributeNoPIAGenerics1-Asm1NoPIAGenerics1-Asm1.dll |,JlFdSz\V4?_ :        0 ( p p p  !p p p p  %(((p)p)p )-t -)p--)x-p)t,p(( )| )|)p)p )p )t )|)p )p )t )p@ @)p 1)| 1)| 1)| )|9|Xt= )p  )p 1t )|  E)pI E EI )pE )p Q  MyTemplate10.0.0.0    My.Computer My.UserMy.ApplicationMy.WebServicesq  a4System.Web.Services.Protocols.SoapHttpClientProtocolCreate__Instance__Dispose__Instance__  p  p !   !pp% Item)p)p )-t )p,()p @ |System.Collections.Generic.List`1[ISubFuncProp], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089~ySystem.Collections.Generic.List`1[FooStruct], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 9|Xtt1t1t )$bd62ff24-a97c-4a9c-a43e-09a31ff8b312)$63370d76-3395-4560-92fd-b69ccfdaf4613$f9c2d51d-4f44-45f0-9eda-c9d599b58257 FooStruct>$f9c2d51d-4f44-45f0-9eda-c9d599b58257NoAttributesDelegate)$ee3c2bee-9dfb-4d1c-91de-4cd32ff133021$f9c2d51d-4f44-45f0-9eda-c9d599b58257FooEnum EI | TWrapNonExceptionThrowsG.NETFramework,Version=v4.0TFrameworkDisplayName.NET Framework 4II I_CorDllMainmscoree.dll% @hSL`.RSDS*{Hc5D:\SCHOOL\NoPIAGenerics1-ClassLibrary1_Embed.229931.22640\obj\Default\Lab Build\NoPIAGenerics1-Asm1.pdb0HXtt4VS_VERSION_INFO?DVarFileInfo$TranslationStringFileInfo000004b0,FileDescription 0FileVersion0.0.0.0PInternalNameNoPIAGenerics1-Asm1.dll(LegalCopyright XOriginalFilenameNoPIAGenerics1-Asm1.dll4ProductVersion0.0.0.08Assembly Version0.0.0.0@ 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/VisualStudio/Core/Def/Implementation/Options/PackageSettingsPersisterProvider.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.ComponentModel.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using IAsyncServiceProvider = Microsoft.VisualStudio.Shell.IAsyncServiceProvider; using SAsyncServiceProvider = Microsoft.VisualStudio.Shell.Interop.SAsyncServiceProvider; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Options { [Export(typeof(IOptionPersisterProvider))] internal sealed class PackageSettingsPersisterProvider : IOptionPersisterProvider { private readonly IThreadingContext _threadingContext; private readonly IAsyncServiceProvider _serviceProvider; private readonly IGlobalOptionService _optionService; private PackageSettingsPersister? _lazyPersister; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public PackageSettingsPersisterProvider( IThreadingContext threadingContext, [Import(typeof(SAsyncServiceProvider))] IAsyncServiceProvider serviceProvider, IGlobalOptionService optionService) { _threadingContext = threadingContext; _serviceProvider = serviceProvider; _optionService = optionService; } public ValueTask<IOptionPersister> GetOrCreatePersisterAsync(CancellationToken cancellationToken) { _lazyPersister ??= new PackageSettingsPersister(_threadingContext, _serviceProvider, _optionService); return new ValueTask<IOptionPersister>(_lazyPersister); } } }
// 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.ComponentModel.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using IAsyncServiceProvider = Microsoft.VisualStudio.Shell.IAsyncServiceProvider; using SAsyncServiceProvider = Microsoft.VisualStudio.Shell.Interop.SAsyncServiceProvider; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Options { [Export(typeof(IOptionPersisterProvider))] internal sealed class PackageSettingsPersisterProvider : IOptionPersisterProvider { private readonly IThreadingContext _threadingContext; private readonly IAsyncServiceProvider _serviceProvider; private readonly IGlobalOptionService _optionService; private PackageSettingsPersister? _lazyPersister; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public PackageSettingsPersisterProvider( IThreadingContext threadingContext, [Import(typeof(SAsyncServiceProvider))] IAsyncServiceProvider serviceProvider, IGlobalOptionService optionService) { _threadingContext = threadingContext; _serviceProvider = serviceProvider; _optionService = optionService; } public ValueTask<IOptionPersister> GetOrCreatePersisterAsync(CancellationToken cancellationToken) { _lazyPersister ??= new PackageSettingsPersister(_threadingContext, _serviceProvider, _optionService); return new ValueTask<IOptionPersister>(_lazyPersister); } } }
-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/vbc/App.config
<?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. --> <configuration> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" /> </startup> <runtime> <AppContextSwitchOverrides value="Switch.System.Security.Cryptography.UseLegacyFipsThrow=false" /> <gcServer enabled="true" /> <gcConcurrent enabled="false"/> </runtime> </configuration>
<?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. --> <configuration> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" /> </startup> <runtime> <AppContextSwitchOverrides value="Switch.System.Security.Cryptography.UseLegacyFipsThrow=false" /> <gcServer enabled="true" /> <gcConcurrent enabled="false"/> </runtime> </configuration>
-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/CodeAnalysis.Debugging/CustomDebugInfoRecord.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; namespace Microsoft.CodeAnalysis.Debugging { internal struct CustomDebugInfoRecord { public readonly CustomDebugInfoKind Kind; public readonly byte Version; public readonly ImmutableArray<byte> Data; public CustomDebugInfoRecord(CustomDebugInfoKind kind, byte version, ImmutableArray<byte> data) { Kind = kind; Version = version; Data = data; } } }
// 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; namespace Microsoft.CodeAnalysis.Debugging { internal struct CustomDebugInfoRecord { public readonly CustomDebugInfoKind Kind; public readonly byte Version; public readonly ImmutableArray<byte> Data; public CustomDebugInfoRecord(CustomDebugInfoKind kind, byte version, ImmutableArray<byte> data) { Kind = kind; Version = version; Data = data; } } }
-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/Structure/BlockStructureService.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.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Structure { internal abstract class BlockStructureService : ILanguageService { /// <summary> /// Gets the service corresponding to the specified document. /// </summary> public static BlockStructureService GetService(Document document) => document.GetLanguageService<BlockStructureService>(); /// <summary> /// The language from <see cref="LanguageNames"/> this service corresponds to. /// </summary> public abstract string Language { get; } public abstract Task<BlockStructure> GetBlockStructureAsync(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. #nullable disable using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Structure { internal abstract class BlockStructureService : ILanguageService { /// <summary> /// Gets the service corresponding to the specified document. /// </summary> public static BlockStructureService GetService(Document document) => document.GetLanguageService<BlockStructureService>(); /// <summary> /// The language from <see cref="LanguageNames"/> this service corresponds to. /// </summary> public abstract string Language { get; } public abstract Task<BlockStructure> GetBlockStructureAsync(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/Scripting/CSharpTest.Desktop/Properties/launchSettings.json
{ "profiles": { "xUnit.net Console (32-bit)": { "commandName": "Executable", "executablePath": "$(NuGetPackageRoot)xunit.runner.console\\$(XUnitVersion)\\tools\\net452\\xunit.console.x86.exe", "commandLineArgs": "$(TargetPath) -noshadow -verbose" }, "xUnit.net Console (64-bit)": { "commandName": "Executable", "executablePath": "$(NuGetPackageRoot)xunit.runner.console\\$(XUnitVersion)\\tools\\net452\\xunit.console.exe", "commandLineArgs": "$(TargetPath) -noshadow -verbose" } } }
{ "profiles": { "xUnit.net Console (32-bit)": { "commandName": "Executable", "executablePath": "$(NuGetPackageRoot)xunit.runner.console\\$(XUnitVersion)\\tools\\net452\\xunit.console.x86.exe", "commandLineArgs": "$(TargetPath) -noshadow -verbose" }, "xUnit.net Console (64-bit)": { "commandName": "Executable", "executablePath": "$(NuGetPackageRoot)xunit.runner.console\\$(XUnitVersion)\\tools\\net452\\xunit.console.exe", "commandLineArgs": "$(TargetPath) -noshadow -verbose" } } }
-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/CSharp/Portable/EncapsulateField/CSharpEncapsulateFieldService.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.Composition; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.EncapsulateField; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.EncapsulateField { [ExportLanguageService(typeof(AbstractEncapsulateFieldService), LanguageNames.CSharp), Shared] internal class CSharpEncapsulateFieldService : AbstractEncapsulateFieldService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpEncapsulateFieldService() { } protected override async Task<SyntaxNode> RewriteFieldNameAndAccessibilityAsync(string originalFieldName, bool makePrivate, Document document, SyntaxAnnotation declarationAnnotation, CancellationToken cancellationToken) { var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var declarator = root.GetAnnotatedNodes<VariableDeclaratorSyntax>(declarationAnnotation).FirstOrDefault(); // There may be no field to rewrite if this document is part of a set of linked files // and the declaration is not conditionally compiled in this document's project. if (declarator == null) { return root; } var tempAnnotation = new SyntaxAnnotation(); var escapedName = originalFieldName.EscapeIdentifier(); var newIdentifier = SyntaxFactory.Identifier( leading: SyntaxTriviaList.Create(SyntaxFactory.ElasticMarker), contextualKind: SyntaxKind.IdentifierName, text: escapedName, valueText: originalFieldName, trailing: SyntaxTriviaList.Create(SyntaxFactory.ElasticMarker)) .WithTrailingTrivia(declarator.Identifier.TrailingTrivia) .WithLeadingTrivia(declarator.Identifier.LeadingTrivia); var updatedDeclarator = declarator.WithIdentifier(newIdentifier).WithAdditionalAnnotations(tempAnnotation); root = root.ReplaceNode(declarator, updatedDeclarator); document = document.WithSyntaxRoot(root); var declaration = root.GetAnnotatedNodes<SyntaxNode>(tempAnnotation).First().Parent as VariableDeclarationSyntax; if (declaration.Variables.Count == 1) { var fieldSyntax = declaration.Parent as FieldDeclarationSyntax; var modifierKinds = new[] { SyntaxKind.PrivateKeyword, SyntaxKind.ProtectedKeyword, SyntaxKind.InternalKeyword, SyntaxKind.PublicKeyword }; if (makePrivate) { var modifiers = SpecializedCollections.SingletonEnumerable(SyntaxFactory.Token(SyntaxKind.PrivateKeyword)) .Concat(fieldSyntax.Modifiers.Where(m => !modifierKinds.Contains(m.Kind()))); root = root.ReplaceNode(fieldSyntax, fieldSyntax.WithModifiers( SyntaxFactory.TokenList(modifiers)) .WithAdditionalAnnotations(Formatter.Annotation) .WithLeadingTrivia(fieldSyntax.GetLeadingTrivia()) .WithTrailingTrivia(fieldSyntax.GetTrailingTrivia())); } } else if (declaration.Variables.Count > 1 && makePrivate) { document = document.WithSyntaxRoot(root); var codeGenService = document.GetLanguageService<ICodeGenerationService>(); var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); declarator = root.GetAnnotatedNodes<VariableDeclaratorSyntax>(tempAnnotation).First(); declaration = declarator.Parent as VariableDeclarationSyntax; var field = semanticModel.GetDeclaredSymbol(declarator, cancellationToken) as IFieldSymbol; var fieldToAdd = declarationAnnotation.AddAnnotationToSymbol(CodeGenerationSymbolFactory.CreateFieldSymbol( field.GetAttributes(), Accessibility.Private, new DeclarationModifiers(isStatic: field.IsStatic, isReadOnly: field.IsReadOnly, isConst: field.IsConst), field.Type, field.Name, field.HasConstantValue, field.ConstantValue, declarator.Initializer)); var withField = await codeGenService.AddFieldAsync(document.Project.Solution, field.ContainingType, fieldToAdd, new CodeGenerationOptions(), cancellationToken).ConfigureAwait(false); root = await withField.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); declarator = root.GetAnnotatedNodes<VariableDeclaratorSyntax>(tempAnnotation).First(); declaration = declarator.Parent as VariableDeclarationSyntax; return root.RemoveNode(declarator, SyntaxRemoveOptions.KeepNoTrivia); } return root; } protected override async Task<ImmutableArray<IFieldSymbol>> GetFieldsAsync(Document document, TextSpan span, CancellationToken cancellationToken) { var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var fields = root.DescendantNodes(d => d.Span.IntersectsWith(span)) .OfType<FieldDeclarationSyntax>() .Where(n => n.Span.IntersectsWith(span)); var declarations = fields.Where(CanEncapsulate).Select(f => f.Declaration); IEnumerable<VariableDeclaratorSyntax> declarators; if (span.IsEmpty) { // no selection, get all variables declarators = declarations.SelectMany(d => d.Variables); } else { // has selection, get only the ones that are included in the selection declarators = declarations.SelectMany(d => d.Variables.Where(v => v.Span.IntersectsWith(span))); } return declarators.Select(d => semanticModel.GetDeclaredSymbol(d, cancellationToken) as IFieldSymbol) .WhereNotNull() .Where(f => f.Name.Length != 0) .ToImmutableArray(); } private bool CanEncapsulate(FieldDeclarationSyntax field) => field.Parent is TypeDeclarationSyntax; protected override (string fieldName, string propertyName) GenerateFieldAndPropertyNames(IFieldSymbol field) { // Special case: if the field is "new", we will preserve its original name and the new keyword. if (field.DeclaredAccessibility == Accessibility.Private || IsNew(field)) { // Create some capitalized version of the field name for the property return (field.Name, MakeUnique(GeneratePropertyName(field.Name), field.ContainingType)); } else { // Generate the new property name using the rules from 695042 var newPropertyName = GeneratePropertyName(field.Name); if (newPropertyName == field.Name) { // If we wind up with the field's old name, give the field the unique version of its current name. return (MakeUnique(GenerateFieldName(field.Name), field.ContainingType), newPropertyName); } // Otherwise, ensure the property's name is unique. newPropertyName = MakeUnique(newPropertyName, field.ContainingType); var newFieldName = GenerateFieldName(newPropertyName); // If converting the new property's name into a field name results in the old field name, we're done. if (newFieldName == field.Name) { return (newFieldName, newPropertyName); } // Otherwise, ensure the new field name is unique. return (MakeUnique(newFieldName, field.ContainingType), newPropertyName); } } private static bool IsNew(IFieldSymbol field) => field.DeclaringSyntaxReferences.Any(d => d.GetSyntax().GetAncestor<FieldDeclarationSyntax>().Modifiers.Any(SyntaxKind.NewKeyword)); private static string GenerateFieldName(string correspondingPropertyName) => char.ToLower(correspondingPropertyName[0]).ToString() + correspondingPropertyName.Substring(1); protected static string MakeUnique(string baseName, INamedTypeSymbol containingType) { var containingTypeMemberNames = containingType.GetAccessibleMembersInThisAndBaseTypes<ISymbol>(containingType).Select(m => m.Name); return NameGenerator.GenerateUniqueName(baseName, containingTypeMemberNames.ToSet(), StringComparer.Ordinal); } internal override IEnumerable<SyntaxNode> GetConstructorNodes(INamedTypeSymbol containingType) => containingType.Constructors.SelectMany(c => c.DeclaringSyntaxReferences.Select(d => d.GetSyntax())); } }
// 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.Composition; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.EncapsulateField; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.EncapsulateField { [ExportLanguageService(typeof(AbstractEncapsulateFieldService), LanguageNames.CSharp), Shared] internal class CSharpEncapsulateFieldService : AbstractEncapsulateFieldService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpEncapsulateFieldService() { } protected override async Task<SyntaxNode> RewriteFieldNameAndAccessibilityAsync(string originalFieldName, bool makePrivate, Document document, SyntaxAnnotation declarationAnnotation, CancellationToken cancellationToken) { var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var declarator = root.GetAnnotatedNodes<VariableDeclaratorSyntax>(declarationAnnotation).FirstOrDefault(); // There may be no field to rewrite if this document is part of a set of linked files // and the declaration is not conditionally compiled in this document's project. if (declarator == null) { return root; } var tempAnnotation = new SyntaxAnnotation(); var escapedName = originalFieldName.EscapeIdentifier(); var newIdentifier = SyntaxFactory.Identifier( leading: SyntaxTriviaList.Create(SyntaxFactory.ElasticMarker), contextualKind: SyntaxKind.IdentifierName, text: escapedName, valueText: originalFieldName, trailing: SyntaxTriviaList.Create(SyntaxFactory.ElasticMarker)) .WithTrailingTrivia(declarator.Identifier.TrailingTrivia) .WithLeadingTrivia(declarator.Identifier.LeadingTrivia); var updatedDeclarator = declarator.WithIdentifier(newIdentifier).WithAdditionalAnnotations(tempAnnotation); root = root.ReplaceNode(declarator, updatedDeclarator); document = document.WithSyntaxRoot(root); var declaration = root.GetAnnotatedNodes<SyntaxNode>(tempAnnotation).First().Parent as VariableDeclarationSyntax; if (declaration.Variables.Count == 1) { var fieldSyntax = declaration.Parent as FieldDeclarationSyntax; var modifierKinds = new[] { SyntaxKind.PrivateKeyword, SyntaxKind.ProtectedKeyword, SyntaxKind.InternalKeyword, SyntaxKind.PublicKeyword }; if (makePrivate) { var modifiers = SpecializedCollections.SingletonEnumerable(SyntaxFactory.Token(SyntaxKind.PrivateKeyword)) .Concat(fieldSyntax.Modifiers.Where(m => !modifierKinds.Contains(m.Kind()))); root = root.ReplaceNode(fieldSyntax, fieldSyntax.WithModifiers( SyntaxFactory.TokenList(modifiers)) .WithAdditionalAnnotations(Formatter.Annotation) .WithLeadingTrivia(fieldSyntax.GetLeadingTrivia()) .WithTrailingTrivia(fieldSyntax.GetTrailingTrivia())); } } else if (declaration.Variables.Count > 1 && makePrivate) { document = document.WithSyntaxRoot(root); var codeGenService = document.GetLanguageService<ICodeGenerationService>(); var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); declarator = root.GetAnnotatedNodes<VariableDeclaratorSyntax>(tempAnnotation).First(); declaration = declarator.Parent as VariableDeclarationSyntax; var field = semanticModel.GetDeclaredSymbol(declarator, cancellationToken) as IFieldSymbol; var fieldToAdd = declarationAnnotation.AddAnnotationToSymbol(CodeGenerationSymbolFactory.CreateFieldSymbol( field.GetAttributes(), Accessibility.Private, new DeclarationModifiers(isStatic: field.IsStatic, isReadOnly: field.IsReadOnly, isConst: field.IsConst), field.Type, field.Name, field.HasConstantValue, field.ConstantValue, declarator.Initializer)); var withField = await codeGenService.AddFieldAsync(document.Project.Solution, field.ContainingType, fieldToAdd, new CodeGenerationOptions(), cancellationToken).ConfigureAwait(false); root = await withField.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); declarator = root.GetAnnotatedNodes<VariableDeclaratorSyntax>(tempAnnotation).First(); declaration = declarator.Parent as VariableDeclarationSyntax; return root.RemoveNode(declarator, SyntaxRemoveOptions.KeepNoTrivia); } return root; } protected override async Task<ImmutableArray<IFieldSymbol>> GetFieldsAsync(Document document, TextSpan span, CancellationToken cancellationToken) { var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var fields = root.DescendantNodes(d => d.Span.IntersectsWith(span)) .OfType<FieldDeclarationSyntax>() .Where(n => n.Span.IntersectsWith(span)); var declarations = fields.Where(CanEncapsulate).Select(f => f.Declaration); IEnumerable<VariableDeclaratorSyntax> declarators; if (span.IsEmpty) { // no selection, get all variables declarators = declarations.SelectMany(d => d.Variables); } else { // has selection, get only the ones that are included in the selection declarators = declarations.SelectMany(d => d.Variables.Where(v => v.Span.IntersectsWith(span))); } return declarators.Select(d => semanticModel.GetDeclaredSymbol(d, cancellationToken) as IFieldSymbol) .WhereNotNull() .Where(f => f.Name.Length != 0) .ToImmutableArray(); } private bool CanEncapsulate(FieldDeclarationSyntax field) => field.Parent is TypeDeclarationSyntax; protected override (string fieldName, string propertyName) GenerateFieldAndPropertyNames(IFieldSymbol field) { // Special case: if the field is "new", we will preserve its original name and the new keyword. if (field.DeclaredAccessibility == Accessibility.Private || IsNew(field)) { // Create some capitalized version of the field name for the property return (field.Name, MakeUnique(GeneratePropertyName(field.Name), field.ContainingType)); } else { // Generate the new property name using the rules from 695042 var newPropertyName = GeneratePropertyName(field.Name); if (newPropertyName == field.Name) { // If we wind up with the field's old name, give the field the unique version of its current name. return (MakeUnique(GenerateFieldName(field.Name), field.ContainingType), newPropertyName); } // Otherwise, ensure the property's name is unique. newPropertyName = MakeUnique(newPropertyName, field.ContainingType); var newFieldName = GenerateFieldName(newPropertyName); // If converting the new property's name into a field name results in the old field name, we're done. if (newFieldName == field.Name) { return (newFieldName, newPropertyName); } // Otherwise, ensure the new field name is unique. return (MakeUnique(newFieldName, field.ContainingType), newPropertyName); } } private static bool IsNew(IFieldSymbol field) => field.DeclaringSyntaxReferences.Any(d => d.GetSyntax().GetAncestor<FieldDeclarationSyntax>().Modifiers.Any(SyntaxKind.NewKeyword)); private static string GenerateFieldName(string correspondingPropertyName) => char.ToLower(correspondingPropertyName[0]).ToString() + correspondingPropertyName.Substring(1); protected static string MakeUnique(string baseName, INamedTypeSymbol containingType) { var containingTypeMemberNames = containingType.GetAccessibleMembersInThisAndBaseTypes<ISymbol>(containingType).Select(m => m.Name); return NameGenerator.GenerateUniqueName(baseName, containingTypeMemberNames.ToSet(), StringComparer.Ordinal); } internal override IEnumerable<SyntaxNode> GetConstructorNodes(INamedTypeSymbol containingType) => containingType.Constructors.SelectMany(c => c.DeclaringSyntaxReferences.Select(d => d.GetSyntax())); } }
-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/CodeGeneration/Symbols/CodeGenerationOperatorSymbol.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.CodeAnalysis.Editing; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CodeGeneration { internal class CodeGenerationOperatorSymbol : CodeGenerationMethodSymbol { public CodeGenerationOperatorSymbol( INamedTypeSymbol containingType, ImmutableArray<AttributeData> attributes, Accessibility accessibility, DeclarationModifiers modifiers, ITypeSymbol returnType, CodeGenerationOperatorKind operatorKind, ImmutableArray<IParameterSymbol> parameters, ImmutableArray<AttributeData> returnTypeAttributes, string documentationCommentXml) : base(containingType, attributes, accessibility, modifiers, returnType, refKind: RefKind.None, explicitInterfaceImplementations: default, GetMetadataName(operatorKind), typeParameters: ImmutableArray<ITypeParameterSymbol>.Empty, parameters, returnTypeAttributes, documentationCommentXml) { } public override MethodKind MethodKind => MethodKind.UserDefinedOperator; public static int GetParameterCount(CodeGenerationOperatorKind operatorKind) { switch (operatorKind) { case CodeGenerationOperatorKind.Addition: case CodeGenerationOperatorKind.BitwiseAnd: case CodeGenerationOperatorKind.BitwiseOr: case CodeGenerationOperatorKind.Concatenate: case CodeGenerationOperatorKind.Division: case CodeGenerationOperatorKind.Equality: case CodeGenerationOperatorKind.ExclusiveOr: case CodeGenerationOperatorKind.Exponent: case CodeGenerationOperatorKind.GreaterThan: case CodeGenerationOperatorKind.GreaterThanOrEqual: case CodeGenerationOperatorKind.Inequality: case CodeGenerationOperatorKind.IntegerDivision: case CodeGenerationOperatorKind.LeftShift: case CodeGenerationOperatorKind.LessThan: case CodeGenerationOperatorKind.LessThanOrEqual: case CodeGenerationOperatorKind.Like: case CodeGenerationOperatorKind.Modulus: case CodeGenerationOperatorKind.Multiplication: case CodeGenerationOperatorKind.RightShift: case CodeGenerationOperatorKind.Subtraction: return 2; case CodeGenerationOperatorKind.Increment: case CodeGenerationOperatorKind.Decrement: case CodeGenerationOperatorKind.False: case CodeGenerationOperatorKind.LogicalNot: case CodeGenerationOperatorKind.OnesComplement: case CodeGenerationOperatorKind.True: case CodeGenerationOperatorKind.UnaryPlus: case CodeGenerationOperatorKind.UnaryNegation: return 1; default: throw ExceptionUtilities.UnexpectedValue(operatorKind); } } private static string GetMetadataName(CodeGenerationOperatorKind operatorKind) => operatorKind switch { CodeGenerationOperatorKind.Addition => WellKnownMemberNames.AdditionOperatorName, CodeGenerationOperatorKind.BitwiseAnd => WellKnownMemberNames.BitwiseAndOperatorName, CodeGenerationOperatorKind.BitwiseOr => WellKnownMemberNames.BitwiseOrOperatorName, CodeGenerationOperatorKind.Concatenate => WellKnownMemberNames.ConcatenateOperatorName, CodeGenerationOperatorKind.Decrement => WellKnownMemberNames.DecrementOperatorName, CodeGenerationOperatorKind.Division => WellKnownMemberNames.DivisionOperatorName, CodeGenerationOperatorKind.Equality => WellKnownMemberNames.EqualityOperatorName, CodeGenerationOperatorKind.ExclusiveOr => WellKnownMemberNames.ExclusiveOrOperatorName, CodeGenerationOperatorKind.Exponent => WellKnownMemberNames.ExponentOperatorName, CodeGenerationOperatorKind.False => WellKnownMemberNames.FalseOperatorName, CodeGenerationOperatorKind.GreaterThan => WellKnownMemberNames.GreaterThanOperatorName, CodeGenerationOperatorKind.GreaterThanOrEqual => WellKnownMemberNames.GreaterThanOrEqualOperatorName, CodeGenerationOperatorKind.Increment => WellKnownMemberNames.IncrementOperatorName, CodeGenerationOperatorKind.Inequality => WellKnownMemberNames.InequalityOperatorName, CodeGenerationOperatorKind.IntegerDivision => WellKnownMemberNames.IntegerDivisionOperatorName, CodeGenerationOperatorKind.LeftShift => WellKnownMemberNames.LeftShiftOperatorName, CodeGenerationOperatorKind.LessThan => WellKnownMemberNames.LessThanOperatorName, CodeGenerationOperatorKind.LessThanOrEqual => WellKnownMemberNames.LessThanOrEqualOperatorName, CodeGenerationOperatorKind.Like => WellKnownMemberNames.LikeOperatorName, CodeGenerationOperatorKind.LogicalNot => WellKnownMemberNames.LogicalNotOperatorName, CodeGenerationOperatorKind.Modulus => WellKnownMemberNames.ModulusOperatorName, CodeGenerationOperatorKind.Multiplication => WellKnownMemberNames.MultiplyOperatorName, CodeGenerationOperatorKind.OnesComplement => WellKnownMemberNames.OnesComplementOperatorName, CodeGenerationOperatorKind.RightShift => WellKnownMemberNames.RightShiftOperatorName, CodeGenerationOperatorKind.Subtraction => WellKnownMemberNames.SubtractionOperatorName, CodeGenerationOperatorKind.True => WellKnownMemberNames.TrueOperatorName, CodeGenerationOperatorKind.UnaryPlus => WellKnownMemberNames.UnaryPlusOperatorName, CodeGenerationOperatorKind.UnaryNegation => WellKnownMemberNames.UnaryNegationOperatorName, _ => throw ExceptionUtilities.UnexpectedValue(operatorKind), }; } }
// 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.CodeAnalysis.Editing; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CodeGeneration { internal class CodeGenerationOperatorSymbol : CodeGenerationMethodSymbol { public CodeGenerationOperatorSymbol( INamedTypeSymbol containingType, ImmutableArray<AttributeData> attributes, Accessibility accessibility, DeclarationModifiers modifiers, ITypeSymbol returnType, CodeGenerationOperatorKind operatorKind, ImmutableArray<IParameterSymbol> parameters, ImmutableArray<AttributeData> returnTypeAttributes, string documentationCommentXml) : base(containingType, attributes, accessibility, modifiers, returnType, refKind: RefKind.None, explicitInterfaceImplementations: default, GetMetadataName(operatorKind), typeParameters: ImmutableArray<ITypeParameterSymbol>.Empty, parameters, returnTypeAttributes, documentationCommentXml) { } public override MethodKind MethodKind => MethodKind.UserDefinedOperator; public static int GetParameterCount(CodeGenerationOperatorKind operatorKind) { switch (operatorKind) { case CodeGenerationOperatorKind.Addition: case CodeGenerationOperatorKind.BitwiseAnd: case CodeGenerationOperatorKind.BitwiseOr: case CodeGenerationOperatorKind.Concatenate: case CodeGenerationOperatorKind.Division: case CodeGenerationOperatorKind.Equality: case CodeGenerationOperatorKind.ExclusiveOr: case CodeGenerationOperatorKind.Exponent: case CodeGenerationOperatorKind.GreaterThan: case CodeGenerationOperatorKind.GreaterThanOrEqual: case CodeGenerationOperatorKind.Inequality: case CodeGenerationOperatorKind.IntegerDivision: case CodeGenerationOperatorKind.LeftShift: case CodeGenerationOperatorKind.LessThan: case CodeGenerationOperatorKind.LessThanOrEqual: case CodeGenerationOperatorKind.Like: case CodeGenerationOperatorKind.Modulus: case CodeGenerationOperatorKind.Multiplication: case CodeGenerationOperatorKind.RightShift: case CodeGenerationOperatorKind.Subtraction: return 2; case CodeGenerationOperatorKind.Increment: case CodeGenerationOperatorKind.Decrement: case CodeGenerationOperatorKind.False: case CodeGenerationOperatorKind.LogicalNot: case CodeGenerationOperatorKind.OnesComplement: case CodeGenerationOperatorKind.True: case CodeGenerationOperatorKind.UnaryPlus: case CodeGenerationOperatorKind.UnaryNegation: return 1; default: throw ExceptionUtilities.UnexpectedValue(operatorKind); } } private static string GetMetadataName(CodeGenerationOperatorKind operatorKind) => operatorKind switch { CodeGenerationOperatorKind.Addition => WellKnownMemberNames.AdditionOperatorName, CodeGenerationOperatorKind.BitwiseAnd => WellKnownMemberNames.BitwiseAndOperatorName, CodeGenerationOperatorKind.BitwiseOr => WellKnownMemberNames.BitwiseOrOperatorName, CodeGenerationOperatorKind.Concatenate => WellKnownMemberNames.ConcatenateOperatorName, CodeGenerationOperatorKind.Decrement => WellKnownMemberNames.DecrementOperatorName, CodeGenerationOperatorKind.Division => WellKnownMemberNames.DivisionOperatorName, CodeGenerationOperatorKind.Equality => WellKnownMemberNames.EqualityOperatorName, CodeGenerationOperatorKind.ExclusiveOr => WellKnownMemberNames.ExclusiveOrOperatorName, CodeGenerationOperatorKind.Exponent => WellKnownMemberNames.ExponentOperatorName, CodeGenerationOperatorKind.False => WellKnownMemberNames.FalseOperatorName, CodeGenerationOperatorKind.GreaterThan => WellKnownMemberNames.GreaterThanOperatorName, CodeGenerationOperatorKind.GreaterThanOrEqual => WellKnownMemberNames.GreaterThanOrEqualOperatorName, CodeGenerationOperatorKind.Increment => WellKnownMemberNames.IncrementOperatorName, CodeGenerationOperatorKind.Inequality => WellKnownMemberNames.InequalityOperatorName, CodeGenerationOperatorKind.IntegerDivision => WellKnownMemberNames.IntegerDivisionOperatorName, CodeGenerationOperatorKind.LeftShift => WellKnownMemberNames.LeftShiftOperatorName, CodeGenerationOperatorKind.LessThan => WellKnownMemberNames.LessThanOperatorName, CodeGenerationOperatorKind.LessThanOrEqual => WellKnownMemberNames.LessThanOrEqualOperatorName, CodeGenerationOperatorKind.Like => WellKnownMemberNames.LikeOperatorName, CodeGenerationOperatorKind.LogicalNot => WellKnownMemberNames.LogicalNotOperatorName, CodeGenerationOperatorKind.Modulus => WellKnownMemberNames.ModulusOperatorName, CodeGenerationOperatorKind.Multiplication => WellKnownMemberNames.MultiplyOperatorName, CodeGenerationOperatorKind.OnesComplement => WellKnownMemberNames.OnesComplementOperatorName, CodeGenerationOperatorKind.RightShift => WellKnownMemberNames.RightShiftOperatorName, CodeGenerationOperatorKind.Subtraction => WellKnownMemberNames.SubtractionOperatorName, CodeGenerationOperatorKind.True => WellKnownMemberNames.TrueOperatorName, CodeGenerationOperatorKind.UnaryPlus => WellKnownMemberNames.UnaryPlusOperatorName, CodeGenerationOperatorKind.UnaryNegation => WellKnownMemberNames.UnaryNegationOperatorName, _ => throw ExceptionUtilities.UnexpectedValue(operatorKind), }; } }
-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/BraceMatching/InterpolatedStringBraceMatcher.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.ComponentModel.Composition Imports System.Threading Imports System.Threading.Tasks Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.BraceMatching <ExportBraceMatcher(LanguageNames.VisualBasic)> Friend Class InterpolatedStringBraceMatcher Implements IBraceMatcher <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub Public Async Function FindBraces( document As Document, position As Integer, Optional cancellationToken As CancellationToken = Nothing ) As Task(Of BraceMatchingResult?) Implements IBraceMatcher.FindBracesAsync Dim root = Await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(False) Dim token = root.FindToken(position) If token.IsKind(SyntaxKind.DollarSignDoubleQuoteToken, SyntaxKind.DoubleQuoteToken) AndAlso token.Parent.IsKind(SyntaxKind.InterpolatedStringExpression) Then Dim interpolatedString = DirectCast(token.Parent, InterpolatedStringExpressionSyntax) Return New BraceMatchingResult( New TextSpan(interpolatedString.DollarSignDoubleQuoteToken.SpanStart, 2), New TextSpan(interpolatedString.DoubleQuoteToken.Span.End - 1, 1)) End If Return Nothing 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.ComponentModel.Composition Imports System.Threading Imports System.Threading.Tasks Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.BraceMatching <ExportBraceMatcher(LanguageNames.VisualBasic)> Friend Class InterpolatedStringBraceMatcher Implements IBraceMatcher <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub Public Async Function FindBraces( document As Document, position As Integer, Optional cancellationToken As CancellationToken = Nothing ) As Task(Of BraceMatchingResult?) Implements IBraceMatcher.FindBracesAsync Dim root = Await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(False) Dim token = root.FindToken(position) If token.IsKind(SyntaxKind.DollarSignDoubleQuoteToken, SyntaxKind.DoubleQuoteToken) AndAlso token.Parent.IsKind(SyntaxKind.InterpolatedStringExpression) Then Dim interpolatedString = DirectCast(token.Parent, InterpolatedStringExpressionSyntax) Return New BraceMatchingResult( New TextSpan(interpolatedString.DollarSignDoubleQuoteToken.SpanStart, 2), New TextSpan(interpolatedString.DoubleQuoteToken.Span.End - 1, 1)) End If Return Nothing 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/Workspace/Solution/TextAndVersion.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.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis { /// <summary> /// A class that represents both a source text and its version stamp. /// </summary> public sealed class TextAndVersion { /// <summary> /// The source text. /// </summary> public SourceText Text { get; } /// <summary> /// The version of the source text /// </summary> public VersionStamp Version { get; } /// <summary> /// An optional file path that identifies the origin of the source text. Empty if not available. /// </summary> public string FilePath { get; } /// <summary> /// If an error occurred while loading the text the corresponding diagnostic, otherwise null. /// </summary> internal Diagnostic? LoadDiagnostic { get; } private TextAndVersion(SourceText text, VersionStamp version, string? filePath, Diagnostic? loadDiagnostic) { Text = text; Version = version; FilePath = filePath ?? string.Empty; LoadDiagnostic = loadDiagnostic; } /// <summary> /// Create a new <see cref="TextAndVersion"/> instance. /// </summary> /// <param name="text">The text</param> /// <param name="version">The version</param> /// <param name="filePath">An optional file path that identifies the original of the source text.</param> /// <returns></returns> public static TextAndVersion Create(SourceText text, VersionStamp version, string? filePath = null) => Create(text, version, filePath, loadDiagnostic: null); /// <summary> /// Create a new <see cref="TextAndVersion"/> instance. /// </summary> /// <param name="text">The text</param> /// <param name="version">The version</param> /// <param name="filePath">An optional file path that identifies the original of the source text.</param> /// <param name="loadDiagnostic">Diagnostic describing failure to load the source text.</param> /// <returns></returns> internal static TextAndVersion Create(SourceText text, VersionStamp version, string? filePath, Diagnostic? loadDiagnostic) { if (text == null) { throw new ArgumentNullException(nameof(text)); } return new TextAndVersion(text, version, filePath, loadDiagnostic); } } }
// 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.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis { /// <summary> /// A class that represents both a source text and its version stamp. /// </summary> public sealed class TextAndVersion { /// <summary> /// The source text. /// </summary> public SourceText Text { get; } /// <summary> /// The version of the source text /// </summary> public VersionStamp Version { get; } /// <summary> /// An optional file path that identifies the origin of the source text. Empty if not available. /// </summary> public string FilePath { get; } /// <summary> /// If an error occurred while loading the text the corresponding diagnostic, otherwise null. /// </summary> internal Diagnostic? LoadDiagnostic { get; } private TextAndVersion(SourceText text, VersionStamp version, string? filePath, Diagnostic? loadDiagnostic) { Text = text; Version = version; FilePath = filePath ?? string.Empty; LoadDiagnostic = loadDiagnostic; } /// <summary> /// Create a new <see cref="TextAndVersion"/> instance. /// </summary> /// <param name="text">The text</param> /// <param name="version">The version</param> /// <param name="filePath">An optional file path that identifies the original of the source text.</param> /// <returns></returns> public static TextAndVersion Create(SourceText text, VersionStamp version, string? filePath = null) => Create(text, version, filePath, loadDiagnostic: null); /// <summary> /// Create a new <see cref="TextAndVersion"/> instance. /// </summary> /// <param name="text">The text</param> /// <param name="version">The version</param> /// <param name="filePath">An optional file path that identifies the original of the source text.</param> /// <param name="loadDiagnostic">Diagnostic describing failure to load the source text.</param> /// <returns></returns> internal static TextAndVersion Create(SourceText text, VersionStamp version, string? filePath, Diagnostic? loadDiagnostic) { if (text == null) { throw new ArgumentNullException(nameof(text)); } return new TextAndVersion(text, version, filePath, loadDiagnostic); } } }
-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/SplitComment/SplitCommentOptions.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 Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Options.Providers; namespace Microsoft.CodeAnalysis.Editor.Implementation.SplitComment { internal class SplitCommentOptions { public static PerLanguageOption2<bool> Enabled = new PerLanguageOption2<bool>(nameof(SplitCommentOptions), nameof(Enabled), defaultValue: true, storageLocation: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.SplitComments")); } [ExportOptionProvider, Shared] internal class SplitCommentOptionsProvider : IOptionProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public SplitCommentOptionsProvider() { } public ImmutableArray<IOption> Options { get; } = ImmutableArray.Create<IOption>( SplitCommentOptions.Enabled); } }
// 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 Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Options.Providers; namespace Microsoft.CodeAnalysis.Editor.Implementation.SplitComment { internal class SplitCommentOptions { public static PerLanguageOption2<bool> Enabled = new PerLanguageOption2<bool>(nameof(SplitCommentOptions), nameof(Enabled), defaultValue: true, storageLocation: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.SplitComments")); } [ExportOptionProvider, Shared] internal class SplitCommentOptionsProvider : IOptionProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public SplitCommentOptionsProvider() { } public ImmutableArray<IOption> Options { get; } = ImmutableArray.Create<IOption>( SplitCommentOptions.Enabled); } }
-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/Binding/DeclarationInitializerBinder.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 Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic ''' <summary> ''' Binder used for field, auto property initializations and parameter default values. ''' </summary> Friend NotInheritable Class DeclarationInitializerBinder Inherits Binder ''' <summary> ''' Backing field for the ContainingMember property ''' </summary> Private ReadOnly _symbol As Symbol ''' <summary> ''' Backing field for the AdditionalContainingMembers property ''' </summary> Private ReadOnly _additionalSymbols As ImmutableArray(Of Symbol) ''' <summary> Root syntax node </summary> Private ReadOnly _root As VisualBasicSyntaxNode ''' <summary> ''' Initializes a new instance of the <see cref="DeclarationInitializerBinder"/> class. ''' </summary> ''' <param name="symbol">The field, property or parameter symbol with an initializer or default value.</param> ''' <param name="additionalSymbols">Additional field for property symbols initialized with the initializer.</param> ''' <param name="next">The next binder.</param> ''' <param name="root">Root syntax node</param> Public Sub New(symbol As Symbol, additionalSymbols As ImmutableArray(Of Symbol), [next] As Binder, root As VisualBasicSyntaxNode) MyBase.New([next]) Debug.Assert((symbol.Kind = SymbolKind.Field) OrElse (symbol.Kind = SymbolKind.Property) OrElse (symbol.Kind = SymbolKind.Parameter)) Debug.Assert(additionalSymbols.All(Function(s) s.Kind = symbol.Kind AndAlso (s.Kind = SymbolKind.Field OrElse s.Kind = SymbolKind.Property))) Debug.Assert(symbol.Kind <> SymbolKind.Parameter OrElse additionalSymbols.IsEmpty) Me._symbol = symbol Me._additionalSymbols = additionalSymbols Debug.Assert(root IsNot Nothing) _root = root End Sub ''' <summary> ''' The member containing the binding context. ''' This property is the main reason for this binder, because the binding context for an initialization ''' needs to be the field or property symbol. ''' </summary> Public Overrides ReadOnly Property ContainingMember As Symbol Get Return Me._symbol End Get End Property ''' <summary> ''' Additional members associated with the binding context ''' Currently, this field is only used for multiple field/property symbols initialized by an AsNew initializer, e.g. "Dim x, y As New Integer" or "WithEvents x, y as New Object" ''' </summary> Public Overrides ReadOnly Property AdditionalContainingMembers As ImmutableArray(Of Symbol) Get Return Me._additionalSymbols End Get End Property ''' <summary> Field or property declaration statement syntax node </summary> Friend ReadOnly Property Root As VisualBasicSyntaxNode Get Return _root End Get End Property ' Initializers are expressions and so contain no descendant binders, except for lambda bodies, which are handled ' elsewhere (in MemberSemanticModel). Public Overrides Function GetBinder(node As SyntaxNode) As Binder Return Nothing End Function Public Overrides Function GetBinder(stmts As SyntaxList(Of StatementSyntax)) As Binder Return Nothing 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 Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic ''' <summary> ''' Binder used for field, auto property initializations and parameter default values. ''' </summary> Friend NotInheritable Class DeclarationInitializerBinder Inherits Binder ''' <summary> ''' Backing field for the ContainingMember property ''' </summary> Private ReadOnly _symbol As Symbol ''' <summary> ''' Backing field for the AdditionalContainingMembers property ''' </summary> Private ReadOnly _additionalSymbols As ImmutableArray(Of Symbol) ''' <summary> Root syntax node </summary> Private ReadOnly _root As VisualBasicSyntaxNode ''' <summary> ''' Initializes a new instance of the <see cref="DeclarationInitializerBinder"/> class. ''' </summary> ''' <param name="symbol">The field, property or parameter symbol with an initializer or default value.</param> ''' <param name="additionalSymbols">Additional field for property symbols initialized with the initializer.</param> ''' <param name="next">The next binder.</param> ''' <param name="root">Root syntax node</param> Public Sub New(symbol As Symbol, additionalSymbols As ImmutableArray(Of Symbol), [next] As Binder, root As VisualBasicSyntaxNode) MyBase.New([next]) Debug.Assert((symbol.Kind = SymbolKind.Field) OrElse (symbol.Kind = SymbolKind.Property) OrElse (symbol.Kind = SymbolKind.Parameter)) Debug.Assert(additionalSymbols.All(Function(s) s.Kind = symbol.Kind AndAlso (s.Kind = SymbolKind.Field OrElse s.Kind = SymbolKind.Property))) Debug.Assert(symbol.Kind <> SymbolKind.Parameter OrElse additionalSymbols.IsEmpty) Me._symbol = symbol Me._additionalSymbols = additionalSymbols Debug.Assert(root IsNot Nothing) _root = root End Sub ''' <summary> ''' The member containing the binding context. ''' This property is the main reason for this binder, because the binding context for an initialization ''' needs to be the field or property symbol. ''' </summary> Public Overrides ReadOnly Property ContainingMember As Symbol Get Return Me._symbol End Get End Property ''' <summary> ''' Additional members associated with the binding context ''' Currently, this field is only used for multiple field/property symbols initialized by an AsNew initializer, e.g. "Dim x, y As New Integer" or "WithEvents x, y as New Object" ''' </summary> Public Overrides ReadOnly Property AdditionalContainingMembers As ImmutableArray(Of Symbol) Get Return Me._additionalSymbols End Get End Property ''' <summary> Field or property declaration statement syntax node </summary> Friend ReadOnly Property Root As VisualBasicSyntaxNode Get Return _root End Get End Property ' Initializers are expressions and so contain no descendant binders, except for lambda bodies, which are handled ' elsewhere (in MemberSemanticModel). Public Overrides Function GetBinder(node As SyntaxNode) As Binder Return Nothing End Function Public Overrides Function GetBinder(stmts As SyntaxList(Of StatementSyntax)) As Binder Return Nothing 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/CSharp/Test/Semantic/Semantics/NullableContextTests.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.Linq; using System.Text; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Semantics { public class NullableContextTests : CSharpTestBase { [InlineData("#nullable enable", NullableContextOptions.Disable, NullableContext.Enabled)] [InlineData("#nullable enable", NullableContextOptions.Annotations, NullableContext.Enabled)] [InlineData("#nullable enable", NullableContextOptions.Warnings, NullableContext.Enabled)] [InlineData("#nullable enable", NullableContextOptions.Enable, NullableContext.Enabled)] [InlineData("#nullable enable warnings", NullableContextOptions.Disable, NullableContext.WarningsEnabled | NullableContext.AnnotationsContextInherited)] [InlineData("#nullable enable warnings", NullableContextOptions.Warnings, NullableContext.WarningsEnabled | NullableContext.AnnotationsContextInherited)] [InlineData("#nullable enable warnings", NullableContextOptions.Annotations, NullableContext.Enabled | NullableContext.AnnotationsContextInherited)] [InlineData("#nullable enable warnings", NullableContextOptions.Enable, NullableContext.Enabled | NullableContext.AnnotationsContextInherited)] [InlineData("#nullable enable annotations", NullableContextOptions.Disable, NullableContext.AnnotationsEnabled | NullableContext.WarningsContextInherited)] [InlineData("#nullable enable annotations", NullableContextOptions.Warnings, NullableContext.Enabled | NullableContext.WarningsContextInherited)] [InlineData("#nullable enable annotations", NullableContextOptions.Annotations, NullableContext.AnnotationsEnabled | NullableContext.WarningsContextInherited)] [InlineData("#nullable enable annotations", NullableContextOptions.Enable, NullableContext.Enabled | NullableContext.WarningsContextInherited)] [InlineData("#nullable disable", NullableContextOptions.Disable, NullableContext.Disabled)] [InlineData("#nullable disable", NullableContextOptions.Annotations, NullableContext.Disabled)] [InlineData("#nullable disable", NullableContextOptions.Warnings, NullableContext.Disabled)] [InlineData("#nullable disable", NullableContextOptions.Enable, NullableContext.Disabled)] [InlineData("#nullable disable warnings", NullableContextOptions.Disable, NullableContext.Disabled | NullableContext.AnnotationsContextInherited)] [InlineData("#nullable disable warnings", NullableContextOptions.Warnings, NullableContext.Disabled | NullableContext.AnnotationsContextInherited)] [InlineData("#nullable disable warnings", NullableContextOptions.Annotations, NullableContext.AnnotationsEnabled | NullableContext.AnnotationsContextInherited)] [InlineData("#nullable disable warnings", NullableContextOptions.Enable, NullableContext.AnnotationsEnabled | NullableContext.AnnotationsContextInherited)] [InlineData("#nullable disable annotations", NullableContextOptions.Disable, NullableContext.Disabled | NullableContext.WarningsContextInherited)] [InlineData("#nullable disable annotations", NullableContextOptions.Warnings, NullableContext.WarningsEnabled | NullableContext.WarningsContextInherited)] [InlineData("#nullable disable annotations", NullableContextOptions.Annotations, NullableContext.Disabled | NullableContext.WarningsContextInherited)] [InlineData("#nullable disable annotations", NullableContextOptions.Enable, NullableContext.WarningsEnabled | NullableContext.WarningsContextInherited)] [Theory] public void NullableContextExplicitlySpecifiedAndRestoredInFile(string pragma, NullableContextOptions globalContext, NullableContext expectedContext) { var source = $@" {pragma} class C {{ #nullable restore void M() {{}} }}"; var comp = CreateCompilation(source, options: WithNullable(globalContext)); var syntaxTree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(syntaxTree); var classDeclPosition = syntaxTree.GetRoot().DescendantNodes().OfType<ClassDeclarationSyntax>().Single().SpanStart; var methodDeclPosition = syntaxTree.GetRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().Single().SpanStart; Assert.Equal(expectedContext, model.GetNullableContext(classDeclPosition)); // The context at the start of the file should always be inherited and match the global context var restoredContext = ((NullableContext)globalContext) | NullableContext.ContextInherited; Assert.Equal(restoredContext, model.GetNullableContext(0)); Assert.Equal(restoredContext, model.GetNullableContext(methodDeclPosition)); } [Fact] public void NullableContextMultipleFiles() { var source1 = @" #nullable enable partial class C { void M1() {}; }"; var source2 = @" partial class C { #nullable enable void M2(); }"; var comp = CreateCompilation(new[] { source1, source2 }, options: WithNullableEnable()); var syntaxTree1 = comp.SyntaxTrees[0]; var model1 = comp.GetSemanticModel(syntaxTree1); var syntaxTree2 = comp.SyntaxTrees[1]; var model2 = comp.GetSemanticModel(syntaxTree2); var classDecl1 = syntaxTree1.GetRoot().DescendantNodes().OfType<ClassDeclarationSyntax>().Single().SpanStart; var classDecl2 = syntaxTree2.GetRoot().DescendantNodes().OfType<ClassDeclarationSyntax>().Single().SpanStart; Assert.Equal(NullableContext.Enabled, model1.GetNullableContext(classDecl1)); Assert.Equal(NullableContext.Enabled | NullableContext.ContextInherited, model2.GetNullableContext(classDecl2)); } [Fact] public void NullableContextOptionsFlags() { Assert.True(NullableContextOptions.Enable.AnnotationsEnabled()); Assert.True(NullableContextOptions.Enable.WarningsEnabled()); Assert.True(NullableContextOptions.Annotations.AnnotationsEnabled()); Assert.False(NullableContextOptions.Annotations.WarningsEnabled()); Assert.False(NullableContextOptions.Warnings.AnnotationsEnabled()); Assert.True(NullableContextOptions.Warnings.WarningsEnabled()); Assert.False(NullableContextOptions.Disable.AnnotationsEnabled()); Assert.False(NullableContextOptions.Disable.WarningsEnabled()); } [Fact] public void NullableContextFlags() { AssertEnabledForInheritance(NullableContext.Disabled, warningsEnabled: false, annotationsEnabled: false); AssertEnabledForInheritance(NullableContext.WarningsEnabled, warningsEnabled: true, annotationsEnabled: false); AssertEnabledForInheritance(NullableContext.AnnotationsEnabled, warningsEnabled: false, annotationsEnabled: true); AssertEnabledForInheritance(NullableContext.Enabled, warningsEnabled: true, annotationsEnabled: true); void AssertEnabledForInheritance(NullableContext context, bool warningsEnabled, bool annotationsEnabled) { Assert.Equal(warningsEnabled, context.WarningsEnabled()); Assert.Equal(annotationsEnabled, context.AnnotationsEnabled()); Assert.False(context.WarningsInherited()); Assert.False(context.AnnotationsInherited()); var warningsInherited = context | NullableContext.WarningsContextInherited; Assert.Equal(warningsEnabled, warningsInherited.WarningsEnabled()); Assert.Equal(annotationsEnabled, warningsInherited.AnnotationsEnabled()); Assert.True(warningsInherited.WarningsInherited()); Assert.False(warningsInherited.AnnotationsInherited()); var annotationsInherited = context | NullableContext.AnnotationsContextInherited; Assert.Equal(warningsEnabled, annotationsInherited.WarningsEnabled()); Assert.Equal(annotationsEnabled, annotationsInherited.AnnotationsEnabled()); Assert.False(annotationsInherited.WarningsInherited()); Assert.True(annotationsInherited.AnnotationsInherited()); var contextInherited = context | NullableContext.ContextInherited; Assert.Equal(warningsEnabled, contextInherited.WarningsEnabled()); Assert.Equal(annotationsEnabled, contextInherited.AnnotationsEnabled()); Assert.True(contextInherited.WarningsInherited()); Assert.True(contextInherited.AnnotationsInherited()); } } // See also CommandLineTests.NullableAnalysisFlags(). [Fact] public void NullableAnalysisFlags_01() { var source = @"#nullable enable class Program { const object? C1 = null; const object? C2 = null; #nullable enable static object F1() => C1; #nullable disable static object F2() => C2; }"; var expectedAnalyzedKeysAll = new[] { ".cctor", ".ctor", "F1", "F2" }; var expectedAnalyzedKeysDefault = #if DEBUG new[] { ".cctor", ".ctor", "F1", "F2" }; #else new[] { ".cctor", "F1" }; #endif verify(parseOptions: TestOptions.Regular, expectedAnalyzedKeysDefault); verify(parseOptions: TestOptions.Regular.WithFeature("run-nullable-analysis", null), expectedAnalyzedKeysDefault); verify(parseOptions: TestOptions.Regular.WithFeature("run-nullable-analysis", "always"), expectedAnalyzedKeysAll); verify(parseOptions: TestOptions.Regular.WithFeature("run-nullable-analysis", "never")); verify(parseOptions: TestOptions.Regular.WithFeature("run-nullable-analysis", "ALWAYS"), expectedAnalyzedKeysDefault); // unrecognized value (incorrect case) ignored verify(parseOptions: TestOptions.Regular.WithFeature("run-nullable-analysis", "NEVER"), expectedAnalyzedKeysDefault); // unrecognized value (incorrect case) ignored verify(parseOptions: TestOptions.Regular.WithFeature("run-nullable-analysis", "true"), expectedAnalyzedKeysDefault); // unrecognized value ignored verify(parseOptions: TestOptions.Regular.WithFeature("run-nullable-analysis", "false"), expectedAnalyzedKeysDefault); // unrecognized value ignored verify(parseOptions: TestOptions.Regular.WithFeature("run-nullable-analysis", "unknown"), expectedAnalyzedKeysDefault); // unrecognized value ignored void verify(CSharpParseOptions parseOptions, params string[] expectedAnalyzedKeys) { var comp = CreateCompilation(source, parseOptions: parseOptions); comp.NullableAnalysisData = new(); if (expectedAnalyzedKeys.Length > 0) { comp.VerifyDiagnostics( // (7,27): warning CS8603: Possible null reference return. // static object F1() => C1; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "C1").WithLocation(7, 27)); } else { comp.VerifyDiagnostics(); } var actualAnalyzedKeys = GetNullableDataKeysAsStrings(comp.NullableAnalysisData); AssertEx.Equal(expectedAnalyzedKeys, actualAnalyzedKeys); } } [Fact] public void NullableAnalysisFlags_02() { var source = @"#nullable enable class Program { const object? C1 = null; const object? C2 = null; #nullable enable static void F1(object obj = C1) { } #nullable disable static void F2(object obj = C2) { } }"; var expectedAnalyzedKeysAll = new[] { ".cctor", ".ctor", "= C1", "= C2", "F1", "F2" }; var expectedAnalyzedKeysDefault = #if DEBUG new[] { ".cctor", ".ctor", "= C1", "= C2", "F1", "F2" }; #else new[] { ".cctor", "= C1", "F1" }; #endif verify(parseOptions: TestOptions.Regular, expectedAnalyzedKeysDefault); verify(parseOptions: TestOptions.Regular.WithFeature("run-nullable-analysis", null), expectedAnalyzedKeysDefault); verify(parseOptions: TestOptions.Regular.WithFeature("run-nullable-analysis", "always"), expectedAnalyzedKeysAll); verify(parseOptions: TestOptions.Regular.WithFeature("run-nullable-analysis", "never")); void verify(CSharpParseOptions parseOptions, params string[] expectedAnalyzedKeys) { var comp = CreateCompilation(source, parseOptions: parseOptions); comp.NullableAnalysisData = new(); if (expectedAnalyzedKeys.Length > 0) { comp.VerifyDiagnostics( // (7,33): warning CS8625: Cannot convert null literal to non-nullable reference type. // static void F1(object obj = C1) { } Diagnostic(ErrorCode.WRN_NullAsNonNullable, "C1").WithLocation(7, 33)); } else { comp.VerifyDiagnostics(); } var actualAnalyzedKeys = GetNullableDataKeysAsStrings(comp.NullableAnalysisData); AssertEx.Equal(expectedAnalyzedKeys, actualAnalyzedKeys); } } [Fact] public void NullableAnalysisFlags_03() { var sourceA = @"#nullable enable public class A : System.Attribute { public A(object obj) { } public const object? C1 = null; public const object? C2 = null; }"; var refA = CreateCompilation(sourceA).EmitToImageReference(); var sourceB = @"#nullable enable [A(A.C1)] struct B1 { } #nullable disable [A(A.C2)] struct B2 { }"; var expectedAnalyzedKeysAll = new[] { ".cctor", ".cctor", "A(A.C1)", "A(A.C2)" }; var expectedAnalyzedKeysDefault = #if DEBUG new[] { ".cctor", ".cctor", "A(A.C1)", "A(A.C2)" }; #else new[] { "A(A.C1)" }; #endif verify(parseOptions: TestOptions.Regular, expectedAnalyzedKeysDefault); verify(parseOptions: TestOptions.Regular.WithFeature("run-nullable-analysis", null), expectedAnalyzedKeysDefault); verify(parseOptions: TestOptions.Regular.WithFeature("run-nullable-analysis", "always"), expectedAnalyzedKeysAll); verify(parseOptions: TestOptions.Regular.WithFeature("run-nullable-analysis", "never")); void verify(CSharpParseOptions parseOptions, params string[] expectedAnalyzedKeys) { var comp = CreateCompilation(sourceB, references: new[] { refA }, parseOptions: parseOptions); comp.NullableAnalysisData = new(); if (expectedAnalyzedKeys.Length > 0) { comp.VerifyDiagnostics( // (2,4): warning CS8625: Cannot convert null literal to non-nullable reference type. // [A(A.C1)] Diagnostic(ErrorCode.WRN_NullAsNonNullable, "A.C1").WithLocation(2, 4)); } else { comp.VerifyDiagnostics(); } var actualAnalyzedKeys = GetNullableDataKeysAsStrings(comp.NullableAnalysisData); AssertEx.Equal(expectedAnalyzedKeys, actualAnalyzedKeys); } } [Fact] public void NullableAnalysisFlags_MethodBodySemanticModel() { var source = @"#nullable enable class Program { static object F(object? obj) { if (obj == null) return null; return obj; } }"; var expectedAnalyzedKeysAll = new[] { "F" }; verify(parseOptions: TestOptions.Regular, expectedFlowState: true, expectedAnalyzedKeysAll); verify(parseOptions: TestOptions.Regular.WithFeature("run-nullable-analysis", null), expectedFlowState: true, expectedAnalyzedKeysAll); verify(parseOptions: TestOptions.Regular.WithFeature("run-nullable-analysis", "always"), expectedFlowState: true, expectedAnalyzedKeysAll); verify(parseOptions: TestOptions.Regular.WithFeature("run-nullable-analysis", "never"), expectedFlowState: false); void verify(CSharpParseOptions parseOptions, bool expectedFlowState, params string[] expectedAnalyzedKeys) { var comp = CreateCompilation(source, parseOptions: parseOptions); comp.NullableAnalysisData = new(); var syntaxTree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(syntaxTree); var syntax = syntaxTree.GetRoot().DescendantNodes().OfType<ReturnStatementSyntax>().Skip(1).Single(); Assert.Equal("return obj;", syntax.ToString()); var typeInfo = model.GetTypeInfo(syntax.Expression); var expectedNullability = expectedFlowState ? Microsoft.CodeAnalysis.NullableFlowState.NotNull : Microsoft.CodeAnalysis.NullableFlowState.None; Assert.Equal(expectedNullability, typeInfo.Nullability.FlowState); var actualAnalyzedKeys = GetNullableDataKeysAsStrings(comp.NullableAnalysisData); AssertEx.Equal(expectedAnalyzedKeys, actualAnalyzedKeys); } } [Fact] public void NullableAnalysisFlags_AttributeSemanticModel() { var source = @"#nullable enable class A : System.Attribute { public A(object obj) { } public static object F; } [A(A.F = null)] class B { }"; var expectedAnalyzedKeysAll = new[] { "A(A.F = null)" }; verify(parseOptions: TestOptions.Regular, expectedFlowState: true, expectedAnalyzedKeysAll); verify(parseOptions: TestOptions.Regular.WithFeature("run-nullable-analysis", null), expectedFlowState: true, expectedAnalyzedKeysAll); verify(parseOptions: TestOptions.Regular.WithFeature("run-nullable-analysis", "always"), expectedFlowState: true, expectedAnalyzedKeysAll); verify(parseOptions: TestOptions.Regular.WithFeature("run-nullable-analysis", "never"), expectedFlowState: false); void verify(CSharpParseOptions parseOptions, bool expectedFlowState, params string[] expectedAnalyzedKeys) { var comp = CreateCompilation(source, parseOptions: parseOptions); comp.NullableAnalysisData = new(); var syntaxTree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(syntaxTree); var syntax = syntaxTree.GetRoot().DescendantNodes().OfType<AttributeArgumentSyntax>().Single(); Assert.Equal("A.F = null", syntax.ToString()); var typeInfo = model.GetTypeInfo(syntax.Expression); var expectedNullability = expectedFlowState ? Microsoft.CodeAnalysis.NullableFlowState.MaybeNull : Microsoft.CodeAnalysis.NullableFlowState.None; Assert.Equal(expectedNullability, typeInfo.Nullability.FlowState); var actualAnalyzedKeys = GetNullableDataKeysAsStrings(comp.NullableAnalysisData); AssertEx.Equal(expectedAnalyzedKeys, actualAnalyzedKeys); } } [Fact] public void NullableAnalysisFlags_InitializerSemanticModel() { var source = @"#nullable enable class Program { static object F; static void M(object arg = (F = null)) { } }"; var expectedAnalyzedKeysAll = new[] { "arg" }; verify(parseOptions: TestOptions.Regular, expectedFlowState: true, expectedAnalyzedKeysAll); verify(parseOptions: TestOptions.Regular.WithFeature("run-nullable-analysis", null), expectedFlowState: true, expectedAnalyzedKeysAll); verify(parseOptions: TestOptions.Regular.WithFeature("run-nullable-analysis", "always"), expectedFlowState: true, expectedAnalyzedKeysAll); verify(parseOptions: TestOptions.Regular.WithFeature("run-nullable-analysis", "never"), expectedFlowState: false); void verify(CSharpParseOptions parseOptions, bool expectedFlowState, params string[] expectedAnalyzedKeys) { var comp = CreateCompilation(source, parseOptions: parseOptions); comp.NullableAnalysisData = new(); var syntaxTree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(syntaxTree); var syntax = syntaxTree.GetRoot().DescendantNodes().OfType<EqualsValueClauseSyntax>().First().Value; Assert.Equal("(F = null)", syntax.ToString()); var typeInfo = model.GetTypeInfo(syntax); var expectedNullability = expectedFlowState ? Microsoft.CodeAnalysis.NullableFlowState.MaybeNull : Microsoft.CodeAnalysis.NullableFlowState.None; Assert.Equal(expectedNullability, typeInfo.Nullability.FlowState); var actualAnalyzedKeys = GetNullableDataKeysAsStrings(comp.NullableAnalysisData); AssertEx.Equal(expectedAnalyzedKeys, actualAnalyzedKeys); } } public readonly struct NullableDirectives { internal readonly string[] Directives; internal readonly NullableContextState.State ExpectedWarningsState; internal readonly NullableContextState.State ExpectedAnnotationsState; internal NullableDirectives(string[] directives, NullableContextState.State expectedWarningsState, NullableContextState.State expectedAnnotationsState) { Directives = directives; ExpectedWarningsState = expectedWarningsState; ExpectedAnnotationsState = expectedAnnotationsState; } public override string ToString() { var builder = new StringBuilder(); foreach (var str in Directives) builder.AppendLine(str); return builder.ToString(); } } private static readonly NullableDirectives[] s_nullableDirectives = new[] { new NullableDirectives(new string[0], NullableContextState.State.Unknown, NullableContextState.State.Unknown), new NullableDirectives(new[] { "#nullable disable" }, NullableContextState.State.Disabled, NullableContextState.State.Disabled), new NullableDirectives(new[] { "#nullable enable" }, NullableContextState.State.Enabled, NullableContextState.State.Enabled), new NullableDirectives(new[] { "#nullable restore" }, NullableContextState.State.ExplicitlyRestored, NullableContextState.State.ExplicitlyRestored), new NullableDirectives(new[] { "#nullable disable annotations" }, NullableContextState.State.Unknown, NullableContextState.State.Disabled), new NullableDirectives(new[] { "#nullable enable warnings", "#nullable disable annotations", }, NullableContextState.State.Enabled, NullableContextState.State.Disabled), new NullableDirectives(new[] { "#nullable restore warnings", "#nullable disable annotations" }, NullableContextState.State.ExplicitlyRestored, NullableContextState.State.Disabled), new NullableDirectives(new[] { "#nullable enable annotations" }, NullableContextState.State.Unknown, NullableContextState.State.Enabled), new NullableDirectives(new[] { "#nullable disable warnings", "#nullable enable annotations" }, NullableContextState.State.Disabled, NullableContextState.State.Enabled), new NullableDirectives(new[] { "#nullable restore warnings", "#nullable enable annotations" }, NullableContextState.State.ExplicitlyRestored, NullableContextState.State.Enabled), new NullableDirectives(new[] { "#nullable restore annotations" }, NullableContextState.State.Unknown, NullableContextState.State.ExplicitlyRestored), new NullableDirectives(new[] { "#nullable enable warnings" , "#nullable restore annotations" }, NullableContextState.State.Enabled, NullableContextState.State.ExplicitlyRestored), new NullableDirectives(new[] { "#nullable disable warnings", "#nullable restore annotations" }, NullableContextState.State.Disabled, NullableContextState.State.ExplicitlyRestored), new NullableDirectives(new[] { "#nullable disable warnings" }, NullableContextState.State.Disabled, NullableContextState.State.Unknown), new NullableDirectives(new[] { "#nullable enable warnings" }, NullableContextState.State.Enabled, NullableContextState.State.Unknown), new NullableDirectives(new[] { "#nullable restore warnings" }, NullableContextState.State.ExplicitlyRestored, NullableContextState.State.Unknown), }; // AnalyzeMethodsInEnabledContextOnly_01_Data is split due to https://github.com/dotnet/roslyn/issues/50337 public static IEnumerable<object[]> AnalyzeMethodsInEnabledContextOnly_01_Data1() { var projectSettings = new[] { (NullableContextOptions?)null, NullableContextOptions.Disable, }; foreach (var projectSetting in projectSettings) { foreach (var classDirectives in s_nullableDirectives) { foreach (var methodDirectives in s_nullableDirectives) { yield return new object[] { projectSetting, classDirectives, methodDirectives }; } } } } public static IEnumerable<object[]> AnalyzeMethodsInEnabledContextOnly_01_Data2() { var projectSettings = new[] { NullableContextOptions.Warnings, NullableContextOptions.Annotations, NullableContextOptions.Enable, }; foreach (var projectSetting in projectSettings) { foreach (var classDirectives in s_nullableDirectives) { foreach (var methodDirectives in s_nullableDirectives) { yield return new object[] { projectSetting, classDirectives, methodDirectives }; } } } } [Theory] [MemberData(nameof(AnalyzeMethodsInEnabledContextOnly_01_Data1))] [WorkItem(49746, "https://github.com/dotnet/roslyn/issues/49746")] public void AnalyzeMethodsInEnabledContextOnly_01A(NullableContextOptions? projectContext, NullableDirectives classDirectives, NullableDirectives methodDirectives) { AnalyzeMethodsInEnabledContextOnly_01_Execute(projectContext, classDirectives, methodDirectives); } [Theory] [MemberData(nameof(AnalyzeMethodsInEnabledContextOnly_01_Data2))] [WorkItem(49746, "https://github.com/dotnet/roslyn/issues/49746")] public void AnalyzeMethodsInEnabledContextOnly_01B(NullableContextOptions? projectContext, NullableDirectives classDirectives, NullableDirectives methodDirectives) { AnalyzeMethodsInEnabledContextOnly_01_Execute(projectContext, classDirectives, methodDirectives); } private static void AnalyzeMethodsInEnabledContextOnly_01_Execute(NullableContextOptions? projectContext, NullableDirectives classDirectives, NullableDirectives methodDirectives) { var sourceA = @"#nullable enable public class A { public static void M(object obj) { } }"; var refA = CreateCompilation(sourceA).EmitToImageReference(); var sourceB = $@"{classDirectives} static class B {{ {methodDirectives} static void Main() {{ A.M(null); }} }}"; var expectedWarningsStateForMethod = CombineState(methodDirectives.ExpectedWarningsState, classDirectives.ExpectedWarningsState); var expectedAnnotationsStateForMethod = CombineState(methodDirectives.ExpectedAnnotationsState, classDirectives.ExpectedAnnotationsState); bool isNullableEnabledForProject = projectContext != null && (projectContext.Value & NullableContextOptions.Warnings) != 0; bool isNullableEnabledForMethod = IsNullableEnabled(expectedWarningsStateForMethod, isNullableEnabledForProject); var options = TestOptions.ReleaseDll; if (projectContext != null) options = options.WithNullableContextOptions(projectContext.Value); var comp = CreateCompilation(sourceB, options: options, references: new[] { refA }); comp.NullableAnalysisData = new(); if (isNullableEnabledForMethod) { comp.VerifyDiagnostics( // (4,30): warning CS8625: Cannot convert null literal to non-nullable reference type. // static void Main() { A.M(null); } Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null")); } else { comp.VerifyDiagnostics(); } var actualAnalyzedKeys = GetNullableDataKeysAsStrings(comp.NullableAnalysisData, requiredAnalysis: true); Assert.Equal(isNullableEnabledForMethod, actualAnalyzedKeys.Contains("Main")); var tree = (CSharpSyntaxTree)comp.SyntaxTrees[0]; var syntaxNodes = tree.GetRoot().DescendantNodes(); verifyContextState(tree, syntaxNodes.OfType<ClassDeclarationSyntax>().Single(), classDirectives.ExpectedWarningsState, classDirectives.ExpectedAnnotationsState); verifyContextState(tree, syntaxNodes.OfType<MethodDeclarationSyntax>().Single(), expectedWarningsStateForMethod, expectedAnnotationsStateForMethod); static void verifyContextState(CSharpSyntaxTree tree, CSharpSyntaxNode syntax, NullableContextState.State expectedWarningsState, NullableContextState.State expectedAnnotationsState) { var actualState = tree.GetNullableContextState(syntax.SpanStart); Assert.Equal(expectedWarningsState, actualState.WarningsState); Assert.Equal(expectedAnnotationsState, actualState.AnnotationsState); } } private static NullableContextState.State CombineState(NullableContextState.State currentState, NullableContextState.State previousState) { return currentState == NullableContextState.State.Unknown ? previousState : currentState; } private static bool IsNullableEnabled(NullableContextState.State state, bool isNullableEnabledForProject) { return state switch { NullableContextState.State.Enabled => true, NullableContextState.State.Disabled => false, _ => isNullableEnabledForProject, }; } [Fact] [WorkItem(49746, "https://github.com/dotnet/roslyn/issues/49746")] public void AnalyzeMethodsInEnabledContextOnly_02() { var source = @"#pragma warning disable 219 static class Program { #nullable disable static void M1 #nullable enable () { object obj = null; } }"; verify(source, expectedAnalyzedKeys: new[] { "M1" }, // (9,22): warning CS8600: Converting null literal or possible null value to non-nullable type. // object obj = null; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(9, 22)); source = @"#pragma warning disable 219 static class Program { #nullable disable static void M2() #nullable enable { object obj = null; } }"; verify(source, expectedAnalyzedKeys: new[] { "M2" }, // (8,22): warning CS8600: Converting null literal or possible null value to non-nullable type. // object obj = null; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(8, 22)); source = @"#pragma warning disable 219 static class Program { #nullable disable static void M3() { #nullable enable object obj = null; } }"; verify(source, expectedAnalyzedKeys: new[] { "M3" }, // (8,22): warning CS8600: Converting null literal or possible null value to non-nullable type. // object obj = null; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(8, 22)); source = @"#pragma warning disable 219 static class Program { #nullable disable static void M4() { #nullable disable object obj = null; } #nullable enable }"; verify(source, expectedAnalyzedKeys: new string[0]); source = @"#pragma warning disable 219 static class Program { #nullable enable static void M5 #nullable disable () { object obj = null; } }"; verify(source, expectedAnalyzedKeys: new[] { "M5" }); source = @"#pragma warning disable 219 static class Program { static void M6 #nullable enable () #nullable disable { object obj = null; } }"; verify(source, expectedAnalyzedKeys: new[] { "M6" }); source = @"static class Program { static object M7() #nullable enable => default(object); }"; verify(source, expectedAnalyzedKeys: new[] { "M7" }); source = @"static class Program { #nullable disable static object M8() => default( #nullable enable object); }"; verify(source, expectedAnalyzedKeys: new[] { "M8" }); static void verify(string source, string[] expectedAnalyzedKeys, params DiagnosticDescription[] expectedDiagnostics) { var comp = CreateCompilation(source); comp.NullableAnalysisData = new(); comp.VerifyDiagnostics(expectedDiagnostics); AssertEx.Equal(expectedAnalyzedKeys, GetNullableDataKeysAsStrings(comp.NullableAnalysisData, requiredAnalysis: true)); AssertEx.Equal(expectedAnalyzedKeys, GetIsNullableEnabledMethods(comp.NullableAnalysisData)); var tree = (CSharpSyntaxTree)comp.SyntaxTrees[0]; var methodDeclarations = tree.GetRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().ToArray(); foreach (var methodDeclaration in methodDeclarations) { bool expectedAnalysis = expectedAnalyzedKeys.Contains(methodDeclaration.Identifier.Text); bool actualAnalysis = tree.IsNullableAnalysisEnabled(methodDeclaration.Span).Value; Assert.Equal(expectedAnalysis, actualAnalysis); } } } [Fact] [WorkItem(49746, "https://github.com/dotnet/roslyn/issues/49746")] public void AnalyzeMethodsInEnabledContextOnly_03() { var source = @"class Program { Program(object o) { o = null; } } #nullable enable "; verify(source, expectedAnalyzedKeys: new string[0]); source = @"#nullable enable #nullable disable class Program { Program(object o) { o = null; } }"; verify(source, expectedAnalyzedKeys: new string[0]); source = @"class Program { Program(object o) { o = null; } #nullable enable }"; verify(source, expectedAnalyzedKeys: new string[0]); source = @"#pragma warning disable 414 class Program { #nullable disable object F1 = null; #nullable enable }"; verify(source, expectedAnalyzedKeys: new string[0]); source = @"#pragma warning disable 414 class Program { #nullable disable object F1 = null; #nullable enable static object F2 = null; }"; verify(source, expectedAnalyzedKeys: new[] { ".cctor" }, // (7,24): warning CS8625: Cannot convert null literal to non-nullable reference type. // static object F2 = null; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(7, 24)); source = @"#pragma warning disable 414 class Program { #nullable enable object F1 = null; #nullable disable static object F2 = null; }"; verify(source, expectedAnalyzedKeys: new[] { ".ctor" }, // (5,17): warning CS8625: Cannot convert null literal to non-nullable reference type. // object F1 = null; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(5, 17)); source = @"#pragma warning disable 414 static class Program { #nullable disable static object F1 = null; #nullable enable static Program() { F1 = null; } }"; verify(source, expectedAnalyzedKeys: new[] { ".cctor" }); source = @"#pragma warning disable 414 static class Program { #nullable enable static object F1 = null; #nullable disable static Program() { F1 = null; } }"; verify(source, expectedAnalyzedKeys: new[] { ".cctor" }, // (5,24): warning CS8625: Cannot convert null literal to non-nullable reference type. // static object F1 = null; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(5, 24)); source = @"#pragma warning disable 414 class Program { #nullable disable object F1 = null; #nullable enable Program() { F1 = null; } }"; verify(source, expectedAnalyzedKeys: new[] { ".ctor" }); source = @"#pragma warning disable 414 class Program { #nullable enable object F1 = null; #nullable disable Program() { F1 = null; } }"; verify(source, expectedAnalyzedKeys: new[] { ".ctor" }, // (5,17): warning CS8625: Cannot convert null literal to non-nullable reference type. // object F1 = null; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(5, 17)); source = @"#pragma warning disable 414 class Program { #nullable enable object F1 = null; #nullable disable object F2 = null; #nullable enable object F3 = null; }"; verify(source, expectedAnalyzedKeys: new[] { ".ctor" }, // (5,17): warning CS8625: Cannot convert null literal to non-nullable reference type. // object F1 = null; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(5, 17), // (9,17): warning CS8625: Cannot convert null literal to non-nullable reference type. // object F3 = null; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(9, 17)); source = @"#pragma warning disable 414 class Program { #nullable disable object F1 = null; #nullable enable object F2() => null; #nullable disable object F3 = null; }"; verify(source, expectedAnalyzedKeys: new[] { "F2" }, // (7,20): warning CS8603: Possible null reference return. // object F2() => null; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "null").WithLocation(7, 20)); source = @"#pragma warning disable 169 class Program { #nullable enable object F1; #nullable disable Program() { } Program(object obj) : base() { } }"; verify(source, expectedAnalyzedKeys: new[] { ".ctor", ".ctor" }); source = @"#pragma warning disable 169 class Program { #nullable enable object F1; #nullable disable Program() { } Program(object obj) : this() { } }"; verify(source, expectedAnalyzedKeys: new[] { ".ctor" }); source = @"#pragma warning disable 169 class Program { #nullable enable object F1; #nullable disable Program() { } #nullable enable Program(object obj) : this() { } }"; verify(source, expectedAnalyzedKeys: new[] { ".ctor", ".ctor" }); source = @"#pragma warning disable 169 class Program { #nullable disable object F1; Program() { } #nullable enable Program(object obj) : this() { } }"; verify(source, expectedAnalyzedKeys: new[] { ".ctor" }); source = @"#pragma warning disable 169 class Program { #nullable disable object F1; #nullable enable Program() { } #nullable disable Program(object obj) : this() { } }"; verify(source, expectedAnalyzedKeys: new[] { ".ctor" }); source = @"#pragma warning disable 169 struct S { #nullable enable object F1; S(object obj) : this() { } }"; verify(source, expectedAnalyzedKeys: new[] { ".ctor" }, // (6,5): warning CS8618: Non-nullable field 'F1' must contain a non-null value when exiting constructor. Consider declaring the field as nullable. // S(object obj) : this() { } Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "S").WithArguments("field", "F1").WithLocation(6, 5) ); source = @"#pragma warning disable 169 struct S { #nullable enable object F1; #nullable disable S(object obj) : this() { } }"; verify(source, expectedAnalyzedKeys: new string[0]); static void verify(string source, string[] expectedAnalyzedKeys, params DiagnosticDescription[] expectedDiagnostics) { var comp = CreateCompilation(source); comp.NullableAnalysisData = new(); comp.VerifyDiagnostics(expectedDiagnostics); AssertEx.Equal(expectedAnalyzedKeys, GetNullableDataKeysAsStrings(comp.NullableAnalysisData, requiredAnalysis: true)); AssertEx.Equal(expectedAnalyzedKeys, GetIsNullableEnabledMethods(comp.NullableAnalysisData)); } } [Fact] [WorkItem(49746, "https://github.com/dotnet/roslyn/issues/49746")] public void AnalyzeMethodsInEnabledContextOnly_04() { var source1 = @"#pragma warning disable 414 partial class Program { object F1 = null; }"; var source2 = @"#pragma warning disable 414 partial class Program { #nullable disable object F2 = null; }"; var source3 = @"#pragma warning disable 414 partial class Program { #nullable enable object F3 = null; }"; var source4 = @"#pragma warning disable 414 partial class Program { #nullable restore object F4 = null; }"; var options = TestOptions.ReleaseDll.WithNullableContextOptions(NullableContextOptions.Disable); verify(new[] { source1, source2 }, options, new string[0]); verify(new[] { source1, source3 }, options, new[] { ".ctor" }, // (5,17): warning CS8625: Cannot convert null literal to non-nullable reference type. // object F3 = null; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(5, 17)); verify(new[] { source1, source4 }, options, new string[0]); verify(new[] { source2, source3 }, options, new[] { ".ctor" }, // (5,17): warning CS8625: Cannot convert null literal to non-nullable reference type. // object F3 = null; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(5, 17)); verify(new[] { source2, source4 }, options, new string[0]); verify(new[] { source3, source4 }, options, new[] { ".ctor" }, // (5,17): warning CS8625: Cannot convert null literal to non-nullable reference type. // object F3 = null; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(5, 17)); verify(new[] { source1, source2, source3, source4 }, options, new[] { ".ctor" }, // (5,17): warning CS8625: Cannot convert null literal to non-nullable reference type. // object F3 = null; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(5, 17)); verify(new[] { source1, source2, source3, source4 }, TestOptions.ReleaseDll.WithNullableContextOptions(NullableContextOptions.Enable), new[] { ".ctor" }, // (4,17): warning CS8625: Cannot convert null literal to non-nullable reference type. // object F1 = null; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(4, 17), // (5,17): warning CS8625: Cannot convert null literal to non-nullable reference type. // object F3 = null; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(5, 17), // (5,17): warning CS8625: Cannot convert null literal to non-nullable reference type. // object F4 = null; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(5, 17)); static void verify(string[] source, CSharpCompilationOptions options, string[] expectedAnalyzedKeys, params DiagnosticDescription[] expectedDiagnostics) { var comp = CreateCompilation(source, options: options); comp.NullableAnalysisData = new(); comp.VerifyDiagnostics(expectedDiagnostics); AssertEx.Equal(expectedAnalyzedKeys, GetNullableDataKeysAsStrings(comp.NullableAnalysisData, requiredAnalysis: true)); AssertEx.Equal(expectedAnalyzedKeys, GetIsNullableEnabledMethods(comp.NullableAnalysisData)); } } [Fact] [WorkItem(49746, "https://github.com/dotnet/roslyn/issues/49746")] public void AnalyzeMethodsInEnabledContextOnly_05() { var source = @"class Program { #nullable disable object P1 { get; set; } #nullable enable static object P2 { get; set; } }"; verify(source, expectedAnalyzedKeys: new[] { ".cctor" }, // (6,19): warning CS8618: Non-nullable property 'P2' must contain a non-null value when exiting constructor. Consider declaring the property as nullable. // static object P2 { get; set; } Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "P2").WithArguments("property", "P2").WithLocation(6, 19)); source = @"class Program { #nullable enable object P1 { get; set; } #nullable disable static object P2 { get; set; } }"; verify(source, expectedAnalyzedKeys: new[] { ".ctor" }, // (4,12): warning CS8618: Non-nullable property 'P1' must contain a non-null value when exiting constructor. Consider declaring the property as nullable. // object P1 { get; set; } Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "P1").WithArguments("property", "P1").WithLocation(4, 12)); source = @"class Program { #nullable enable object P1 { get; } object P2 { get { return 2; } set { } } object P3 => 3; }"; verify(source, expectedAnalyzedKeys: new[] { ".ctor", "get_P2", "get_P3", "set_P2" }, // (4,12): warning CS8618: Non-nullable property 'P1' must contain a non-null value when exiting constructor. Consider declaring the property as nullable. // object P1 { get; } Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "P1").WithArguments("property", "P1").WithLocation(4, 12)); source = @"#pragma warning disable 67 delegate void D(); class Program { #nullable disable event D E1; #nullable enable static event D E2; }"; verify(source, expectedAnalyzedKeys: new[] { ".cctor" }, // (8,20): warning CS8618: Non-nullable event 'E2' must contain a non-null value when exiting constructor. Consider declaring the event as nullable. // static event D E2; Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "E2").WithArguments("event", "E2").WithLocation(8, 20)); source = @"#pragma warning disable 67 delegate void D(); class Program { #nullable enable event D E1; #nullable disable static event D E2; }"; verify(source, expectedAnalyzedKeys: new[] { ".ctor" }, // (6,13): warning CS8618: Non-nullable event 'E1' must contain a non-null value when exiting constructor. Consider declaring the event as nullable. // event D E1; Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "E1").WithArguments("event", "E1").WithLocation(6, 13)); static void verify(string source, string[] expectedAnalyzedKeys, params DiagnosticDescription[] expectedDiagnostics) { var comp = CreateCompilation(source); comp.NullableAnalysisData = new(); comp.VerifyDiagnostics(expectedDiagnostics); AssertEx.Equal(expectedAnalyzedKeys, GetNullableDataKeysAsStrings(comp.NullableAnalysisData, requiredAnalysis: true)); AssertEx.Equal(expectedAnalyzedKeys, GetIsNullableEnabledMethods(comp.NullableAnalysisData)); } } [Fact] [WorkItem(49746, "https://github.com/dotnet/roslyn/issues/49746")] public void AnalyzeMethodsInEnabledContextOnly_06() { var source = @"#pragma warning disable 414 class Program { #nullable enable object F = 1; #nullable disable ~Program() { F = null; } }"; verify(source, expectedAnalyzedKeys: new[] { ".ctor" }); source = @"#pragma warning disable 414 class Program { #nullable disable object F = 1; #nullable enable ~Program() { F = null; } }"; verify(source, expectedAnalyzedKeys: new[] { "Finalize" }); source = @"#pragma warning disable 414 class Program { #nullable enable object F = 1; ~Program() { F = null; } }"; verify(source, expectedAnalyzedKeys: new[] { ".ctor", "Finalize" }, // (8,13): warning CS8625: Cannot convert null literal to non-nullable reference type. // F = null; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(8, 13)); static void verify(string source, string[] expectedAnalyzedKeys, params DiagnosticDescription[] expectedDiagnostics) { var comp = CreateCompilation(source); comp.NullableAnalysisData = new(); comp.VerifyDiagnostics(expectedDiagnostics); AssertEx.Equal(expectedAnalyzedKeys, GetNullableDataKeysAsStrings(comp.NullableAnalysisData, requiredAnalysis: true)); AssertEx.Equal(expectedAnalyzedKeys, GetIsNullableEnabledMethods(comp.NullableAnalysisData)); } } [Fact] [WorkItem(49746, "https://github.com/dotnet/roslyn/issues/49746")] public void AnalyzeMethodsInEnabledContextOnly_07() { var source = @"class Program { #nullable enable object P #nullable disable #nullable enable => null; object Q #nullable disable => null; }"; verify(source, expectedAnalyzedKeys: new[] { "get_P" }, // (7,12): warning CS8603: Possible null reference return. // => null; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "null").WithLocation(7, 12)); source = @"class Program { #nullable enable object P { get { return null; } #nullable disable set { value = null; } } #nullable enable object Q { #nullable disable get => null; #nullable enable set => value = null; } }"; verify(source, expectedAnalyzedKeys: new[] { "get_P", "set_Q" }, // (6,22): warning CS8603: Possible null reference return. // get { return null; } Diagnostic(ErrorCode.WRN_NullReferenceReturn, "null").WithLocation(6, 22), // (16,24): warning CS8600: Converting null literal or possible null value to non-nullable type. // set => value = null; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(16, 24)); source = @"#pragma warning disable 414 delegate void D(); class Program { #nullable enable D _e = null!; D _f = null!; #nullable disable event D E { #nullable enable add { _e = null; } #nullable disable remove { _e = null; } } event D F { #nullable disable add => _f = null; #nullable enable remove => _f = null; } }"; verify(source, expectedAnalyzedKeys: new[] { ".ctor", "add_E", "remove_F" }, // (12,20): warning CS8625: Cannot convert null literal to non-nullable reference type. // add { _e = null; } Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(12, 20), // (21,24): warning CS8625: Cannot convert null literal to non-nullable reference type. // remove => _f = null; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(21, 24)); static void verify(string source, string[] expectedAnalyzedKeys, params DiagnosticDescription[] expectedDiagnostics) { var comp = CreateCompilation(source); comp.NullableAnalysisData = new(); comp.VerifyDiagnostics(expectedDiagnostics); AssertEx.Equal(expectedAnalyzedKeys, GetNullableDataKeysAsStrings(comp.NullableAnalysisData, requiredAnalysis: true)); AssertEx.Equal(expectedAnalyzedKeys, GetIsNullableEnabledMethods(comp.NullableAnalysisData)); } } [Fact] [WorkItem(49746, "https://github.com/dotnet/roslyn/issues/49746")] public void AnalyzeMethodsInEnabledContextOnly_08() { var source = @"class A { } class B { public static explicit operator B(A a) => null; }"; verify(source, expectedAnalyzedKeys: new string[0]); source = @"class A { } class B { #nullable enable public static explicit operator B(A a) => null; }"; verify(source, expectedAnalyzedKeys: new[] { "op_Explicit" }, // (7,47): warning CS8603: Possible null reference return. // public static explicit operator B(A a) => null; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "null").WithLocation(7, 47)); source = @"class C { public static C operator~(C c) => null; }"; verify(source, expectedAnalyzedKeys: new string[0]); source = @"class C { #nullable enable public static C operator~(C c) => null; }"; verify(source, expectedAnalyzedKeys: new[] { "op_OnesComplement" }, // (4,39): warning CS8603: Possible null reference return. // public static C operator~(C c) => null; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "null").WithLocation(4, 39)); static void verify(string source, string[] expectedAnalyzedKeys, params DiagnosticDescription[] expectedDiagnostics) { var comp = CreateCompilation(source); comp.NullableAnalysisData = new(); comp.VerifyDiagnostics(expectedDiagnostics); AssertEx.Equal(expectedAnalyzedKeys, GetNullableDataKeysAsStrings(comp.NullableAnalysisData, requiredAnalysis: true)); AssertEx.Equal(expectedAnalyzedKeys, GetIsNullableEnabledMethods(comp.NullableAnalysisData)); } } [Fact] [WorkItem(49746, "https://github.com/dotnet/roslyn/issues/49746")] public void AnalyzeMethodsInEnabledContextOnly_09() { var source = @"#nullable enable record R; "; verify(source, expectedAnalyzedKeys: new string[0]); source = @"#nullable enable record R(); "; verify(source, expectedAnalyzedKeys: new[] { "R..ctor()" }); source = @"record R(object P #nullable enable ); "; verify(source, expectedAnalyzedKeys: new[] { "R..ctor(System.Object P)" }); source = @"record A; #nullable disable record B0 : A #nullable enable { } #nullable disable record B1() : A #nullable enable { } #nullable disable record B2() : A #nullable enable (); "; verify(source, expectedAnalyzedKeys: new[] { "B2..ctor()" }); source = @"record A; #nullable disable record B0 #nullable enable : #nullable disable A; #nullable disable record B1 : #nullable enable A #nullable disable ; #nullable disable record B2() : #nullable enable A #nullable disable (); "; verify(source, expectedAnalyzedKeys: new string[0]); source = @"record A(object P) { #nullable enable internal static object F(object obj) => obj; #nullable disable } #nullable disable record B1() : A( F(null)); record B2() : A( #nullable enable F(null)); "; verify(source, expectedAnalyzedKeys: new[] { "B2..ctor()", "System.Object A.F(System.Object obj)" }, // (12,7): warning CS8625: Cannot convert null literal to non-nullable reference type. // F(null)); Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(12, 7)); static void verify(string source, string[] expectedAnalyzedKeys, params DiagnosticDescription[] expectedDiagnostics) { var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }); comp.NullableAnalysisData = new(); comp.VerifyDiagnostics(expectedDiagnostics); var actualAnalyzedKeys = GetIsNullableEnabledMethods(comp.NullableAnalysisData, key => ((MethodSymbol)key).ToTestDisplayString()); AssertEx.Equal(expectedAnalyzedKeys, actualAnalyzedKeys); } } [Fact] [WorkItem(49746, "https://github.com/dotnet/roslyn/issues/49746")] public void AnalyzeMethodsInEnabledContextOnly_10() { var source1 = @"partial class Program { #nullable enable partial void F1(ref object o1) { o1 = null; } partial void F2(ref object o2); #nullable disable partial void F3(ref object o3) { o3 = null; } partial void F4(ref object o4); }"; var source2 = @"partial class Program { #nullable disable partial void F1(ref object o1); partial void F2(ref object o2) { o2 = null; } #nullable enable partial void F3(ref object o3); partial void F4(ref object o4) { o4 = null; } }"; var comp = CreateCompilation(new[] { source1, source2 }); comp.NullableAnalysisData = new(); comp.VerifyDiagnostics( // (4,43): warning CS8625: Cannot convert null literal to non-nullable reference type. // partial void F1(ref object o1) { o1 = null; } Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(4, 43), // (8,43): warning CS8625: Cannot convert null literal to non-nullable reference type. // partial void F4(ref object o4) { o4 = null; } Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(8, 43)); var expectedAnalyzedKeys = new[] { "F1", "F4" }; AssertEx.Equal(expectedAnalyzedKeys, GetNullableDataKeysAsStrings(comp.NullableAnalysisData, requiredAnalysis: true)); AssertEx.Equal(expectedAnalyzedKeys, GetIsNullableEnabledMethods(comp.NullableAnalysisData)); } [Fact] [WorkItem(49746, "https://github.com/dotnet/roslyn/issues/49746")] public void AnalyzeMethodsInEnabledContextOnly_11() { var source = @"partial class Program { #nullable enable partial void F1(object x = null); partial void F2(object y = null) { } #nullable disable partial void F1(object x = null) { } partial void F2(object y = null); }"; var comp = CreateCompilation(source); comp.NullableAnalysisData = new(); comp.VerifyDiagnostics( // (4,32): warning CS8625: Cannot convert null literal to non-nullable reference type. // partial void F1(object x = null); Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(4, 32), // (5,28): warning CS1066: The default value specified for parameter 'y' will have no effect because it applies to a member that is used in contexts that do not allow optional arguments // partial void F2(object y = null) { } Diagnostic(ErrorCode.WRN_DefaultValueForUnconsumedLocation, "y").WithArguments("y").WithLocation(5, 28), // (5,32): warning CS8625: Cannot convert null literal to non-nullable reference type. // partial void F2(object y = null) { } Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(5, 32), // (7,28): warning CS1066: The default value specified for parameter 'x' will have no effect because it applies to a member that is used in contexts that do not allow optional arguments // partial void F1(object x = null) { } Diagnostic(ErrorCode.WRN_DefaultValueForUnconsumedLocation, "x").WithArguments("x").WithLocation(7, 28)); var actualAnalyzedKeys = GetNullableDataKeysAsStrings(comp.NullableAnalysisData, requiredAnalysis: true); AssertEx.Equal(new[] { "= null", "= null", "F2" }, actualAnalyzedKeys); } [Fact] [WorkItem(49746, "https://github.com/dotnet/roslyn/issues/49746")] public void AnalyzeMethodsInEnabledContextOnly_12() { var source = @"using System.Runtime.InteropServices; class Program { #nullable enable const object? C1 = null; const object? C2 = null; const object? C3 = null; const object? C4 = null; #nullable disable static void F1( [DefaultParameterValue( #nullable enable C1 #nullable disable )] [A] object x) { } static void F2( #nullable enable [DefaultParameterValue(C2)] #nullable disable [A] object x) { } #nullable disable static void F3( [DefaultParameterValue(C3)] #nullable enable [A] object x #nullable disable ) { } static void F4( [DefaultParameterValue(C4)] [A] object x) #nullable enable #nullable disable { } } class A : System.Attribute { }"; var comp = CreateCompilation(source); comp.NullableAnalysisData = new(); comp.VerifyDiagnostics(); var actualAnalyzedKeys = GetNullableDataKeysAsStrings(comp.NullableAnalysisData, requiredAnalysis: true); var expectedAnalyzedKeys = new[] { ".cctor", @"[DefaultParameterValue( #nullable enable C1 #nullable disable )] [A] object x", @"[DefaultParameterValue(C2)] #nullable disable [A] object x", @"[DefaultParameterValue(C3)] #nullable enable [A] object x", "A", @"DefaultParameterValue( #nullable enable C1 #nullable disable )", "DefaultParameterValue(C2)", "F1", "F2", "F3", "F4", }; AssertEx.Equal(expectedAnalyzedKeys, actualAnalyzedKeys); } [Fact] [WorkItem(49746, "https://github.com/dotnet/roslyn/issues/49746")] public void AnalyzeMethodsInEnabledContextOnly_13() { var source = @"#nullable disable object x = typeof(string); if (x == null) { } _ = x.ToString(); #nullable enable "; verify(new[] { source }, projectContext: null, expectedAnalyzedKeys: new string[0]); source = @"#nullable disable object x = typeof(string); if (x == null) { } #nullable enable _ = x.ToString(); "; verify(new[] { source }, projectContext: null, expectedAnalyzedKeys: new[] { "<Main>$" }, // (5,5): warning CS8602: Dereference of a possibly null reference. // _ = x.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(5, 5)); source = @"#nullable disable object x = typeof(string); if (x == null) { } #nullable restore _ = x.ToString(); "; verify(new[] { source }, projectContext: NullableContextOptions.Warnings, expectedAnalyzedKeys: new[] { "<Main>$" }, // (5,5): warning CS8602: Dereference of a possibly null reference. // _ = x.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(5, 5)); source = @"object x = typeof(string); if (x == null) { } #nullable enable #nullable disable _ = x.ToString(); "; verify(new[] { source }, projectContext: null, expectedAnalyzedKeys: new string[0]); source = @"object x = A.F(); if (x == null) { } _ = x.ToString(); static class A { #nullable enable internal static object F() => new object(); }"; verify(new[] { source }, projectContext: null, expectedAnalyzedKeys: new[] { "F" }); source = @"object x = typeof(A); class A { #nullable enable #nullable disable } if (x == null) { } _ = x.ToString(); "; verify(new[] { source }, projectContext: null, expectedAnalyzedKeys: new string[0], // (7,1): error CS8803: Top-level statements must precede namespace and type declarations. // if (x == null) { } Diagnostic(ErrorCode.ERR_TopLevelStatementAfterNamespaceOrType, "if (x == null) { }").WithLocation(7, 1)); source = @"#nullable enable object x = A.F(); #nullable disable static class A { internal static object F() => new object(); } if (x == null) { } _ = x.ToString(); "; verify(new[] { source }, projectContext: null, expectedAnalyzedKeys: new[] { "<Main>$" }, // (8,1): error CS8803: Top-level statements must precede namespace and type declarations. // if (x == null) { } Diagnostic(ErrorCode.ERR_TopLevelStatementAfterNamespaceOrType, "if (x == null) { }").WithLocation(8, 1)); source = @"object x = F(); if (x == null) { } _ = x.ToString(); static object F() { #nullable enable return new object(); #nullable disable }"; verify(new[] { source }, projectContext: null, expectedAnalyzedKeys: new[] { "<Main>$" }); var sourceA = @"static class A { #nullable enable internal static object F() => new object(); }"; var sourceB = @"object x = A.F(); if (x == null) { } _ = x.ToString(); "; verify(new[] { sourceA, sourceB }, projectContext: null, expectedAnalyzedKeys: new[] { "F" }); static void verify(string[] source, NullableContextOptions? projectContext, string[] expectedAnalyzedKeys, params DiagnosticDescription[] expectedDiagnostics) { var options = TestOptions.ReleaseExe; if (projectContext != null) options = options.WithNullableContextOptions(projectContext.GetValueOrDefault()); var comp = CreateCompilation(source, options: options); comp.NullableAnalysisData = new(); comp.VerifyDiagnostics(expectedDiagnostics); AssertEx.Equal(expectedAnalyzedKeys, GetNullableDataKeysAsStrings(comp.NullableAnalysisData, requiredAnalysis: true)); AssertEx.Equal(expectedAnalyzedKeys, GetIsNullableEnabledMethods(comp.NullableAnalysisData)); } } [Fact] [WorkItem(49746, "https://github.com/dotnet/roslyn/issues/49746")] public void AnalyzeMethodsInEnabledContextOnly_MethodBodySemanticModel_01() { var source = @"class Program { #nullable enable static object F1(object o1) { if (o1 == null) { } return o1; } #nullable disable static object F2(object o2) { if (o2 == null) { } return o2; } }"; var comp = CreateCompilation(source); comp.NullableAnalysisData = new(); var syntaxTree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(syntaxTree); var returnStatements = syntaxTree.GetRoot().DescendantNodes().OfType<ReturnStatementSyntax>().ToArray(); var syntax = returnStatements[0]; Assert.Equal("return o1;", syntax.ToString()); var typeInfo = model.GetTypeInfo(syntax.Expression); Assert.Equal(Microsoft.CodeAnalysis.NullableFlowState.MaybeNull, typeInfo.Nullability.FlowState); syntax = returnStatements[1]; Assert.Equal("return o2;", syntax.ToString()); typeInfo = model.GetTypeInfo(syntax.Expression); Assert.Equal(Microsoft.CodeAnalysis.NullableFlowState.None, typeInfo.Nullability.FlowState); var expectedAnalyzedKeys = new[] { "F1" }; AssertEx.Equal(expectedAnalyzedKeys, GetNullableDataKeysAsStrings(comp.NullableAnalysisData, requiredAnalysis: true)); AssertEx.Equal(expectedAnalyzedKeys, GetIsNullableEnabledMethods(comp.NullableAnalysisData)); } [Fact] [WorkItem(49746, "https://github.com/dotnet/roslyn/issues/49746")] public void AnalyzeMethodsInEnabledContextOnly_MethodBodySemanticModel_02() { var source = @"class Program { #nullable enable object F; Program(object obj) #nullable disable { if (obj == null) { } F = obj; } }"; verify(source, Microsoft.CodeAnalysis.NullableFlowState.MaybeNull, ".ctor"); source = @"class Program { #nullable enable object F; #nullable disable Program(object obj) { if (obj == null) { } F = obj; } }"; verify(source, Microsoft.CodeAnalysis.NullableFlowState.MaybeNull, ".ctor"); source = @"class Program { #nullable enable object F = new object(); #nullable disable Program(object obj) { if (obj == null) { } F = obj; } }"; verify(source, Microsoft.CodeAnalysis.NullableFlowState.MaybeNull, ".ctor"); static void verify(string source, Microsoft.CodeAnalysis.NullableFlowState expectedFlowState, params string[] expectedAnalyzedKeys) { var comp = CreateCompilation(source); comp.NullableAnalysisData = new(); var syntaxTree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(syntaxTree); var syntax = syntaxTree.GetRoot().DescendantNodes().OfType<AssignmentExpressionSyntax>().Single().Right; Assert.Equal("obj", syntax.ToString()); var typeInfo = model.GetTypeInfo(syntax); Assert.Equal(expectedFlowState, typeInfo.Nullability.FlowState); AssertEx.Equal(expectedAnalyzedKeys, GetNullableDataKeysAsStrings(comp.NullableAnalysisData, requiredAnalysis: true)); AssertEx.Equal(expectedAnalyzedKeys, GetIsNullableEnabledMethods(comp.NullableAnalysisData)); } } [Fact] [WorkItem(49746, "https://github.com/dotnet/roslyn/issues/49746")] public void AnalyzeMethodsInEnabledContextOnly_AttributeSemanticModel_01() { var source = @"class A : System.Attribute { #nullable enable public A(object obj) { } public static object F1; public static object F2; } #nullable enable [A(A.F1 = null)] class B1 { } #nullable disable [A(A.F2 = null)] class B2 { }"; var comp = CreateCompilation(source); comp.NullableAnalysisData = new(); var syntaxTree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(syntaxTree); var attributeArguments = syntaxTree.GetRoot().DescendantNodes().OfType<AttributeArgumentSyntax>().ToArray(); verify(attributeArguments[0], "A.F1 = null", Microsoft.CodeAnalysis.NullableFlowState.MaybeNull); verify(attributeArguments[1], "A.F2 = null", Microsoft.CodeAnalysis.NullableFlowState.None); var actualAnalyzedKeys = GetNullableDataKeysAsStrings(comp.NullableAnalysisData, requiredAnalysis: true); AssertEx.Equal(new[] { "A(A.F1 = null)" }, actualAnalyzedKeys); void verify(AttributeArgumentSyntax syntax, string expectedText, Microsoft.CodeAnalysis.NullableFlowState expectedFlowState) { Assert.Equal(expectedText, syntax.ToString()); var typeInfo = model.GetTypeInfo(syntax.Expression); Assert.Equal(expectedFlowState, typeInfo.Nullability.FlowState); } } [Fact] [WorkItem(49746, "https://github.com/dotnet/roslyn/issues/49746")] public void AnalyzeMethodsInEnabledContextOnly_AttributeSemanticModel_02() { var source = @"using System.Runtime.InteropServices; class Program { #nullable enable const object? C1 = null; const object? C2 = null; #nullable disable static void F1([DefaultParameterValue( #nullable enable C1 #nullable disable )] object x) { } #nullable disable static void F2([DefaultParameterValue(C2)] #nullable enable object x #nullable disable ) { } }"; var comp = CreateCompilation(source); comp.NullableAnalysisData = new(); var syntaxTree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(syntaxTree); var attributeArguments = syntaxTree.GetRoot().DescendantNodes().OfType<AttributeArgumentSyntax>().ToArray(); verify(attributeArguments[0], "C1", Microsoft.CodeAnalysis.NullableFlowState.MaybeNull); verify(attributeArguments[1], "C2", Microsoft.CodeAnalysis.NullableFlowState.None); var actualAnalyzedKeys = GetNullableDataKeysAsStrings(comp.NullableAnalysisData, requiredAnalysis: true); var expectedAnalyzedKey = @"DefaultParameterValue( #nullable enable C1 #nullable disable )"; AssertEx.Equal(new[] { expectedAnalyzedKey }, actualAnalyzedKeys); void verify(AttributeArgumentSyntax syntax, string expectedText, Microsoft.CodeAnalysis.NullableFlowState expectedFlowState) { Assert.Equal(expectedText, syntax.ToString()); var typeInfo = model.GetTypeInfo(syntax.Expression); Assert.Equal(expectedFlowState, typeInfo.Nullability.FlowState); } } [Fact] [WorkItem(49746, "https://github.com/dotnet/roslyn/issues/49746")] public void AnalyzeMethodsInEnabledContextOnly_InitializerSemanticModel_01() { var source = @"class Program { #nullable enable static object F1; static object F2; #nullable enable static void M1(object o1 = (F1 = null)) { } #nullable disable static void M2(object o2 = (F2 = null)) { } }"; var comp = CreateCompilation(source); comp.NullableAnalysisData = new(); var syntaxTree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(syntaxTree); var equalsValueClauses = syntaxTree.GetRoot().DescendantNodes().OfType<EqualsValueClauseSyntax>().ToArray(); verify(equalsValueClauses[0], "(F1 = null)", Microsoft.CodeAnalysis.NullableFlowState.MaybeNull); verify(equalsValueClauses[1], "(F2 = null)", Microsoft.CodeAnalysis.NullableFlowState.None); var actualAnalyzedKeys = GetNullableDataKeysAsStrings(comp.NullableAnalysisData, requiredAnalysis: true); AssertEx.Equal(new[] { "o1" }, actualAnalyzedKeys); void verify(EqualsValueClauseSyntax syntax, string expectedText, Microsoft.CodeAnalysis.NullableFlowState expectedFlowState) { var value = syntax.Value; Assert.Equal(expectedText, value.ToString()); var typeInfo = model.GetTypeInfo(value); Assert.Equal(expectedFlowState, typeInfo.Nullability.FlowState); } } [Fact] [WorkItem(49746, "https://github.com/dotnet/roslyn/issues/49746")] public void AnalyzeMethodsInEnabledContextOnly_InitializerSemanticModel_02() { var source = @"#pragma warning disable 414 class A { #nullable disable object F1 = null; } class B { #nullable disable object F2 = null; #nullable enable object F3 = null; }"; var comp = CreateCompilation(source); comp.NullableAnalysisData = new(); var syntaxTree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(syntaxTree); var declarations = syntaxTree.GetRoot().DescendantNodes().OfType<FieldDeclarationSyntax>().Select(f => f.Declaration.Variables[0]).ToArray(); verify(declarations[0], "F1", Microsoft.CodeAnalysis.NullableFlowState.None); verify(declarations[1], "F2", Microsoft.CodeAnalysis.NullableFlowState.MaybeNull); verify(declarations[2], "F3", Microsoft.CodeAnalysis.NullableFlowState.MaybeNull); var actualAnalyzedKeys = GetNullableDataKeysAsStrings(comp.NullableAnalysisData, requiredAnalysis: true); AssertEx.Equal(new[] { "F2", "F3" }, actualAnalyzedKeys); void verify(VariableDeclaratorSyntax syntax, string expectedText, Microsoft.CodeAnalysis.NullableFlowState expectedFlowState) { Assert.Equal(expectedText, syntax.Identifier.ValueText); var typeInfo = model.GetTypeInfo(syntax.Initializer.Value); Assert.Equal(expectedFlowState, typeInfo.Nullability.FlowState); } } [Fact] [WorkItem(49746, "https://github.com/dotnet/roslyn/issues/49746")] public void AnalyzeMethodsInEnabledContextOnly_InitializerSemanticModel_03() { var source = @"class A { #nullable disable object P1 { get; set; } = null; } class B { #nullable disable object P2 { get; set; } = null; #nullable enable object P3 { get; set; } = null; }"; var comp = CreateCompilation(source); comp.NullableAnalysisData = new(); var syntaxTree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(syntaxTree); var declarations = syntaxTree.GetRoot().DescendantNodes().OfType<PropertyDeclarationSyntax>().ToArray(); verify(declarations[0], "P1", Microsoft.CodeAnalysis.NullableFlowState.None); verify(declarations[1], "P2", Microsoft.CodeAnalysis.NullableFlowState.MaybeNull); verify(declarations[2], "P3", Microsoft.CodeAnalysis.NullableFlowState.MaybeNull); var actualAnalyzedKeys = GetNullableDataKeysAsStrings(comp.NullableAnalysisData, requiredAnalysis: true); AssertEx.Equal(new[] { "P2", "P3" }, actualAnalyzedKeys); void verify(PropertyDeclarationSyntax syntax, string expectedText, Microsoft.CodeAnalysis.NullableFlowState expectedFlowState) { Assert.Equal(expectedText, syntax.Identifier.ValueText); var typeInfo = model.GetTypeInfo(syntax.Initializer.Value); Assert.Equal(expectedFlowState, typeInfo.Nullability.FlowState); } } [Fact] [WorkItem(49746, "https://github.com/dotnet/roslyn/issues/49746")] public void AnalyzeMethodsInEnabledContextOnly_SpeculativeSemanticModel_MethodBody() { var source = @"class Program { #nullable disable static void Main() { object obj = typeof(object); } #nullable enable }"; VerifySpeculativeSemanticModel(source, null, "string", Microsoft.CodeAnalysis.NullableAnnotation.None); source = @"class Program { #nullable disable static void Main() { object obj = #nullable enable typeof(object); } }"; VerifySpeculativeSemanticModel(source, null, "string", Microsoft.CodeAnalysis.NullableAnnotation.NotAnnotated); } [Fact] [WorkItem(49746, "https://github.com/dotnet/roslyn/issues/49746")] public void AnalyzeMethodsInEnabledContextOnly_SpeculativeSemanticModel_Initializer() { var source = @"class Program { #nullable disable static object F = typeof(object); #nullable enable }"; VerifySpeculativeSemanticModel(source, null, "string", Microsoft.CodeAnalysis.NullableAnnotation.None); source = @"class Program { #nullable disable static object F = #nullable enable typeof(object); }"; VerifySpeculativeSemanticModel(source, null, "string", Microsoft.CodeAnalysis.NullableAnnotation.NotAnnotated); source = @"class Program { #nullable disable static object P { get; } = typeof(object); #nullable enable }"; VerifySpeculativeSemanticModel(source, null, "string", Microsoft.CodeAnalysis.NullableAnnotation.None); source = @"class Program { #nullable disable static object P { get; } = #nullable enable typeof(object); }"; VerifySpeculativeSemanticModel(source, null, "string", Microsoft.CodeAnalysis.NullableAnnotation.NotAnnotated); } [Fact] [WorkItem(49746, "https://github.com/dotnet/roslyn/issues/49746")] public void AnalyzeMethodsInEnabledContextOnly_SpeculativeSemanticModel_Attribute() { var source = @"class A : System.Attribute { internal A(object obj) { } } class Program { #nullable disable [A(typeof(object)] static void Main() { } #nullable enable }"; VerifySpeculativeSemanticModel(source, null, "string", Microsoft.CodeAnalysis.NullableAnnotation.None); source = @"class A : System.Attribute { internal A(object obj) { } } class Program { #nullable disable [A( #nullable enable typeof(object)] static void Main() { } }"; VerifySpeculativeSemanticModel(source, null, "string", Microsoft.CodeAnalysis.NullableAnnotation.NotAnnotated); } [Theory] [MemberData(nameof(AnalyzeMethodsInEnabledContextOnly_01_Data1))] [WorkItem(49746, "https://github.com/dotnet/roslyn/issues/49746")] public void AnalyzeMethodsInEnabledContextOnly_SpeculativeSemanticModel_A(NullableContextOptions? projectContext, NullableDirectives sourceDirectives, NullableDirectives speculativeDirectives) { AnalyzeMethodsInEnabledContextOnly_SpeculativeSemanticModel_Execute(projectContext, sourceDirectives, speculativeDirectives); } [Theory] [MemberData(nameof(AnalyzeMethodsInEnabledContextOnly_01_Data2))] [WorkItem(49746, "https://github.com/dotnet/roslyn/issues/49746")] public void AnalyzeMethodsInEnabledContextOnly_SpeculativeSemanticModel_B(NullableContextOptions? projectContext, NullableDirectives sourceDirectives, NullableDirectives speculativeDirectives) { AnalyzeMethodsInEnabledContextOnly_SpeculativeSemanticModel_Execute(projectContext, sourceDirectives, speculativeDirectives); } private static void AnalyzeMethodsInEnabledContextOnly_SpeculativeSemanticModel_Execute(NullableContextOptions? projectContext, NullableDirectives sourceDirectives, NullableDirectives speculativeDirectives) { // https://github.com/dotnet/roslyn/issues/50234: SyntaxTreeSemanticModel.IsNullableAnalysisEnabledAtSpeculativePosition() // does not handle '#nullable restore'. if (speculativeDirectives.ExpectedWarningsState == NullableContextState.State.ExplicitlyRestored) return; var source = $@"class Program {{ {sourceDirectives} static void Main() {{ object obj = typeof(object); }} }}"; var typeName = $@"{speculativeDirectives} string"; var expectedWarningsState = CombineState(speculativeDirectives.ExpectedWarningsState, sourceDirectives.ExpectedWarningsState); bool isNullableEnabledForProject = projectContext != null && (projectContext.Value & NullableContextOptions.Warnings) != 0; Microsoft.CodeAnalysis.NullableAnnotation expectedAnnotation = IsNullableEnabled(expectedWarningsState, isNullableEnabledForProject) ? Microsoft.CodeAnalysis.NullableAnnotation.NotAnnotated : Microsoft.CodeAnalysis.NullableAnnotation.None; VerifySpeculativeSemanticModel(source, projectContext, typeName, expectedAnnotation); } private static void VerifySpeculativeSemanticModel(string source, NullableContextOptions? projectContext, string typeName, Microsoft.CodeAnalysis.NullableAnnotation expectedAnnotation) { var options = TestOptions.ReleaseDll; if (projectContext != null) options = options.WithNullableContextOptions(projectContext.GetValueOrDefault()); var comp = CreateCompilation(source, options: options); var syntaxTree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(syntaxTree); var typeOf = syntaxTree.GetRoot().DescendantNodes().OfType<TypeOfExpressionSyntax>().Single(); var type = SyntaxFactory.ParseTypeName(typeName); Assert.True(model.TryGetSpeculativeSemanticModel(typeOf.Type.SpanStart, type, out model, SpeculativeBindingOption.BindAsTypeOrNamespace)); var typeInfo = model.GetTypeInfo(type); Assert.Equal(expectedAnnotation, typeInfo.Nullability.Annotation); } private static string[] GetNullableDataKeysAsStrings(CSharpCompilation.NullableData nullableData, bool requiredAnalysis = false) => nullableData.Data. Where(pair => !requiredAnalysis || pair.Value.RequiredAnalysis). Select(pair => GetNullableDataKeyAsString(pair.Key)). OrderBy(key => key). ToArray(); private static string[] GetIsNullableEnabledMethods(CSharpCompilation.NullableData nullableData, Func<object, string> toString = null) { toString ??= GetNullableDataKeyAsString; return nullableData.Data. Where(pair => pair.Value.RequiredAnalysis && pair.Key is MethodSymbol method && method.IsNullableAnalysisEnabled()). Select(pair => toString(pair.Key)). OrderBy(key => key). ToArray(); } private static string GetNullableDataKeyAsString(object key) => key is Symbol symbol ? symbol.MetadataName : ((SyntaxNode)key).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. #nullable disable using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Semantics { public class NullableContextTests : CSharpTestBase { [InlineData("#nullable enable", NullableContextOptions.Disable, NullableContext.Enabled)] [InlineData("#nullable enable", NullableContextOptions.Annotations, NullableContext.Enabled)] [InlineData("#nullable enable", NullableContextOptions.Warnings, NullableContext.Enabled)] [InlineData("#nullable enable", NullableContextOptions.Enable, NullableContext.Enabled)] [InlineData("#nullable enable warnings", NullableContextOptions.Disable, NullableContext.WarningsEnabled | NullableContext.AnnotationsContextInherited)] [InlineData("#nullable enable warnings", NullableContextOptions.Warnings, NullableContext.WarningsEnabled | NullableContext.AnnotationsContextInherited)] [InlineData("#nullable enable warnings", NullableContextOptions.Annotations, NullableContext.Enabled | NullableContext.AnnotationsContextInherited)] [InlineData("#nullable enable warnings", NullableContextOptions.Enable, NullableContext.Enabled | NullableContext.AnnotationsContextInherited)] [InlineData("#nullable enable annotations", NullableContextOptions.Disable, NullableContext.AnnotationsEnabled | NullableContext.WarningsContextInherited)] [InlineData("#nullable enable annotations", NullableContextOptions.Warnings, NullableContext.Enabled | NullableContext.WarningsContextInherited)] [InlineData("#nullable enable annotations", NullableContextOptions.Annotations, NullableContext.AnnotationsEnabled | NullableContext.WarningsContextInherited)] [InlineData("#nullable enable annotations", NullableContextOptions.Enable, NullableContext.Enabled | NullableContext.WarningsContextInherited)] [InlineData("#nullable disable", NullableContextOptions.Disable, NullableContext.Disabled)] [InlineData("#nullable disable", NullableContextOptions.Annotations, NullableContext.Disabled)] [InlineData("#nullable disable", NullableContextOptions.Warnings, NullableContext.Disabled)] [InlineData("#nullable disable", NullableContextOptions.Enable, NullableContext.Disabled)] [InlineData("#nullable disable warnings", NullableContextOptions.Disable, NullableContext.Disabled | NullableContext.AnnotationsContextInherited)] [InlineData("#nullable disable warnings", NullableContextOptions.Warnings, NullableContext.Disabled | NullableContext.AnnotationsContextInherited)] [InlineData("#nullable disable warnings", NullableContextOptions.Annotations, NullableContext.AnnotationsEnabled | NullableContext.AnnotationsContextInherited)] [InlineData("#nullable disable warnings", NullableContextOptions.Enable, NullableContext.AnnotationsEnabled | NullableContext.AnnotationsContextInherited)] [InlineData("#nullable disable annotations", NullableContextOptions.Disable, NullableContext.Disabled | NullableContext.WarningsContextInherited)] [InlineData("#nullable disable annotations", NullableContextOptions.Warnings, NullableContext.WarningsEnabled | NullableContext.WarningsContextInherited)] [InlineData("#nullable disable annotations", NullableContextOptions.Annotations, NullableContext.Disabled | NullableContext.WarningsContextInherited)] [InlineData("#nullable disable annotations", NullableContextOptions.Enable, NullableContext.WarningsEnabled | NullableContext.WarningsContextInherited)] [Theory] public void NullableContextExplicitlySpecifiedAndRestoredInFile(string pragma, NullableContextOptions globalContext, NullableContext expectedContext) { var source = $@" {pragma} class C {{ #nullable restore void M() {{}} }}"; var comp = CreateCompilation(source, options: WithNullable(globalContext)); var syntaxTree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(syntaxTree); var classDeclPosition = syntaxTree.GetRoot().DescendantNodes().OfType<ClassDeclarationSyntax>().Single().SpanStart; var methodDeclPosition = syntaxTree.GetRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().Single().SpanStart; Assert.Equal(expectedContext, model.GetNullableContext(classDeclPosition)); // The context at the start of the file should always be inherited and match the global context var restoredContext = ((NullableContext)globalContext) | NullableContext.ContextInherited; Assert.Equal(restoredContext, model.GetNullableContext(0)); Assert.Equal(restoredContext, model.GetNullableContext(methodDeclPosition)); } [Fact] public void NullableContextMultipleFiles() { var source1 = @" #nullable enable partial class C { void M1() {}; }"; var source2 = @" partial class C { #nullable enable void M2(); }"; var comp = CreateCompilation(new[] { source1, source2 }, options: WithNullableEnable()); var syntaxTree1 = comp.SyntaxTrees[0]; var model1 = comp.GetSemanticModel(syntaxTree1); var syntaxTree2 = comp.SyntaxTrees[1]; var model2 = comp.GetSemanticModel(syntaxTree2); var classDecl1 = syntaxTree1.GetRoot().DescendantNodes().OfType<ClassDeclarationSyntax>().Single().SpanStart; var classDecl2 = syntaxTree2.GetRoot().DescendantNodes().OfType<ClassDeclarationSyntax>().Single().SpanStart; Assert.Equal(NullableContext.Enabled, model1.GetNullableContext(classDecl1)); Assert.Equal(NullableContext.Enabled | NullableContext.ContextInherited, model2.GetNullableContext(classDecl2)); } [Fact] public void NullableContextOptionsFlags() { Assert.True(NullableContextOptions.Enable.AnnotationsEnabled()); Assert.True(NullableContextOptions.Enable.WarningsEnabled()); Assert.True(NullableContextOptions.Annotations.AnnotationsEnabled()); Assert.False(NullableContextOptions.Annotations.WarningsEnabled()); Assert.False(NullableContextOptions.Warnings.AnnotationsEnabled()); Assert.True(NullableContextOptions.Warnings.WarningsEnabled()); Assert.False(NullableContextOptions.Disable.AnnotationsEnabled()); Assert.False(NullableContextOptions.Disable.WarningsEnabled()); } [Fact] public void NullableContextFlags() { AssertEnabledForInheritance(NullableContext.Disabled, warningsEnabled: false, annotationsEnabled: false); AssertEnabledForInheritance(NullableContext.WarningsEnabled, warningsEnabled: true, annotationsEnabled: false); AssertEnabledForInheritance(NullableContext.AnnotationsEnabled, warningsEnabled: false, annotationsEnabled: true); AssertEnabledForInheritance(NullableContext.Enabled, warningsEnabled: true, annotationsEnabled: true); void AssertEnabledForInheritance(NullableContext context, bool warningsEnabled, bool annotationsEnabled) { Assert.Equal(warningsEnabled, context.WarningsEnabled()); Assert.Equal(annotationsEnabled, context.AnnotationsEnabled()); Assert.False(context.WarningsInherited()); Assert.False(context.AnnotationsInherited()); var warningsInherited = context | NullableContext.WarningsContextInherited; Assert.Equal(warningsEnabled, warningsInherited.WarningsEnabled()); Assert.Equal(annotationsEnabled, warningsInherited.AnnotationsEnabled()); Assert.True(warningsInherited.WarningsInherited()); Assert.False(warningsInherited.AnnotationsInherited()); var annotationsInherited = context | NullableContext.AnnotationsContextInherited; Assert.Equal(warningsEnabled, annotationsInherited.WarningsEnabled()); Assert.Equal(annotationsEnabled, annotationsInherited.AnnotationsEnabled()); Assert.False(annotationsInherited.WarningsInherited()); Assert.True(annotationsInherited.AnnotationsInherited()); var contextInherited = context | NullableContext.ContextInherited; Assert.Equal(warningsEnabled, contextInherited.WarningsEnabled()); Assert.Equal(annotationsEnabled, contextInherited.AnnotationsEnabled()); Assert.True(contextInherited.WarningsInherited()); Assert.True(contextInherited.AnnotationsInherited()); } } // See also CommandLineTests.NullableAnalysisFlags(). [Fact] public void NullableAnalysisFlags_01() { var source = @"#nullable enable class Program { const object? C1 = null; const object? C2 = null; #nullable enable static object F1() => C1; #nullable disable static object F2() => C2; }"; var expectedAnalyzedKeysAll = new[] { ".cctor", ".ctor", "F1", "F2" }; var expectedAnalyzedKeysDefault = #if DEBUG new[] { ".cctor", ".ctor", "F1", "F2" }; #else new[] { ".cctor", "F1" }; #endif verify(parseOptions: TestOptions.Regular, expectedAnalyzedKeysDefault); verify(parseOptions: TestOptions.Regular.WithFeature("run-nullable-analysis", null), expectedAnalyzedKeysDefault); verify(parseOptions: TestOptions.Regular.WithFeature("run-nullable-analysis", "always"), expectedAnalyzedKeysAll); verify(parseOptions: TestOptions.Regular.WithFeature("run-nullable-analysis", "never")); verify(parseOptions: TestOptions.Regular.WithFeature("run-nullable-analysis", "ALWAYS"), expectedAnalyzedKeysDefault); // unrecognized value (incorrect case) ignored verify(parseOptions: TestOptions.Regular.WithFeature("run-nullable-analysis", "NEVER"), expectedAnalyzedKeysDefault); // unrecognized value (incorrect case) ignored verify(parseOptions: TestOptions.Regular.WithFeature("run-nullable-analysis", "true"), expectedAnalyzedKeysDefault); // unrecognized value ignored verify(parseOptions: TestOptions.Regular.WithFeature("run-nullable-analysis", "false"), expectedAnalyzedKeysDefault); // unrecognized value ignored verify(parseOptions: TestOptions.Regular.WithFeature("run-nullable-analysis", "unknown"), expectedAnalyzedKeysDefault); // unrecognized value ignored void verify(CSharpParseOptions parseOptions, params string[] expectedAnalyzedKeys) { var comp = CreateCompilation(source, parseOptions: parseOptions); comp.NullableAnalysisData = new(); if (expectedAnalyzedKeys.Length > 0) { comp.VerifyDiagnostics( // (7,27): warning CS8603: Possible null reference return. // static object F1() => C1; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "C1").WithLocation(7, 27)); } else { comp.VerifyDiagnostics(); } var actualAnalyzedKeys = GetNullableDataKeysAsStrings(comp.NullableAnalysisData); AssertEx.Equal(expectedAnalyzedKeys, actualAnalyzedKeys); } } [Fact] public void NullableAnalysisFlags_02() { var source = @"#nullable enable class Program { const object? C1 = null; const object? C2 = null; #nullable enable static void F1(object obj = C1) { } #nullable disable static void F2(object obj = C2) { } }"; var expectedAnalyzedKeysAll = new[] { ".cctor", ".ctor", "= C1", "= C2", "F1", "F2" }; var expectedAnalyzedKeysDefault = #if DEBUG new[] { ".cctor", ".ctor", "= C1", "= C2", "F1", "F2" }; #else new[] { ".cctor", "= C1", "F1" }; #endif verify(parseOptions: TestOptions.Regular, expectedAnalyzedKeysDefault); verify(parseOptions: TestOptions.Regular.WithFeature("run-nullable-analysis", null), expectedAnalyzedKeysDefault); verify(parseOptions: TestOptions.Regular.WithFeature("run-nullable-analysis", "always"), expectedAnalyzedKeysAll); verify(parseOptions: TestOptions.Regular.WithFeature("run-nullable-analysis", "never")); void verify(CSharpParseOptions parseOptions, params string[] expectedAnalyzedKeys) { var comp = CreateCompilation(source, parseOptions: parseOptions); comp.NullableAnalysisData = new(); if (expectedAnalyzedKeys.Length > 0) { comp.VerifyDiagnostics( // (7,33): warning CS8625: Cannot convert null literal to non-nullable reference type. // static void F1(object obj = C1) { } Diagnostic(ErrorCode.WRN_NullAsNonNullable, "C1").WithLocation(7, 33)); } else { comp.VerifyDiagnostics(); } var actualAnalyzedKeys = GetNullableDataKeysAsStrings(comp.NullableAnalysisData); AssertEx.Equal(expectedAnalyzedKeys, actualAnalyzedKeys); } } [Fact] public void NullableAnalysisFlags_03() { var sourceA = @"#nullable enable public class A : System.Attribute { public A(object obj) { } public const object? C1 = null; public const object? C2 = null; }"; var refA = CreateCompilation(sourceA).EmitToImageReference(); var sourceB = @"#nullable enable [A(A.C1)] struct B1 { } #nullable disable [A(A.C2)] struct B2 { }"; var expectedAnalyzedKeysAll = new[] { ".cctor", ".cctor", "A(A.C1)", "A(A.C2)" }; var expectedAnalyzedKeysDefault = #if DEBUG new[] { ".cctor", ".cctor", "A(A.C1)", "A(A.C2)" }; #else new[] { "A(A.C1)" }; #endif verify(parseOptions: TestOptions.Regular, expectedAnalyzedKeysDefault); verify(parseOptions: TestOptions.Regular.WithFeature("run-nullable-analysis", null), expectedAnalyzedKeysDefault); verify(parseOptions: TestOptions.Regular.WithFeature("run-nullable-analysis", "always"), expectedAnalyzedKeysAll); verify(parseOptions: TestOptions.Regular.WithFeature("run-nullable-analysis", "never")); void verify(CSharpParseOptions parseOptions, params string[] expectedAnalyzedKeys) { var comp = CreateCompilation(sourceB, references: new[] { refA }, parseOptions: parseOptions); comp.NullableAnalysisData = new(); if (expectedAnalyzedKeys.Length > 0) { comp.VerifyDiagnostics( // (2,4): warning CS8625: Cannot convert null literal to non-nullable reference type. // [A(A.C1)] Diagnostic(ErrorCode.WRN_NullAsNonNullable, "A.C1").WithLocation(2, 4)); } else { comp.VerifyDiagnostics(); } var actualAnalyzedKeys = GetNullableDataKeysAsStrings(comp.NullableAnalysisData); AssertEx.Equal(expectedAnalyzedKeys, actualAnalyzedKeys); } } [Fact] public void NullableAnalysisFlags_MethodBodySemanticModel() { var source = @"#nullable enable class Program { static object F(object? obj) { if (obj == null) return null; return obj; } }"; var expectedAnalyzedKeysAll = new[] { "F" }; verify(parseOptions: TestOptions.Regular, expectedFlowState: true, expectedAnalyzedKeysAll); verify(parseOptions: TestOptions.Regular.WithFeature("run-nullable-analysis", null), expectedFlowState: true, expectedAnalyzedKeysAll); verify(parseOptions: TestOptions.Regular.WithFeature("run-nullable-analysis", "always"), expectedFlowState: true, expectedAnalyzedKeysAll); verify(parseOptions: TestOptions.Regular.WithFeature("run-nullable-analysis", "never"), expectedFlowState: false); void verify(CSharpParseOptions parseOptions, bool expectedFlowState, params string[] expectedAnalyzedKeys) { var comp = CreateCompilation(source, parseOptions: parseOptions); comp.NullableAnalysisData = new(); var syntaxTree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(syntaxTree); var syntax = syntaxTree.GetRoot().DescendantNodes().OfType<ReturnStatementSyntax>().Skip(1).Single(); Assert.Equal("return obj;", syntax.ToString()); var typeInfo = model.GetTypeInfo(syntax.Expression); var expectedNullability = expectedFlowState ? Microsoft.CodeAnalysis.NullableFlowState.NotNull : Microsoft.CodeAnalysis.NullableFlowState.None; Assert.Equal(expectedNullability, typeInfo.Nullability.FlowState); var actualAnalyzedKeys = GetNullableDataKeysAsStrings(comp.NullableAnalysisData); AssertEx.Equal(expectedAnalyzedKeys, actualAnalyzedKeys); } } [Fact] public void NullableAnalysisFlags_AttributeSemanticModel() { var source = @"#nullable enable class A : System.Attribute { public A(object obj) { } public static object F; } [A(A.F = null)] class B { }"; var expectedAnalyzedKeysAll = new[] { "A(A.F = null)" }; verify(parseOptions: TestOptions.Regular, expectedFlowState: true, expectedAnalyzedKeysAll); verify(parseOptions: TestOptions.Regular.WithFeature("run-nullable-analysis", null), expectedFlowState: true, expectedAnalyzedKeysAll); verify(parseOptions: TestOptions.Regular.WithFeature("run-nullable-analysis", "always"), expectedFlowState: true, expectedAnalyzedKeysAll); verify(parseOptions: TestOptions.Regular.WithFeature("run-nullable-analysis", "never"), expectedFlowState: false); void verify(CSharpParseOptions parseOptions, bool expectedFlowState, params string[] expectedAnalyzedKeys) { var comp = CreateCompilation(source, parseOptions: parseOptions); comp.NullableAnalysisData = new(); var syntaxTree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(syntaxTree); var syntax = syntaxTree.GetRoot().DescendantNodes().OfType<AttributeArgumentSyntax>().Single(); Assert.Equal("A.F = null", syntax.ToString()); var typeInfo = model.GetTypeInfo(syntax.Expression); var expectedNullability = expectedFlowState ? Microsoft.CodeAnalysis.NullableFlowState.MaybeNull : Microsoft.CodeAnalysis.NullableFlowState.None; Assert.Equal(expectedNullability, typeInfo.Nullability.FlowState); var actualAnalyzedKeys = GetNullableDataKeysAsStrings(comp.NullableAnalysisData); AssertEx.Equal(expectedAnalyzedKeys, actualAnalyzedKeys); } } [Fact] public void NullableAnalysisFlags_InitializerSemanticModel() { var source = @"#nullable enable class Program { static object F; static void M(object arg = (F = null)) { } }"; var expectedAnalyzedKeysAll = new[] { "arg" }; verify(parseOptions: TestOptions.Regular, expectedFlowState: true, expectedAnalyzedKeysAll); verify(parseOptions: TestOptions.Regular.WithFeature("run-nullable-analysis", null), expectedFlowState: true, expectedAnalyzedKeysAll); verify(parseOptions: TestOptions.Regular.WithFeature("run-nullable-analysis", "always"), expectedFlowState: true, expectedAnalyzedKeysAll); verify(parseOptions: TestOptions.Regular.WithFeature("run-nullable-analysis", "never"), expectedFlowState: false); void verify(CSharpParseOptions parseOptions, bool expectedFlowState, params string[] expectedAnalyzedKeys) { var comp = CreateCompilation(source, parseOptions: parseOptions); comp.NullableAnalysisData = new(); var syntaxTree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(syntaxTree); var syntax = syntaxTree.GetRoot().DescendantNodes().OfType<EqualsValueClauseSyntax>().First().Value; Assert.Equal("(F = null)", syntax.ToString()); var typeInfo = model.GetTypeInfo(syntax); var expectedNullability = expectedFlowState ? Microsoft.CodeAnalysis.NullableFlowState.MaybeNull : Microsoft.CodeAnalysis.NullableFlowState.None; Assert.Equal(expectedNullability, typeInfo.Nullability.FlowState); var actualAnalyzedKeys = GetNullableDataKeysAsStrings(comp.NullableAnalysisData); AssertEx.Equal(expectedAnalyzedKeys, actualAnalyzedKeys); } } public readonly struct NullableDirectives { internal readonly string[] Directives; internal readonly NullableContextState.State ExpectedWarningsState; internal readonly NullableContextState.State ExpectedAnnotationsState; internal NullableDirectives(string[] directives, NullableContextState.State expectedWarningsState, NullableContextState.State expectedAnnotationsState) { Directives = directives; ExpectedWarningsState = expectedWarningsState; ExpectedAnnotationsState = expectedAnnotationsState; } public override string ToString() { var builder = new StringBuilder(); foreach (var str in Directives) builder.AppendLine(str); return builder.ToString(); } } private static readonly NullableDirectives[] s_nullableDirectives = new[] { new NullableDirectives(new string[0], NullableContextState.State.Unknown, NullableContextState.State.Unknown), new NullableDirectives(new[] { "#nullable disable" }, NullableContextState.State.Disabled, NullableContextState.State.Disabled), new NullableDirectives(new[] { "#nullable enable" }, NullableContextState.State.Enabled, NullableContextState.State.Enabled), new NullableDirectives(new[] { "#nullable restore" }, NullableContextState.State.ExplicitlyRestored, NullableContextState.State.ExplicitlyRestored), new NullableDirectives(new[] { "#nullable disable annotations" }, NullableContextState.State.Unknown, NullableContextState.State.Disabled), new NullableDirectives(new[] { "#nullable enable warnings", "#nullable disable annotations", }, NullableContextState.State.Enabled, NullableContextState.State.Disabled), new NullableDirectives(new[] { "#nullable restore warnings", "#nullable disable annotations" }, NullableContextState.State.ExplicitlyRestored, NullableContextState.State.Disabled), new NullableDirectives(new[] { "#nullable enable annotations" }, NullableContextState.State.Unknown, NullableContextState.State.Enabled), new NullableDirectives(new[] { "#nullable disable warnings", "#nullable enable annotations" }, NullableContextState.State.Disabled, NullableContextState.State.Enabled), new NullableDirectives(new[] { "#nullable restore warnings", "#nullable enable annotations" }, NullableContextState.State.ExplicitlyRestored, NullableContextState.State.Enabled), new NullableDirectives(new[] { "#nullable restore annotations" }, NullableContextState.State.Unknown, NullableContextState.State.ExplicitlyRestored), new NullableDirectives(new[] { "#nullable enable warnings" , "#nullable restore annotations" }, NullableContextState.State.Enabled, NullableContextState.State.ExplicitlyRestored), new NullableDirectives(new[] { "#nullable disable warnings", "#nullable restore annotations" }, NullableContextState.State.Disabled, NullableContextState.State.ExplicitlyRestored), new NullableDirectives(new[] { "#nullable disable warnings" }, NullableContextState.State.Disabled, NullableContextState.State.Unknown), new NullableDirectives(new[] { "#nullable enable warnings" }, NullableContextState.State.Enabled, NullableContextState.State.Unknown), new NullableDirectives(new[] { "#nullable restore warnings" }, NullableContextState.State.ExplicitlyRestored, NullableContextState.State.Unknown), }; // AnalyzeMethodsInEnabledContextOnly_01_Data is split due to https://github.com/dotnet/roslyn/issues/50337 public static IEnumerable<object[]> AnalyzeMethodsInEnabledContextOnly_01_Data1() { var projectSettings = new[] { (NullableContextOptions?)null, NullableContextOptions.Disable, }; foreach (var projectSetting in projectSettings) { foreach (var classDirectives in s_nullableDirectives) { foreach (var methodDirectives in s_nullableDirectives) { yield return new object[] { projectSetting, classDirectives, methodDirectives }; } } } } public static IEnumerable<object[]> AnalyzeMethodsInEnabledContextOnly_01_Data2() { var projectSettings = new[] { NullableContextOptions.Warnings, NullableContextOptions.Annotations, NullableContextOptions.Enable, }; foreach (var projectSetting in projectSettings) { foreach (var classDirectives in s_nullableDirectives) { foreach (var methodDirectives in s_nullableDirectives) { yield return new object[] { projectSetting, classDirectives, methodDirectives }; } } } } [Theory] [MemberData(nameof(AnalyzeMethodsInEnabledContextOnly_01_Data1))] [WorkItem(49746, "https://github.com/dotnet/roslyn/issues/49746")] public void AnalyzeMethodsInEnabledContextOnly_01A(NullableContextOptions? projectContext, NullableDirectives classDirectives, NullableDirectives methodDirectives) { AnalyzeMethodsInEnabledContextOnly_01_Execute(projectContext, classDirectives, methodDirectives); } [Theory] [MemberData(nameof(AnalyzeMethodsInEnabledContextOnly_01_Data2))] [WorkItem(49746, "https://github.com/dotnet/roslyn/issues/49746")] public void AnalyzeMethodsInEnabledContextOnly_01B(NullableContextOptions? projectContext, NullableDirectives classDirectives, NullableDirectives methodDirectives) { AnalyzeMethodsInEnabledContextOnly_01_Execute(projectContext, classDirectives, methodDirectives); } private static void AnalyzeMethodsInEnabledContextOnly_01_Execute(NullableContextOptions? projectContext, NullableDirectives classDirectives, NullableDirectives methodDirectives) { var sourceA = @"#nullable enable public class A { public static void M(object obj) { } }"; var refA = CreateCompilation(sourceA).EmitToImageReference(); var sourceB = $@"{classDirectives} static class B {{ {methodDirectives} static void Main() {{ A.M(null); }} }}"; var expectedWarningsStateForMethod = CombineState(methodDirectives.ExpectedWarningsState, classDirectives.ExpectedWarningsState); var expectedAnnotationsStateForMethod = CombineState(methodDirectives.ExpectedAnnotationsState, classDirectives.ExpectedAnnotationsState); bool isNullableEnabledForProject = projectContext != null && (projectContext.Value & NullableContextOptions.Warnings) != 0; bool isNullableEnabledForMethod = IsNullableEnabled(expectedWarningsStateForMethod, isNullableEnabledForProject); var options = TestOptions.ReleaseDll; if (projectContext != null) options = options.WithNullableContextOptions(projectContext.Value); var comp = CreateCompilation(sourceB, options: options, references: new[] { refA }); comp.NullableAnalysisData = new(); if (isNullableEnabledForMethod) { comp.VerifyDiagnostics( // (4,30): warning CS8625: Cannot convert null literal to non-nullable reference type. // static void Main() { A.M(null); } Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null")); } else { comp.VerifyDiagnostics(); } var actualAnalyzedKeys = GetNullableDataKeysAsStrings(comp.NullableAnalysisData, requiredAnalysis: true); Assert.Equal(isNullableEnabledForMethod, actualAnalyzedKeys.Contains("Main")); var tree = (CSharpSyntaxTree)comp.SyntaxTrees[0]; var syntaxNodes = tree.GetRoot().DescendantNodes(); verifyContextState(tree, syntaxNodes.OfType<ClassDeclarationSyntax>().Single(), classDirectives.ExpectedWarningsState, classDirectives.ExpectedAnnotationsState); verifyContextState(tree, syntaxNodes.OfType<MethodDeclarationSyntax>().Single(), expectedWarningsStateForMethod, expectedAnnotationsStateForMethod); static void verifyContextState(CSharpSyntaxTree tree, CSharpSyntaxNode syntax, NullableContextState.State expectedWarningsState, NullableContextState.State expectedAnnotationsState) { var actualState = tree.GetNullableContextState(syntax.SpanStart); Assert.Equal(expectedWarningsState, actualState.WarningsState); Assert.Equal(expectedAnnotationsState, actualState.AnnotationsState); } } private static NullableContextState.State CombineState(NullableContextState.State currentState, NullableContextState.State previousState) { return currentState == NullableContextState.State.Unknown ? previousState : currentState; } private static bool IsNullableEnabled(NullableContextState.State state, bool isNullableEnabledForProject) { return state switch { NullableContextState.State.Enabled => true, NullableContextState.State.Disabled => false, _ => isNullableEnabledForProject, }; } [Fact] [WorkItem(49746, "https://github.com/dotnet/roslyn/issues/49746")] public void AnalyzeMethodsInEnabledContextOnly_02() { var source = @"#pragma warning disable 219 static class Program { #nullable disable static void M1 #nullable enable () { object obj = null; } }"; verify(source, expectedAnalyzedKeys: new[] { "M1" }, // (9,22): warning CS8600: Converting null literal or possible null value to non-nullable type. // object obj = null; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(9, 22)); source = @"#pragma warning disable 219 static class Program { #nullable disable static void M2() #nullable enable { object obj = null; } }"; verify(source, expectedAnalyzedKeys: new[] { "M2" }, // (8,22): warning CS8600: Converting null literal or possible null value to non-nullable type. // object obj = null; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(8, 22)); source = @"#pragma warning disable 219 static class Program { #nullable disable static void M3() { #nullable enable object obj = null; } }"; verify(source, expectedAnalyzedKeys: new[] { "M3" }, // (8,22): warning CS8600: Converting null literal or possible null value to non-nullable type. // object obj = null; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(8, 22)); source = @"#pragma warning disable 219 static class Program { #nullable disable static void M4() { #nullable disable object obj = null; } #nullable enable }"; verify(source, expectedAnalyzedKeys: new string[0]); source = @"#pragma warning disable 219 static class Program { #nullable enable static void M5 #nullable disable () { object obj = null; } }"; verify(source, expectedAnalyzedKeys: new[] { "M5" }); source = @"#pragma warning disable 219 static class Program { static void M6 #nullable enable () #nullable disable { object obj = null; } }"; verify(source, expectedAnalyzedKeys: new[] { "M6" }); source = @"static class Program { static object M7() #nullable enable => default(object); }"; verify(source, expectedAnalyzedKeys: new[] { "M7" }); source = @"static class Program { #nullable disable static object M8() => default( #nullable enable object); }"; verify(source, expectedAnalyzedKeys: new[] { "M8" }); static void verify(string source, string[] expectedAnalyzedKeys, params DiagnosticDescription[] expectedDiagnostics) { var comp = CreateCompilation(source); comp.NullableAnalysisData = new(); comp.VerifyDiagnostics(expectedDiagnostics); AssertEx.Equal(expectedAnalyzedKeys, GetNullableDataKeysAsStrings(comp.NullableAnalysisData, requiredAnalysis: true)); AssertEx.Equal(expectedAnalyzedKeys, GetIsNullableEnabledMethods(comp.NullableAnalysisData)); var tree = (CSharpSyntaxTree)comp.SyntaxTrees[0]; var methodDeclarations = tree.GetRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().ToArray(); foreach (var methodDeclaration in methodDeclarations) { bool expectedAnalysis = expectedAnalyzedKeys.Contains(methodDeclaration.Identifier.Text); bool actualAnalysis = tree.IsNullableAnalysisEnabled(methodDeclaration.Span).Value; Assert.Equal(expectedAnalysis, actualAnalysis); } } } [Fact] [WorkItem(49746, "https://github.com/dotnet/roslyn/issues/49746")] public void AnalyzeMethodsInEnabledContextOnly_03() { var source = @"class Program { Program(object o) { o = null; } } #nullable enable "; verify(source, expectedAnalyzedKeys: new string[0]); source = @"#nullable enable #nullable disable class Program { Program(object o) { o = null; } }"; verify(source, expectedAnalyzedKeys: new string[0]); source = @"class Program { Program(object o) { o = null; } #nullable enable }"; verify(source, expectedAnalyzedKeys: new string[0]); source = @"#pragma warning disable 414 class Program { #nullable disable object F1 = null; #nullable enable }"; verify(source, expectedAnalyzedKeys: new string[0]); source = @"#pragma warning disable 414 class Program { #nullable disable object F1 = null; #nullable enable static object F2 = null; }"; verify(source, expectedAnalyzedKeys: new[] { ".cctor" }, // (7,24): warning CS8625: Cannot convert null literal to non-nullable reference type. // static object F2 = null; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(7, 24)); source = @"#pragma warning disable 414 class Program { #nullable enable object F1 = null; #nullable disable static object F2 = null; }"; verify(source, expectedAnalyzedKeys: new[] { ".ctor" }, // (5,17): warning CS8625: Cannot convert null literal to non-nullable reference type. // object F1 = null; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(5, 17)); source = @"#pragma warning disable 414 static class Program { #nullable disable static object F1 = null; #nullable enable static Program() { F1 = null; } }"; verify(source, expectedAnalyzedKeys: new[] { ".cctor" }); source = @"#pragma warning disable 414 static class Program { #nullable enable static object F1 = null; #nullable disable static Program() { F1 = null; } }"; verify(source, expectedAnalyzedKeys: new[] { ".cctor" }, // (5,24): warning CS8625: Cannot convert null literal to non-nullable reference type. // static object F1 = null; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(5, 24)); source = @"#pragma warning disable 414 class Program { #nullable disable object F1 = null; #nullable enable Program() { F1 = null; } }"; verify(source, expectedAnalyzedKeys: new[] { ".ctor" }); source = @"#pragma warning disable 414 class Program { #nullable enable object F1 = null; #nullable disable Program() { F1 = null; } }"; verify(source, expectedAnalyzedKeys: new[] { ".ctor" }, // (5,17): warning CS8625: Cannot convert null literal to non-nullable reference type. // object F1 = null; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(5, 17)); source = @"#pragma warning disable 414 class Program { #nullable enable object F1 = null; #nullable disable object F2 = null; #nullable enable object F3 = null; }"; verify(source, expectedAnalyzedKeys: new[] { ".ctor" }, // (5,17): warning CS8625: Cannot convert null literal to non-nullable reference type. // object F1 = null; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(5, 17), // (9,17): warning CS8625: Cannot convert null literal to non-nullable reference type. // object F3 = null; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(9, 17)); source = @"#pragma warning disable 414 class Program { #nullable disable object F1 = null; #nullable enable object F2() => null; #nullable disable object F3 = null; }"; verify(source, expectedAnalyzedKeys: new[] { "F2" }, // (7,20): warning CS8603: Possible null reference return. // object F2() => null; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "null").WithLocation(7, 20)); source = @"#pragma warning disable 169 class Program { #nullable enable object F1; #nullable disable Program() { } Program(object obj) : base() { } }"; verify(source, expectedAnalyzedKeys: new[] { ".ctor", ".ctor" }); source = @"#pragma warning disable 169 class Program { #nullable enable object F1; #nullable disable Program() { } Program(object obj) : this() { } }"; verify(source, expectedAnalyzedKeys: new[] { ".ctor" }); source = @"#pragma warning disable 169 class Program { #nullable enable object F1; #nullable disable Program() { } #nullable enable Program(object obj) : this() { } }"; verify(source, expectedAnalyzedKeys: new[] { ".ctor", ".ctor" }); source = @"#pragma warning disable 169 class Program { #nullable disable object F1; Program() { } #nullable enable Program(object obj) : this() { } }"; verify(source, expectedAnalyzedKeys: new[] { ".ctor" }); source = @"#pragma warning disable 169 class Program { #nullable disable object F1; #nullable enable Program() { } #nullable disable Program(object obj) : this() { } }"; verify(source, expectedAnalyzedKeys: new[] { ".ctor" }); source = @"#pragma warning disable 169 struct S { #nullable enable object F1; S(object obj) : this() { } }"; verify(source, expectedAnalyzedKeys: new[] { ".ctor" }, // (6,5): warning CS8618: Non-nullable field 'F1' must contain a non-null value when exiting constructor. Consider declaring the field as nullable. // S(object obj) : this() { } Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "S").WithArguments("field", "F1").WithLocation(6, 5) ); source = @"#pragma warning disable 169 struct S { #nullable enable object F1; #nullable disable S(object obj) : this() { } }"; verify(source, expectedAnalyzedKeys: new string[0]); static void verify(string source, string[] expectedAnalyzedKeys, params DiagnosticDescription[] expectedDiagnostics) { var comp = CreateCompilation(source); comp.NullableAnalysisData = new(); comp.VerifyDiagnostics(expectedDiagnostics); AssertEx.Equal(expectedAnalyzedKeys, GetNullableDataKeysAsStrings(comp.NullableAnalysisData, requiredAnalysis: true)); AssertEx.Equal(expectedAnalyzedKeys, GetIsNullableEnabledMethods(comp.NullableAnalysisData)); } } [Fact] [WorkItem(49746, "https://github.com/dotnet/roslyn/issues/49746")] public void AnalyzeMethodsInEnabledContextOnly_04() { var source1 = @"#pragma warning disable 414 partial class Program { object F1 = null; }"; var source2 = @"#pragma warning disable 414 partial class Program { #nullable disable object F2 = null; }"; var source3 = @"#pragma warning disable 414 partial class Program { #nullable enable object F3 = null; }"; var source4 = @"#pragma warning disable 414 partial class Program { #nullable restore object F4 = null; }"; var options = TestOptions.ReleaseDll.WithNullableContextOptions(NullableContextOptions.Disable); verify(new[] { source1, source2 }, options, new string[0]); verify(new[] { source1, source3 }, options, new[] { ".ctor" }, // (5,17): warning CS8625: Cannot convert null literal to non-nullable reference type. // object F3 = null; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(5, 17)); verify(new[] { source1, source4 }, options, new string[0]); verify(new[] { source2, source3 }, options, new[] { ".ctor" }, // (5,17): warning CS8625: Cannot convert null literal to non-nullable reference type. // object F3 = null; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(5, 17)); verify(new[] { source2, source4 }, options, new string[0]); verify(new[] { source3, source4 }, options, new[] { ".ctor" }, // (5,17): warning CS8625: Cannot convert null literal to non-nullable reference type. // object F3 = null; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(5, 17)); verify(new[] { source1, source2, source3, source4 }, options, new[] { ".ctor" }, // (5,17): warning CS8625: Cannot convert null literal to non-nullable reference type. // object F3 = null; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(5, 17)); verify(new[] { source1, source2, source3, source4 }, TestOptions.ReleaseDll.WithNullableContextOptions(NullableContextOptions.Enable), new[] { ".ctor" }, // (4,17): warning CS8625: Cannot convert null literal to non-nullable reference type. // object F1 = null; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(4, 17), // (5,17): warning CS8625: Cannot convert null literal to non-nullable reference type. // object F3 = null; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(5, 17), // (5,17): warning CS8625: Cannot convert null literal to non-nullable reference type. // object F4 = null; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(5, 17)); static void verify(string[] source, CSharpCompilationOptions options, string[] expectedAnalyzedKeys, params DiagnosticDescription[] expectedDiagnostics) { var comp = CreateCompilation(source, options: options); comp.NullableAnalysisData = new(); comp.VerifyDiagnostics(expectedDiagnostics); AssertEx.Equal(expectedAnalyzedKeys, GetNullableDataKeysAsStrings(comp.NullableAnalysisData, requiredAnalysis: true)); AssertEx.Equal(expectedAnalyzedKeys, GetIsNullableEnabledMethods(comp.NullableAnalysisData)); } } [Fact] [WorkItem(49746, "https://github.com/dotnet/roslyn/issues/49746")] public void AnalyzeMethodsInEnabledContextOnly_05() { var source = @"class Program { #nullable disable object P1 { get; set; } #nullable enable static object P2 { get; set; } }"; verify(source, expectedAnalyzedKeys: new[] { ".cctor" }, // (6,19): warning CS8618: Non-nullable property 'P2' must contain a non-null value when exiting constructor. Consider declaring the property as nullable. // static object P2 { get; set; } Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "P2").WithArguments("property", "P2").WithLocation(6, 19)); source = @"class Program { #nullable enable object P1 { get; set; } #nullable disable static object P2 { get; set; } }"; verify(source, expectedAnalyzedKeys: new[] { ".ctor" }, // (4,12): warning CS8618: Non-nullable property 'P1' must contain a non-null value when exiting constructor. Consider declaring the property as nullable. // object P1 { get; set; } Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "P1").WithArguments("property", "P1").WithLocation(4, 12)); source = @"class Program { #nullable enable object P1 { get; } object P2 { get { return 2; } set { } } object P3 => 3; }"; verify(source, expectedAnalyzedKeys: new[] { ".ctor", "get_P2", "get_P3", "set_P2" }, // (4,12): warning CS8618: Non-nullable property 'P1' must contain a non-null value when exiting constructor. Consider declaring the property as nullable. // object P1 { get; } Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "P1").WithArguments("property", "P1").WithLocation(4, 12)); source = @"#pragma warning disable 67 delegate void D(); class Program { #nullable disable event D E1; #nullable enable static event D E2; }"; verify(source, expectedAnalyzedKeys: new[] { ".cctor" }, // (8,20): warning CS8618: Non-nullable event 'E2' must contain a non-null value when exiting constructor. Consider declaring the event as nullable. // static event D E2; Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "E2").WithArguments("event", "E2").WithLocation(8, 20)); source = @"#pragma warning disable 67 delegate void D(); class Program { #nullable enable event D E1; #nullable disable static event D E2; }"; verify(source, expectedAnalyzedKeys: new[] { ".ctor" }, // (6,13): warning CS8618: Non-nullable event 'E1' must contain a non-null value when exiting constructor. Consider declaring the event as nullable. // event D E1; Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "E1").WithArguments("event", "E1").WithLocation(6, 13)); static void verify(string source, string[] expectedAnalyzedKeys, params DiagnosticDescription[] expectedDiagnostics) { var comp = CreateCompilation(source); comp.NullableAnalysisData = new(); comp.VerifyDiagnostics(expectedDiagnostics); AssertEx.Equal(expectedAnalyzedKeys, GetNullableDataKeysAsStrings(comp.NullableAnalysisData, requiredAnalysis: true)); AssertEx.Equal(expectedAnalyzedKeys, GetIsNullableEnabledMethods(comp.NullableAnalysisData)); } } [Fact] [WorkItem(49746, "https://github.com/dotnet/roslyn/issues/49746")] public void AnalyzeMethodsInEnabledContextOnly_06() { var source = @"#pragma warning disable 414 class Program { #nullable enable object F = 1; #nullable disable ~Program() { F = null; } }"; verify(source, expectedAnalyzedKeys: new[] { ".ctor" }); source = @"#pragma warning disable 414 class Program { #nullable disable object F = 1; #nullable enable ~Program() { F = null; } }"; verify(source, expectedAnalyzedKeys: new[] { "Finalize" }); source = @"#pragma warning disable 414 class Program { #nullable enable object F = 1; ~Program() { F = null; } }"; verify(source, expectedAnalyzedKeys: new[] { ".ctor", "Finalize" }, // (8,13): warning CS8625: Cannot convert null literal to non-nullable reference type. // F = null; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(8, 13)); static void verify(string source, string[] expectedAnalyzedKeys, params DiagnosticDescription[] expectedDiagnostics) { var comp = CreateCompilation(source); comp.NullableAnalysisData = new(); comp.VerifyDiagnostics(expectedDiagnostics); AssertEx.Equal(expectedAnalyzedKeys, GetNullableDataKeysAsStrings(comp.NullableAnalysisData, requiredAnalysis: true)); AssertEx.Equal(expectedAnalyzedKeys, GetIsNullableEnabledMethods(comp.NullableAnalysisData)); } } [Fact] [WorkItem(49746, "https://github.com/dotnet/roslyn/issues/49746")] public void AnalyzeMethodsInEnabledContextOnly_07() { var source = @"class Program { #nullable enable object P #nullable disable #nullable enable => null; object Q #nullable disable => null; }"; verify(source, expectedAnalyzedKeys: new[] { "get_P" }, // (7,12): warning CS8603: Possible null reference return. // => null; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "null").WithLocation(7, 12)); source = @"class Program { #nullable enable object P { get { return null; } #nullable disable set { value = null; } } #nullable enable object Q { #nullable disable get => null; #nullable enable set => value = null; } }"; verify(source, expectedAnalyzedKeys: new[] { "get_P", "set_Q" }, // (6,22): warning CS8603: Possible null reference return. // get { return null; } Diagnostic(ErrorCode.WRN_NullReferenceReturn, "null").WithLocation(6, 22), // (16,24): warning CS8600: Converting null literal or possible null value to non-nullable type. // set => value = null; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(16, 24)); source = @"#pragma warning disable 414 delegate void D(); class Program { #nullable enable D _e = null!; D _f = null!; #nullable disable event D E { #nullable enable add { _e = null; } #nullable disable remove { _e = null; } } event D F { #nullable disable add => _f = null; #nullable enable remove => _f = null; } }"; verify(source, expectedAnalyzedKeys: new[] { ".ctor", "add_E", "remove_F" }, // (12,20): warning CS8625: Cannot convert null literal to non-nullable reference type. // add { _e = null; } Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(12, 20), // (21,24): warning CS8625: Cannot convert null literal to non-nullable reference type. // remove => _f = null; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(21, 24)); static void verify(string source, string[] expectedAnalyzedKeys, params DiagnosticDescription[] expectedDiagnostics) { var comp = CreateCompilation(source); comp.NullableAnalysisData = new(); comp.VerifyDiagnostics(expectedDiagnostics); AssertEx.Equal(expectedAnalyzedKeys, GetNullableDataKeysAsStrings(comp.NullableAnalysisData, requiredAnalysis: true)); AssertEx.Equal(expectedAnalyzedKeys, GetIsNullableEnabledMethods(comp.NullableAnalysisData)); } } [Fact] [WorkItem(49746, "https://github.com/dotnet/roslyn/issues/49746")] public void AnalyzeMethodsInEnabledContextOnly_08() { var source = @"class A { } class B { public static explicit operator B(A a) => null; }"; verify(source, expectedAnalyzedKeys: new string[0]); source = @"class A { } class B { #nullable enable public static explicit operator B(A a) => null; }"; verify(source, expectedAnalyzedKeys: new[] { "op_Explicit" }, // (7,47): warning CS8603: Possible null reference return. // public static explicit operator B(A a) => null; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "null").WithLocation(7, 47)); source = @"class C { public static C operator~(C c) => null; }"; verify(source, expectedAnalyzedKeys: new string[0]); source = @"class C { #nullable enable public static C operator~(C c) => null; }"; verify(source, expectedAnalyzedKeys: new[] { "op_OnesComplement" }, // (4,39): warning CS8603: Possible null reference return. // public static C operator~(C c) => null; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "null").WithLocation(4, 39)); static void verify(string source, string[] expectedAnalyzedKeys, params DiagnosticDescription[] expectedDiagnostics) { var comp = CreateCompilation(source); comp.NullableAnalysisData = new(); comp.VerifyDiagnostics(expectedDiagnostics); AssertEx.Equal(expectedAnalyzedKeys, GetNullableDataKeysAsStrings(comp.NullableAnalysisData, requiredAnalysis: true)); AssertEx.Equal(expectedAnalyzedKeys, GetIsNullableEnabledMethods(comp.NullableAnalysisData)); } } [Fact] [WorkItem(49746, "https://github.com/dotnet/roslyn/issues/49746")] public void AnalyzeMethodsInEnabledContextOnly_09() { var source = @"#nullable enable record R; "; verify(source, expectedAnalyzedKeys: new string[0]); source = @"#nullable enable record R(); "; verify(source, expectedAnalyzedKeys: new[] { "R..ctor()" }); source = @"record R(object P #nullable enable ); "; verify(source, expectedAnalyzedKeys: new[] { "R..ctor(System.Object P)" }); source = @"record A; #nullable disable record B0 : A #nullable enable { } #nullable disable record B1() : A #nullable enable { } #nullable disable record B2() : A #nullable enable (); "; verify(source, expectedAnalyzedKeys: new[] { "B2..ctor()" }); source = @"record A; #nullable disable record B0 #nullable enable : #nullable disable A; #nullable disable record B1 : #nullable enable A #nullable disable ; #nullable disable record B2() : #nullable enable A #nullable disable (); "; verify(source, expectedAnalyzedKeys: new string[0]); source = @"record A(object P) { #nullable enable internal static object F(object obj) => obj; #nullable disable } #nullable disable record B1() : A( F(null)); record B2() : A( #nullable enable F(null)); "; verify(source, expectedAnalyzedKeys: new[] { "B2..ctor()", "System.Object A.F(System.Object obj)" }, // (12,7): warning CS8625: Cannot convert null literal to non-nullable reference type. // F(null)); Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(12, 7)); static void verify(string source, string[] expectedAnalyzedKeys, params DiagnosticDescription[] expectedDiagnostics) { var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }); comp.NullableAnalysisData = new(); comp.VerifyDiagnostics(expectedDiagnostics); var actualAnalyzedKeys = GetIsNullableEnabledMethods(comp.NullableAnalysisData, key => ((MethodSymbol)key).ToTestDisplayString()); AssertEx.Equal(expectedAnalyzedKeys, actualAnalyzedKeys); } } [Fact] [WorkItem(49746, "https://github.com/dotnet/roslyn/issues/49746")] public void AnalyzeMethodsInEnabledContextOnly_10() { var source1 = @"partial class Program { #nullable enable partial void F1(ref object o1) { o1 = null; } partial void F2(ref object o2); #nullable disable partial void F3(ref object o3) { o3 = null; } partial void F4(ref object o4); }"; var source2 = @"partial class Program { #nullable disable partial void F1(ref object o1); partial void F2(ref object o2) { o2 = null; } #nullable enable partial void F3(ref object o3); partial void F4(ref object o4) { o4 = null; } }"; var comp = CreateCompilation(new[] { source1, source2 }); comp.NullableAnalysisData = new(); comp.VerifyDiagnostics( // (4,43): warning CS8625: Cannot convert null literal to non-nullable reference type. // partial void F1(ref object o1) { o1 = null; } Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(4, 43), // (8,43): warning CS8625: Cannot convert null literal to non-nullable reference type. // partial void F4(ref object o4) { o4 = null; } Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(8, 43)); var expectedAnalyzedKeys = new[] { "F1", "F4" }; AssertEx.Equal(expectedAnalyzedKeys, GetNullableDataKeysAsStrings(comp.NullableAnalysisData, requiredAnalysis: true)); AssertEx.Equal(expectedAnalyzedKeys, GetIsNullableEnabledMethods(comp.NullableAnalysisData)); } [Fact] [WorkItem(49746, "https://github.com/dotnet/roslyn/issues/49746")] public void AnalyzeMethodsInEnabledContextOnly_11() { var source = @"partial class Program { #nullable enable partial void F1(object x = null); partial void F2(object y = null) { } #nullable disable partial void F1(object x = null) { } partial void F2(object y = null); }"; var comp = CreateCompilation(source); comp.NullableAnalysisData = new(); comp.VerifyDiagnostics( // (4,32): warning CS8625: Cannot convert null literal to non-nullable reference type. // partial void F1(object x = null); Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(4, 32), // (5,28): warning CS1066: The default value specified for parameter 'y' will have no effect because it applies to a member that is used in contexts that do not allow optional arguments // partial void F2(object y = null) { } Diagnostic(ErrorCode.WRN_DefaultValueForUnconsumedLocation, "y").WithArguments("y").WithLocation(5, 28), // (5,32): warning CS8625: Cannot convert null literal to non-nullable reference type. // partial void F2(object y = null) { } Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(5, 32), // (7,28): warning CS1066: The default value specified for parameter 'x' will have no effect because it applies to a member that is used in contexts that do not allow optional arguments // partial void F1(object x = null) { } Diagnostic(ErrorCode.WRN_DefaultValueForUnconsumedLocation, "x").WithArguments("x").WithLocation(7, 28)); var actualAnalyzedKeys = GetNullableDataKeysAsStrings(comp.NullableAnalysisData, requiredAnalysis: true); AssertEx.Equal(new[] { "= null", "= null", "F2" }, actualAnalyzedKeys); } [Fact] [WorkItem(49746, "https://github.com/dotnet/roslyn/issues/49746")] public void AnalyzeMethodsInEnabledContextOnly_12() { var source = @"using System.Runtime.InteropServices; class Program { #nullable enable const object? C1 = null; const object? C2 = null; const object? C3 = null; const object? C4 = null; #nullable disable static void F1( [DefaultParameterValue( #nullable enable C1 #nullable disable )] [A] object x) { } static void F2( #nullable enable [DefaultParameterValue(C2)] #nullable disable [A] object x) { } #nullable disable static void F3( [DefaultParameterValue(C3)] #nullable enable [A] object x #nullable disable ) { } static void F4( [DefaultParameterValue(C4)] [A] object x) #nullable enable #nullable disable { } } class A : System.Attribute { }"; var comp = CreateCompilation(source); comp.NullableAnalysisData = new(); comp.VerifyDiagnostics(); var actualAnalyzedKeys = GetNullableDataKeysAsStrings(comp.NullableAnalysisData, requiredAnalysis: true); var expectedAnalyzedKeys = new[] { ".cctor", @"[DefaultParameterValue( #nullable enable C1 #nullable disable )] [A] object x", @"[DefaultParameterValue(C2)] #nullable disable [A] object x", @"[DefaultParameterValue(C3)] #nullable enable [A] object x", "A", @"DefaultParameterValue( #nullable enable C1 #nullable disable )", "DefaultParameterValue(C2)", "F1", "F2", "F3", "F4", }; AssertEx.Equal(expectedAnalyzedKeys, actualAnalyzedKeys); } [Fact] [WorkItem(49746, "https://github.com/dotnet/roslyn/issues/49746")] public void AnalyzeMethodsInEnabledContextOnly_13() { var source = @"#nullable disable object x = typeof(string); if (x == null) { } _ = x.ToString(); #nullable enable "; verify(new[] { source }, projectContext: null, expectedAnalyzedKeys: new string[0]); source = @"#nullable disable object x = typeof(string); if (x == null) { } #nullable enable _ = x.ToString(); "; verify(new[] { source }, projectContext: null, expectedAnalyzedKeys: new[] { "<Main>$" }, // (5,5): warning CS8602: Dereference of a possibly null reference. // _ = x.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(5, 5)); source = @"#nullable disable object x = typeof(string); if (x == null) { } #nullable restore _ = x.ToString(); "; verify(new[] { source }, projectContext: NullableContextOptions.Warnings, expectedAnalyzedKeys: new[] { "<Main>$" }, // (5,5): warning CS8602: Dereference of a possibly null reference. // _ = x.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(5, 5)); source = @"object x = typeof(string); if (x == null) { } #nullable enable #nullable disable _ = x.ToString(); "; verify(new[] { source }, projectContext: null, expectedAnalyzedKeys: new string[0]); source = @"object x = A.F(); if (x == null) { } _ = x.ToString(); static class A { #nullable enable internal static object F() => new object(); }"; verify(new[] { source }, projectContext: null, expectedAnalyzedKeys: new[] { "F" }); source = @"object x = typeof(A); class A { #nullable enable #nullable disable } if (x == null) { } _ = x.ToString(); "; verify(new[] { source }, projectContext: null, expectedAnalyzedKeys: new string[0], // (7,1): error CS8803: Top-level statements must precede namespace and type declarations. // if (x == null) { } Diagnostic(ErrorCode.ERR_TopLevelStatementAfterNamespaceOrType, "if (x == null) { }").WithLocation(7, 1)); source = @"#nullable enable object x = A.F(); #nullable disable static class A { internal static object F() => new object(); } if (x == null) { } _ = x.ToString(); "; verify(new[] { source }, projectContext: null, expectedAnalyzedKeys: new[] { "<Main>$" }, // (8,1): error CS8803: Top-level statements must precede namespace and type declarations. // if (x == null) { } Diagnostic(ErrorCode.ERR_TopLevelStatementAfterNamespaceOrType, "if (x == null) { }").WithLocation(8, 1)); source = @"object x = F(); if (x == null) { } _ = x.ToString(); static object F() { #nullable enable return new object(); #nullable disable }"; verify(new[] { source }, projectContext: null, expectedAnalyzedKeys: new[] { "<Main>$" }); var sourceA = @"static class A { #nullable enable internal static object F() => new object(); }"; var sourceB = @"object x = A.F(); if (x == null) { } _ = x.ToString(); "; verify(new[] { sourceA, sourceB }, projectContext: null, expectedAnalyzedKeys: new[] { "F" }); static void verify(string[] source, NullableContextOptions? projectContext, string[] expectedAnalyzedKeys, params DiagnosticDescription[] expectedDiagnostics) { var options = TestOptions.ReleaseExe; if (projectContext != null) options = options.WithNullableContextOptions(projectContext.GetValueOrDefault()); var comp = CreateCompilation(source, options: options); comp.NullableAnalysisData = new(); comp.VerifyDiagnostics(expectedDiagnostics); AssertEx.Equal(expectedAnalyzedKeys, GetNullableDataKeysAsStrings(comp.NullableAnalysisData, requiredAnalysis: true)); AssertEx.Equal(expectedAnalyzedKeys, GetIsNullableEnabledMethods(comp.NullableAnalysisData)); } } [Fact] [WorkItem(49746, "https://github.com/dotnet/roslyn/issues/49746")] public void AnalyzeMethodsInEnabledContextOnly_MethodBodySemanticModel_01() { var source = @"class Program { #nullable enable static object F1(object o1) { if (o1 == null) { } return o1; } #nullable disable static object F2(object o2) { if (o2 == null) { } return o2; } }"; var comp = CreateCompilation(source); comp.NullableAnalysisData = new(); var syntaxTree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(syntaxTree); var returnStatements = syntaxTree.GetRoot().DescendantNodes().OfType<ReturnStatementSyntax>().ToArray(); var syntax = returnStatements[0]; Assert.Equal("return o1;", syntax.ToString()); var typeInfo = model.GetTypeInfo(syntax.Expression); Assert.Equal(Microsoft.CodeAnalysis.NullableFlowState.MaybeNull, typeInfo.Nullability.FlowState); syntax = returnStatements[1]; Assert.Equal("return o2;", syntax.ToString()); typeInfo = model.GetTypeInfo(syntax.Expression); Assert.Equal(Microsoft.CodeAnalysis.NullableFlowState.None, typeInfo.Nullability.FlowState); var expectedAnalyzedKeys = new[] { "F1" }; AssertEx.Equal(expectedAnalyzedKeys, GetNullableDataKeysAsStrings(comp.NullableAnalysisData, requiredAnalysis: true)); AssertEx.Equal(expectedAnalyzedKeys, GetIsNullableEnabledMethods(comp.NullableAnalysisData)); } [Fact] [WorkItem(49746, "https://github.com/dotnet/roslyn/issues/49746")] public void AnalyzeMethodsInEnabledContextOnly_MethodBodySemanticModel_02() { var source = @"class Program { #nullable enable object F; Program(object obj) #nullable disable { if (obj == null) { } F = obj; } }"; verify(source, Microsoft.CodeAnalysis.NullableFlowState.MaybeNull, ".ctor"); source = @"class Program { #nullable enable object F; #nullable disable Program(object obj) { if (obj == null) { } F = obj; } }"; verify(source, Microsoft.CodeAnalysis.NullableFlowState.MaybeNull, ".ctor"); source = @"class Program { #nullable enable object F = new object(); #nullable disable Program(object obj) { if (obj == null) { } F = obj; } }"; verify(source, Microsoft.CodeAnalysis.NullableFlowState.MaybeNull, ".ctor"); static void verify(string source, Microsoft.CodeAnalysis.NullableFlowState expectedFlowState, params string[] expectedAnalyzedKeys) { var comp = CreateCompilation(source); comp.NullableAnalysisData = new(); var syntaxTree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(syntaxTree); var syntax = syntaxTree.GetRoot().DescendantNodes().OfType<AssignmentExpressionSyntax>().Single().Right; Assert.Equal("obj", syntax.ToString()); var typeInfo = model.GetTypeInfo(syntax); Assert.Equal(expectedFlowState, typeInfo.Nullability.FlowState); AssertEx.Equal(expectedAnalyzedKeys, GetNullableDataKeysAsStrings(comp.NullableAnalysisData, requiredAnalysis: true)); AssertEx.Equal(expectedAnalyzedKeys, GetIsNullableEnabledMethods(comp.NullableAnalysisData)); } } [Fact] [WorkItem(49746, "https://github.com/dotnet/roslyn/issues/49746")] public void AnalyzeMethodsInEnabledContextOnly_AttributeSemanticModel_01() { var source = @"class A : System.Attribute { #nullable enable public A(object obj) { } public static object F1; public static object F2; } #nullable enable [A(A.F1 = null)] class B1 { } #nullable disable [A(A.F2 = null)] class B2 { }"; var comp = CreateCompilation(source); comp.NullableAnalysisData = new(); var syntaxTree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(syntaxTree); var attributeArguments = syntaxTree.GetRoot().DescendantNodes().OfType<AttributeArgumentSyntax>().ToArray(); verify(attributeArguments[0], "A.F1 = null", Microsoft.CodeAnalysis.NullableFlowState.MaybeNull); verify(attributeArguments[1], "A.F2 = null", Microsoft.CodeAnalysis.NullableFlowState.None); var actualAnalyzedKeys = GetNullableDataKeysAsStrings(comp.NullableAnalysisData, requiredAnalysis: true); AssertEx.Equal(new[] { "A(A.F1 = null)" }, actualAnalyzedKeys); void verify(AttributeArgumentSyntax syntax, string expectedText, Microsoft.CodeAnalysis.NullableFlowState expectedFlowState) { Assert.Equal(expectedText, syntax.ToString()); var typeInfo = model.GetTypeInfo(syntax.Expression); Assert.Equal(expectedFlowState, typeInfo.Nullability.FlowState); } } [Fact] [WorkItem(49746, "https://github.com/dotnet/roslyn/issues/49746")] public void AnalyzeMethodsInEnabledContextOnly_AttributeSemanticModel_02() { var source = @"using System.Runtime.InteropServices; class Program { #nullable enable const object? C1 = null; const object? C2 = null; #nullable disable static void F1([DefaultParameterValue( #nullable enable C1 #nullable disable )] object x) { } #nullable disable static void F2([DefaultParameterValue(C2)] #nullable enable object x #nullable disable ) { } }"; var comp = CreateCompilation(source); comp.NullableAnalysisData = new(); var syntaxTree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(syntaxTree); var attributeArguments = syntaxTree.GetRoot().DescendantNodes().OfType<AttributeArgumentSyntax>().ToArray(); verify(attributeArguments[0], "C1", Microsoft.CodeAnalysis.NullableFlowState.MaybeNull); verify(attributeArguments[1], "C2", Microsoft.CodeAnalysis.NullableFlowState.None); var actualAnalyzedKeys = GetNullableDataKeysAsStrings(comp.NullableAnalysisData, requiredAnalysis: true); var expectedAnalyzedKey = @"DefaultParameterValue( #nullable enable C1 #nullable disable )"; AssertEx.Equal(new[] { expectedAnalyzedKey }, actualAnalyzedKeys); void verify(AttributeArgumentSyntax syntax, string expectedText, Microsoft.CodeAnalysis.NullableFlowState expectedFlowState) { Assert.Equal(expectedText, syntax.ToString()); var typeInfo = model.GetTypeInfo(syntax.Expression); Assert.Equal(expectedFlowState, typeInfo.Nullability.FlowState); } } [Fact] [WorkItem(49746, "https://github.com/dotnet/roslyn/issues/49746")] public void AnalyzeMethodsInEnabledContextOnly_InitializerSemanticModel_01() { var source = @"class Program { #nullable enable static object F1; static object F2; #nullable enable static void M1(object o1 = (F1 = null)) { } #nullable disable static void M2(object o2 = (F2 = null)) { } }"; var comp = CreateCompilation(source); comp.NullableAnalysisData = new(); var syntaxTree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(syntaxTree); var equalsValueClauses = syntaxTree.GetRoot().DescendantNodes().OfType<EqualsValueClauseSyntax>().ToArray(); verify(equalsValueClauses[0], "(F1 = null)", Microsoft.CodeAnalysis.NullableFlowState.MaybeNull); verify(equalsValueClauses[1], "(F2 = null)", Microsoft.CodeAnalysis.NullableFlowState.None); var actualAnalyzedKeys = GetNullableDataKeysAsStrings(comp.NullableAnalysisData, requiredAnalysis: true); AssertEx.Equal(new[] { "o1" }, actualAnalyzedKeys); void verify(EqualsValueClauseSyntax syntax, string expectedText, Microsoft.CodeAnalysis.NullableFlowState expectedFlowState) { var value = syntax.Value; Assert.Equal(expectedText, value.ToString()); var typeInfo = model.GetTypeInfo(value); Assert.Equal(expectedFlowState, typeInfo.Nullability.FlowState); } } [Fact] [WorkItem(49746, "https://github.com/dotnet/roslyn/issues/49746")] public void AnalyzeMethodsInEnabledContextOnly_InitializerSemanticModel_02() { var source = @"#pragma warning disable 414 class A { #nullable disable object F1 = null; } class B { #nullable disable object F2 = null; #nullable enable object F3 = null; }"; var comp = CreateCompilation(source); comp.NullableAnalysisData = new(); var syntaxTree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(syntaxTree); var declarations = syntaxTree.GetRoot().DescendantNodes().OfType<FieldDeclarationSyntax>().Select(f => f.Declaration.Variables[0]).ToArray(); verify(declarations[0], "F1", Microsoft.CodeAnalysis.NullableFlowState.None); verify(declarations[1], "F2", Microsoft.CodeAnalysis.NullableFlowState.MaybeNull); verify(declarations[2], "F3", Microsoft.CodeAnalysis.NullableFlowState.MaybeNull); var actualAnalyzedKeys = GetNullableDataKeysAsStrings(comp.NullableAnalysisData, requiredAnalysis: true); AssertEx.Equal(new[] { "F2", "F3" }, actualAnalyzedKeys); void verify(VariableDeclaratorSyntax syntax, string expectedText, Microsoft.CodeAnalysis.NullableFlowState expectedFlowState) { Assert.Equal(expectedText, syntax.Identifier.ValueText); var typeInfo = model.GetTypeInfo(syntax.Initializer.Value); Assert.Equal(expectedFlowState, typeInfo.Nullability.FlowState); } } [Fact] [WorkItem(49746, "https://github.com/dotnet/roslyn/issues/49746")] public void AnalyzeMethodsInEnabledContextOnly_InitializerSemanticModel_03() { var source = @"class A { #nullable disable object P1 { get; set; } = null; } class B { #nullable disable object P2 { get; set; } = null; #nullable enable object P3 { get; set; } = null; }"; var comp = CreateCompilation(source); comp.NullableAnalysisData = new(); var syntaxTree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(syntaxTree); var declarations = syntaxTree.GetRoot().DescendantNodes().OfType<PropertyDeclarationSyntax>().ToArray(); verify(declarations[0], "P1", Microsoft.CodeAnalysis.NullableFlowState.None); verify(declarations[1], "P2", Microsoft.CodeAnalysis.NullableFlowState.MaybeNull); verify(declarations[2], "P3", Microsoft.CodeAnalysis.NullableFlowState.MaybeNull); var actualAnalyzedKeys = GetNullableDataKeysAsStrings(comp.NullableAnalysisData, requiredAnalysis: true); AssertEx.Equal(new[] { "P2", "P3" }, actualAnalyzedKeys); void verify(PropertyDeclarationSyntax syntax, string expectedText, Microsoft.CodeAnalysis.NullableFlowState expectedFlowState) { Assert.Equal(expectedText, syntax.Identifier.ValueText); var typeInfo = model.GetTypeInfo(syntax.Initializer.Value); Assert.Equal(expectedFlowState, typeInfo.Nullability.FlowState); } } [Fact] [WorkItem(49746, "https://github.com/dotnet/roslyn/issues/49746")] public void AnalyzeMethodsInEnabledContextOnly_SpeculativeSemanticModel_MethodBody() { var source = @"class Program { #nullable disable static void Main() { object obj = typeof(object); } #nullable enable }"; VerifySpeculativeSemanticModel(source, null, "string", Microsoft.CodeAnalysis.NullableAnnotation.None); source = @"class Program { #nullable disable static void Main() { object obj = #nullable enable typeof(object); } }"; VerifySpeculativeSemanticModel(source, null, "string", Microsoft.CodeAnalysis.NullableAnnotation.NotAnnotated); } [Fact] [WorkItem(49746, "https://github.com/dotnet/roslyn/issues/49746")] public void AnalyzeMethodsInEnabledContextOnly_SpeculativeSemanticModel_Initializer() { var source = @"class Program { #nullable disable static object F = typeof(object); #nullable enable }"; VerifySpeculativeSemanticModel(source, null, "string", Microsoft.CodeAnalysis.NullableAnnotation.None); source = @"class Program { #nullable disable static object F = #nullable enable typeof(object); }"; VerifySpeculativeSemanticModel(source, null, "string", Microsoft.CodeAnalysis.NullableAnnotation.NotAnnotated); source = @"class Program { #nullable disable static object P { get; } = typeof(object); #nullable enable }"; VerifySpeculativeSemanticModel(source, null, "string", Microsoft.CodeAnalysis.NullableAnnotation.None); source = @"class Program { #nullable disable static object P { get; } = #nullable enable typeof(object); }"; VerifySpeculativeSemanticModel(source, null, "string", Microsoft.CodeAnalysis.NullableAnnotation.NotAnnotated); } [Fact] [WorkItem(49746, "https://github.com/dotnet/roslyn/issues/49746")] public void AnalyzeMethodsInEnabledContextOnly_SpeculativeSemanticModel_Attribute() { var source = @"class A : System.Attribute { internal A(object obj) { } } class Program { #nullable disable [A(typeof(object)] static void Main() { } #nullable enable }"; VerifySpeculativeSemanticModel(source, null, "string", Microsoft.CodeAnalysis.NullableAnnotation.None); source = @"class A : System.Attribute { internal A(object obj) { } } class Program { #nullable disable [A( #nullable enable typeof(object)] static void Main() { } }"; VerifySpeculativeSemanticModel(source, null, "string", Microsoft.CodeAnalysis.NullableAnnotation.NotAnnotated); } [Theory] [MemberData(nameof(AnalyzeMethodsInEnabledContextOnly_01_Data1))] [WorkItem(49746, "https://github.com/dotnet/roslyn/issues/49746")] public void AnalyzeMethodsInEnabledContextOnly_SpeculativeSemanticModel_A(NullableContextOptions? projectContext, NullableDirectives sourceDirectives, NullableDirectives speculativeDirectives) { AnalyzeMethodsInEnabledContextOnly_SpeculativeSemanticModel_Execute(projectContext, sourceDirectives, speculativeDirectives); } [Theory] [MemberData(nameof(AnalyzeMethodsInEnabledContextOnly_01_Data2))] [WorkItem(49746, "https://github.com/dotnet/roslyn/issues/49746")] public void AnalyzeMethodsInEnabledContextOnly_SpeculativeSemanticModel_B(NullableContextOptions? projectContext, NullableDirectives sourceDirectives, NullableDirectives speculativeDirectives) { AnalyzeMethodsInEnabledContextOnly_SpeculativeSemanticModel_Execute(projectContext, sourceDirectives, speculativeDirectives); } private static void AnalyzeMethodsInEnabledContextOnly_SpeculativeSemanticModel_Execute(NullableContextOptions? projectContext, NullableDirectives sourceDirectives, NullableDirectives speculativeDirectives) { // https://github.com/dotnet/roslyn/issues/50234: SyntaxTreeSemanticModel.IsNullableAnalysisEnabledAtSpeculativePosition() // does not handle '#nullable restore'. if (speculativeDirectives.ExpectedWarningsState == NullableContextState.State.ExplicitlyRestored) return; var source = $@"class Program {{ {sourceDirectives} static void Main() {{ object obj = typeof(object); }} }}"; var typeName = $@"{speculativeDirectives} string"; var expectedWarningsState = CombineState(speculativeDirectives.ExpectedWarningsState, sourceDirectives.ExpectedWarningsState); bool isNullableEnabledForProject = projectContext != null && (projectContext.Value & NullableContextOptions.Warnings) != 0; Microsoft.CodeAnalysis.NullableAnnotation expectedAnnotation = IsNullableEnabled(expectedWarningsState, isNullableEnabledForProject) ? Microsoft.CodeAnalysis.NullableAnnotation.NotAnnotated : Microsoft.CodeAnalysis.NullableAnnotation.None; VerifySpeculativeSemanticModel(source, projectContext, typeName, expectedAnnotation); } private static void VerifySpeculativeSemanticModel(string source, NullableContextOptions? projectContext, string typeName, Microsoft.CodeAnalysis.NullableAnnotation expectedAnnotation) { var options = TestOptions.ReleaseDll; if (projectContext != null) options = options.WithNullableContextOptions(projectContext.GetValueOrDefault()); var comp = CreateCompilation(source, options: options); var syntaxTree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(syntaxTree); var typeOf = syntaxTree.GetRoot().DescendantNodes().OfType<TypeOfExpressionSyntax>().Single(); var type = SyntaxFactory.ParseTypeName(typeName); Assert.True(model.TryGetSpeculativeSemanticModel(typeOf.Type.SpanStart, type, out model, SpeculativeBindingOption.BindAsTypeOrNamespace)); var typeInfo = model.GetTypeInfo(type); Assert.Equal(expectedAnnotation, typeInfo.Nullability.Annotation); } private static string[] GetNullableDataKeysAsStrings(CSharpCompilation.NullableData nullableData, bool requiredAnalysis = false) => nullableData.Data. Where(pair => !requiredAnalysis || pair.Value.RequiredAnalysis). Select(pair => GetNullableDataKeyAsString(pair.Key)). OrderBy(key => key). ToArray(); private static string[] GetIsNullableEnabledMethods(CSharpCompilation.NullableData nullableData, Func<object, string> toString = null) { toString ??= GetNullableDataKeyAsString; return nullableData.Data. Where(pair => pair.Value.RequiredAnalysis && pair.Key is MethodSymbol method && method.IsNullableAnalysisEnabled()). Select(pair => toString(pair.Key)). OrderBy(key => key). ToArray(); } private static string GetNullableDataKeyAsString(object key) => key is Symbol symbol ? symbol.MetadataName : ((SyntaxNode)key).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
./docs/compilers/Co-located core types.md
Co-located core types ===================== ## Customer Scenario and Context The ECMA 335 spec indicates that a few types, such as `System.Object`, or `System.Int16`, can be referenced in metadata as an integer value rather than a type ref token (built-in types). Additionally, the spec indicates that certain conversions are allowed between these types and a small set of token-referenced types – we shall refer to these as special types. Finally, a few types have special runtime treatment without being referenced like the other built-in types. Scenarios 1. A compiler needs to find the type definition for a built-in type, given a reference to it. Given that the reference is not a type token, the compiler needs to know the assembly containing the def 2. A compiler encounters two definitions for a built-in type 3. A compiler is asked to type check two references to a built-in type, one of which is originating from a library compiled to an incompatible definition of core types ## Design Compilers may assume that there is exactly one assembly representing the "core assembly". This core assembly is either referenced or is currently being compiled. The core assembly must not reference any other assemblies. The core assembly contains the type definitions for the subset of built-in and special types supported on a platform. References to types having the same name as built-in types but found outside the core assembly are made via type tokens. An assembly `A` referencing only built-in types may exclude (as per ECMA spec) a reference to the core library. In the case `A` is further referenced by the compiler when compiling a second assembly `B`, the references to the built-in types in `A` are resolved by the compiler based on the core library used for compiling `B`. A platform implementation may choose to define a core assembly with only a subset of the built-in and special types. Compilation in such a scenario succeeds, as long as built-in or special types outside of the subset are not referenced, directly (by user code) or indirectly (by compiler features). This means that, while the compiler can safely assume that all built-in and special types are co-located in the same assembly, they may not all be present. If a later version of the platform introduces more built-in or special types, they must do so in the core assembly. Correspondingly, a runtime for such a platform need only support the subset in the corresponding core assembly. The list of co-located types is exactly the following: - `System.Object` - `System.Enum` - `System.MulticastDelegate` - `System.Delegate` - `System.ValueType` - `System.Void` - `System.Boolean` - `System.Char` - `System.SByte` - `System.Byte` - `System.Int16` - `System.UInt16` - `System.Int32` - `System.UInt32` - `System.Int64` - `System.UInt64` - `System.Decimal` - `System.Single` - `System.Double` - `System.String` - `System.IntPtr` - `System.UIntPtr` - `System.Array` - `System.DateTime` - `System.Collections.IEnumerable` - `System.Collections.Generic.IEnumerable<>` - `System.Collections.Generic.IList<>` - `System.Collections.Generic.ICollection<>` - `System.Collections.Generic.IEnumerator<>` - `System.Collections.IEnumerator` - `System.Nullable<>` - `System.Runtime.CompilerServices.IsVolatile` - `System.IDisposable` - `System.TypedReference` - `System.IAsyncResult` - `System.AsyncCallback` - `System.Collections.Generic.IReadOnlyList<>` - `System.Collections.Generic.IReadOnlyCollection<>` We continue to assume that references to `System.Type` are made by-enumeration value when the reference is made in a custom attribute, and as a regular reference when not. Note the departure from the ECMA spec which included `System.Type`. `System.Type` and other reflection types are intentionally not in the core library. Since `System.Type` may be referenced as a built-in type, the compiler may assume that there is at most one definition for this type available in the compilation context, and treat as an error the case where there is more than one. No definition should be accepted as long as there is no reference. Language features relying on APIs not in the list should not assume any particular assembly location for the definition of such APIs. Compilers should either use heuristics, or require explicit specification of the location of such APIs.
Co-located core types ===================== ## Customer Scenario and Context The ECMA 335 spec indicates that a few types, such as `System.Object`, or `System.Int16`, can be referenced in metadata as an integer value rather than a type ref token (built-in types). Additionally, the spec indicates that certain conversions are allowed between these types and a small set of token-referenced types – we shall refer to these as special types. Finally, a few types have special runtime treatment without being referenced like the other built-in types. Scenarios 1. A compiler needs to find the type definition for a built-in type, given a reference to it. Given that the reference is not a type token, the compiler needs to know the assembly containing the def 2. A compiler encounters two definitions for a built-in type 3. A compiler is asked to type check two references to a built-in type, one of which is originating from a library compiled to an incompatible definition of core types ## Design Compilers may assume that there is exactly one assembly representing the "core assembly". This core assembly is either referenced or is currently being compiled. The core assembly must not reference any other assemblies. The core assembly contains the type definitions for the subset of built-in and special types supported on a platform. References to types having the same name as built-in types but found outside the core assembly are made via type tokens. An assembly `A` referencing only built-in types may exclude (as per ECMA spec) a reference to the core library. In the case `A` is further referenced by the compiler when compiling a second assembly `B`, the references to the built-in types in `A` are resolved by the compiler based on the core library used for compiling `B`. A platform implementation may choose to define a core assembly with only a subset of the built-in and special types. Compilation in such a scenario succeeds, as long as built-in or special types outside of the subset are not referenced, directly (by user code) or indirectly (by compiler features). This means that, while the compiler can safely assume that all built-in and special types are co-located in the same assembly, they may not all be present. If a later version of the platform introduces more built-in or special types, they must do so in the core assembly. Correspondingly, a runtime for such a platform need only support the subset in the corresponding core assembly. The list of co-located types is exactly the following: - `System.Object` - `System.Enum` - `System.MulticastDelegate` - `System.Delegate` - `System.ValueType` - `System.Void` - `System.Boolean` - `System.Char` - `System.SByte` - `System.Byte` - `System.Int16` - `System.UInt16` - `System.Int32` - `System.UInt32` - `System.Int64` - `System.UInt64` - `System.Decimal` - `System.Single` - `System.Double` - `System.String` - `System.IntPtr` - `System.UIntPtr` - `System.Array` - `System.DateTime` - `System.Collections.IEnumerable` - `System.Collections.Generic.IEnumerable<>` - `System.Collections.Generic.IList<>` - `System.Collections.Generic.ICollection<>` - `System.Collections.Generic.IEnumerator<>` - `System.Collections.IEnumerator` - `System.Nullable<>` - `System.Runtime.CompilerServices.IsVolatile` - `System.IDisposable` - `System.TypedReference` - `System.IAsyncResult` - `System.AsyncCallback` - `System.Collections.Generic.IReadOnlyList<>` - `System.Collections.Generic.IReadOnlyCollection<>` We continue to assume that references to `System.Type` are made by-enumeration value when the reference is made in a custom attribute, and as a regular reference when not. Note the departure from the ECMA spec which included `System.Type`. `System.Type` and other reflection types are intentionally not in the core library. Since `System.Type` may be referenced as a built-in type, the compiler may assume that there is at most one definition for this type available in the compilation context, and treat as an error the case where there is more than one. No definition should be accepted as long as there is no reference. Language features relying on APIs not in the list should not assume any particular assembly location for the definition of such APIs. Compilers should either use heuristics, or require explicit specification of the location of such APIs.
-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/TempFiles/TempDirectory.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.IO; namespace Microsoft.CodeAnalysis.Test.Utilities { public class TempDirectory { private readonly string _path; private readonly TempRoot _root; protected TempDirectory(TempRoot root) : this(CreateUniqueDirectory(TempRoot.Root), root) { } private TempDirectory(string path, TempRoot root) { Debug.Assert(path != null); Debug.Assert(root != null); _path = path; _root = root; } private static string CreateUniqueDirectory(string basePath) { while (true) { string dir = System.IO.Path.Combine(basePath, Guid.NewGuid().ToString()); try { Directory.CreateDirectory(dir); return dir; } catch (IOException) { // retry } } } public string Path { get { return _path; } } /// <summary> /// Creates a file in this directory. /// </summary> /// <param name="name">File name.</param> public TempFile CreateFile(string name) { string filePath = System.IO.Path.Combine(_path, name); TempRoot.CreateStream(filePath, FileMode.CreateNew); return _root.AddFile(new DisposableFile(filePath)); } /// <summary> /// Creates a file or opens an existing file in this directory. /// </summary> public TempFile CreateOrOpenFile(string name) { string filePath = System.IO.Path.Combine(_path, name); TempRoot.CreateStream(filePath, FileMode.OpenOrCreate); return _root.AddFile(new DisposableFile(filePath)); } /// <summary> /// Creates a file in this directory that is a copy of the specified file. /// </summary> public TempFile CopyFile(string originalPath, string name = null) { string filePath = System.IO.Path.Combine(_path, name ?? System.IO.Path.GetFileName(originalPath)); File.Copy(originalPath, filePath); return _root.AddFile(new DisposableFile(filePath)); } /// <summary> /// Creates a subdirectory in this directory. /// </summary> /// <param name="name">Directory name or unrooted directory path.</param> public TempDirectory CreateDirectory(string name) { string dirPath = System.IO.Path.Combine(_path, name); Directory.CreateDirectory(dirPath); return new TempDirectory(dirPath, _root); } public override string ToString() { return _path; } } }
// 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.IO; namespace Microsoft.CodeAnalysis.Test.Utilities { public class TempDirectory { private readonly string _path; private readonly TempRoot _root; protected TempDirectory(TempRoot root) : this(CreateUniqueDirectory(TempRoot.Root), root) { } private TempDirectory(string path, TempRoot root) { Debug.Assert(path != null); Debug.Assert(root != null); _path = path; _root = root; } private static string CreateUniqueDirectory(string basePath) { while (true) { string dir = System.IO.Path.Combine(basePath, Guid.NewGuid().ToString()); try { Directory.CreateDirectory(dir); return dir; } catch (IOException) { // retry } } } public string Path { get { return _path; } } /// <summary> /// Creates a file in this directory. /// </summary> /// <param name="name">File name.</param> public TempFile CreateFile(string name) { string filePath = System.IO.Path.Combine(_path, name); TempRoot.CreateStream(filePath, FileMode.CreateNew); return _root.AddFile(new DisposableFile(filePath)); } /// <summary> /// Creates a file or opens an existing file in this directory. /// </summary> public TempFile CreateOrOpenFile(string name) { string filePath = System.IO.Path.Combine(_path, name); TempRoot.CreateStream(filePath, FileMode.OpenOrCreate); return _root.AddFile(new DisposableFile(filePath)); } /// <summary> /// Creates a file in this directory that is a copy of the specified file. /// </summary> public TempFile CopyFile(string originalPath, string name = null) { string filePath = System.IO.Path.Combine(_path, name ?? System.IO.Path.GetFileName(originalPath)); File.Copy(originalPath, filePath); return _root.AddFile(new DisposableFile(filePath)); } /// <summary> /// Creates a subdirectory in this directory. /// </summary> /// <param name="name">Directory name or unrooted directory path.</param> public TempDirectory CreateDirectory(string name) { string dirPath = System.IO.Path.Combine(_path, name); Directory.CreateDirectory(dirPath); return new TempDirectory(dirPath, _root); } public override string ToString() { return _path; } } }
-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/InteractiveCompiler.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.IO; using System.Linq; using Microsoft.Build.Framework; using Microsoft.Build.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.BuildTasks { /// <summary> /// This class defines all of the common stuff that is shared between the Vbc and Csc tasks. /// This class is not instantiatable as a Task just by itself. /// </summary> public abstract class InteractiveCompiler : ManagedToolTask { internal readonly PropertyDictionary _store = new PropertyDictionary(); public InteractiveCompiler() : base(ErrorString.ResourceManager) { } #region Properties - Please keep these alphabetized. public string[]? AdditionalLibPaths { set { _store[nameof(AdditionalLibPaths)] = value; } get { return (string[]?)_store[nameof(AdditionalLibPaths)]; } } public string[]? AdditionalLoadPaths { set { _store[nameof(AdditionalLoadPaths)] = value; } get { return (string[]?)_store[nameof(AdditionalLoadPaths)]; } } [Output] public ITaskItem[]? CommandLineArgs { set { _store[nameof(CommandLineArgs)] = value; } get { return (ITaskItem[]?)_store[nameof(CommandLineArgs)]; } } public string? Features { set { _store[nameof(Features)] = value; } get { return (string?)_store[nameof(Features)]; } } public ITaskItem[]? Imports { set { _store[nameof(Imports)] = value; } get { return (ITaskItem[]?)_store[nameof(Imports)]; } } public bool ProvideCommandLineArgs { set { _store[nameof(ProvideCommandLineArgs)] = value; } get { return _store.GetOrDefault(nameof(ProvideCommandLineArgs), false); } } public ITaskItem[]? References { set { _store[nameof(References)] = value; } get { return (ITaskItem[]?)_store[nameof(References)]; } } public ITaskItem[]? ResponseFiles { set { _store[nameof(ResponseFiles)] = value; } get { return (ITaskItem[]?)_store[nameof(ResponseFiles)]; } } public string[]? ScriptArguments { set { _store[nameof(ScriptArguments)] = value; } get { return (string[]?)_store[nameof(ScriptArguments)]; } } public ITaskItem[]? ScriptResponseFiles { set { _store[nameof(ScriptResponseFiles)] = value; } get { return (ITaskItem[]?)_store[nameof(ScriptResponseFiles)]; } } public bool SkipInteractiveExecution { set { _store[nameof(SkipInteractiveExecution)] = value; } get { return _store.GetOrDefault(nameof(SkipInteractiveExecution), false); } } public ITaskItem? Source { set { _store[nameof(Source)] = value; } get { return (ITaskItem?)_store[nameof(Source)]; } } #endregion #region Tool Members // See ManagedCompiler.cs on the logic of this property private bool HasToolBeenOverridden => !(string.IsNullOrEmpty(ToolPath) && ToolExe == ToolName); protected sealed override bool IsManagedTool => !HasToolBeenOverridden; protected sealed override string PathToManagedTool => Utilities.GenerateFullPathToTool(ToolName); protected sealed override string PathToNativeTool => Path.Combine(ToolPath ?? "", ToolExe); protected override int ExecuteTool(string pathToTool, string responseFileCommands, string commandLineCommands) { if (ProvideCommandLineArgs) { CommandLineArgs = GetArguments(commandLineCommands, responseFileCommands).Select(arg => new TaskItem(arg)).ToArray(); } return (SkipInteractiveExecution) ? 0 : base.ExecuteTool(pathToTool, responseFileCommands, commandLineCommands); } public string GenerateCommandLineContents() => GenerateCommandLineCommands(); protected sealed override string ToolArguments { get { var builder = new CommandLineBuilderExtension(); AddCommandLineCommands(builder); return builder.ToString(); } } public string GenerateResponseFileContents() => GenerateResponseFileCommands(); protected sealed override string GenerateResponseFileCommands() { var commandLineBuilder = new CommandLineBuilderExtension(); AddResponseFileCommands(commandLineBuilder); return commandLineBuilder.ToString(); } #endregion /// <summary> /// Fills the provided CommandLineBuilderExtension with those switches and other information that can't go into a response file and /// must go directly onto the command line. /// </summary> protected virtual void AddCommandLineCommands(CommandLineBuilderExtension commandLine) { } /// <summary> /// Fills the provided CommandLineBuilderExtension with those switches and other information that can go into a response file. /// </summary> protected virtual void AddResponseFileCommands(CommandLineBuilderExtension commandLine) { commandLine.AppendSwitch("/i-"); ManagedCompiler.AddFeatures(commandLine, Features); if (ResponseFiles != null) { foreach (var response in ResponseFiles) { commandLine.AppendSwitchIfNotNull("@", response.ItemSpec); } } commandLine.AppendFileNameIfNotNull(Source); if (ScriptArguments != null) { foreach (var scriptArgument in ScriptArguments) { commandLine.AppendArgumentIfNotNull(scriptArgument); } } if (ScriptResponseFiles != null) { foreach (var scriptResponse in ScriptResponseFiles) { commandLine.AppendSwitchIfNotNull("@", scriptResponse.ItemSpec); } } } /// <summary> /// Get the command line arguments to pass to the compiler. /// </summary> private string[] GetArguments(string commandLineCommands, string responseFileCommands) { var commandLineArguments = CommandLineUtilities.SplitCommandLineIntoArguments(commandLineCommands, removeHashComments: true); var responseFileArguments = CommandLineUtilities.SplitCommandLineIntoArguments(responseFileCommands, removeHashComments: true); return commandLineArguments.Concat(responseFileArguments).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.IO; using System.Linq; using Microsoft.Build.Framework; using Microsoft.Build.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.BuildTasks { /// <summary> /// This class defines all of the common stuff that is shared between the Vbc and Csc tasks. /// This class is not instantiatable as a Task just by itself. /// </summary> public abstract class InteractiveCompiler : ManagedToolTask { internal readonly PropertyDictionary _store = new PropertyDictionary(); public InteractiveCompiler() : base(ErrorString.ResourceManager) { } #region Properties - Please keep these alphabetized. public string[]? AdditionalLibPaths { set { _store[nameof(AdditionalLibPaths)] = value; } get { return (string[]?)_store[nameof(AdditionalLibPaths)]; } } public string[]? AdditionalLoadPaths { set { _store[nameof(AdditionalLoadPaths)] = value; } get { return (string[]?)_store[nameof(AdditionalLoadPaths)]; } } [Output] public ITaskItem[]? CommandLineArgs { set { _store[nameof(CommandLineArgs)] = value; } get { return (ITaskItem[]?)_store[nameof(CommandLineArgs)]; } } public string? Features { set { _store[nameof(Features)] = value; } get { return (string?)_store[nameof(Features)]; } } public ITaskItem[]? Imports { set { _store[nameof(Imports)] = value; } get { return (ITaskItem[]?)_store[nameof(Imports)]; } } public bool ProvideCommandLineArgs { set { _store[nameof(ProvideCommandLineArgs)] = value; } get { return _store.GetOrDefault(nameof(ProvideCommandLineArgs), false); } } public ITaskItem[]? References { set { _store[nameof(References)] = value; } get { return (ITaskItem[]?)_store[nameof(References)]; } } public ITaskItem[]? ResponseFiles { set { _store[nameof(ResponseFiles)] = value; } get { return (ITaskItem[]?)_store[nameof(ResponseFiles)]; } } public string[]? ScriptArguments { set { _store[nameof(ScriptArguments)] = value; } get { return (string[]?)_store[nameof(ScriptArguments)]; } } public ITaskItem[]? ScriptResponseFiles { set { _store[nameof(ScriptResponseFiles)] = value; } get { return (ITaskItem[]?)_store[nameof(ScriptResponseFiles)]; } } public bool SkipInteractiveExecution { set { _store[nameof(SkipInteractiveExecution)] = value; } get { return _store.GetOrDefault(nameof(SkipInteractiveExecution), false); } } public ITaskItem? Source { set { _store[nameof(Source)] = value; } get { return (ITaskItem?)_store[nameof(Source)]; } } #endregion #region Tool Members // See ManagedCompiler.cs on the logic of this property private bool HasToolBeenOverridden => !(string.IsNullOrEmpty(ToolPath) && ToolExe == ToolName); protected sealed override bool IsManagedTool => !HasToolBeenOverridden; protected sealed override string PathToManagedTool => Utilities.GenerateFullPathToTool(ToolName); protected sealed override string PathToNativeTool => Path.Combine(ToolPath ?? "", ToolExe); protected override int ExecuteTool(string pathToTool, string responseFileCommands, string commandLineCommands) { if (ProvideCommandLineArgs) { CommandLineArgs = GetArguments(commandLineCommands, responseFileCommands).Select(arg => new TaskItem(arg)).ToArray(); } return (SkipInteractiveExecution) ? 0 : base.ExecuteTool(pathToTool, responseFileCommands, commandLineCommands); } public string GenerateCommandLineContents() => GenerateCommandLineCommands(); protected sealed override string ToolArguments { get { var builder = new CommandLineBuilderExtension(); AddCommandLineCommands(builder); return builder.ToString(); } } public string GenerateResponseFileContents() => GenerateResponseFileCommands(); protected sealed override string GenerateResponseFileCommands() { var commandLineBuilder = new CommandLineBuilderExtension(); AddResponseFileCommands(commandLineBuilder); return commandLineBuilder.ToString(); } #endregion /// <summary> /// Fills the provided CommandLineBuilderExtension with those switches and other information that can't go into a response file and /// must go directly onto the command line. /// </summary> protected virtual void AddCommandLineCommands(CommandLineBuilderExtension commandLine) { } /// <summary> /// Fills the provided CommandLineBuilderExtension with those switches and other information that can go into a response file. /// </summary> protected virtual void AddResponseFileCommands(CommandLineBuilderExtension commandLine) { commandLine.AppendSwitch("/i-"); ManagedCompiler.AddFeatures(commandLine, Features); if (ResponseFiles != null) { foreach (var response in ResponseFiles) { commandLine.AppendSwitchIfNotNull("@", response.ItemSpec); } } commandLine.AppendFileNameIfNotNull(Source); if (ScriptArguments != null) { foreach (var scriptArgument in ScriptArguments) { commandLine.AppendArgumentIfNotNull(scriptArgument); } } if (ScriptResponseFiles != null) { foreach (var scriptResponse in ScriptResponseFiles) { commandLine.AppendSwitchIfNotNull("@", scriptResponse.ItemSpec); } } } /// <summary> /// Get the command line arguments to pass to the compiler. /// </summary> private string[] GetArguments(string commandLineCommands, string responseFileCommands) { var commandLineArguments = CommandLineUtilities.SplitCommandLineIntoArguments(commandLineCommands, removeHashComments: true); var responseFileArguments = CommandLineUtilities.SplitCommandLineIntoArguments(responseFileCommands, removeHashComments: true); return commandLineArguments.Concat(responseFileArguments).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/Analyzers/VisualBasic/CodeFixes/xlf/VisualBasicCodeFixesResources.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="../VisualBasicCodeFixesResources.resx"> <body> <trans-unit id="Add_Me"> <source>Add 'Me.'</source> <target state="translated">Me'를 추가하세요.</target> <note /> </trans-unit> <trans-unit id="Convert_GetType_to_NameOf"> <source>Convert 'GetType' to 'NameOf'</source> <target state="translated">'GetType'을 'NameOf'로 변환</target> <note /> </trans-unit> <trans-unit id="Remove_Unnecessary_Imports"> <source>Remove Unnecessary Imports</source> <target state="translated">불필요한 Imports 제거</target> <note /> </trans-unit> <trans-unit id="Simplify_object_creation"> <source>Simplify object creation</source> <target state="translated">개체 만들기 간소화</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="../VisualBasicCodeFixesResources.resx"> <body> <trans-unit id="Add_Me"> <source>Add 'Me.'</source> <target state="translated">Me'를 추가하세요.</target> <note /> </trans-unit> <trans-unit id="Convert_GetType_to_NameOf"> <source>Convert 'GetType' to 'NameOf'</source> <target state="translated">'GetType'을 'NameOf'로 변환</target> <note /> </trans-unit> <trans-unit id="Remove_Unnecessary_Imports"> <source>Remove Unnecessary Imports</source> <target state="translated">불필요한 Imports 제거</target> <note /> </trans-unit> <trans-unit id="Simplify_object_creation"> <source>Simplify object creation</source> <target state="translated">개체 만들기 간소화</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
./docs/wiki/images/how-to-investigate-ci-test-failures-figure13.png
PNG  IHDR sRGBgAMA a pHYsodtEXtSoftwarepaint.net 4.1.6N 2GIDATx^ۓ]ŕ#y:<4OLvica7RHt*%B<P# TTVn% ff̕;se:׺~POʕ+s>c*O;1em˛YvYx_[~߾ko~_WzW_+[l/~#G<v H_ٷVuofXqe/FnXY,uC'˂O# ܊ <l̋,\,9R`r޽-j!YG2K @)@!.4tV!w$YBHߑ{;HCg?P B!}G2K @)@!.4tV!w$YBHߑ{;HCg?P B!}G2K @)@!.4tV@!,jld.4'( *aaaaaB)@)PReJJ,,,,P $P `aaaYąR R ". (XXXXqH(@)² @@JE\(( P ,B)@)P`Iw~ue/Q!i² @@$޽{Wk~[_\Z,B)@)P`aI#G<Zȱ'P: P]㯬ڟe:<ηcQTο{yB)f_W죅V,2H( O?hphjƭ/ZS`OKl1QFyU+_ӓ_(-&ly7>F*gg؆Ycm ai9iHf*9fK)P>(s.t&)q}?'f|u>3# %= J N _zy_f͚|;<Ǯ\yߒidC7:ڂk]yo3wcߺMDNKPQV-m/>mܪ̉0[vK۴L2e%^r43m&?/RA[R3Ut`mlx"׻x]3eB)@)P`1I}q<{I6tla3;EҼ.9UͶY4;j<lma?RiUX tXi;>Fް)ŹӊlsS4KB` @(8$O <#wQ %ih ;EΔ;Okv7P2a>uU1[w'{.X$/fQ-|G`r/k>ڸxjG9Kb4u sZ׻4 NzXQX 5E4ƨװ/Գ/w0Y0RL+]RR Zok6Is}RTKNP?ĂiX-B)@)P`qHiPKuǻaH\ONSߝfZ(Zl^L2T8roS9#{e6Rة<̷~`fF|Mŏ(~eOǢâAl;&n!G>޵c󯬒*M#6|̆FwE7\WK4ꠎOZRU}gaFU~RDg؏BBq,ړzq?ڿׯ>^\u_}vzov_߿TU)ؓ%P6>A)P`qHϵk}6 K[I"Gy-M)E67X*?$1FݡLȬڭ]*Vmm|Kwp_"-8z7L,&Y{>-H)({c(@R*hcOeyVBT`} m 0|@tdc Ηl=z#,Rh̰_#?p-e GgjcU<+؊%P>A)P`K9#q[CiɌ77Q%d'*m5E&qCR9X}[?Iۤ *އ8Mg|Wx[E<F힊P4~T`KywEEM|*q P mʺd. yqR8l#% `uZA<]ę%}(Kd(U Ylb?*Y%R.Z =vܵ)؊%P>A)P`IK{6g]znt 4v';W͋rmQ} BM<#j %:;EVUIC&BŗdPٌgWJl)(劏 ZҰSmtBd6`d^PLBW^rs5#RtTEr%< RJl\^_ڿ}]vC}oşUG b.4OP XRlF-#=wxUbF{w{RM_TԶndmfjuyl!A5c9Q:t=Ť~r RTbP%{(PQU_أ#Ћ #-07sxO"iP%[uuEE-KVg*uΰԗKFw}R8]XJM͜nGP9:~w"Dنnk66[~l1Vn7 jxyف)C|<xWjѵ0{ `QaΈ*0Fv_q-)= ދ͵B>Qд(rɅ]5^0Ruxr*X;ֽa4c"{R ]=ڱ$YG΋{_sA)A)P`J{,K8gJ8AUjJi4o(ֲooxw QV>HWb7$c̿BjIX9Sy0ɬU%1hKIĎ9YB$#R3˽۶YQLŠ E=:nJbپM$g JðEK._5jA5o(l)*[H)m'ʼn-qU*q:@@%{U5[/*f<,K\^, ( ?Q(+WY(( ,,) 5ԥ@r~fP $P XXR޽{W[(f,])`{g.,RR7 fn. Q $P X@RƝߺeS² @۶m[nǛ7oꭿ,2<25{[RRDžR aKxC)2R<_ xv)"رl߾Re>H".,6) "-Kr=])e?*| ˢ,#ȗ}][F4Ą}`@)2en@.gx)?50R@@)2e~JeG)4H/7tO :^WB!+7fAf~;@@h)\}z@Q $ FD@p!$%HBz;w\BN42h 3r—_~鄀{) :$R@.JBfwboT_BÌR$@S=NX:@D@rk@Dी~J@@݁Alan/1ݺu 7]> K/..@ ȝSNTxDv @SztM6nxP^DŽ^3e>.*e`&\Gـ p'pwL `HNT;D h b\ذa4!  p5!=E{\se Ve1Y0Bր Į$D8X~uח!|_W#pfȕrɏ@ S${e/@?@ d@F%:`WE;ݏZ6mڴa耵kc@o,W;&&&&'' .2@& 5 ܻwi";;[)/]u$cwWbD.˕ : "A /K%8D fA.?mwOdI' ,Z NMMݻw jk]I{""+vTO'0~OЋo Xz/x…󄐖VrVt5矻ƄgrN8qIA 2?+I ;w|"\ N؟0_@}G@.@wb5k^z%+W|&*>#t j ̄KK%&''ZCdCI :)۷ԀHбP K@t$Fx ÆQE W#Es=bŊO+NBԁD 8CF\Zʐ[8x  kEHM`ApsMOO,nV";[7R<#=ཌCBc#"f~&`ݺu^Z+gyiBH `XPW\q!q={ݻWr-'<(ߘ+YRkH01153͛8V.AWj)`TR@t\:@+O'(tlذaڵk֬r"g]|9SO=O< ,all zd&^}dٲG^uo3:|.u=vyg7-{tR+i7W^`QZ 0λD~l@ wn݊ 2Mt3g>3/4@rm',nn$tcH c}/"@? /@ <?R{1|+nwXCe?l 5}cśoOR\e?8h^a@P>k?-{ueW ohv=g3}u+=hmX7u\iEs+:$PIO$|Ӈ(ejgC W{Ojf$`- +ȾNϽkD p'LF @%B?.]rv !sV@mFږ@!)ȧrmƍ)6H,K|kaRBK.A /׸S\ Kh!=ȧSSS/_zMkHRI AD  Q B!݃|zE{m9o5;vآ BܹsPA{ 5) 7䒀<%C0G)@!t B. @ ^ $3QCR@tH$}m۶(!=ȧgϞx~pVJF %FKlRB3gLLL 7n܀HJpB et+eٟDU$+BH :uj||\t<1p~f$)CӔBH ?~̙3I;k.TB0 BH =zO?Ο??55̍0 ()o;[###ÔBH 9rɓgΜ/_`'{ H;m6؂顡!JB!{O:Sg() R:`w{^ <(ӃBH 8pѣO#п5H@ϥP@] 7nH)@!t'|rȑSN~]R 0 e)09}O'5z\Xto:yUη >ؒ0y6{3qKtFqX ]:WHg0(moW6v,e5qHy Gq:JhЋ5H| ?qfMzlˤ{ ӏ?'Oʓ{PFR@I襀~fphhh-H_4fJe#s`NTrѧʎ]yt1F H=e6@k'OԻ"8i`(s%W:VF#׆Y.&,8l'j3Jk %=3-8 i e݋V=]uVu+{WN Y+k) 5OwС'N'{)s-K01Z4ܸ4uxv{ku%+>ƵU JRߤk>IRitjINR꫽37YR-DKFuFaIКqdl8V@8fޕny޵H'X a0]It^gnԱh: cqlA1JPGC \5s-u@!8\_H:սN^q"XMb/ v2(F_?S$Uqf|U0k^&qx7dX: ]iݮU4qi̽N@i55 SYgUaF) laa¸6?j;hhUqטۃ;U缶5x蚛&aA~ n";AO9H>AP3XŵF%3,A>ݻwD ȗR M6mZn]Rof(7D6>TeYe_c$]mrdIEܙ9I'+km,YWz͚fꏊ~k7>C ajjQ|H >hx%Fts=71R냊vüDkvYZ)u4^nP<pP"R1UatĚy"A5Hƒ&P xd:UP&=Ni{AStT2.?{ ]gi4O](t t]?h18* *Lo Z;r<muhc#O)p1%i;aa݀W/]"Ћ,',;?#u/GήH4@y[0bD6{cb> uh`Ч&9ͼihP'AHP[0;U7^ 5MKIQ ;<YyUPq3ǢH^OVE~D5O|\{'kMδ5<#AdԡZ2#wc.a&TŤZ VZb-4 tOAQv УKg 1z![Sӣv5Oo@>߯OO 8CJCDh 7n\vmR6tfl<zD+>Y(f8! ]Me5]{I/YaQ9 ꛮ#,[Ouܵ^gHGvF<f>vYKO9k@|IO]oqԷ GPYm[$8 HTTTC<2h1&"LQMi׀X1Mt (JeR?T EdǮm㑶 StTrk>0 PaR/u@{ N@MՅe_o]k |p"n޼ХZzy5OvL[4] U,X>N]s *u'@6@eǮjھg'8fM/Bi/œnQ'!oa8+ *IʓfT1LVHa5X~*."Jh7"B컼Z&s5D$oļfzy8ʵ ?*طj#1T ~9u@Q3iU?v8Gf.9h&{OO _"(Jٯ 9!0R`֭7oXfM+Rfs6Tɖu q/jNt EeHuYDZMQ.'Ezj5 BoYKGOAǼ} Ey䛊x2SA*s%~ny<Ԉ{]?Yh TnDYZZu"NA J79ޖYbIJ]w4G5ׇVr8MTځ>Uდ4ѓTn"=GGYz# 3si[X=*TAl'T jSWvx:_dyO:zU>-Mj{wT}ק'q:~]Ӌu,1݅hjIpGMcJ9,mYN<!a*ƷC40F>[BpB5W4W&BNPKkXS~5`W{TGV@Po!{i":tDAS ;KzaDCWj!Zgоzi ? },8ՌV#Z~0;oj<|,b)#(5Ы!6)YCB͌ w(m|1CJ~DB)#aԩ{zH C֨6hÛ/'zksNTEaO]/s倩V3갺Ҋ(G{ަi\aLdVuVWy TTø:8hm(S80: Va th^R/ΈAlFA+N&*}n7h#SN2.C5ώd'}`ZMn@^A {h YS ͕<d-~: KJr)psJY=_ƜL\ 4ΚӗL|,$)0::J)/X^@On)`lzrH(JR`iD@w/%@X mAfHRqBJB!d@)@!,iD |G" JB!P B!K !s(!%˄0[K׾hF#+]90l6K{@-2BA؂v fo1_T j@Oρ^pP BH <˄ovh(RB-^ =zR`bbbI;w{$L2?%?gBWH( MsuWZx]S)QC(7#r?D6M[oe1CeyC{z'E$BYl ~8}of"`v7mڴnݺk\{O$6T\,$5⼮"H6 y yU{<?zu=DƏT,/{l2d<!,:O)p1/._<_] v)m6w(4>&i#*GXLMU$'3BS(Ri}V 0P ͹*9aXz'؉ԉOPL!ӽ{8pR̙3/^vH{͙x7)044ԕ09BI$-d`l\ y}rUE{bGQQkmzcUtL1e4J.OFs+BY| ۷Ǐ_R`݉@{F u[nq uF`[ :ޫ15#*c4OGZUN!kWIc%.(!:qٳg!\)p H;wܽ{wjHXذaCGR NTuRl:&5Y!O]$Fo7)ʛRnFTJ7R=XAc6ǴI'EG}t'O;wNs)0RGGGaqxxxƍI{LJREM5 LSybl@W 'x[F4B$T̚<W7?Z~9RAXm0(2?e{SY;UJBT0Ԕ [) :8!o) 'D=AcX޴iSGR%v|9l $K6rқ?nkx6NHBpR}A0Y\*!دM*FeP+^yCC7s)T! E &&&_R(PF鹿i֥@ט <_!,6OOpoB 4?3H%YwI/YR\XzB:СCyfP+_PFR@ x뭷 Piǎh 5222<<O)gIϘR@ DY 9rD?3($gg[ \ ȯ <9BRTM©)~PK3) 2RU<.ӔBH 9qH0 R,.!=ȧN }}@ ޽Ka&!=ȧWyP@.  8 `q&jP R@}BRBS}I۷Jk_OϤ[o%O*1 !=ȧ@5S-Е5) X-JB!{O;@gU $ ېra@L!=ȧyJ $0/@!JB!{O._lJQ{6<1@)@!t)t5_ )?ѩK"<</ S B!݃| i8Y!{s L'R@x)/ ZuB!t<" /th[ -b@amFGGn݊M6nܸ~u֭YfիVZr /s=˗/駟z'x~ӟ'?yB|Pˇ={ݻw?O8pÇ=zN:}|_@D -lA .@O###x6lXv-/K/&x yh AB!dd[%:tرcP'OOϜ9011p耿97nCI`Em`T.@^!B "VXME"H!?~/_@>Lxp%SB:X )D o)QXuVpj`E4/kA"B<^bb ٳ^LMM7tupI5z) mryȣry@?@DhAzj/qB!d!|/ K+%@7o'z@Ϥ0"$j_Aò"oZYF !2A=%_|YիW/:@Dp*2|t(J  E Hm@k^ ZD ꖁBY( H>/  @:t.'*)D < @ WFFF͛W DBYH@Q['V_r۷!y`ݺu.rB~IEp*w:t+ D ,:O!Y w 6lB! I$~/_+EpzG@ NT 6) j kr !/H^(;7R@Ԁ"mी}0|3M);.lBȂEr _$.NTx)ी6nv84jlAЀ!p _r~ ̻R 0Hyb@R@. .NB"%Kc\&K&5 ?JB!KKoqi?å^{)ڒ_&0'p"B2.~=/R@ЂKYx5o€* !q9%0KR@ ^IB!d2vߘm)D P B!3u?)(!f\3s&An?t\Cp E8 wsB!A)@!,i(!%MR?Um"ǼIENDB`
PNG  IHDR sRGBgAMA a pHYsodtEXtSoftwarepaint.net 4.1.6N 2GIDATx^ۓ]ŕ#y:<4OLvica7RHt*%B<P# TTVn% ff̕;se:׺~POʕ+s>c*O;1em˛YvYx_[~߾ko~_WzW_+[l/~#G<v H_ٷVuofXqe/FnXY,uC'˂O# ܊ <l̋,\,9R`r޽-j!YG2K @)@!.4tV!w$YBHߑ{;HCg?P B!}G2K @)@!.4tV!w$YBHߑ{;HCg?P B!}G2K @)@!.4tV@!,jld.4'( *aaaaaB)@)PReJJ,,,,P $P `aaaYąR R ". (XXXXqH(@)² @@JE\(( P ,B)@)P`Iw~ue/Q!i² @@$޽{Wk~[_\Z,B)@)P`aI#G<Zȱ'P: P]㯬ڟe:<ηcQTο{yB)f_W죅V,2H( O?hphjƭ/ZS`OKl1QFyU+_ӓ_(-&ly7>F*gg؆Ycm ai9iHf*9fK)P>(s.t&)q}?'f|u>3# %= J N _zy_f͚|;<Ǯ\yߒidC7:ڂk]yo3wcߺMDNKPQV-m/>mܪ̉0[vK۴L2e%^r43m&?/RA[R3Ut`mlx"׻x]3eB)@)P`1I}q<{I6tla3;EҼ.9UͶY4;j<lma?RiUX tXi;>Fް)ŹӊlsS4KB` @(8$O <#wQ %ih ;EΔ;Okv7P2a>uU1[w'{.X$/fQ-|G`r/k>ڸxjG9Kb4u sZ׻4 NzXQX 5E4ƨװ/Գ/w0Y0RL+]RR Zok6Is}RTKNP?ĂiX-B)@)P`qHiPKuǻaH\ONSߝfZ(Zl^L2T8roS9#{e6Rة<̷~`fF|Mŏ(~eOǢâAl;&n!G>޵c󯬒*M#6|̆FwE7\WK4ꠎOZRU}gaFU~RDg؏BBq,ړzq?ڿׯ>^\u_}vzov_߿TU)ؓ%P6>A)P`qHϵk}6 K[I"Gy-M)E67X*?$1FݡLȬڭ]*Vmm|Kwp_"-8z7L,&Y{>-H)({c(@R*hcOeyVBT`} m 0|@tdc Ηl=z#,Rh̰_#?p-e GgjcU<+؊%P>A)P`K9#q[CiɌ77Q%d'*m5E&qCR9X}[?Iۤ *އ8Mg|Wx[E<F힊P4~T`KywEEM|*q P mʺd. yqR8l#% `uZA<]ę%}(Kd(U Ylb?*Y%R.Z =vܵ)؊%P>A)P`IK{6g]znt 4v';W͋rmQ} BM<#j %:;EVUIC&BŗdPٌgWJl)(劏 ZҰSmtBd6`d^PLBW^rs5#RtTEr%< RJl\^_ڿ}]vC}oşUG b.4OP XRlF-#=wxUbF{w{RM_TԶndmfjuyl!A5c9Q:t=Ť~r RTbP%{(PQU_أ#Ћ #-07sxO"iP%[uuEE-KVg*uΰԗKFw}R8]XJM͜nGP9:~w"Dنnk66[~l1Vn7 jxyف)C|<xWjѵ0{ `QaΈ*0Fv_q-)= ދ͵B>Qд(rɅ]5^0Ruxr*X;ֽa4c"{R ]=ڱ$YG΋{_sA)A)P`J{,K8gJ8AUjJi4o(ֲooxw QV>HWb7$c̿BjIX9Sy0ɬU%1hKIĎ9YB$#R3˽۶YQLŠ E=:nJbپM$g JðEK._5jA5o(l)*[H)m'ʼn-qU*q:@@%{U5[/*f<,K\^, ( ?Q(+WY(( ,,) 5ԥ@r~fP $P XXR޽{W[(f,])`{g.,RR7 fn. Q $P X@RƝߺeS² @۶m[nǛ7oꭿ,2<25{[RRDžR aKxC)2R<_ xv)"رl߾Re>H".,6) "-Kr=])e?*| ˢ,#ȗ}][F4Ą}`@)2en@.gx)?50R@@)2e~JeG)4H/7tO :^WB!+7fAf~;@@h)\}z@Q $ FD@p!$%HBz;w\BN42h 3r—_~鄀{) :$R@.JBfwboT_BÌR$@S=NX:@D@rk@Dी~J@@݁Alan/1ݺu 7]> K/..@ ȝSNTxDv @SztM6nxP^DŽ^3e>.*e`&\Gـ p'pwL `HNT;D h b\ذa4!  p5!=E{\se Ve1Y0Bր Į$D8X~uח!|_W#pfȕrɏ@ S${e/@?@ d@F%:`WE;ݏZ6mڴa耵kc@o,W;&&&&'' .2@& 5 ܻwi";;[)/]u$cwWbD.˕ : "A /K%8D fA.?mwOdI' ,Z NMMݻw jk]I{""+vTO'0~OЋo Xz/x…󄐖VrVt5矻ƄgrN8qIA 2?+I ;w|"\ N؟0_@}G@.@wb5k^z%+W|&*>#t j ̄KK%&''ZCdCI :)۷ԀHбP K@t$Fx ÆQE W#Es=bŊO+NBԁD 8CF\Zʐ[8x  kEHM`ApsMOO,nV";[7R<#=ཌCBc#"f~&`ݺu^Z+gyiBH `XPW\q!q={ݻWr-'<(ߘ+YRkH01153͛8V.AWj)`TR@t\:@+O'(tlذaڵk֬r"g]|9SO=O< ,all zd&^}dٲG^uo3:|.u=vyg7-{tR+i7W^`QZ 0λD~l@ wn݊ 2Mt3g>3/4@rm',nn$tcH c}/"@? /@ <?R{1|+nwXCe?l 5}cśoOR\e?8h^a@P>k?-{ueW ohv=g3}u+=hmX7u\iEs+:$PIO$|Ӈ(ejgC W{Ojf$`- +ȾNϽkD p'LF @%B?.]rv !sV@mFږ@!)ȧrmƍ)6H,K|kaRBK.A /׸S\ Kh!=ȧSSS/_zMkHRI AD  Q B!݃|zE{m9o5;vآ BܹsPA{ 5) 7䒀<%C0G)@!t B. @ ^ $3QCR@tH$}m۶(!=ȧgϞx~pVJF %FKlRB3gLLL 7n܀HJpB et+eٟDU$+BH :uj||\t<1p~f$)CӔBH ?~̙3I;k.TB0 BH =zO?Ο??55̍0 ()o;[###ÔBH 9rɓgΜ/_`'{ H;m6؂顡!JB!{O:Sg() R:`w{^ <(ӃBH 8pѣO#п5H@ϥP@] 7nH)@!t'|rȑSN~]R 0 e)09}O'5z\Xto:yUη >ؒ0y6{3qKtFqX ]:WHg0(moW6v,e5qHy Gq:JhЋ5H| ?qfMzlˤ{ ӏ?'Oʓ{PFR@I襀~fphhh-H_4fJe#s`NTrѧʎ]yt1F H=e6@k'OԻ"8i`(s%W:VF#׆Y.&,8l'j3Jk %=3-8 i e݋V=]uVu+{WN Y+k) 5OwС'N'{)s-K01Z4ܸ4uxv{ku%+>ƵU JRߤk>IRitjINR꫽37YR-DKFuFaIКqdl8V@8fޕny޵H'X a0]It^gnԱh: cqlA1JPGC \5s-u@!8\_H:սN^q"XMb/ v2(F_?S$Uqf|U0k^&qx7dX: ]iݮU4qi̽N@i55 SYgUaF) laa¸6?j;hhUqטۃ;U缶5x蚛&aA~ n";AO9H>AP3XŵF%3,A>ݻwD ȗR M6mZn]Rof(7D6>TeYe_c$]mrdIEܙ9I'+km,YWz͚fꏊ~k7>C ajjQ|H >hx%Fts=71R냊vüDkvYZ)u4^nP<pP"R1UatĚy"A5Hƒ&P xd:UP&=Ni{AStT2.?{ ]gi4O](t t]?h18* *Lo Z;r<muhc#O)p1%i;aa݀W/]"Ћ,',;?#u/GήH4@y[0bD6{cb> uh`Ч&9ͼihP'AHP[0;U7^ 5MKIQ ;<YyUPq3ǢH^OVE~D5O|\{'kMδ5<#AdԡZ2#wc.a&TŤZ VZb-4 tOAQv УKg 1z![Sӣv5Oo@>߯OO 8CJCDh 7n\vmR6tfl<zD+>Y(f8! ]Me5]{I/YaQ9 ꛮ#,[Ouܵ^gHGvF<f>vYKO9k@|IO]oqԷ GPYm[$8 HTTTC<2h1&"LQMi׀X1Mt (JeR?T EdǮm㑶 StTrk>0 PaR/u@{ N@MՅe_o]k |p"n޼ХZzy5OvL[4] U,X>N]s *u'@6@eǮjھg'8fM/Bi/œnQ'!oa8+ *IʓfT1LVHa5X~*."Jh7"B컼Z&s5D$oļfzy8ʵ ?*طj#1T ~9u@Q3iU?v8Gf.9h&{OO _"(Jٯ 9!0R`֭7oXfM+Rfs6Tɖu q/jNt EeHuYDZMQ.'Ezj5 BoYKGOAǼ} Ey䛊x2SA*s%~ny<Ԉ{]?Yh TnDYZZu"NA J79ޖYbIJ]w4G5ׇVr8MTځ>Uდ4ѓTn"=GGYz# 3si[X=*TAl'T jSWvx:_dyO:zU>-Mj{wT}ק'q:~]Ӌu,1݅hjIpGMcJ9,mYN<!a*ƷC40F>[BpB5W4W&BNPKkXS~5`W{TGV@Po!{i":tDAS ;KzaDCWj!Zgоzi ? },8ՌV#Z~0;oj<|,b)#(5Ы!6)YCB͌ w(m|1CJ~DB)#aԩ{zH C֨6hÛ/'zksNTEaO]/s倩V3갺Ҋ(G{ަi\aLdVuVWy TTø:8hm(S80: Va th^R/ΈAlFA+N&*}n7h#SN2.C5ώd'}`ZMn@^A {h YS ͕<d-~: KJr)psJY=_ƜL\ 4ΚӗL|,$)0::J)/X^@On)`lzrH(JR`iD@w/%@X mAfHRqBJB!d@)@!,iD |G" JB!P B!K !s(!%˄0[K׾hF#+]90l6K{@-2BA؂v fo1_T j@Oρ^pP BH <˄ovh(RB-^ =zR`bbbI;w{$L2?%?gBWH( MsuWZx]S)QC(7#r?D6M[oe1CeyC{z'E$BYl ~8}of"`v7mڴnݺk\{O$6T\,$5⼮"H6 y yU{<?zu=DƏT,/{l2d<!,:O)p1/._<_] v)m6w(4>&i#*GXLMU$'3BS(Ri}V 0P ͹*9aXz'؉ԉOPL!ӽ{8pR̙3/^vH{͙x7)044ԕ09BI$-d`l\ y}rUE{bGQQkmzcUtL1e4J.OFs+BY| ۷Ǐ_R`݉@{F u[nq uF`[ :ޫ15#*c4OGZUN!kWIc%.(!:qٳg!\)p H;wܽ{wjHXذaCGR NTuRl:&5Y!O]$Fo7)ʛRnFTJ7R=XAc6ǴI'EG}t'O;wNs)0RGGGaqxxxƍI{LJREM5 LSybl@W 'x[F4B$T̚<W7?Z~9RAXm0(2?e{SY;UJBT0Ԕ [) :8!o) 'D=AcX޴iSGR%v|9l $K6rқ?nkx6NHBpR}A0Y\*!دM*FeP+^yCC7s)T! E &&&_R(PF鹿i֥@ט <_!,6OOpoB 4?3H%YwI/YR\XzB:СCyfP+_PFR@ x뭷 Piǎh 5222<<O)gIϘR@ DY 9rD?3($gg[ \ ȯ <9BRTM©)~PK3) 2RU<.ӔBH 9qH0 R,.!=ȧN }}@ ޽Ka&!=ȧWyP@.  8 `q&jP R@}BRBS}I۷Jk_OϤ[o%O*1 !=ȧ@5S-Е5) X-JB!{O;@gU $ ېra@L!=ȧyJ $0/@!JB!{O._lJQ{6<1@)@!t)t5_ )?ѩK"<</ S B!݃| i8Y!{s L'R@x)/ ZuB!t<" /th[ -b@amFGGn݊M6nܸ~u֭YfիVZr /s=˗/駟z'x~ӟ'?yB|Pˇ={ݻw?O8pÇ=zN:}|_@D -lA .@O###x6lXv-/K/&x yh AB!dd[%:tرcP'OOϜ9011p耿97nCI`Em`T.@^!B "VXME"H!?~/_@>Lxp%SB:X )D o)QXuVpj`E4/kA"B<^bb ٳ^LMM7tupI5z) mryȣry@?@DhAzj/qB!d!|/ K+%@7o'z@Ϥ0"$j_Aò"oZYF !2A=%_|YիW/:@Dp*2|t(J  E Hm@k^ ZD ꖁBY( H>/  @:t.'*)D < @ WFFF͛W DBYH@Q['V_r۷!y`ݺu.rB~IEp*w:t+ D ,:O!Y w 6lB! I$~/_+EpzG@ NT 6) j kr !/H^(;7R@Ԁ"mी}0|3M);.lBȂEr _$.NTx)ी6nv84jlAЀ!p _r~ ̻R 0Hyb@R@. .NB"%Kc\&K&5 ?JB!KKoqi?å^{)ڒ_&0'p"B2.~=/R@ЂKYx5o€* !q9%0KR@ ^IB!d2vߘm)D P B!3u?)(!f\3s&An?t\Cp E8 wsB!A)@!,i(!%MR?Um"ǼIENDB`
-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/Workspace/VisualStudioErrorReportingServiceFactory.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; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.VisualStudio.LanguageServices.Implementation { [ExportWorkspaceServiceFactory(typeof(IErrorReportingService), ServiceLayer.Host), Shared] internal sealed class VisualStudioErrorReportingServiceFactory : IWorkspaceServiceFactory { private IErrorReportingService _singleton; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public VisualStudioErrorReportingServiceFactory() { } public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices) { if (_singleton == null) { _singleton = new VisualStudioErrorReportingService(workspaceServices.GetRequiredService<IInfoBarService>()); } return _singleton; } } }
// 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; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.VisualStudio.LanguageServices.Implementation { [ExportWorkspaceServiceFactory(typeof(IErrorReportingService), ServiceLayer.Host), Shared] internal sealed class VisualStudioErrorReportingServiceFactory : IWorkspaceServiceFactory { private IErrorReportingService _singleton; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public VisualStudioErrorReportingServiceFactory() { } public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices) { if (_singleton == null) { _singleton = new VisualStudioErrorReportingService(workspaceServices.GetRequiredService<IInfoBarService>()); } return _singleton; } } }
-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/Shared/Utilities/CommonFormattingHelpers.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.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Text; namespace Microsoft.CodeAnalysis.Editor.Shared.Utilities { internal static class CommonFormattingHelpers { public static TextSpan GetFormattingSpan(SyntaxNode root, TextSpan span) => CodeAnalysis.Shared.Utilities.CommonFormattingHelpers.GetFormattingSpan(root, span); public static TextSpan GetFormattingSpan(ITextSnapshot snapshot, SnapshotSpan selectedSpan) { var currentLine = snapshot.GetLineFromPosition(selectedSpan.Start); var endPosition = selectedSpan.IsEmpty ? currentLine.End : selectedSpan.End; var previousLine = GetNonEmptyPreviousLine(snapshot, currentLine); // first line on screen if (currentLine == previousLine) { return TextSpan.FromBounds(currentLine.Start, endPosition); } var lastNonNoisyCharPosition = previousLine.GetLastNonWhitespacePosition().GetValueOrDefault(); return TextSpan.FromBounds(lastNonNoisyCharPosition, endPosition); } public static ITextSnapshotLine GetNonEmptyPreviousLine(ITextSnapshot snapshot, ITextSnapshotLine currentLine) { do { var previousLine = snapshot.GetLineFromLineNumber(Math.Max(currentLine.LineNumber - 1, 0)); // first line in the file if (previousLine.LineNumber == currentLine.LineNumber) { return currentLine; } if (previousLine.IsEmptyOrWhitespace()) { // keep goes up until it find non empty previous line currentLine = previousLine; continue; } return previousLine; } while (true); } } }
// 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.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Text; namespace Microsoft.CodeAnalysis.Editor.Shared.Utilities { internal static class CommonFormattingHelpers { public static TextSpan GetFormattingSpan(SyntaxNode root, TextSpan span) => CodeAnalysis.Shared.Utilities.CommonFormattingHelpers.GetFormattingSpan(root, span); public static TextSpan GetFormattingSpan(ITextSnapshot snapshot, SnapshotSpan selectedSpan) { var currentLine = snapshot.GetLineFromPosition(selectedSpan.Start); var endPosition = selectedSpan.IsEmpty ? currentLine.End : selectedSpan.End; var previousLine = GetNonEmptyPreviousLine(snapshot, currentLine); // first line on screen if (currentLine == previousLine) { return TextSpan.FromBounds(currentLine.Start, endPosition); } var lastNonNoisyCharPosition = previousLine.GetLastNonWhitespacePosition().GetValueOrDefault(); return TextSpan.FromBounds(lastNonNoisyCharPosition, endPosition); } public static ITextSnapshotLine GetNonEmptyPreviousLine(ITextSnapshot snapshot, ITextSnapshotLine currentLine) { do { var previousLine = snapshot.GetLineFromLineNumber(Math.Max(currentLine.LineNumber - 1, 0)); // first line in the file if (previousLine.LineNumber == currentLine.LineNumber) { return currentLine; } if (previousLine.IsEmptyOrWhitespace()) { // keep goes up until it find non empty previous line currentLine = previousLine; continue; } return previousLine; } while (true); } } }
-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/Services/Precedence/AbstractCSharpPrecedenceService.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.Extensions; using Microsoft.CodeAnalysis.Precedence; namespace Microsoft.CodeAnalysis.CSharp.Precedence { internal abstract class AbstractCSharpPrecedenceService<TSyntax> : AbstractPrecedenceService<TSyntax, OperatorPrecedence> where TSyntax : SyntaxNode { protected AbstractCSharpPrecedenceService() { } public sealed override PrecedenceKind GetPrecedenceKind(OperatorPrecedence precedence) { switch (precedence) { case OperatorPrecedence.NullCoalescing: return PrecedenceKind.Coalesce; case OperatorPrecedence.ConditionalOr: case OperatorPrecedence.ConditionalAnd: return PrecedenceKind.Logical; case OperatorPrecedence.LogicalOr: case OperatorPrecedence.LogicalXor: case OperatorPrecedence.LogicalAnd: return PrecedenceKind.Bitwise; case OperatorPrecedence.Equality: return PrecedenceKind.Equality; case OperatorPrecedence.RelationalAndTypeTesting: return PrecedenceKind.Relational; case OperatorPrecedence.Shift: return PrecedenceKind.Shift; case OperatorPrecedence.Additive: case OperatorPrecedence.Multiplicative: return PrecedenceKind.Arithmetic; default: return PrecedenceKind.Other; } } } }
// 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.Extensions; using Microsoft.CodeAnalysis.Precedence; namespace Microsoft.CodeAnalysis.CSharp.Precedence { internal abstract class AbstractCSharpPrecedenceService<TSyntax> : AbstractPrecedenceService<TSyntax, OperatorPrecedence> where TSyntax : SyntaxNode { protected AbstractCSharpPrecedenceService() { } public sealed override PrecedenceKind GetPrecedenceKind(OperatorPrecedence precedence) { switch (precedence) { case OperatorPrecedence.NullCoalescing: return PrecedenceKind.Coalesce; case OperatorPrecedence.ConditionalOr: case OperatorPrecedence.ConditionalAnd: return PrecedenceKind.Logical; case OperatorPrecedence.LogicalOr: case OperatorPrecedence.LogicalXor: case OperatorPrecedence.LogicalAnd: return PrecedenceKind.Bitwise; case OperatorPrecedence.Equality: return PrecedenceKind.Equality; case OperatorPrecedence.RelationalAndTypeTesting: return PrecedenceKind.Relational; case OperatorPrecedence.Shift: return PrecedenceKind.Shift; case OperatorPrecedence.Additive: case OperatorPrecedence.Multiplicative: return PrecedenceKind.Arithmetic; default: return PrecedenceKind.Other; } } } }
-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/Workspace/Host/TaskScheduler/TaskSchedulerProvider.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.Mef; using System; using System.Composition; using System.Threading; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.Host { [ExportWorkspaceService(typeof(ITaskSchedulerProvider), ServiceLayer.Default)] [Shared] internal sealed class TaskSchedulerProvider : ITaskSchedulerProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public TaskSchedulerProvider() { } public TaskScheduler CurrentContextScheduler => (SynchronizationContext.Current != null) ? TaskScheduler.FromCurrentSynchronizationContext() : TaskScheduler.Default; } }
// 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.Mef; using System; using System.Composition; using System.Threading; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.Host { [ExportWorkspaceService(typeof(ITaskSchedulerProvider), ServiceLayer.Default)] [Shared] internal sealed class TaskSchedulerProvider : ITaskSchedulerProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public TaskSchedulerProvider() { } public TaskScheduler CurrentContextScheduler => (SynchronizationContext.Current != null) ? TaskScheduler.FromCurrentSynchronizationContext() : TaskScheduler.Default; } }
-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/Impl/CodeModel/Collections/NamespaceCollection.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 System.Linq; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Collections { [ComVisible(true)] [ComDefaultInterface(typeof(ICodeElements))] public sealed class NamespaceCollection : AbstractCodeElementCollection { internal static EnvDTE.CodeElements Create( CodeModelState state, object parent, FileCodeModel fileCodeModel, SyntaxNodeKey nodeKey) { var collection = new NamespaceCollection(state, parent, fileCodeModel, nodeKey); return (EnvDTE.CodeElements)ComAggregate.CreateAggregatedObject(collection); } private readonly ComHandle<EnvDTE.FileCodeModel, FileCodeModel> _fileCodeModel; private readonly SyntaxNodeKey _nodeKey; private NamespaceCollection( CodeModelState state, object parent, FileCodeModel fileCodeModel, SyntaxNodeKey nodeKey) : base(state, parent) { Debug.Assert(fileCodeModel != null); _fileCodeModel = new ComHandle<EnvDTE.FileCodeModel, FileCodeModel>(fileCodeModel); _nodeKey = nodeKey; } private FileCodeModel FileCodeModel { get { return _fileCodeModel.Object; } } private bool IsRootNamespace { get { return _nodeKey == SyntaxNodeKey.Empty; } } private SyntaxNode LookupNode() { if (!IsRootNamespace) { return FileCodeModel.LookupNode(_nodeKey); } else { return FileCodeModel.GetSyntaxRoot(); } } private EnvDTE.CodeElement CreateCodeOptionsStatement(SyntaxNode node, SyntaxNode parentNode) { CodeModelService.GetOptionNameAndOrdinal(parentNode, node, out var name, out var ordinal); return CodeOptionsStatement.Create(this.State, this.FileCodeModel, name, ordinal); } private EnvDTE.CodeElement CreateCodeImport(SyntaxNode node, AbstractCodeElement parentElement) { var name = CodeModelService.GetImportNamespaceOrType(node); return CodeImport.Create(this.State, this.FileCodeModel, parentElement, name); } private EnvDTE.CodeElement CreateCodeAttribute(SyntaxNode node, SyntaxNode parentNode, AbstractCodeElement parentElement) { CodeModelService.GetAttributeNameAndOrdinal(parentNode, node, out var name, out var ordinal); return (EnvDTE.CodeElement)CodeAttribute.Create(this.State, this.FileCodeModel, parentElement, name, ordinal); } internal override Snapshot CreateSnapshot() { var node = LookupNode(); var parentElement = !this.IsRootNamespace ? (AbstractCodeElement)this.Parent : null; var nodesBuilder = ArrayBuilder<SyntaxNode>.GetInstance(); nodesBuilder.AddRange(CodeModelService.GetOptionNodes(node)); nodesBuilder.AddRange(CodeModelService.GetImportNodes(node)); nodesBuilder.AddRange(CodeModelService.GetAttributeNodes(node)); nodesBuilder.AddRange(CodeModelService.GetLogicalSupportedMemberNodes(node)); return new NodeSnapshot(this.State, _fileCodeModel, node, parentElement, nodesBuilder.ToImmutableAndFree()); } protected override bool TryGetItemByIndex(int index, out EnvDTE.CodeElement element) { var node = LookupNode(); var parentElement = !this.IsRootNamespace ? (AbstractCodeElement)this.Parent : null; var currentIndex = 0; // Option statements var optionNodes = CodeModelService.GetOptionNodes(node); var optionNodeCount = optionNodes.Count(); if (index < currentIndex + optionNodeCount) { var child = optionNodes.ElementAt(index - currentIndex); element = CreateCodeOptionsStatement(child, node); return true; } currentIndex += optionNodeCount; // Imports/using statements var importNodes = CodeModelService.GetImportNodes(node); var importNodeCount = importNodes.Count(); if (index < currentIndex + importNodeCount) { var child = importNodes.ElementAt(index - currentIndex); element = CreateCodeImport(child, parentElement); return true; } currentIndex += importNodeCount; // Attributes var attributeNodes = CodeModelService.GetAttributeNodes(node); var attributeNodeCount = attributeNodes.Count(); if (index < currentIndex + attributeNodeCount) { var child = attributeNodes.ElementAt(index - currentIndex); element = CreateCodeAttribute(child, node, parentElement); return true; } currentIndex += attributeNodeCount; // Members var memberNodes = CodeModelService.GetLogicalSupportedMemberNodes(node); var memberNodeCount = memberNodes.Count(); if (index < currentIndex + memberNodeCount) { var child = memberNodes.ElementAt(index - currentIndex); element = FileCodeModel.GetOrCreateCodeElement<EnvDTE.CodeElement>(child); return true; } element = null; return false; } protected override bool TryGetItemByName(string name, out EnvDTE.CodeElement element) { var node = LookupNode(); var parentElement = !IsRootNamespace ? (AbstractCodeElement)Parent : null; // Option statements foreach (var child in CodeModelService.GetOptionNodes(node)) { CodeModelService.GetOptionNameAndOrdinal(node, child, out var childName, out var ordinal); if (childName == name) { element = CodeOptionsStatement.Create(State, FileCodeModel, childName, ordinal); return true; } } // Imports/using statements foreach (var child in CodeModelService.GetImportNodes(node)) { var childName = CodeModelService.GetImportNamespaceOrType(child); if (childName == name) { element = CodeImport.Create(State, FileCodeModel, parentElement, childName); return true; } } // Attributes foreach (var child in CodeModelService.GetAttributeNodes(node)) { CodeModelService.GetAttributeNameAndOrdinal(node, child, out var childName, out var ordinal); if (childName == name) { element = (EnvDTE.CodeElement)CodeAttribute.Create(State, FileCodeModel, parentElement, childName, ordinal); return true; } } // Members foreach (var child in CodeModelService.GetLogicalSupportedMemberNodes(node)) { var childName = CodeModelService.GetName(child); if (childName == name) { element = FileCodeModel.GetOrCreateCodeElement<EnvDTE.CodeElement>(child); return true; } } element = null; return false; } public override int Count { get { var node = LookupNode(); return CodeModelService.GetOptionNodes(node).Count() + CodeModelService.GetImportNodes(node).Count() + CodeModelService.GetAttributeNodes(node).Count() + CodeModelService.GetLogicalSupportedMemberNodes(node).Count(); } } } }
// 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 System.Linq; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Collections { [ComVisible(true)] [ComDefaultInterface(typeof(ICodeElements))] public sealed class NamespaceCollection : AbstractCodeElementCollection { internal static EnvDTE.CodeElements Create( CodeModelState state, object parent, FileCodeModel fileCodeModel, SyntaxNodeKey nodeKey) { var collection = new NamespaceCollection(state, parent, fileCodeModel, nodeKey); return (EnvDTE.CodeElements)ComAggregate.CreateAggregatedObject(collection); } private readonly ComHandle<EnvDTE.FileCodeModel, FileCodeModel> _fileCodeModel; private readonly SyntaxNodeKey _nodeKey; private NamespaceCollection( CodeModelState state, object parent, FileCodeModel fileCodeModel, SyntaxNodeKey nodeKey) : base(state, parent) { Debug.Assert(fileCodeModel != null); _fileCodeModel = new ComHandle<EnvDTE.FileCodeModel, FileCodeModel>(fileCodeModel); _nodeKey = nodeKey; } private FileCodeModel FileCodeModel { get { return _fileCodeModel.Object; } } private bool IsRootNamespace { get { return _nodeKey == SyntaxNodeKey.Empty; } } private SyntaxNode LookupNode() { if (!IsRootNamespace) { return FileCodeModel.LookupNode(_nodeKey); } else { return FileCodeModel.GetSyntaxRoot(); } } private EnvDTE.CodeElement CreateCodeOptionsStatement(SyntaxNode node, SyntaxNode parentNode) { CodeModelService.GetOptionNameAndOrdinal(parentNode, node, out var name, out var ordinal); return CodeOptionsStatement.Create(this.State, this.FileCodeModel, name, ordinal); } private EnvDTE.CodeElement CreateCodeImport(SyntaxNode node, AbstractCodeElement parentElement) { var name = CodeModelService.GetImportNamespaceOrType(node); return CodeImport.Create(this.State, this.FileCodeModel, parentElement, name); } private EnvDTE.CodeElement CreateCodeAttribute(SyntaxNode node, SyntaxNode parentNode, AbstractCodeElement parentElement) { CodeModelService.GetAttributeNameAndOrdinal(parentNode, node, out var name, out var ordinal); return (EnvDTE.CodeElement)CodeAttribute.Create(this.State, this.FileCodeModel, parentElement, name, ordinal); } internal override Snapshot CreateSnapshot() { var node = LookupNode(); var parentElement = !this.IsRootNamespace ? (AbstractCodeElement)this.Parent : null; var nodesBuilder = ArrayBuilder<SyntaxNode>.GetInstance(); nodesBuilder.AddRange(CodeModelService.GetOptionNodes(node)); nodesBuilder.AddRange(CodeModelService.GetImportNodes(node)); nodesBuilder.AddRange(CodeModelService.GetAttributeNodes(node)); nodesBuilder.AddRange(CodeModelService.GetLogicalSupportedMemberNodes(node)); return new NodeSnapshot(this.State, _fileCodeModel, node, parentElement, nodesBuilder.ToImmutableAndFree()); } protected override bool TryGetItemByIndex(int index, out EnvDTE.CodeElement element) { var node = LookupNode(); var parentElement = !this.IsRootNamespace ? (AbstractCodeElement)this.Parent : null; var currentIndex = 0; // Option statements var optionNodes = CodeModelService.GetOptionNodes(node); var optionNodeCount = optionNodes.Count(); if (index < currentIndex + optionNodeCount) { var child = optionNodes.ElementAt(index - currentIndex); element = CreateCodeOptionsStatement(child, node); return true; } currentIndex += optionNodeCount; // Imports/using statements var importNodes = CodeModelService.GetImportNodes(node); var importNodeCount = importNodes.Count(); if (index < currentIndex + importNodeCount) { var child = importNodes.ElementAt(index - currentIndex); element = CreateCodeImport(child, parentElement); return true; } currentIndex += importNodeCount; // Attributes var attributeNodes = CodeModelService.GetAttributeNodes(node); var attributeNodeCount = attributeNodes.Count(); if (index < currentIndex + attributeNodeCount) { var child = attributeNodes.ElementAt(index - currentIndex); element = CreateCodeAttribute(child, node, parentElement); return true; } currentIndex += attributeNodeCount; // Members var memberNodes = CodeModelService.GetLogicalSupportedMemberNodes(node); var memberNodeCount = memberNodes.Count(); if (index < currentIndex + memberNodeCount) { var child = memberNodes.ElementAt(index - currentIndex); element = FileCodeModel.GetOrCreateCodeElement<EnvDTE.CodeElement>(child); return true; } element = null; return false; } protected override bool TryGetItemByName(string name, out EnvDTE.CodeElement element) { var node = LookupNode(); var parentElement = !IsRootNamespace ? (AbstractCodeElement)Parent : null; // Option statements foreach (var child in CodeModelService.GetOptionNodes(node)) { CodeModelService.GetOptionNameAndOrdinal(node, child, out var childName, out var ordinal); if (childName == name) { element = CodeOptionsStatement.Create(State, FileCodeModel, childName, ordinal); return true; } } // Imports/using statements foreach (var child in CodeModelService.GetImportNodes(node)) { var childName = CodeModelService.GetImportNamespaceOrType(child); if (childName == name) { element = CodeImport.Create(State, FileCodeModel, parentElement, childName); return true; } } // Attributes foreach (var child in CodeModelService.GetAttributeNodes(node)) { CodeModelService.GetAttributeNameAndOrdinal(node, child, out var childName, out var ordinal); if (childName == name) { element = (EnvDTE.CodeElement)CodeAttribute.Create(State, FileCodeModel, parentElement, childName, ordinal); return true; } } // Members foreach (var child in CodeModelService.GetLogicalSupportedMemberNodes(node)) { var childName = CodeModelService.GetName(child); if (childName == name) { element = FileCodeModel.GetOrCreateCodeElement<EnvDTE.CodeElement>(child); return true; } } element = null; return false; } public override int Count { get { var node = LookupNode(); return CodeModelService.GetOptionNodes(node).Count() + CodeModelService.GetImportNodes(node).Count() + CodeModelService.GetAttributeNodes(node).Count() + CodeModelService.GetLogicalSupportedMemberNodes(node).Count(); } } } }
-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/ShadowCopyAnalyzerAssemblyLoader.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.IO; using System.Reflection; using System.Threading; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis { internal sealed class ShadowCopyAnalyzerAssemblyLoader : DefaultAnalyzerAssemblyLoader { /// <summary> /// The base directory for shadow copies. Each instance of /// <see cref="ShadowCopyAnalyzerAssemblyLoader"/> gets its own /// subdirectory under this directory. This is also the starting point /// for scavenge operations. /// </summary> private readonly string _baseDirectory; internal readonly Task DeleteLeftoverDirectoriesTask; /// <summary> /// The directory where this instance of <see cref="ShadowCopyAnalyzerAssemblyLoader"/> /// will shadow-copy assemblies, and the mutex created to mark that the owner of it is still active. /// </summary> private readonly Lazy<(string directory, Mutex)> _shadowCopyDirectoryAndMutex; /// <summary> /// Used to generate unique names for per-assembly directories. Should be updated with <see cref="Interlocked.Increment(ref int)"/>. /// </summary> private int _assemblyDirectoryId; public ShadowCopyAnalyzerAssemblyLoader(string baseDirectory = null) { if (baseDirectory != null) { _baseDirectory = baseDirectory; } else { _baseDirectory = Path.Combine(Path.GetTempPath(), "CodeAnalysis", "AnalyzerShadowCopies"); } _shadowCopyDirectoryAndMutex = new Lazy<(string directory, Mutex)>( () => CreateUniqueDirectoryForProcess(), LazyThreadSafetyMode.ExecutionAndPublication); DeleteLeftoverDirectoriesTask = Task.Run((Action)DeleteLeftoverDirectories); } private void DeleteLeftoverDirectories() { // Avoid first chance exception if (!Directory.Exists(_baseDirectory)) return; IEnumerable<string> subDirectories; try { subDirectories = Directory.EnumerateDirectories(_baseDirectory); } catch (DirectoryNotFoundException) { return; } foreach (var subDirectory in subDirectories) { string name = Path.GetFileName(subDirectory).ToLowerInvariant(); Mutex mutex = null; try { // We only want to try deleting the directory if no-one else is currently // using it. That is, if there is no corresponding mutex. if (!Mutex.TryOpenExisting(name, out mutex)) { ClearReadOnlyFlagOnFiles(subDirectory); Directory.Delete(subDirectory, recursive: true); } } catch { // If something goes wrong we will leave it to the next run to clean up. // Just swallow the exception and move on. } finally { if (mutex != null) { mutex.Dispose(); } } } } #nullable enable protected override string GetPathToLoad(string fullPath) { string assemblyDirectory = CreateUniqueDirectoryForAssembly(); string shadowCopyPath = CopyFileAndResources(fullPath, assemblyDirectory); return shadowCopyPath; } #nullable disable private static string CopyFileAndResources(string fullPath, string assemblyDirectory) { string fileNameWithExtension = Path.GetFileName(fullPath); string shadowCopyPath = Path.Combine(assemblyDirectory, fileNameWithExtension); CopyFile(fullPath, shadowCopyPath); string originalDirectory = Path.GetDirectoryName(fullPath); string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fileNameWithExtension); string resourcesNameWithoutExtension = fileNameWithoutExtension + ".resources"; string resourcesNameWithExtension = resourcesNameWithoutExtension + ".dll"; foreach (var directory in Directory.EnumerateDirectories(originalDirectory)) { string directoryName = Path.GetFileName(directory); string resourcesPath = Path.Combine(directory, resourcesNameWithExtension); if (File.Exists(resourcesPath)) { string resourcesShadowCopyPath = Path.Combine(assemblyDirectory, directoryName, resourcesNameWithExtension); CopyFile(resourcesPath, resourcesShadowCopyPath); } resourcesPath = Path.Combine(directory, resourcesNameWithoutExtension, resourcesNameWithExtension); if (File.Exists(resourcesPath)) { string resourcesShadowCopyPath = Path.Combine(assemblyDirectory, directoryName, resourcesNameWithoutExtension, resourcesNameWithExtension); CopyFile(resourcesPath, resourcesShadowCopyPath); } } return shadowCopyPath; } private static void CopyFile(string originalPath, string shadowCopyPath) { var directory = Path.GetDirectoryName(shadowCopyPath); Directory.CreateDirectory(directory); File.Copy(originalPath, shadowCopyPath); ClearReadOnlyFlagOnFile(new FileInfo(shadowCopyPath)); } private static void ClearReadOnlyFlagOnFiles(string directoryPath) { DirectoryInfo directory = new DirectoryInfo(directoryPath); foreach (var file in directory.EnumerateFiles(searchPattern: "*", searchOption: SearchOption.AllDirectories)) { ClearReadOnlyFlagOnFile(file); } } private static void ClearReadOnlyFlagOnFile(FileInfo fileInfo) { try { if (fileInfo.IsReadOnly) { fileInfo.IsReadOnly = false; } } catch { // There are many reasons this could fail. Ignore it and keep going. } } private string CreateUniqueDirectoryForAssembly() { int directoryId = Interlocked.Increment(ref _assemblyDirectoryId); string directory = Path.Combine(_shadowCopyDirectoryAndMutex.Value.directory, directoryId.ToString()); Directory.CreateDirectory(directory); return directory; } private (string directory, Mutex mutex) CreateUniqueDirectoryForProcess() { string guid = Guid.NewGuid().ToString("N").ToLowerInvariant(); string directory = Path.Combine(_baseDirectory, guid); var mutex = new Mutex(initiallyOwned: false, name: guid); Directory.CreateDirectory(directory); return (directory, mutex); } } }
// 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.IO; using System.Reflection; using System.Threading; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis { internal sealed class ShadowCopyAnalyzerAssemblyLoader : DefaultAnalyzerAssemblyLoader { /// <summary> /// The base directory for shadow copies. Each instance of /// <see cref="ShadowCopyAnalyzerAssemblyLoader"/> gets its own /// subdirectory under this directory. This is also the starting point /// for scavenge operations. /// </summary> private readonly string _baseDirectory; internal readonly Task DeleteLeftoverDirectoriesTask; /// <summary> /// The directory where this instance of <see cref="ShadowCopyAnalyzerAssemblyLoader"/> /// will shadow-copy assemblies, and the mutex created to mark that the owner of it is still active. /// </summary> private readonly Lazy<(string directory, Mutex)> _shadowCopyDirectoryAndMutex; /// <summary> /// Used to generate unique names for per-assembly directories. Should be updated with <see cref="Interlocked.Increment(ref int)"/>. /// </summary> private int _assemblyDirectoryId; public ShadowCopyAnalyzerAssemblyLoader(string baseDirectory = null) { if (baseDirectory != null) { _baseDirectory = baseDirectory; } else { _baseDirectory = Path.Combine(Path.GetTempPath(), "CodeAnalysis", "AnalyzerShadowCopies"); } _shadowCopyDirectoryAndMutex = new Lazy<(string directory, Mutex)>( () => CreateUniqueDirectoryForProcess(), LazyThreadSafetyMode.ExecutionAndPublication); DeleteLeftoverDirectoriesTask = Task.Run((Action)DeleteLeftoverDirectories); } private void DeleteLeftoverDirectories() { // Avoid first chance exception if (!Directory.Exists(_baseDirectory)) return; IEnumerable<string> subDirectories; try { subDirectories = Directory.EnumerateDirectories(_baseDirectory); } catch (DirectoryNotFoundException) { return; } foreach (var subDirectory in subDirectories) { string name = Path.GetFileName(subDirectory).ToLowerInvariant(); Mutex mutex = null; try { // We only want to try deleting the directory if no-one else is currently // using it. That is, if there is no corresponding mutex. if (!Mutex.TryOpenExisting(name, out mutex)) { ClearReadOnlyFlagOnFiles(subDirectory); Directory.Delete(subDirectory, recursive: true); } } catch { // If something goes wrong we will leave it to the next run to clean up. // Just swallow the exception and move on. } finally { if (mutex != null) { mutex.Dispose(); } } } } #nullable enable protected override string GetPathToLoad(string fullPath) { string assemblyDirectory = CreateUniqueDirectoryForAssembly(); string shadowCopyPath = CopyFileAndResources(fullPath, assemblyDirectory); return shadowCopyPath; } #nullable disable private static string CopyFileAndResources(string fullPath, string assemblyDirectory) { string fileNameWithExtension = Path.GetFileName(fullPath); string shadowCopyPath = Path.Combine(assemblyDirectory, fileNameWithExtension); CopyFile(fullPath, shadowCopyPath); string originalDirectory = Path.GetDirectoryName(fullPath); string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fileNameWithExtension); string resourcesNameWithoutExtension = fileNameWithoutExtension + ".resources"; string resourcesNameWithExtension = resourcesNameWithoutExtension + ".dll"; foreach (var directory in Directory.EnumerateDirectories(originalDirectory)) { string directoryName = Path.GetFileName(directory); string resourcesPath = Path.Combine(directory, resourcesNameWithExtension); if (File.Exists(resourcesPath)) { string resourcesShadowCopyPath = Path.Combine(assemblyDirectory, directoryName, resourcesNameWithExtension); CopyFile(resourcesPath, resourcesShadowCopyPath); } resourcesPath = Path.Combine(directory, resourcesNameWithoutExtension, resourcesNameWithExtension); if (File.Exists(resourcesPath)) { string resourcesShadowCopyPath = Path.Combine(assemblyDirectory, directoryName, resourcesNameWithoutExtension, resourcesNameWithExtension); CopyFile(resourcesPath, resourcesShadowCopyPath); } } return shadowCopyPath; } private static void CopyFile(string originalPath, string shadowCopyPath) { var directory = Path.GetDirectoryName(shadowCopyPath); Directory.CreateDirectory(directory); File.Copy(originalPath, shadowCopyPath); ClearReadOnlyFlagOnFile(new FileInfo(shadowCopyPath)); } private static void ClearReadOnlyFlagOnFiles(string directoryPath) { DirectoryInfo directory = new DirectoryInfo(directoryPath); foreach (var file in directory.EnumerateFiles(searchPattern: "*", searchOption: SearchOption.AllDirectories)) { ClearReadOnlyFlagOnFile(file); } } private static void ClearReadOnlyFlagOnFile(FileInfo fileInfo) { try { if (fileInfo.IsReadOnly) { fileInfo.IsReadOnly = false; } } catch { // There are many reasons this could fail. Ignore it and keep going. } } private string CreateUniqueDirectoryForAssembly() { int directoryId = Interlocked.Increment(ref _assemblyDirectoryId); string directory = Path.Combine(_shadowCopyDirectoryAndMutex.Value.directory, directoryId.ToString()); Directory.CreateDirectory(directory); return directory; } private (string directory, Mutex mutex) CreateUniqueDirectoryForProcess() { string guid = Guid.NewGuid().ToString("N").ToLowerInvariant(); string directory = Path.Combine(_baseDirectory, guid); var mutex = new Mutex(initiallyOwned: false, name: guid); Directory.CreateDirectory(directory); return (directory, mutex); } } }
-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/SwitchStatementSyntax.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.Syntax; namespace Microsoft.CodeAnalysis.CSharp.Syntax { public partial class SwitchStatementSyntax { public SwitchStatementSyntax Update(SyntaxToken switchKeyword, SyntaxToken openParenToken, ExpressionSyntax expression, SyntaxToken closeParenToken, SyntaxToken openBraceToken, SyntaxList<SwitchSectionSyntax> sections, SyntaxToken closeBraceToken) => Update(AttributeLists, switchKeyword, openParenToken, expression, closeParenToken, openBraceToken, sections, closeBraceToken); } } namespace Microsoft.CodeAnalysis.CSharp { public partial class SyntaxFactory { public static SwitchStatementSyntax SwitchStatement(SyntaxToken switchKeyword, SyntaxToken openParenToken, ExpressionSyntax expression, SyntaxToken closeParenToken, SyntaxToken openBraceToken, SyntaxList<SwitchSectionSyntax> sections, SyntaxToken closeBraceToken) => SwitchStatement(attributeLists: default, switchKeyword, openParenToken, expression, closeParenToken, openBraceToken, sections, closeBraceToken); } }
// 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.Syntax; namespace Microsoft.CodeAnalysis.CSharp.Syntax { public partial class SwitchStatementSyntax { public SwitchStatementSyntax Update(SyntaxToken switchKeyword, SyntaxToken openParenToken, ExpressionSyntax expression, SyntaxToken closeParenToken, SyntaxToken openBraceToken, SyntaxList<SwitchSectionSyntax> sections, SyntaxToken closeBraceToken) => Update(AttributeLists, switchKeyword, openParenToken, expression, closeParenToken, openBraceToken, sections, closeBraceToken); } } namespace Microsoft.CodeAnalysis.CSharp { public partial class SyntaxFactory { public static SwitchStatementSyntax SwitchStatement(SyntaxToken switchKeyword, SyntaxToken openParenToken, ExpressionSyntax expression, SyntaxToken closeParenToken, SyntaxToken openBraceToken, SyntaxList<SwitchSectionSyntax> sections, SyntaxToken closeBraceToken) => SwitchStatement(attributeLists: default, switchKeyword, openParenToken, expression, closeParenToken, openBraceToken, sections, closeBraceToken); } }
-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/.editorconfig
# Prevent unit tests from inheriting an EditorConfig file from a parent directory root = true
# Prevent unit tests from inheriting an EditorConfig file from a parent directory root = true
-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
./scripts/all-ci-times.xlsx
PK!uCc[Content_Types].xml (ĖN0EHC-J\@5ec H{DulBMHl<<\{2Ln׵N౲&gو%`U1f a@6vz~6y8 pZ`fzRX_@~Ɲs1>& ih4trX<։,NlX9J@NҨ_%d`Y9 $4Oqϴ5RDM6Zk~.mQTv CA(,B8f̗=8y.6Ҭ/ cO>wVD ǰрC?"ƒz *tp?P^ =$ycREn.moc\Ym=1y_=>1O_v?/:*WlSGBCrW&Rك+P;<WL?PK!U0#L _rels/.rels (MO0 HݐBKwAH!T~I$ݿ'TG~<!4;#wqu*&rFqvGJy(v*K#FD.W =ZMYbBS7ϛז ?9Lҙsbgٮ|l!USh9ibr:"y_dlD|-NR"42G%Z4˝y7 ëɂPK!?w U1xl/workbook.xmlUo:~O *_کڲ%RSfiRM1iC},WZ*ÈWLOa RZȊ'k?wRT:1u캚弤DּK&UI սkisMYEnIE;X!L0>)ye: jE{WRnjɲ;Q؂bThxN`zU)Zfݎ+r?=+UNJhj%-si& ~IѺLKj3Oi0~0z҈ x=J!P?ﰖ7;c6Ymbh0\U sjŞP t1+jrԨ"xMCXVJb[jѫgҥK;z0K2 >@@鮢!'dp[1۟q0^0u293d8H0Ψ(f6&ߩB'8}iBqlmܻ|tch{#Tn8! mZHMa?/90&! m(2KYhcF3J UmU1uH5F<K9C{=T<%߂}!A؃@zJVtmvߚ mD,I8x1~A63DpHfyO~ͩilMض~2&va=(̺w Z#/\8|<r|y{hs޺(>-n۟PK!JaGxl/_rels/workbook.xml.rels (j0 ѽqP:{)0Mlc?y6У$41f9#u)(ڛε ^OW 3H./6kNOd@"8R`ÃT[4e>KAsc+EY5iQw~ om4]~ ɉ -i^Yy\YD>qW$KS3b2k T>:3[/%s* }+4?rV PK!&皲Mxl/worksheets/sheet1.xmlYے6}OU $xR}V*3 8\6{Z`@ bƶ:-OzM2O+;ȶSVYE}tOO?p_$,@8+K-$J'?''9EUxrsDQvt BEnpHd/Yr"9F|NeSನr^yvV_kPǧS^DG;QlZ7uSE^dxnwHO-TN`EKH}'XЁIK_>P"o|K" ̱o֛:N~-,S|ln[ErXx#HVԍLRlUUOg|y2q/#1ϿNͤ($L`Vߵogsۋm `0򷟓Uru1D5v8?'ИE[W6/eg5XvkH/ > 7Zn7\Mk6Q Hnxɮ ,mX(a^ѝ ƗjBukuݠVxܩ^ J>rb4%0ZTn`psn{ng :}qAHוݐ;"/HxfOL^Hv&N>xEMQEDKCb^[Cņ ; y<.wsyFT{Dqpy^LwH4`t0!NPpcT)ܩCSgLF sH s5؂9F挥!w̉sҩk †SͧC!FDC87x ]^Zwjz1#se:8TkO]3ISp ǧv[XrF`_qGF8L^H4)/G,K:;< {Q0kQ S!J25<kUYX4176b Sk8T{0Ɖ@8T{ᰀx͑wP gJ XJª=+ j͘@~ ZpHOLp{q|9gC^{OPuz|y 8TD@=g|6ơYKC2|Mߪު]Զx<Kqf/AulV+ yH䟋0X^iQ5Kc7PŇw߁}\4( ֭)Dl|j@!(/m;Aʠ 8YHC|~3U{sG 7=cɹp*p3 .A8`A{šYlC(V8 dmGp8<VF>֞K>`rQ)Ϻ`=\B3V!eg/ 6m' i^7NYտ8b%F;.¶d٭?| m7hʕs$u 2v[[O&Tc~n)%*SiCN/|3rdgdǼq~I 80y^_dҽg!X<~q_PK!uxl/worksheets/sheet2.xmlY[6~x6v,<z}f E'i1$` gyM*+ {uCRlLNULJm/VwV_4@8T s߯4+8e|cfP Bb˒tY$/yz[25̿zΎ-Onq }Vm@]'O柟E?wLy/&4#MyEUjvc/8_z=)aa,F0ށ)K]S0 Ì$ C\R*s<aeS 7]@f[}w)$ާ?+ۃ/#e奏EEt&_>^(݃$];(;Muٿ6/4{zA5{̷_ij0{Ny|ey 1A(KU_mGc}7i &`rHmTg?Jr2xs]10v`Bir{}[}[F@F :T,qj5%6V)U[\][_ [պ)V[wK,օےxH9AAޫY`ZVr68f". `%Nem'*xz& {I8aj6p)OJ;\*|qуc!/v<kky|RqGBN>d̝)1w<Pyak/6N'^Bs}>)q+w;;TK̻3?N .; "wow;kkl1KR(ҷҷCkm7vK+`r*8P>kcT *C~FWBem'j,֞( Q<A89 <N\@xr]zLlbtyq ȻaH'*'Ha3F G#zK>@=EvƘCc!%v1%ciɵu<Ha$7FF" ae7l;kP$wF$wC"rBΫ]!qR퉺9D2HG3f2%,j@AxH2Ր6VᔂB,.B<ir af( !|׊hc, ũ@ .EIe{İ63{}}}(G0 jTnXx<d )䤐`_pR5-Vp~u<`=r঑h&Q8r@(70IEW5 N T1{D.(EIؤJK{s^1<Pa @ >SfYZ0mc w[ O&@ںH(Y=NρU3 n7mʄҮ0npJ^"JZ~XxJSiۣcO١r9w+ۓm)O.8[2?5O=f<؈wEQ 2~JN9Wo4^#PK!N xl/theme/theme1.xmlY͋7? sw5%l$dQV32%9R(Bo=@ $'#$lJZv G~ztҽzG ’_P=ؘ$Ӗk8(4|OHe n ,K۟~rmDlI9*f8&H#ޘ+R#^bP{}2!# J{O1B (W%òBR!a1;{(~h%/V&DYCn2L`|Xsj Z{_\Zҧh4:na PաWU_]נT E A)>\Çfgנ_[K^PkPDIr.jwd A)Q RSLX"7Z2>R$I O(9%o&`T) JU>#02]`XRxbL+7 /={=_*Kn%SSՏ__7'Ŀ˗:/}}O!c&a?0BĒ@v^[ uX<kٺ$Fcvw:ચpLݓ󹉻Бk.J3WRٍe 8SCC=2L%Cr`%R.Cbe mèk=|d#a[ 0~h.QR9D15d2rG&/$Dz)c,K:A ]6Krҹ3=v؍P<sL~&!EwI|;D=CP1ܷ f"j'ete<ص͉3;:ڻSt{>sXa3W"`J+U`ek)r+emgoqx(ߤDJ]8TzM5)0IYgz|]p+~o`_=|j Qk<a ݂\DZl؛6FVω'wws[:(eD ,kzhpsyUs^f^>ekZAj|&O3!ŻBw}ь0Q'j"5,ܔ#-q&?'2ڏ ZCeLTx3&cu+ЭNxNg x)\CJZ=ޭ~TwY(aLfQuQ_B^g^ٙXtXPꗡZFq 0mxEAAfc ΙFz3Pb/3 tSٺqyjuiE-#t00,;͖Yƺ2Obr3kE"'&&S;nj*#4kx#[SvInwaD:\N1{-_- 4m+W>Z@+qt;x2#iQNSp$½:7XX/+r1w`h׼9#:Pvd5O+Oٚ.<O7sig*t; CԲ*nN-rk.yJ}0-2MYNÊQ۴3, O6muF8='?ȝZu@,Jܼfw<zp8RPBo#(Ȕ6`ܓY߼9'-~)lJ-aTRvV\u*`Q\\aEvi.-ͅL_\|q ʠYmvjf=(N:^[ zݰ<# nP7 r[j%e~YJ; +c`)}djPK!Z uB xl/styles.xml\[oF~`Y#pەJ}57 {ؒV=gl<38nsf>mTURcݺ2u-Σb䫱CZE|E?M~aT4D도 ,uoE˕Q8\T8(K 4F&^#\g HOu/*uHy&bZ]^ESPukam~ikr'ݓ%QYTŒ\Q,IF ߆dyi o7"FO0|d,rRiQ BG~ʋg&{K7&HR#;p=Y\_1 d^&x2̒>m ,IQ gggѾ$GrڪV=Io "Du]gF1\z@nL`:a#̟ b¼,s'tjE+Qtٽc5R3'\^LϓAK% ZA MҴ莃LF!qp5PsX[WٲiPi@-V3`h\N3Y-lwSֽ31荇͇Pufº])i$uy5}há:R'F'"ƋMx (0g hx *r(*]adfG@QT9 Euq(*r(*t8Wˤr(*vl2<iEn{ۣ5a/UxI`VbW~b B%=-pUa{нFX'I„aƮE|6;v9p=_ol:ŋd[>?p#^Fk'9FZrpbG ]Țz6r#lHȍEb7^8IwGg0<9fߟ'1]fj㇮"%7B7Ip#ƛOhZpkj4*G7.hMd34--{}`.clx&e@oRi,!є8v|&<iEa#Bo:ӎ1}#X >~{`</Jϔv;@xRON `BX42 @WXy`abkp%rAh &_d[\37GXUbLc.bUg%]ЁyeX\"qTZPG ʯqj7(<zr!ī AWj 5*Ϗȑng G[U~ɠ>Aڪ$GVy2O>?: aZO)>Iy~T.wPޜm-A%i{{zlzbHuIi7Q=[06‰IRُ>@G M[#aAk, E\,@h0qXc5 gcAipXP 4X=I߻Hg 2zX,X9,0\,G,|.# \,G,\6.f~I09IrbqHrbq&bq+'x,G1Oybq}IeFoK2FaHFaQYHFaJFa+Uj3Eﺒޝ] cK^6) odJHLc=i3˨ vyHY{I\D(  okBu&L;D`m ߣ= bR |i#$R,2_)^=rxCʰߋ%{|ZSrx}EI!i˞J\Xxh7r7i LGBr%޻#,s-}#M[;3%~ܻ&%/:+}\5^ 1wb5bx͗ ڦLwӁ{ؽ9\'z7ylz{m^ Fr^/c忱sc;է-ڼ7o<i~8 <˾;/8ݽ7oUyT޻&II.BYbtPK!xl/sharedStrings.xmlSQK0~%ڹ)v@b{.:m:}*ei7p-'Vx|\Xa 1.2"NB.R.j*M(:-`Xg[:PlR49Pţ^zP"y,֠br 2cwt1 Y('k}IceIN^ٶrЏ kJ>^I1c;K٦Oԡ9oj;DЀ73UO=m:4NvEH5-cZc.d;(Hέw%|o0)08 L4q$+c>l׼4w PK!8w/xl/drawings/drawing1.xmlTn0`N IQJ^Uv2&;$Uw_ۘ&[0|Ͱ= =8P!;r(#.~"o TոJx[|:";ʭLs*|_X2}p1`b5Q kR tx h,lfKkFZ.FU#0Jr h4E6'{#G'݅V[kx9\t+^"<h|>FxOyxv <P0`"x][ y8< 9 `+ev={EWͼB%&6Ur(^VQ0͈X'nݡyJިϛ#t=+a[vm ^nP{e\xIYͽu<<7Z~mV1n*vD<\g-4Xv^ƞGgpʡޭ`6/@F%jrr9['nc{шSA2+9"lDr#[NԸv&d%"3'бvQeE8NcML}X?*PK!ܟ ^Nxl/charts/chart1.xml\o8~> Y[FE"Eq}iw2W%*.KKqm;FbQj8gi2$ep@(`T󇃊l<#R =_^F@%Y5ѨI+=/Hyb r4/T&#0d(+ q]"$dTpQS@u-Bniު12գ<T2䌚V'Cc8b ΖdSQXu6'0/3i4>J()3*3 \Ky;I<E]hnILox/<y >/u\`!{%0?2eBc=MBDa֎r8If8`i=<74 ?2_,|(eNY' "eE~%Q@ßE_ I.Ġ _KK2,b-EH6qRSt~QC#pS}Gmqb>f0ذ+ rY~ @7?>Ib64 O<$O$l0)5$u621:o_,DGP:nldzS؁?LKQq#R(HQqy ,6fWxcz0ɴ(flQN%gMߤśKUEu2(khGjwTQ 9|0!4L/ ٜi R<AD Ylb=1֛-%d }SQ6v`pJVЧv3j$)l'v1! Dc9INJ4sLe !I,-g OP 2.qyI6)l8_iu^Ή\$FXd(;6\ _bzb ar.t</4UrɇL]Te₳ԌǏ8c;x)g=)sK s"|mqBP Pu0 鱉 q2?=Uu6!zEdJ"hC. siR]мgj{r"wes'ڐG0/wݓdvAoV= v[zL[6XP⻛ΑֹBzo⬾D)$Iq(@K}3pcHi:t2{vR*EZ<2"|@lɤpuQV`kl 7Wqa>'4W7I<㥷s=f`șUZ.3,uG6Z'ZOUJOēd5)mwǫl99mo ay<YMylcv0um;:Wנ&˶Md.z'ZwM&us,P>j ISBY%Dahk=l#N<sbXagk=ޫ)vk!Y&M#W O 쩣v,˚"Ȓ@ vӏ{4n~~,%<Ћ]_ (f b1c"9uwofIX @ YB/Ý0,Lt;{լSRn-@`TlzU[Uu,iwju` 3M;[*[ZӞBZo+B}ϳS<L\|bmdƌf= _M0.w~rst̍]ovq㑆󰦾džfG^/&=n|!lwIK^g[>b-Eپ3kƖ9[ 49 ]1}ْ/Qa\fZ0n a@`v"Hf=n]Al@ $@E$ϴCvEld Wd/Jjhrx&C{kZ`M :dsY!x)ta{7ߔ !EC]7^!ptp-:;:cv!"etX5ԷF2"3Ohݱ A?Als.gI2=7[ALMn{~ϛ|%>0 6r>KZ}dX T'4"-cK[vJ%<]2Lߥ"}ò< 칦 ;mP?+Pi$n(pZ#|"|r=ɒ |g? !5C#p`x 2Gap "[[dOpI?M+G,#p#'&`eLg~* LY&(3loutX?h}@cV&pس 5et'*B Z=ێaZ"5#aDܾ7  mG,؞Z-}ݵDؗ>+c_ \vJEQ8VlH#}7ŧW-ͰmX' #Y# kK\a;Cbfv0R|M`,dyöFxQ{,񭡝TKyC8 -ͭ ^ ș@4kM8m| IMS]EKXI2>iݶ₰mfpr5W&?#yW.;{Ы#V9=سM&T}v̒#@EY!"jë]ةL`l4fLve&67x%;=7vThp#9/[lW{muL!^ąFXLi|)?=bc?C8P}n}Nϗ3~Y"}qUQ/ՑLPALvR88 D|m@S'a煰1QLY5 7QSxŽ? |Q< A%Mb}$A6uȈ}u~r8A=xQ=%NbZro']N!ZBeU)݃Kv*orvw.ZES.QD/ghs,PK!x&xl/charts/style1.xmlZr:~ R`Bfd:rL-ZYD yMwhm$oW b Fq!j |_Scu@ %"}QD)V/gA4xeKDBX !'1YZW~)G ӿF7=L7#ƿ^x(I@+RS.$,VMrϤ !m+fQj_(_b4ҵC}}zI$ߠ¼`M&B.@SV\%O ̸7~E^!3N֊O tfh ,y5U^@FSsLׯ܊Y{0aaHICZوrR?g~WvZ81V < 7 ao#]׻|gkFjpQϝ5oL7%5T&n(,X ڞ)"\@B8$D#&҆z" " ^FM|{ po%Á.Wvuz=q L5Sn(uFN)#z> 7GLSD{ +A8%[oN!kbty:g;.40lUWܹٓ`NBuD0Md nS3HlXB*;ӿWеk| 9@`@9 NZc|@e}!Cͮ SI"tR.}u2}ӾLmbd}޷f󏸆xyG]Fe{ʖłMoK H;Yqߗh<XX]c:v` w q<0BP},7?8"uNcXmBb- ScAsJG⏊Ś~!~Cp$8$o`]fVALϤPyeK&u ')ջSʽӪRn(>#ۮCm:V6Ɗ9kߛT_KvtWV7h<`5M?/P tVpv[:#hNsY,9VcoqH>󏏮su˪Fw&OnPK!nxl/charts/colors1.xmlAn0Eq "¦'Mlb ۥp{PhC!;$/WH&HFkֆ8 >5 y!E2T(x[-/؂ =`vSr HJn@Yښ`jjglO#>Kk†Z1FN+݃SٛkTOj ,[ӣRQq}QOFOy~ t:PK!2W0xl/drawings/drawing2.xmlTn0`N %@ªR1-#MRU}IM7? ˻#sp@@M϶9RBAg$D»ALfN]w"9;mEJo:hh:Q$  tx h 63uC.}SڶNjs7pTq]Xk0Eg%A,σΝǨs,N #OQ(‚е\\>}rXuH(j7zIE9|먼ԱWkɋ2M|<Dɻ kf6LإSV0>oiZoٵYq428+ouL2HVzb짯bTx .[oi\[[=Bt9C[l^J<i-r0N\#açgVrD/,وiG2PԸ v&d$"3'бvQe ۢKzCM&>_PK!Ro cNxl/charts/chart2.xmlko8|F&DK@˴^4b _ZΆXg3>&MzׄqH8[?~~d8$Q8Ĕ8"=$+Qb<%Iq9 ENS.Gs?Ci22 N|Rg/qD&yT$c J̀e\4h^ 6t$;Ӄΐ3Gu DcFP`ؽk7&8[ >FWٜÜf0h|0B3*3X+z;Q<*nInŰϡ2zޓOULIyԏ"/ oL50XdKv9 d|)N8m׏sMbp(FYBďs<wGs'W4%{KS;RŸE>$^x;P!_GS)pA3PQ}2F|x]\xG9Yl/m>3U,VG D@\ G A<>%Ib.'yϧq .$L>A♤J_s:t'ҷltԽmMcY83 q`y#*7nD` ME*A/ 21ar |}$.;U\TIV08%ef/LDxm$nL4&1.J(ϗ^7@oh!ثq!oPdI1g$pbBˆdIN(r+2xik{+rYS,9kLo<V%`BWtNT %)ޓX.x s&=;{80Ġ8hBX&ZL$zREJ>M,./y'Bd ;ZJ.qƗ7d Z-{ߋ3s,|m'q.B` `upJ ]Vq25bBfղ T@RltZa'by!a/,.tYN,\ՍA 0S`vo֔S v렝z[6QQ7݌4׹z⬺ D3Iqh.)X V\3%MSVHHyE#"rgM |*G낮ջ5^^Ņ_t\B% N~]:h7G}Js MӶ};p,߳A8Kk&i}v]d[շ>wjG c!UVRx?taF`:g;mVjN.B-lVJ其2!7zв|# 3q3y <˱Ɩ*vc/WY"/;3C~b9?5S?s)p&7 i =7,YrKvKpǷc7rVol^{L:;,)9k΂"hy~El8p {ܳk<bv5ЭcPv8rYj+ĝ{:`Mh㟞6XٛvԞh{fޕN\k{Z3 ;ߪbg=+z;r_28,wO\~%ٺ!qev#9w2;Sci B떏x얉 H p6̚w"[@hpvu'<[ 㻇wI]-xiZlWnP7sITQj6Г&܅@FhAMdY{OX@.L9$XdKHHg>y uy uCw^H~m|To"F #W38=·`g*Sl;wUmZHEEU=cC 2;b.:Fl }r-t e8M5k;RBnF`yv?չCǷS 廮Ȗ:V5Qu*?4|sنB8=! `~Aj ipgZ.?]s 0CHP]lM?U_|޹0Yn`" tC3 <_E%yS[r jG|G bnv/lDݢ|'\p<>8.1Y,\-SY& w|N?mCZ.Nx0tlǀ؇<Zy[ᡆ.Cϰ]OCp ;\Nۅvƒ!8ӎ|iuu 7! ֛@VJh'ٮij. (Z kPu-|vmt&CD7<;VV];3PZgNWi7;~* j7c>-Íw>0HWy0#5jK\٥JM B1V|SM`Jӆ}C f%l՞~CuqNc^JJ^xUY9 zOS @9NX@Jqt%NYPPik 2}Uu[ 췍 nϻE\*пG*re.>剪z@Cp?*Wk,9lK^e>j䯫ůFJZ@vRe&[4 D "=-*Uvtc94c-aĽK:%3!J_䅲FjАډV[CUJqX!QK<<f5$?qK\U+'8^\%9ip!~>';,ucȰՑM 5o qrEoI)Ѱ< mݒ&&>Ȇu&Q[7N3]9)C49apRX["rpp $-M =g jXWx"/eU!#x9@ PK!x&xl/charts/style2.xmlZr:~ R`Bfd:rL-ZYD yMwhm$oW b Fq!j |_Scu@ %"}QD)V/gA4xeKDBX !'1YZW~)G ӿF7=L7#ƿ^x(I@+RS.$,VMrϤ !m+fQj_(_b4ҵC}}zI$ߠ¼`M&B.@SV\%O ̸7~E^!3N֊O tfh ,y5U^@FSsLׯ܊Y{0aaHICZوrR?g~WvZ81V < 7 ao#]׻|gkFjpQϝ5oL7%5T&n(,X ڞ)"\@B8$D#&҆z" " ^FM|{ po%Á.Wvuz=q L5Sn(uFN)#z> 7GLSD{ +A8%[oN!kbty:g;.40lUWܹٓ`NBuD0Md nS3HlXB*;ӿWеk| 9@`@9 NZc|@e}!Cͮ SI"tR.}u2}ӾLmbd}޷f󏸆xyG]Fe{ʖłMoK H;Yqߗh<XX]c:v` w q<0BP},7?8"uNcXmBb- ScAsJG⏊Ś~!~Cp$8$o`]fVALϤPyeK&u ')ջSʽӪRn(>#ۮCm:V6Ɗ9kߛT_KvtWV7h<`5M?/P tVpv[:#hNsY,9VcoqH>󏏮su˪Fw&OnPK!nxl/charts/colors2.xmlAn0Eq "¦'Mlb ۥp{PhC!;$/WH&HFkֆ8 >5 y!E2T(x[-/؂ =`vSr HJn@Yښ`jjglO#>Kk†Z1FN+݃SٛkTOj ,[ӣRQq}QOFOy~ t:PK!<+#xl/worksheets/_rels/sheet1.xml.rels 0nz^D*dmoo.mgf?Q)R oi4'tGHL z4bOE8ЧvJiB>˗ SS;Rبɀ)NVC<D3v0t6K?,2cGIRȠJ}U_PK!=d+#xl/worksheets/_rels/sheet2.xml.rels 0nR{U,$dۛ xe<EӰra ;$^.Mc`)5 )RlqƔeU@sTY?P1jG>Cv]7{sɥFfAC)sdPu*/PK!D߼%#xl/drawings/_rels/drawing1.xml.rels 0nzЫXIFooӰ;7;E'r k\;^í 8mqr4,PMq c:a,Ų!FR@3tlr:fi hؓgAO_LQB ŧlu3l̀!& ) ,P_7PK!܁xl/charts/_rels/chart1.xml.relsJ0nAD6݃ U dLG3}?s<}>%P`fOcȳ(..RF + FW[HPD5J KYk &'2'Wȳ._݌3`1y겖fayJ)j̞⸾P$~kFs<cෝF+[޽qPK!&ꇻ%#xl/drawings/_rels/drawing2.xml.rels 0n "MzWXIFѷ7EA4N<Y)䝆R YMnp97;u8{GИ>ь)8XØR+vY@.; <AWHUEU)NClrB.PvĘ2@I YPV_ PK!z!xl/charts/_rels/chart2.xml.relsj0 Bhod(sCpk{}(929.o_g)ѱ$x ^])hkZP-.O/`s$+ LJy,5$K*%؅JÉbL:Y'Imo ;:iATwlf4irvvݞ킹YVOybn;Z?wZZX7PK!\w<KidocProps/core.xml (|]K0C}~v2oNbn k>HiDMrNrM *%)@1ͅZUy1'(r*NB;phZ-<Xmz. $3Z{oƎAR R[I}6m pWXz;`l": 96=3 HP,׃ 2rJw&t:9ۋ{`l6i>FȟS_5TfzmGوN;J<!6yRÁG!8*/b<8<_),{.@BO4لa#Ps_PK!S EGdocProps/app.xml (n0EW"AaP <EYjdI3~}) qf y\^ΐjs6狌3&ToKvCJ}ZdYX] EjԩCiJi܊PM0<". |E{2㲧V |9 Xomєn~Xހbڔn *bʵC AC[iQɞ= Vp[# 8%uSdcr]կ " 1j s`0qcW:[Gw@;b瑝_XY}b.D?'ى߭‡vn4Ent*SAާG7\7ozּn Oq*\d&5)^~PK-!uCc[Content_Types].xmlPK-!U0#L _rels/.relsPK-!?w U1xl/workbook.xmlPK-!JaG xl/_rels/workbook.xml.relsPK-!&皲M xl/worksheets/sheet1.xmlPK-!uxl/worksheets/sheet2.xmlPK-!N xl/theme/theme1.xmlPK-!Z uB "xl/styles.xmlPK-!*xl/sharedStrings.xmlPK-!8w/T,xl/drawings/drawing1.xmlPK-!ܟ ^N.xl/charts/chart1.xmlPK-!x&;xl/charts/style1.xmlPK-!nE@xl/charts/colors1.xmlPK-!2W0uAxl/drawings/drawing2.xmlPK-!Ro cNCxl/charts/chart2.xmlPK-!x&|Pxl/charts/style2.xmlPK-!n7Uxl/charts/colors2.xmlPK-!<+#gVxl/worksheets/_rels/sheet1.xml.relsPK-!=d+#eWxl/worksheets/_rels/sheet2.xml.relsPK-!D߼%#cXxl/drawings/_rels/drawing1.xml.relsPK-!܁`Yxl/charts/_rels/chart1.xml.relsPK-!&ꇻ%#oZxl/drawings/_rels/drawing2.xml.relsPK-!z!k[xl/charts/_rels/chart2.xml.relsPK-!\w<Ki{\docProps/core.xmlPK-!S EG^docProps/app.xmlPKa
PK!uCc[Content_Types].xml (ĖN0EHC-J\@5ec H{DulBMHl<<\{2Ln׵N౲&gو%`U1f a@6vz~6y8 pZ`fzRX_@~Ɲs1>& ih4trX<։,NlX9J@NҨ_%d`Y9 $4Oqϴ5RDM6Zk~.mQTv CA(,B8f̗=8y.6Ҭ/ cO>wVD ǰрC?"ƒz *tp?P^ =$ycREn.moc\Ym=1y_=>1O_v?/:*WlSGBCrW&Rك+P;<WL?PK!U0#L _rels/.rels (MO0 HݐBKwAH!T~I$ݿ'TG~<!4;#wqu*&rFqvGJy(v*K#FD.W =ZMYbBS7ϛז ?9Lҙsbgٮ|l!USh9ibr:"y_dlD|-NR"42G%Z4˝y7 ëɂPK!?w U1xl/workbook.xmlUo:~O *_کڲ%RSfiRM1iC},WZ*ÈWLOa RZȊ'k?wRT:1u캚弤DּK&UI սkisMYEnIE;X!L0>)ye: jE{WRnjɲ;Q؂bThxN`zU)Zfݎ+r?=+UNJhj%-si& ~IѺLKj3Oi0~0z҈ x=J!P?ﰖ7;c6Ymbh0\U sjŞP t1+jrԨ"xMCXVJb[jѫgҥK;z0K2 >@@鮢!'dp[1۟q0^0u293d8H0Ψ(f6&ߩB'8}iBqlmܻ|tch{#Tn8! mZHMa?/90&! m(2KYhcF3J UmU1uH5F<K9C{=T<%߂}!A؃@zJVtmvߚ mD,I8x1~A63DpHfyO~ͩilMض~2&va=(̺w Z#/\8|<r|y{hs޺(>-n۟PK!JaGxl/_rels/workbook.xml.rels (j0 ѽqP:{)0Mlc?y6У$41f9#u)(ڛε ^OW 3H./6kNOd@"8R`ÃT[4e>KAsc+EY5iQw~ om4]~ ɉ -i^Yy\YD>qW$KS3b2k T>:3[/%s* }+4?rV PK!&皲Mxl/worksheets/sheet1.xmlYے6}OU $xR}V*3 8\6{Z`@ bƶ:-OzM2O+;ȶSVYE}tOO?p_$,@8+K-$J'?''9EUxrsDQvt BEnpHd/Yr"9F|NeSನr^yvV_kPǧS^DG;QlZ7uSE^dxnwHO-TN`EKH}'XЁIK_>P"o|K" ̱o֛:N~-,S|ln[ErXx#HVԍLRlUUOg|y2q/#1ϿNͤ($L`Vߵogsۋm `0򷟓Uru1D5v8?'ИE[W6/eg5XvkH/ > 7Zn7\Mk6Q Hnxɮ ,mX(a^ѝ ƗjBukuݠVxܩ^ J>rb4%0ZTn`psn{ng :}qAHוݐ;"/HxfOL^Hv&N>xEMQEDKCb^[Cņ ; y<.wsyFT{Dqpy^LwH4`t0!NPpcT)ܩCSgLF sH s5؂9F挥!w̉sҩk †SͧC!FDC87x ]^Zwjz1#se:8TkO]3ISp ǧv[XrF`_qGF8L^H4)/G,K:;< {Q0kQ S!J25<kUYX4176b Sk8T{0Ɖ@8T{ᰀx͑wP gJ XJª=+ j͘@~ ZpHOLp{q|9gC^{OPuz|y 8TD@=g|6ơYKC2|Mߪު]Զx<Kqf/AulV+ yH䟋0X^iQ5Kc7PŇw߁}\4( ֭)Dl|j@!(/m;Aʠ 8YHC|~3U{sG 7=cɹp*p3 .A8`A{šYlC(V8 dmGp8<VF>֞K>`rQ)Ϻ`=\B3V!eg/ 6m' i^7NYտ8b%F;.¶d٭?| m7hʕs$u 2v[[O&Tc~n)%*SiCN/|3rdgdǼq~I 80y^_dҽg!X<~q_PK!uxl/worksheets/sheet2.xmlY[6~x6v,<z}f E'i1$` gyM*+ {uCRlLNULJm/VwV_4@8T s߯4+8e|cfP Bb˒tY$/yz[25̿zΎ-Onq }Vm@]'O柟E?wLy/&4#MyEUjvc/8_z=)aa,F0ށ)K]S0 Ì$ C\R*s<aeS 7]@f[}w)$ާ?+ۃ/#e奏EEt&_>^(݃$];(;Muٿ6/4{zA5{̷_ij0{Ny|ey 1A(KU_mGc}7i &`rHmTg?Jr2xs]10v`Bir{}[}[F@F :T,qj5%6V)U[\][_ [պ)V[wK,օےxH9AAޫY`ZVr68f". `%Nem'*xz& {I8aj6p)OJ;\*|qуc!/v<kky|RqGBN>d̝)1w<Pyak/6N'^Bs}>)q+w;;TK̻3?N .; "wow;kkl1KR(ҷҷCkm7vK+`r*8P>kcT *C~FWBem'j,֞( Q<A89 <N\@xr]zLlbtyq ȻaH'*'Ha3F G#zK>@=EvƘCc!%v1%ciɵu<Ha$7FF" ae7l;kP$wF$wC"rBΫ]!qR퉺9D2HG3f2%,j@AxH2Ր6VᔂB,.B<ir af( !|׊hc, ũ@ .EIe{İ63{}}}(G0 jTnXx<d )䤐`_pR5-Vp~u<`=r঑h&Q8r@(70IEW5 N T1{D.(EIؤJK{s^1<Pa @ >SfYZ0mc w[ O&@ںH(Y=NρU3 n7mʄҮ0npJ^"JZ~XxJSiۣcO١r9w+ۓm)O.8[2?5O=f<؈wEQ 2~JN9Wo4^#PK!N xl/theme/theme1.xmlY͋7? sw5%l$dQV32%9R(Bo=@ $'#$lJZv G~ztҽzG ’_P=ؘ$Ӗk8(4|OHe n ,K۟~rmDlI9*f8&H#ޘ+R#^bP{}2!# J{O1B (W%òBR!a1;{(~h%/V&DYCn2L`|Xsj Z{_\Zҧh4:na PաWU_]נT E A)>\Çfgנ_[K^PkPDIr.jwd A)Q RSLX"7Z2>R$I O(9%o&`T) JU>#02]`XRxbL+7 /={=_*Kn%SSՏ__7'Ŀ˗:/}}O!c&a?0BĒ@v^[ uX<kٺ$Fcvw:ચpLݓ󹉻Бk.J3WRٍe 8SCC=2L%Cr`%R.Cbe mèk=|d#a[ 0~h.QR9D15d2rG&/$Dz)c,K:A ]6Krҹ3=v؍P<sL~&!EwI|;D=CP1ܷ f"j'ete<ص͉3;:ڻSt{>sXa3W"`J+U`ek)r+emgoqx(ߤDJ]8TzM5)0IYgz|]p+~o`_=|j Qk<a ݂\DZl؛6FVω'wws[:(eD ,kzhpsyUs^f^>ekZAj|&O3!ŻBw}ь0Q'j"5,ܔ#-q&?'2ڏ ZCeLTx3&cu+ЭNxNg x)\CJZ=ޭ~TwY(aLfQuQ_B^g^ٙXtXPꗡZFq 0mxEAAfc ΙFz3Pb/3 tSٺqyjuiE-#t00,;͖Yƺ2Obr3kE"'&&S;nj*#4kx#[SvInwaD:\N1{-_- 4m+W>Z@+qt;x2#iQNSp$½:7XX/+r1w`h׼9#:Pvd5O+Oٚ.<O7sig*t; CԲ*nN-rk.yJ}0-2MYNÊQ۴3, O6muF8='?ȝZu@,Jܼfw<zp8RPBo#(Ȕ6`ܓY߼9'-~)lJ-aTRvV\u*`Q\\aEvi.-ͅL_\|q ʠYmvjf=(N:^[ zݰ<# nP7 r[j%e~YJ; +c`)}djPK!Z uB xl/styles.xml\[oF~`Y#pەJ}57 {ؒV=gl<38nsf>mTURcݺ2u-Σb䫱CZE|E?M~aT4D도 ,uoE˕Q8\T8(K 4F&^#\g HOu/*uHy&bZ]^ESPukam~ikr'ݓ%QYTŒ\Q,IF ߆dyi o7"FO0|d,rRiQ BG~ʋg&{K7&HR#;p=Y\_1 d^&x2̒>m ,IQ gggѾ$GrڪV=Io "Du]gF1\z@nL`:a#̟ b¼,s'tjE+Qtٽc5R3'\^LϓAK% ZA MҴ莃LF!qp5PsX[WٲiPi@-V3`h\N3Y-lwSֽ31荇͇Pufº])i$uy5}há:R'F'"ƋMx (0g hx *r(*]adfG@QT9 Euq(*r(*t8Wˤr(*vl2<iEn{ۣ5a/UxI`VbW~b B%=-pUa{нFX'I„aƮE|6;v9p=_ol:ŋd[>?p#^Fk'9FZrpbG ]Țz6r#lHȍEb7^8IwGg0<9fߟ'1]fj㇮"%7B7Ip#ƛOhZpkj4*G7.hMd34--{}`.clx&e@oRi,!є8v|&<iEa#Bo:ӎ1}#X >~{`</Jϔv;@xRON `BX42 @WXy`abkp%rAh &_d[\37GXUbLc.bUg%]ЁyeX\"qTZPG ʯqj7(<zr!ī AWj 5*Ϗȑng G[U~ɠ>Aڪ$GVy2O>?: aZO)>Iy~T.wPޜm-A%i{{zlzbHuIi7Q=[06‰IRُ>@G M[#aAk, E\,@h0qXc5 gcAipXP 4X=I߻Hg 2zX,X9,0\,G,|.# \,G,\6.f~I09IrbqHrbq&bq+'x,G1Oybq}IeFoK2FaHFaQYHFaJFa+Uj3Eﺒޝ] cK^6) odJHLc=i3˨ vyHY{I\D(  okBu&L;D`m ߣ= bR |i#$R,2_)^=rxCʰߋ%{|ZSrx}EI!i˞J\Xxh7r7i LGBr%޻#,s-}#M[;3%~ܻ&%/:+}\5^ 1wb5bx͗ ڦLwӁ{ؽ9\'z7ylz{m^ Fr^/c忱sc;է-ڼ7o<i~8 <˾;/8ݽ7oUyT޻&II.BYbtPK!xl/sharedStrings.xmlSQK0~%ڹ)v@b{.:m:}*ei7p-'Vx|\Xa 1.2"NB.R.j*M(:-`Xg[:PlR49Pţ^zP"y,֠br 2cwt1 Y('k}IceIN^ٶrЏ kJ>^I1c;K٦Oԡ9oj;DЀ73UO=m:4NvEH5-cZc.d;(Hέw%|o0)08 L4q$+c>l׼4w PK!8w/xl/drawings/drawing1.xmlTn0`N IQJ^Uv2&;$Uw_ۘ&[0|Ͱ= =8P!;r(#.~"o TոJx[|:";ʭLs*|_X2}p1`b5Q kR tx h,lfKkFZ.FU#0Jr h4E6'{#G'݅V[kx9\t+^"<h|>FxOyxv <P0`"x][ y8< 9 `+ev={EWͼB%&6Ur(^VQ0͈X'nݡyJިϛ#t=+a[vm ^nP{e\xIYͽu<<7Z~mV1n*vD<\g-4Xv^ƞGgpʡޭ`6/@F%jrr9['nc{шSA2+9"lDr#[NԸv&d%"3'бvQeE8NcML}X?*PK!ܟ ^Nxl/charts/chart1.xml\o8~> Y[FE"Eq}iw2W%*.KKqm;FbQj8gi2$ep@(`T󇃊l<#R =_^F@%Y5ѨI+=/Hyb r4/T&#0d(+ q]"$dTpQS@u-Bniު12գ<T2䌚V'Cc8b ΖdSQXu6'0/3i4>J()3*3 \Ky;I<E]hnILox/<y >/u\`!{%0?2eBc=MBDa֎r8If8`i=<74 ?2_,|(eNY' "eE~%Q@ßE_ I.Ġ _KK2,b-EH6qRSt~QC#pS}Gmqb>f0ذ+ rY~ @7?>Ib64 O<$O$l0)5$u621:o_,DGP:nldzS؁?LKQq#R(HQqy ,6fWxcz0ɴ(flQN%gMߤśKUEu2(khGjwTQ 9|0!4L/ ٜi R<AD Ylb=1֛-%d }SQ6v`pJVЧv3j$)l'v1! Dc9INJ4sLe !I,-g OP 2.qyI6)l8_iu^Ή\$FXd(;6\ _bzb ar.t</4UrɇL]Te₳ԌǏ8c;x)g=)sK s"|mqBP Pu0 鱉 q2?=Uu6!zEdJ"hC. siR]мgj{r"wes'ڐG0/wݓdvAoV= v[zL[6XP⻛ΑֹBzo⬾D)$Iq(@K}3pcHi:t2{vR*EZ<2"|@lɤpuQV`kl 7Wqa>'4W7I<㥷s=f`șUZ.3,uG6Z'ZOUJOēd5)mwǫl99mo ay<YMylcv0um;:Wנ&˶Md.z'ZwM&us,P>j ISBY%Dahk=l#N<sbXagk=ޫ)vk!Y&M#W O 쩣v,˚"Ȓ@ vӏ{4n~~,%<Ћ]_ (f b1c"9uwofIX @ YB/Ý0,Lt;{լSRn-@`TlzU[Uu,iwju` 3M;[*[ZӞBZo+B}ϳS<L\|bmdƌf= _M0.w~rst̍]ovq㑆󰦾džfG^/&=n|!lwIK^g[>b-Eپ3kƖ9[ 49 ]1}ْ/Qa\fZ0n a@`v"Hf=n]Al@ $@E$ϴCvEld Wd/Jjhrx&C{kZ`M :dsY!x)ta{7ߔ !EC]7^!ptp-:;:cv!"etX5ԷF2"3Ohݱ A?Als.gI2=7[ALMn{~ϛ|%>0 6r>KZ}dX T'4"-cK[vJ%<]2Lߥ"}ò< 칦 ;mP?+Pi$n(pZ#|"|r=ɒ |g? !5C#p`x 2Gap "[[dOpI?M+G,#p#'&`eLg~* LY&(3loutX?h}@cV&pس 5et'*B Z=ێaZ"5#aDܾ7  mG,؞Z-}ݵDؗ>+c_ \vJEQ8VlH#}7ŧW-ͰmX' #Y# kK\a;Cbfv0R|M`,dyöFxQ{,񭡝TKyC8 -ͭ ^ ș@4kM8m| IMS]EKXI2>iݶ₰mfpr5W&?#yW.;{Ы#V9=سM&T}v̒#@EY!"jë]ةL`l4fLve&67x%;=7vThp#9/[lW{muL!^ąFXLi|)?=bc?C8P}n}Nϗ3~Y"}qUQ/ՑLPALvR88 D|m@S'a煰1QLY5 7QSxŽ? |Q< A%Mb}$A6uȈ}u~r8A=xQ=%NbZro']N!ZBeU)݃Kv*orvw.ZES.QD/ghs,PK!x&xl/charts/style1.xmlZr:~ R`Bfd:rL-ZYD yMwhm$oW b Fq!j |_Scu@ %"}QD)V/gA4xeKDBX !'1YZW~)G ӿF7=L7#ƿ^x(I@+RS.$,VMrϤ !m+fQj_(_b4ҵC}}zI$ߠ¼`M&B.@SV\%O ̸7~E^!3N֊O tfh ,y5U^@FSsLׯ܊Y{0aaHICZوrR?g~WvZ81V < 7 ao#]׻|gkFjpQϝ5oL7%5T&n(,X ڞ)"\@B8$D#&҆z" " ^FM|{ po%Á.Wvuz=q L5Sn(uFN)#z> 7GLSD{ +A8%[oN!kbty:g;.40lUWܹٓ`NBuD0Md nS3HlXB*;ӿWеk| 9@`@9 NZc|@e}!Cͮ SI"tR.}u2}ӾLmbd}޷f󏸆xyG]Fe{ʖłMoK H;Yqߗh<XX]c:v` w q<0BP},7?8"uNcXmBb- ScAsJG⏊Ś~!~Cp$8$o`]fVALϤPyeK&u ')ջSʽӪRn(>#ۮCm:V6Ɗ9kߛT_KvtWV7h<`5M?/P tVpv[:#hNsY,9VcoqH>󏏮su˪Fw&OnPK!nxl/charts/colors1.xmlAn0Eq "¦'Mlb ۥp{PhC!;$/WH&HFkֆ8 >5 y!E2T(x[-/؂ =`vSr HJn@Yښ`jjglO#>Kk†Z1FN+݃SٛkTOj ,[ӣRQq}QOFOy~ t:PK!2W0xl/drawings/drawing2.xmlTn0`N %@ªR1-#MRU}IM7? ˻#sp@@M϶9RBAg$D»ALfN]w"9;mEJo:hh:Q$  tx h 63uC.}SڶNjs7pTq]Xk0Eg%A,σΝǨs,N #OQ(‚е\\>}rXuH(j7zIE9|먼ԱWkɋ2M|<Dɻ kf6LإSV0>oiZoٵYq428+ouL2HVzb짯bTx .[oi\[[=Bt9C[l^J<i-r0N\#açgVrD/,وiG2PԸ v&d$"3'бvQe ۢKzCM&>_PK!Ro cNxl/charts/chart2.xmlko8|F&DK@˴^4b _ZΆXg3>&MzׄqH8[?~~d8$Q8Ĕ8"=$+Qb<%Iq9 ENS.Gs?Ci22 N|Rg/qD&yT$c J̀e\4h^ 6t$;Ӄΐ3Gu DcFP`ؽk7&8[ >FWٜÜf0h|0B3*3X+z;Q<*nInŰϡ2zޓOULIyԏ"/ oL50XdKv9 d|)N8m׏sMbp(FYBďs<wGs'W4%{KS;RŸE>$^x;P!_GS)pA3PQ}2F|x]\xG9Yl/m>3U,VG D@\ G A<>%Ib.'yϧq .$L>A♤J_s:t'ҷltԽmMcY83 q`y#*7nD` ME*A/ 21ar |}$.;U\TIV08%ef/LDxm$nL4&1.J(ϗ^7@oh!ثq!oPdI1g$pbBˆdIN(r+2xik{+rYS,9kLo<V%`BWtNT %)ޓX.x s&=;{80Ġ8hBX&ZL$zREJ>M,./y'Bd ;ZJ.qƗ7d Z-{ߋ3s,|m'q.B` `upJ ]Vq25bBfղ T@RltZa'by!a/,.tYN,\ՍA 0S`vo֔S v렝z[6QQ7݌4׹z⬺ D3Iqh.)X V\3%MSVHHyE#"rgM |*G낮ջ5^^Ņ_t\B% N~]:h7G}Js MӶ};p,߳A8Kk&i}v]d[շ>wjG c!UVRx?taF`:g;mVjN.B-lVJ其2!7zв|# 3q3y <˱Ɩ*vc/WY"/;3C~b9?5S?s)p&7 i =7,YrKvKpǷc7rVol^{L:;,)9k΂"hy~El8p {ܳk<bv5ЭcPv8rYj+ĝ{:`Mh㟞6XٛvԞh{fޕN\k{Z3 ;ߪbg=+z;r_28,wO\~%ٺ!qev#9w2;Sci B떏x얉 H p6̚w"[@hpvu'<[ 㻇wI]-xiZlWnP7sITQj6Г&܅@FhAMdY{OX@.L9$XdKHHg>y uy uCw^H~m|To"F #W38=·`g*Sl;wUmZHEEU=cC 2;b.:Fl }r-t e8M5k;RBnF`yv?չCǷS 廮Ȗ:V5Qu*?4|sنB8=! `~Aj ipgZ.?]s 0CHP]lM?U_|޹0Yn`" tC3 <_E%yS[r jG|G bnv/lDݢ|'\p<>8.1Y,\-SY& w|N?mCZ.Nx0tlǀ؇<Zy[ᡆ.Cϰ]OCp ;\Nۅvƒ!8ӎ|iuu 7! ֛@VJh'ٮij. (Z kPu-|vmt&CD7<;VV];3PZgNWi7;~* j7c>-Íw>0HWy0#5jK\٥JM B1V|SM`Jӆ}C f%l՞~CuqNc^JJ^xUY9 zOS @9NX@Jqt%NYPPik 2}Uu[ 췍 nϻE\*пG*re.>剪z@Cp?*Wk,9lK^e>j䯫ůFJZ@vRe&[4 D "=-*Uvtc94c-aĽK:%3!J_䅲FjАډV[CUJqX!QK<<f5$?qK\U+'8^\%9ip!~>';,ucȰՑM 5o qrEoI)Ѱ< mݒ&&>Ȇu&Q[7N3]9)C49apRX["rpp $-M =g jXWx"/eU!#x9@ PK!x&xl/charts/style2.xmlZr:~ R`Bfd:rL-ZYD yMwhm$oW b Fq!j |_Scu@ %"}QD)V/gA4xeKDBX !'1YZW~)G ӿF7=L7#ƿ^x(I@+RS.$,VMrϤ !m+fQj_(_b4ҵC}}zI$ߠ¼`M&B.@SV\%O ̸7~E^!3N֊O tfh ,y5U^@FSsLׯ܊Y{0aaHICZوrR?g~WvZ81V < 7 ao#]׻|gkFjpQϝ5oL7%5T&n(,X ڞ)"\@B8$D#&҆z" " ^FM|{ po%Á.Wvuz=q L5Sn(uFN)#z> 7GLSD{ +A8%[oN!kbty:g;.40lUWܹٓ`NBuD0Md nS3HlXB*;ӿWеk| 9@`@9 NZc|@e}!Cͮ SI"tR.}u2}ӾLmbd}޷f󏸆xyG]Fe{ʖłMoK H;Yqߗh<XX]c:v` w q<0BP},7?8"uNcXmBb- ScAsJG⏊Ś~!~Cp$8$o`]fVALϤPyeK&u ')ջSʽӪRn(>#ۮCm:V6Ɗ9kߛT_KvtWV7h<`5M?/P tVpv[:#hNsY,9VcoqH>󏏮su˪Fw&OnPK!nxl/charts/colors2.xmlAn0Eq "¦'Mlb ۥp{PhC!;$/WH&HFkֆ8 >5 y!E2T(x[-/؂ =`vSr HJn@Yښ`jjglO#>Kk†Z1FN+݃SٛkTOj ,[ӣRQq}QOFOy~ t:PK!<+#xl/worksheets/_rels/sheet1.xml.rels 0nz^D*dmoo.mgf?Q)R oi4'tGHL z4bOE8ЧvJiB>˗ SS;Rبɀ)NVC<D3v0t6K?,2cGIRȠJ}U_PK!=d+#xl/worksheets/_rels/sheet2.xml.rels 0nR{U,$dۛ xe<EӰra ;$^.Mc`)5 )RlqƔeU@sTY?P1jG>Cv]7{sɥFfAC)sdPu*/PK!D߼%#xl/drawings/_rels/drawing1.xml.rels 0nzЫXIFooӰ;7;E'r k\;^í 8mqr4,PMq c:a,Ų!FR@3tlr:fi hؓgAO_LQB ŧlu3l̀!& ) ,P_7PK!܁xl/charts/_rels/chart1.xml.relsJ0nAD6݃ U dLG3}?s<}>%P`fOcȳ(..RF + FW[HPD5J KYk &'2'Wȳ._݌3`1y겖fayJ)j̞⸾P$~kFs<cෝF+[޽qPK!&ꇻ%#xl/drawings/_rels/drawing2.xml.rels 0n "MzWXIFѷ7EA4N<Y)䝆R YMnp97;u8{GИ>ь)8XØR+vY@.; <AWHUEU)NClrB.PvĘ2@I YPV_ PK!z!xl/charts/_rels/chart2.xml.relsj0 Bhod(sCpk{}(929.o_g)ѱ$x ^])hkZP-.O/`s$+ LJy,5$K*%؅JÉbL:Y'Imo ;:iATwlf4irvvݞ킹YVOybn;Z?wZZX7PK!\w<KidocProps/core.xml (|]K0C}~v2oNbn k>HiDMrNrM *%)@1ͅZUy1'(r*NB;phZ-<Xmz. $3Z{oƎAR R[I}6m pWXz;`l": 96=3 HP,׃ 2rJw&t:9ۋ{`l6i>FȟS_5TfzmGوN;J<!6yRÁG!8*/b<8<_),{.@BO4لa#Ps_PK!S EGdocProps/app.xml (n0EW"AaP <EYjdI3~}) qf y\^ΐjs6狌3&ToKvCJ}ZdYX] EjԩCiJi܊PM0<". |E{2㲧V |9 Xomєn~Xހbڔn *bʵC AC[iQɞ= Vp[# 8%uSdcr]կ " 1j s`0qcW:[Gw@;b瑝_XY}b.D?'ى߭‡vn4Ent*SAާG7\7ozּn Oq*\d&5)^~PK-!uCc[Content_Types].xmlPK-!U0#L _rels/.relsPK-!?w U1xl/workbook.xmlPK-!JaG xl/_rels/workbook.xml.relsPK-!&皲M xl/worksheets/sheet1.xmlPK-!uxl/worksheets/sheet2.xmlPK-!N xl/theme/theme1.xmlPK-!Z uB "xl/styles.xmlPK-!*xl/sharedStrings.xmlPK-!8w/T,xl/drawings/drawing1.xmlPK-!ܟ ^N.xl/charts/chart1.xmlPK-!x&;xl/charts/style1.xmlPK-!nE@xl/charts/colors1.xmlPK-!2W0uAxl/drawings/drawing2.xmlPK-!Ro cNCxl/charts/chart2.xmlPK-!x&|Pxl/charts/style2.xmlPK-!n7Uxl/charts/colors2.xmlPK-!<+#gVxl/worksheets/_rels/sheet1.xml.relsPK-!=d+#eWxl/worksheets/_rels/sheet2.xml.relsPK-!D߼%#cXxl/drawings/_rels/drawing1.xml.relsPK-!܁`Yxl/charts/_rels/chart1.xml.relsPK-!&ꇻ%#oZxl/drawings/_rels/drawing2.xml.relsPK-!z!k[xl/charts/_rels/chart2.xml.relsPK-!\w<Ki{\docProps/core.xmlPK-!S EG^docProps/app.xmlPKa
-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/VisualBasic/Test/ExpressionCompiler/ReferencedModulesTests.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.Reflection.Metadata Imports System.Reflection.PortableExecutable Imports Microsoft.Cci Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.CodeGen Imports Microsoft.CodeAnalysis.Emit Imports Microsoft.CodeAnalysis.ExpressionEvaluator Imports Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Symbols Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.Emit Imports Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests Imports Microsoft.DiaSymReader Imports Microsoft.VisualStudio.Debugger.Evaluation Imports Roslyn.Test.PdbUtilities Imports Roslyn.Test.Utilities Imports Xunit Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator.UnitTests Public Class ReferencedModulesTests Inherits ExpressionCompilerTestBase ''' <summary> ''' MakeAssemblyReferences should drop unreferenced assemblies. ''' </summary> <Fact> Public Sub UnreferencedAssemblies() Const sourceA1 = "Public Class A1 Private Shared Sub M() End Sub End Class" Const sourceA2 = "Public Class A2 Private Shared Sub M() End Sub End Class" Const sourceB1 = "Public Class B1 Inherits A1 Private Shared Sub M() End Sub End Class" Const sourceB2 = "Public Class B2 Inherits A1 Private Shared Sub M() End Sub End Class" Const sourceC = "Class C1 Inherits B2 Private Shared Sub M() End Sub End Class Class C2 Inherits A2 End Class" Dim moduleMscorlib = (Identity:=MscorlibRef.GetAssemblyIdentity(), [Module]:=MscorlibRef.ToModuleInstance()) Dim moduleIntrinsic = (Identity:=ExpressionCompilerTestHelpers.IntrinsicAssemblyReference.GetAssemblyIdentity(), [Module]:=ExpressionCompilerTestHelpers.IntrinsicAssemblyReference.ToModuleInstance()) Dim moduleA1 = Compile("A1", sourceA1) Dim moduleA2 = Compile("A2", sourceA2) Dim moduleB1 = Compile("B1", sourceB1, moduleA1.Reference) Dim moduleB2 = Compile("B2", sourceB2, moduleA1.Reference) Dim moduleC = Compile("C", sourceC, moduleA1.Reference, moduleA2.Reference, moduleB2.Reference) Using runtime = CreateRuntimeInstance({moduleMscorlib.Module, moduleA1.Module, moduleA2.Module, moduleB1.Module, moduleB2.Module, moduleC.Module}) Dim stateB2 = GetContextState(runtime, "B2.M") ' B2.M with missing A1. Dim context = CreateMethodContext( New AppDomain(), ImmutableArray.Create(moduleMscorlib.Module, moduleA2.Module, moduleB1.Module, moduleB2.Module, moduleC.Module).SelectAsArray(Function(m) m.MetadataBlock), stateB2) Dim resultProperties As ResultProperties = Nothing Dim errorMessage As String = Nothing Dim testData = New CompilationTestData() Dim missingAssemblyIdentities As ImmutableArray(Of AssemblyIdentity) = Nothing context.CompileExpression( "New B2()", DkmEvaluationFlags.TreatAsExpression, NoAliases, DebuggerDiagnosticFormatter.Instance, resultProperties, errorMessage, missingAssemblyIdentities, EnsureEnglishUICulture.PreferredOrNull, testData) Assert.Equal("error BC30652: Reference required to assembly 'A1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' containing the type 'A1'. Add one to your project.", errorMessage) AssertEx.Equal({moduleA1.Identity}, missingAssemblyIdentities) VerifyResolutionRequests(context, (moduleA1.Identity, Nothing, 1)) ' B2.M with all assemblies. context = CreateMethodContext( New AppDomain(), ImmutableArray.Create(moduleMscorlib.Module, moduleA1.Module, moduleA2.Module, moduleB1.Module, moduleB2.Module, moduleC.Module).SelectAsArray(Function(m) m.MetadataBlock), stateB2) testData = New CompilationTestData() context.CompileExpression("New B2()", errorMessage, testData) testData.GetMethodData("<>x.<>m0").VerifyIL( "{ // Code size 6 (0x6) .maxstack 1 IL_0000: newobj ""Sub B2..ctor()"" IL_0005: ret }") VerifyResolutionRequests(context, (moduleA1.Identity, moduleA1.Identity, 1)) ' B2.M with all assemblies in reverse order. context = CreateMethodContext( New AppDomain(), ImmutableArray.Create(moduleC.Module, moduleB2.Module, moduleB1.Module, moduleA2.Module, moduleA1.Module, moduleMscorlib.Module, moduleIntrinsic.Module).SelectAsArray(Function(m) m.MetadataBlock), stateB2) testData = New CompilationTestData() context.CompileExpression("New B2()", errorMessage, testData) testData.GetMethodData("<>x.<>m0").VerifyIL( "{ // Code size 6 (0x6) .maxstack 1 IL_0000: newobj ""Sub B2..ctor()"" IL_0005: ret }") VerifyResolutionRequests(context, (moduleA1.Identity, moduleA1.Identity, 1)) ' A1.M with all assemblies. Dim stateA1 = GetContextState(runtime, "A1.M") context = CreateMethodContext( New AppDomain(), ImmutableArray.Create(moduleMscorlib.Module, moduleA1.Module, moduleA2.Module, moduleB1.Module, moduleB2.Module, moduleC.Module).SelectAsArray(Function(m) m.MetadataBlock), stateA1) testData = New CompilationTestData() context.CompileExpression("New A1()", errorMessage, testData) testData.GetMethodData("<>x.<>m0").VerifyIL( "{ // Code size 6 (0x6) .maxstack 1 IL_0000: newobj ""Sub A1..ctor()"" IL_0005: ret }") VerifyResolutionRequests(context) ' B1.M with all assemblies. Dim stateB1 = GetContextState(runtime, "B1.M") context = CreateMethodContext( New AppDomain(), ImmutableArray.Create(moduleMscorlib.Module, moduleA1.Module, moduleA2.Module, moduleB1.Module, moduleB2.Module, moduleC.Module).SelectAsArray(Function(m) m.MetadataBlock), stateB1) testData = New CompilationTestData() context.CompileExpression("New B1()", errorMessage, testData) testData.GetMethodData("<>x.<>m0").VerifyIL( "{ // Code size 6 (0x6) .maxstack 1 IL_0000: newobj ""Sub B1..ctor()"" IL_0005: ret }") VerifyResolutionRequests(context, (moduleA1.Identity, moduleA1.Identity, 1)) ' C1.M with all assemblies. Dim stateC = GetContextState(runtime, "C1.M") context = CreateMethodContext( New AppDomain(), ImmutableArray.Create(moduleMscorlib.Module, moduleA1.Module, moduleA2.Module, moduleB1.Module, moduleB2.Module, moduleC.Module).SelectAsArray(Function(m) m.MetadataBlock), stateC) testData = New CompilationTestData() context.CompileExpression("New C1()", errorMessage, testData) testData.GetMethodData("<>x.<>m0").VerifyIL( "{ // Code size 6 (0x6) .maxstack 1 IL_0000: newobj ""Sub C1..ctor()"" IL_0005: ret }") VerifyResolutionRequests(context, (moduleB2.Identity, moduleB2.Identity, 1), (moduleA1.Identity, moduleA1.Identity, 1), (moduleA2.Identity, moduleA2.Identity, 1)) ' Other EvaluationContext.CreateMethodContext overload. ' A1.M with all assemblies. Dim allBlocks = ImmutableArray.Create(moduleMscorlib.Module, moduleA1.Module, moduleA2.Module, moduleB1.Module, moduleB2.Module, moduleC.Module).SelectAsArray(Function(m) m.MetadataBlock) context = EvaluationContext.CreateMethodContext( New VisualBasicMetadataContext(), allBlocks, MakeDummyLazyAssemblyReaders(), stateA1.SymReader, stateA1.ModuleVersionId, stateA1.MethodToken, methodVersion:=1, stateA1.ILOffset, stateA1.LocalSignatureToken) testData = New CompilationTestData() context.CompileExpression("New B1()", errorMessage, testData) testData.GetMethodData("<>x.<>m0").VerifyIL( "{ // Code size 6 (0x6) .maxstack 1 IL_0000: newobj ""Sub B1..ctor()"" IL_0005: ret }") ' Other EvaluationContext.CreateMethodContext overload. ' A1.M with all assemblies, offset outside of IL. context = EvaluationContext.CreateMethodContext( New VisualBasicMetadataContext(), allBlocks, MakeDummyLazyAssemblyReaders(), stateA1.SymReader, stateA1.ModuleVersionId, stateA1.MethodToken, methodVersion:=1, UInteger.MaxValue, stateA1.LocalSignatureToken) testData = New CompilationTestData() context.CompileExpression("New C1()", errorMessage, testData) testData.GetMethodData("<>x.<>m0").VerifyIL( "{ // Code size 6 (0x6) .maxstack 1 IL_0000: newobj ""Sub C1..ctor()"" IL_0005: ret }") End Using End Sub ''' <summary> ''' Reuse compilation across evaluations unless current assembly changes. ''' </summary> <Fact> Public Sub ReuseCompilation() Const sourceA1 = "Public Class A1 Private Shared Sub M() End Sub End Class" Const sourceA2 = "Public Class A2 Private Shared Sub M() End Sub End Class Public Class A3 Private Shared Sub M() End Sub End Class" Const sourceB1 = "Public Class B1 Inherits A1 Private Shared Sub M() End Sub End Class Public Class B2 Private Shared Sub M() End Sub End Class" Dim moduleMscorlib = (Identity:=MscorlibRef.GetAssemblyIdentity(), [Module]:=MscorlibRef.ToModuleInstance()) Dim moduleIntrinsic = (Identity:=ExpressionCompilerTestHelpers.IntrinsicAssemblyReference.GetAssemblyIdentity(), [Module]:=ExpressionCompilerTestHelpers.IntrinsicAssemblyReference.ToModuleInstance()) Dim moduleA1 = Compile("A1", sourceA1) Dim moduleA2 = Compile("A2", sourceA2) Dim moduleB1 = Compile("B1", sourceB1, moduleA1.Reference) Using runtime = CreateRuntimeInstance({moduleMscorlib.Module, moduleA1.Module, moduleA2.Module, moduleB1.Module}) Dim blocks = runtime.Modules.SelectAsArray(Function(m) m.MetadataBlock) Dim stateA1 = GetContextState(runtime, "A1.M") Dim stateA2 = GetContextState(runtime, "A2.M") Dim stateA3 = GetContextState(runtime, "A3.M") Dim stateB1 = GetContextState(runtime, "B1.M") Dim stateB2 = GetContextState(runtime, "B2.M") Dim mvidA1 = stateA1.ModuleVersionId Dim mvidA2 = stateA2.ModuleVersionId Dim mvidB1 = stateB1.ModuleVersionId Dim context As EvaluationContext Dim previous As MetadataContext(Of VisualBasicMetadataContext) ' B1 -> B2 -> A1 -> A2 -> A3 ' B1.M: Dim appDomain = New AppDomain() previous = appDomain.GetMetadataContext() context = CreateMethodContext(appDomain, blocks, stateB1) VerifyResolutionRequests(context, (moduleA1.Identity, moduleA1.Identity, 1)) VerifyAppDomainMetadataContext(appDomain, mvidB1) ' B2.M: previous = appDomain.GetMetadataContext() context = CreateMethodContext(appDomain, blocks, stateB2) Assert.NotSame(context, GetMetadataContext(previous, mvidB1).EvaluationContext) Assert.Same(context.Compilation, GetMetadataContext(previous, mvidB1).Compilation) VerifyResolutionRequests(context, (moduleA1.Identity, moduleA1.Identity, 1)) VerifyAppDomainMetadataContext(appDomain, mvidB1) ' A1.M: previous = appDomain.GetMetadataContext() context = CreateMethodContext(appDomain, blocks, stateA1) Assert.NotSame(context, GetMetadataContext(previous, mvidB1).EvaluationContext) Assert.NotSame(context.Compilation, GetMetadataContext(previous, mvidB1).Compilation) VerifyResolutionRequests(context) VerifyAppDomainMetadataContext(appDomain, mvidB1, mvidA1) ' A2.M: previous = appDomain.GetMetadataContext() context = CreateMethodContext(appDomain, blocks, stateA2) Assert.NotSame(context, GetMetadataContext(previous, mvidA1).EvaluationContext) Assert.NotSame(context.Compilation, GetMetadataContext(previous, mvidA1).Compilation) VerifyResolutionRequests(context) VerifyAppDomainMetadataContext(appDomain, mvidB1, mvidA1, mvidA2) ' A3.M: previous = appDomain.GetMetadataContext() context = CreateMethodContext(appDomain, blocks, stateA3) Assert.NotSame(context, GetMetadataContext(previous, mvidA2).EvaluationContext) Assert.Same(context.Compilation, GetMetadataContext(previous, mvidA2).Compilation) VerifyResolutionRequests(context) VerifyAppDomainMetadataContext(appDomain, mvidB1, mvidA1, mvidA2) ' A1 -> A2 -> A3 -> B1 -> B2 ' A1.M: appDomain = New AppDomain() previous = appDomain.GetMetadataContext() context = CreateMethodContext(appDomain, blocks, stateA1) VerifyResolutionRequests(context) VerifyAppDomainMetadataContext(appDomain, mvidA1) ' A2.M: previous = appDomain.GetMetadataContext() context = CreateMethodContext(appDomain, blocks, stateA2) Assert.NotSame(context, GetMetadataContext(previous, mvidA1).EvaluationContext) Assert.NotSame(context.Compilation, GetMetadataContext(previous, mvidA1).Compilation) VerifyResolutionRequests(context) VerifyAppDomainMetadataContext(appDomain, mvidA1, mvidA2) ' A3.M: previous = appDomain.GetMetadataContext() context = CreateMethodContext(appDomain, blocks, stateA3) Assert.NotSame(context, GetMetadataContext(previous, mvidA2).EvaluationContext) Assert.Same(context.Compilation, GetMetadataContext(previous, mvidA2).Compilation) VerifyResolutionRequests(context) VerifyAppDomainMetadataContext(appDomain, mvidA1, mvidA2) ' B1.M: previous = appDomain.GetMetadataContext() context = CreateMethodContext(appDomain, blocks, stateB1) Assert.NotSame(context, GetMetadataContext(previous, mvidA2).EvaluationContext) Assert.NotSame(context.Compilation, GetMetadataContext(previous, mvidA2).Compilation) VerifyResolutionRequests(context, (moduleA1.Identity, moduleA1.Identity, 1)) VerifyAppDomainMetadataContext(appDomain, mvidA1, mvidA2, mvidB1) ' B2.M: previous = appDomain.GetMetadataContext() context = CreateMethodContext(appDomain, blocks, stateB2) Assert.NotSame(context, GetMetadataContext(previous, mvidB1).EvaluationContext) Assert.Same(context.Compilation, GetMetadataContext(previous, mvidB1).Compilation) VerifyResolutionRequests(context, (moduleA1.Identity, moduleA1.Identity, 1)) VerifyAppDomainMetadataContext(appDomain, mvidA1, mvidA2, mvidB1) End Using End Sub Private Shared Sub VerifyAppDomainMetadataContext(appDomain As AppDomain, ParamArray moduleVersionIds As Guid()) ExpressionCompilerTestHelpers.VerifyAppDomainMetadataContext(appDomain.GetMetadataContext(), moduleVersionIds) End Sub <WorkItem(1141029, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1141029")> <Fact> Public Sub AssemblyDuplicateReferences() Const sourceA = "Public Class A End Class" Const sourceB = "Public Class B Public F As New A() End Class" Const sourceC = "Class C Public F As New B() Shared Sub M() End Sub End Class" ' Assembly A, multiple versions, strong name. Dim assemblyNameA = ExpressionCompilerUtilities.GenerateUniqueName() Dim publicKeyA = ImmutableArray.CreateRange(Of Byte)({&H0, &H24, &H0, &H0, &H4, &H80, &H0, &H0, &H94, &H0, &H0, &H0, &H6, &H2, &H0, &H0, &H0, &H24, &H0, &H0, &H52, &H53, &H41, &H31, &H0, &H4, &H0, &H0, &H1, &H0, &H1, &H0, &HED, &HD3, &H22, &HCB, &H6B, &HF8, &HD4, &HA2, &HFC, &HCC, &H87, &H37, &H4, &H6, &H4, &HCE, &HE7, &HB2, &HA6, &HF8, &H4A, &HEE, &HF3, &H19, &HDF, &H5B, &H95, &HE3, &H7A, &H6A, &H28, &H24, &HA4, &HA, &H83, &H83, &HBD, &HBA, &HF2, &HF2, &H52, &H20, &HE9, &HAA, &H3B, &HD1, &HDD, &HE4, &H9A, &H9A, &H9C, &HC0, &H30, &H8F, &H1, &H40, &H6, &HE0, &H2B, &H95, &H62, &H89, &H2A, &H34, &H75, &H22, &H68, &H64, &H6E, &H7C, &H2E, &H83, &H50, &H5A, &HCE, &H7B, &HB, &HE8, &HF8, &H71, &HE6, &HF7, &H73, &H8E, &HEB, &H84, &HD2, &H73, &H5D, &H9D, &HBE, &H5E, &HF5, &H90, &HF9, &HAB, &HA, &H10, &H7E, &H23, &H48, &HF4, &HAD, &H70, &H2E, &HF7, &HD4, &H51, &HD5, &H8B, &H3A, &HF7, &HCA, &H90, &H4C, &HDC, &H80, &H19, &H26, &H65, &HC9, &H37, &HBD, &H52, &H81, &HF1, &H8B, &HCD}) Dim compilationAS1 = CreateEmptyCompilation( New AssemblyIdentity(assemblyNameA, New Version(1, 1, 1, 1), cultureName:="", publicKeyOrToken:=publicKeyA, hasPublicKey:=True), {sourceA}, references:={MscorlibRef}, options:=TestOptions.DebugDll.WithDelaySign(True)) Dim referenceAS1 = compilationAS1.EmitToImageReference() Dim identityAS1 = referenceAS1.GetAssemblyIdentity() Dim compilationAS2 = CreateEmptyCompilation( New AssemblyIdentity(assemblyNameA, New Version(2, 1, 1, 1), cultureName:="", publicKeyOrToken:=publicKeyA, hasPublicKey:=True), {sourceA}, references:={MscorlibRef}, options:=TestOptions.DebugDll.WithDelaySign(True)) Dim referenceAS2 = compilationAS2.EmitToImageReference() Dim identityAS2 = referenceAS2.GetAssemblyIdentity() ' Assembly B, multiple versions, strong name. Dim assemblyNameB = ExpressionCompilerUtilities.GenerateUniqueName() Dim publicKeyB = ImmutableArray.CreateRange(Of Byte)({&H0, &H24, &H0, &H0, &H4, &H80, &H0, &H0, &H94, &H0, &H0, &H0, &H6, &H2, &H0, &H0, &H0, &H24, &H0, &H0, &H53, &H52, &H41, &H31, &H0, &H4, &H0, &H0, &H1, &H0, &H1, &H0, &HED, &HD3, &H22, &HCB, &H6B, &HF8, &HD4, &HA2, &HFC, &HCC, &H87, &H37, &H4, &H6, &H4, &HCE, &HE7, &HB2, &HA6, &HF8, &H4A, &HEE, &HF3, &H19, &HDF, &H5B, &H95, &HE3, &H7A, &H6A, &H28, &H24, &HA4, &HA, &H83, &H83, &HBD, &HBA, &HF2, &HF2, &H52, &H20, &HE9, &HAA, &H3B, &HD1, &HDD, &HE4, &H9A, &H9A, &H9C, &HC0, &H30, &H8F, &H1, &H40, &H6, &HE0, &H2B, &H95, &H62, &H89, &H2A, &H34, &H75, &H22, &H68, &H64, &H6E, &H7C, &H2E, &H83, &H50, &H5A, &HCE, &H7B, &HB, &HE8, &HF8, &H71, &HE6, &HF7, &H73, &H8E, &HEB, &H84, &HD2, &H73, &H5D, &H9D, &HBE, &H5E, &HF5, &H90, &HF9, &HAB, &HA, &H10, &H7E, &H23, &H48, &HF4, &HAD, &H70, &H2E, &HF7, &HD4, &H51, &HD5, &H8B, &H3A, &HF7, &HCA, &H90, &H4C, &HDC, &H80, &H19, &H26, &H65, &HC9, &H37, &HBD, &H52, &H81, &HF1, &H8B, &HCD}) Dim compilationBS1 = CreateEmptyCompilation( New AssemblyIdentity(assemblyNameB, New Version(1, 1, 1, 1), cultureName:="", publicKeyOrToken:=publicKeyB, hasPublicKey:=True), {sourceB}, references:={MscorlibRef, referenceAS1}, options:=TestOptions.DebugDll.WithDelaySign(True)) Dim referenceBS1 = compilationBS1.EmitToImageReference() Dim identityBS1 = referenceBS1.GetAssemblyIdentity() Dim compilationBS2 = CreateEmptyCompilation( New AssemblyIdentity(assemblyNameB, New Version(2, 2, 2, 1), cultureName:="", publicKeyOrToken:=publicKeyB, hasPublicKey:=True), {sourceB}, references:={MscorlibRef, referenceAS2}, options:=TestOptions.DebugDll.WithDelaySign(True)) Dim referenceBS2 = compilationBS2.EmitToImageReference() Dim identityBS2 = referenceBS2.GetAssemblyIdentity() ' Assembly C, multiple versions, not strong name. Dim compilationCN1 = CreateEmptyCompilation( New AssemblyIdentity("C", New Version(1, 1, 1, 1)), {sourceC}, references:={MscorlibRef, referenceBS1}, options:=TestOptions.DebugDll) ' Duplicate assemblies, target module referencing BS1. WithRuntimeInstance(compilationCN1, {MscorlibRef, referenceAS1, referenceAS2, referenceBS2, referenceBS1, referenceBS2}, Sub(runtime) Dim typeBlocks As ImmutableArray(Of MetadataBlock) = Nothing Dim methodBlocks As ImmutableArray(Of MetadataBlock) = Nothing Dim moduleVersionId As Guid = Nothing Dim symReader As ISymUnmanagedReader = Nothing Dim typeToken = 0 Dim methodToken = 0 Dim localSignatureToken = 0 GetContextState(runtime, "C", typeBlocks, moduleVersionId, symReader, typeToken, localSignatureToken) GetContextState(runtime, "C.M", methodBlocks, moduleVersionId, symReader, methodToken, localSignatureToken) ' Compile expression with type context. Dim appDomain = New AppDomain() Dim context = CreateTypeContext( appDomain, typeBlocks, moduleVersionId, typeToken, MakeAssemblyReferencesKind.AllAssemblies) ' If VB supported extern aliases, the following would be true: ' Assert.Equal(identityAS2, context.Compilation.GlobalNamespace.GetMembers("A").OfType(Of INamedTypeSymbol)().Single().ContainingAssembly.Identity) ' Assert.Equal(identityBS2, context.Compilation.GlobalNamespace.GetMembers("B").OfType(Of INamedTypeSymbol)().Single().ContainingAssembly.Identity) Dim errorMessage As String = Nothing ' A is ambiguous since there were no explicit references to AS1 or AS2. context.CompileExpression("New A()", errorMessage) Assert.Equal(errorMessage, "error BC30554: 'A' is ambiguous.") ' Ideally, B should be resolved to BS1. context.CompileExpression("New B()", errorMessage) Assert.Equal(errorMessage, "error BC30554: 'B' is ambiguous.") ' Compile expression with method context. appDomain.SetMetadataContext( SetMetadataContext( New MetadataContext(Of VisualBasicMetadataContext)(typeBlocks, ImmutableDictionary(Of MetadataContextId, VisualBasicMetadataContext).Empty), New VisualBasicMetadataContext(context.Compilation))) Dim previous = appDomain.GetMetadataContext() context = CreateMethodContext( appDomain, methodBlocks, MakeDummyLazyAssemblyReaders(), symReader, moduleVersionId, methodToken, methodVersion:=1, ilOffset:=0, localSignatureToken:=localSignatureToken, kind:=MakeAssemblyReferencesKind.AllAssemblies) Assert.NotSame(GetMetadataContext(previous).EvaluationContext, context) Assert.Same(GetMetadataContext(previous).Compilation, context.Compilation) ' re-use type context compilation ' Ideally, B should be resolved to BS1. context.CompileExpression("New B()", errorMessage) Assert.Equal(errorMessage, "error BC30554: 'B' is ambiguous.") End Sub) End Sub Private Shared Function Compile(assemblyName As String, source As String, ParamArray references As MetadataReference()) As (Identity As AssemblyIdentity, [Module] As ModuleInstance, Reference As MetadataReference) Dim comp = CreateCompilationWithMscorlib40(source, references, options:=TestOptions.DebugDll, assemblyName:=assemblyName) comp.AssertNoDiagnostics() Dim [module] = comp.ToModuleInstance() Return (comp.Assembly.Identity, [module], [module].GetReference()) End Function Private Shared Sub VerifyResolutionRequests(context As EvaluationContext, ParamArray expectedResults As (AssemblyIdentity, AssemblyIdentity, Integer)()) ExpressionCompilerTestHelpers.VerifyResolutionRequests( DirectCast(context.Compilation.Options.MetadataReferenceResolver, EEMetadataReferenceResolver), expectedResults) End Sub <Fact> Public Sub DuplicateTypesAndMethodsDifferentAssemblies() Const sourceA = "Option Strict On Imports System.Runtime.CompilerServices Imports N Namespace N Class C1 End Class Public Module E <Extension> Public Function F(o As A) As A Return o End Function End Module End Namespace Class C2 End Class Public Class A Public Shared Sub M() Dim x As New A() Dim y As Object = x.F() End Sub End Class" Const sourceB = "Option Strict On Imports System.Runtime.CompilerServices Imports N Namespace N Class C1 End Class Public Module E <Extension> Public Function F(o As A) As Integer Return 2 End Function End Module End Namespace Class C2 End Class Class B Shared Sub Main() Dim x As New A() End Sub End Class" Dim compilationA = CreateEmptyCompilationWithReferences( MakeSources(sourceA), options:=TestOptions.DebugDll, references:={MscorlibRef, SystemRef, MsvbRef, SystemCoreRef}) Dim moduleA = compilationA.ToModuleInstance() Dim identityA = compilationA.Assembly.Identity Dim moduleB = CreateEmptyCompilationWithReferences( MakeSources(sourceB), options:=TestOptions.DebugDll, references:={MscorlibRef, SystemRef, MsvbRef, SystemCoreRef, moduleA.GetReference()}).ToModuleInstance() Dim runtime = CreateRuntimeInstance( { MscorlibRef.ToModuleInstance(), SystemRef.ToModuleInstance(), MsvbRef.ToModuleInstance(), SystemCoreRef.ToModuleInstance(), moduleA, moduleB }) Dim blocks As ImmutableArray(Of MetadataBlock) = Nothing Dim moduleVersionId As Guid = Nothing Dim symReader As ISymUnmanagedReader = Nothing Dim typeToken = 0 Dim methodToken = 0 Dim localSignatureToken = 0 GetContextState(runtime, "B", blocks, moduleVersionId, symReader, typeToken, localSignatureToken) Dim contextFactory = CreateTypeContextFactory(moduleVersionId, typeToken) ' Duplicate type in namespace, at type scope. Dim testData As CompilationTestData = Nothing Dim errorMessage As String = Nothing ExpressionCompilerTestHelpers.CompileExpressionWithRetry(blocks, "New N.C1()", ImmutableArray(Of [Alias]).Empty, contextFactory, getMetaDataBytesPtr:=Nothing, errorMessage:=errorMessage, testData:=testData) Assert.Equal($"error BC30560: { String.Format(VBResources.ERR_AmbiguousInNamespace2, "C1", "N") }", errorMessage) GetContextState(runtime, "B.Main", blocks, moduleVersionId, symReader, methodToken, localSignatureToken) contextFactory = CreateMethodContextFactory(moduleVersionId, symReader, methodToken, localSignatureToken) ' Duplicate type in namespace, at method scope. ExpressionCompilerTestHelpers.CompileExpressionWithRetry(blocks, "New C1()", ImmutableArray(Of [Alias]).Empty, contextFactory, getMetaDataBytesPtr:=Nothing, errorMessage:=errorMessage, testData:=testData) Assert.Equal($"error BC30560: { String.Format(VBResources.ERR_AmbiguousInNamespace2, "C1", "N") }", errorMessage) ' Duplicate type in global namespace, at method scope. ExpressionCompilerTestHelpers.CompileExpressionWithRetry(blocks, "New C2()", ImmutableArray(Of [Alias]).Empty, contextFactory, getMetaDataBytesPtr:=Nothing, errorMessage:=errorMessage, testData:=testData) Assert.Equal($"error BC30554: { String.Format(VBResources.ERR_AmbiguousInUnnamedNamespace1, "C2") }", errorMessage) ' Duplicate extension method, at method scope. ExpressionCompilerTestHelpers.CompileExpressionWithRetry(blocks, "x.F()", ImmutableArray(Of [Alias]).Empty, contextFactory, getMetaDataBytesPtr:=Nothing, errorMessage:=errorMessage, testData:=testData) Assert.True(errorMessage.StartsWith($"error BC30521: { String.Format(VBResources.ERR_NoMostSpecificOverload2, "F", "") }")) ' Same tests as above but in library that does not directly reference duplicates. GetContextState(runtime, "A", blocks, moduleVersionId, symReader, typeToken, localSignatureToken) contextFactory = CreateTypeContextFactory(moduleVersionId, typeToken) ' Duplicate type in namespace, at type scope. ExpressionCompilerTestHelpers.CompileExpressionWithRetry(blocks, "New N.C1()", ImmutableArray(Of [Alias]).Empty, contextFactory, getMetaDataBytesPtr:=Nothing, errorMessage:=errorMessage, testData:=testData) Assert.Null(errorMessage) Dim methodData = testData.GetMethodData("<>x.<>m0") methodData.VerifyIL( "{ // Code size 6 (0x6) .maxstack 1 IL_0000: newobj ""Sub N.C1..ctor()"" IL_0005: ret }") Assert.Equal(methodData.Method.ReturnType.ContainingAssembly.ToDisplayString(), identityA.GetDisplayName()) GetContextState(runtime, "A.M", blocks, moduleVersionId, symReader, methodToken, localSignatureToken) contextFactory = CreateMethodContextFactory(moduleVersionId, symReader, methodToken, localSignatureToken) ' Duplicate type in global namespace, at method scope. ExpressionCompilerTestHelpers.CompileExpressionWithRetry(blocks, "New C2()", ImmutableArray(Of [Alias]).Empty, contextFactory, getMetaDataBytesPtr:=Nothing, errorMessage:=errorMessage, testData:=testData) Assert.Null(errorMessage) methodData = testData.GetMethodData("<>x.<>m0") methodData.VerifyIL( "{ // Code size 6 (0x6) .maxstack 1 .locals init (A V_0, //x Object V_1) //y IL_0000: newobj ""Sub C2..ctor()"" IL_0005: ret }") Assert.Equal(methodData.Method.ReturnType.ContainingAssembly.ToDisplayString(), identityA.GetDisplayName()) ' Duplicate extension method, at method scope. ExpressionCompilerTestHelpers.CompileExpressionWithRetry(blocks, "x.F()", ImmutableArray(Of [Alias]).Empty, contextFactory, getMetaDataBytesPtr:=Nothing, errorMessage:=errorMessage, testData:=testData) Assert.Null(errorMessage) methodData = testData.GetMethodData("<>x.<>m0") methodData.VerifyIL( "{ // Code size 7 (0x7) .maxstack 1 .locals init (A V_0, //x Object V_1) //y IL_0000: ldloc.0 IL_0001: call ""Function N.E.F(A) As A"" IL_0006: ret }") Assert.Equal(methodData.Method.ReturnType.ContainingAssembly.ToDisplayString(), identityA.GetDisplayName()) End Sub <Fact> Public Sub DuplicateTypesAndMethodsDifferentAssemblies_2() Const sourceA = "Namespace N Public Module M Public Function F() Return 1 End Function End Module End Namespace" Const sourceB = "Imports N Class C Shared Sub M() F() End Sub End Class" Dim referenceA1 = CreateEmptyCompilation( New AssemblyIdentity("A", New Version(1, 1, 1, 1)), {sourceA}, options:=TestOptions.DebugDll, references:={MscorlibRef, SystemRef, MsvbRef}).EmitToImageReference() Dim referenceA2 = CreateEmptyCompilation( New AssemblyIdentity("A", New Version(2, 1, 1, 2)), {sourceA}, options:=TestOptions.DebugDll, references:={MscorlibRef, SystemRef, MsvbRef}).EmitToImageReference() Dim compilationB = CreateEmptyCompilation( New AssemblyIdentity("B", New Version(1, 1, 1, 1)), {sourceB}, options:=TestOptions.DebugDll, references:={MscorlibRef, referenceA1}) WithRuntimeInstance(compilationB, {MscorlibRef, SystemRef, MsvbRef, referenceA1, referenceA2}, Sub(runtime) Dim blocks As ImmutableArray(Of MetadataBlock) = Nothing Dim moduleVersionId As Guid = Nothing Dim symReader As ISymUnmanagedReader = Nothing Dim typeToken = 0 Dim methodToken = 0 Dim localSignatureToken = 0 GetContextState(runtime, "C.M", blocks, moduleVersionId, symReader, methodToken, localSignatureToken) Dim context = CreateMethodContext( New AppDomain(), blocks, MakeDummyLazyAssemblyReaders(), symReader, moduleVersionId, methodToken, methodVersion:=1, ilOffset:=0, localSignatureToken:=localSignatureToken, kind:=MakeAssemblyReferencesKind.AllAssemblies) Dim errorMessage As String = Nothing context.CompileExpression("F()", errorMessage) Assert.Equal(errorMessage, "error BC30562: 'F' is ambiguous between declarations in Modules 'N.M, N.M'.") Dim testData As New CompilationTestData() Dim contextFactory = CreateMethodContextFactory(moduleVersionId, symReader, methodToken, localSignatureToken) ExpressionCompilerTestHelpers.CompileExpressionWithRetry(blocks, "F()", ImmutableArray(Of [Alias]).Empty, contextFactory, getMetaDataBytesPtr:=Nothing, errorMessage:=errorMessage, testData:=testData) Assert.Null(errorMessage) testData.GetMethodData("<>x.<>m0").VerifyIL( "{ // Code size 6 (0x6) .maxstack 1 IL_0000: call ""Function N.M.F() As Object"" IL_0005: ret }") End Sub) End Sub <WorkItem(1170032, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1170032")> <Fact> Public Sub DuplicateTypesInMscorlib() Const sourceConsole = "Namespace System Public Class Console End Class End Namespace" Const sourceObjectModel = "Namespace System.Collections.ObjectModel Public Class ReadOnlyDictionary(Of K, V) End Class End Namespace" Const source = "Class C Shared Sub Main() Dim t = GetType(System.Console) Dim o = DirectCast(Nothing, System.Collections.ObjectModel.ReadOnlyDictionary(Of Object, Object)) End Sub End Class" Dim systemConsoleComp = CreateCompilationWithMscorlib40({sourceConsole}, options:=TestOptions.DebugDll, assemblyName:="System.Console") Dim systemConsoleRef = systemConsoleComp.EmitToImageReference() Dim systemObjectModelComp = CreateCompilationWithMscorlib40({sourceObjectModel}, options:=TestOptions.DebugDll, assemblyName:="System.ObjectModel") Dim systemObjectModelRef = systemObjectModelComp.EmitToImageReference() Dim identityObjectModel = systemObjectModelRef.GetAssemblyIdentity() ' At runtime System.Runtime.dll contract assembly is replaced ' by mscorlib.dll and System.Runtime.dll facade assemblies; ' System.Console.dll and System.ObjectModel.dll are not replaced. ' Test different ordering of modules containing duplicates: ' { System.Console, mscorlib } and { mscorlib, System.ObjectModel }. Dim contractReferences = ImmutableArray.Create(systemConsoleRef, SystemRuntimePP7Ref, systemObjectModelRef) Dim runtimeReferences = ImmutableArray.Create(systemConsoleRef, MscorlibFacadeRef, SystemRuntimeFacadeRef, systemObjectModelRef) ' Verify the compiler reports duplicate types with facade assemblies. Dim compilation = CreateEmptyCompilationWithReferences(MakeSources(source), references:=runtimeReferences, options:=TestOptions.DebugDll) compilation.VerifyDiagnostics( Diagnostic(ERRID.ERR_AmbiguousInNamespace2, "System.Console").WithArguments("Console", "System").WithLocation(3, 25), Diagnostic(ERRID.ERR_AmbiguousInNamespace2, "System.Collections.ObjectModel.ReadOnlyDictionary(Of Object, Object)").WithArguments("ReadOnlyDictionary", "System.Collections.ObjectModel").WithLocation(4, 37)) ' EE should not report duplicate type when the original source ' is compiled with contract assemblies and the EE expression ' is compiled with facade assemblies. compilation = CreateEmptyCompilationWithReferences(MakeSources(source), references:=contractReferences, options:=TestOptions.DebugDll) WithRuntimeInstance(compilation, runtimeReferences, Sub(runtime) Dim context = CreateMethodContext(runtime, "C.Main") Dim errorMessage As String = Nothing ' { System.Console, mscorlib } Dim testData = New CompilationTestData() context.CompileExpression("GetType(System.Console)", errorMessage, testData) Dim methodData = testData.GetMethodData("<>x.<>m0") methodData.VerifyIL( "{ // Code size 11 (0xb) .maxstack 1 .locals init (System.Type V_0, //t System.Collections.ObjectModel.ReadOnlyDictionary(Of Object, Object) V_1) //o IL_0000: ldtoken ""System.Console"" IL_0005: call ""Function System.Type.GetTypeFromHandle(System.RuntimeTypeHandle) As System.Type"" IL_000a: ret }") ' { mscorlib, System.ObjectModel } testData = New CompilationTestData() context.CompileExpression("DirectCast(Nothing, System.Collections.ObjectModel.ReadOnlyDictionary(Of Object, Object))", errorMessage, testData) methodData = testData.GetMethodData("<>x.<>m0") methodData.VerifyIL( "{ // Code size 2 (0x2) .maxstack 1 .locals init (System.Type V_0, //t System.Collections.ObjectModel.ReadOnlyDictionary(Of Object, Object) V_1) //o IL_0000: ldnull IL_0001: ret }") Assert.Equal(methodData.Method.ReturnType.ContainingAssembly.ToDisplayString(), identityObjectModel.GetDisplayName()) End Sub) End Sub Private Const CorLibAssemblyName = "System.Private.CoreLib" ' An assembly with the expected corlib name and with System.Object should ' be considered the corlib, even with references to external assemblies. <WorkItem(13275, "https://github.com/dotnet/roslyn/issues/13275")> <Fact> Public Sub CorLibWithAssemblyReferences() Const sourceLib = "Public Class Private1 End Class Public Class Private2 End Class" Dim compLib = CreateCompilationWithMscorlib40( {sourceLib}, options:=TestOptions.ReleaseDll, assemblyName:="System.Private.Library") compLib.VerifyDiagnostics() Dim refLib = compLib.EmitToImageReference() Const sourceCorLib = "Imports System.Runtime.CompilerServices <Assembly: TypeForwardedTo(GetType(Private2))> Namespace System Public Class [Object] Public Function F() As Private1 Return Nothing End Function End Class Public Class Void Inherits [Object] End Class End Namespace" ' Create a custom corlib with a reference to compilation ' above and a reference to the actual mscorlib. Dim compCorLib = CreateEmptyCompilation( {Parse(sourceCorLib)}, options:=TestOptions.ReleaseDll, references:={MscorlibRef, refLib}, assemblyName:=CorLibAssemblyName) compCorLib.VerifyDiagnostics() Dim objectType = compCorLib.SourceAssembly.GlobalNamespace.GetMember(Of NamedTypeSymbol)("System.Object") Assert.NotNull(objectType.BaseType) Dim peBytes As ImmutableArray(Of Byte) = Nothing Dim pdbBytes As ImmutableArray(Of Byte) = Nothing ExpressionCompilerTestHelpers.EmitCorLibWithAssemblyReferences( compCorLib, Nothing, Function(moduleBuilder, emitOptions) New PEAssemblyBuilderWithAdditionalReferences(moduleBuilder, emitOptions, objectType.GetCciAdapter()), peBytes, pdbBytes) Using reader As New PEReader(peBytes) Dim metadata = reader.GetMetadata() Dim [module] = metadata.ToModuleMetadata(ignoreAssemblyRefs:=True) Dim metadataReader = metadata.ToMetadataReader() Dim moduleInstance = Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests.ModuleInstance.Create(metadata, metadataReader.GetModuleVersionIdOrThrow()) ' Verify the module declares System.Object. Assert.True(metadataReader.DeclaresTheObjectClass()) ' Verify the PEModule has no assembly references. Assert.Equal(0, [module].Module.ReferencedAssemblies.Length) ' Verify the underlying metadata has the expected assembly references. Dim actualReferences = metadataReader.AssemblyReferences.Select(Function(r) metadataReader.GetString(metadataReader.GetAssemblyReference(r).Name)).ToImmutableArray() AssertEx.Equal({"mscorlib", "System.Private.Library"}, actualReferences) Const source = "Class C Shared Sub M() End Sub End Class" Dim comp = CreateEmptyCompilation( {Parse(source)}, options:=TestOptions.ReleaseDll, references:={refLib, AssemblyMetadata.Create([module]).GetReference()}) comp.VerifyDiagnostics() Using runtime = RuntimeInstance.Create({comp.ToModuleInstance(), moduleInstance}) Dim errorMessage As String = Nothing Dim context = CreateMethodContext(runtime, "C.M") ' Valid expression. Dim testData = New CompilationTestData() context.CompileExpression("New Object()", errorMessage, testData) Assert.Null(errorMessage) Dim methodData = testData.GetMethodData("<>x.<>m0") methodData.VerifyIL( "{ // Code size 6 (0x6) .maxstack 1 IL_0000: newobj ""Sub Object..ctor()"" IL_0005: ret }") ' Invalid expression: System.Int32 is not defined in corlib above. testData = New CompilationTestData() context.CompileExpression("1", errorMessage, testData) Assert.Equal("error BC30002: Type 'System.Int32' is not defined.", errorMessage) ' Invalid expression: type in method signature from missing referenced assembly. testData = New CompilationTestData() context.CompileExpression("(New Object()).F()", errorMessage, testData) Assert.Equal("error BC30657: 'F' has a return type that is not supported or parameter types that are not supported.", errorMessage) ' Invalid expression: type forwarded to missing referenced assembly. testData = New CompilationTestData() context.CompileExpression("New Private2()", errorMessage, testData) Assert.Equal("error BC30002: Type 'Private2' is not defined.", errorMessage) End Using End Using End Sub Private Shared Function CreateTypeContextFactory( moduleVersionId As Guid, typeToken As Integer) As ExpressionCompiler.CreateContextDelegate Return Function(blocks, useReferencedModulesOnly) Dim compilation = If(useReferencedModulesOnly, blocks.ToCompilationReferencedModulesOnly(moduleVersionId), blocks.ToCompilation()) Return EvaluationContext.CreateTypeContext( compilation, moduleVersionId, typeToken) End Function End Function Private Shared Function CreateMethodContextFactory( moduleVersionId As Guid, symReader As ISymUnmanagedReader, methodToken As Integer, localSignatureToken As Integer) As ExpressionCompiler.CreateContextDelegate Return Function(blocks, useReferencedModulesOnly) Dim compilation = If(useReferencedModulesOnly, blocks.ToCompilationReferencedModulesOnly(moduleVersionId), blocks.ToCompilation()) Return EvaluationContext.CreateMethodContext( compilation, MakeDummyLazyAssemblyReaders(), symReader, moduleVersionId, methodToken, methodVersion:=1, ilOffset:=0, localSignatureToken:=localSignatureToken) End Function End Function Private NotInheritable Class PEAssemblyBuilderWithAdditionalReferences Inherits PEModuleBuilder Implements IAssemblyReference Private ReadOnly _builder As CommonPEModuleBuilder Private ReadOnly _objectType As NamespaceTypeDefinitionNoBase Friend Sub New(builder As CommonPEModuleBuilder, emitOptions As EmitOptions, objectType As INamespaceTypeDefinition) MyBase.New(DirectCast(builder.CommonSourceModule, SourceModuleSymbol), emitOptions, builder.OutputKind, builder.SerializationProperties, builder.ManifestResources) _builder = builder _objectType = New NamespaceTypeDefinitionNoBase(objectType) End Sub Public Overrides Iterator Function GetTopLevelSourceTypeDefinitions(context As EmitContext) As IEnumerable(Of INamespaceTypeDefinition) For Each t In MyBase.GetTopLevelSourceTypeDefinitions(context) Yield If(t Is _objectType.UnderlyingType, _objectType, t) Next End Function Public Overrides ReadOnly Property EncSymbolChanges As SymbolChanges Get Return _builder.EncSymbolChanges End Get End Property Public Overrides ReadOnly Property PreviousGeneration As EmitBaseline Get Return Nothing End Get End Property Public Overrides ReadOnly Property SourceAssemblyOpt As ISourceAssemblySymbolInternal Get Return _builder.SourceAssemblyOpt End Get End Property Public Overrides Function GetFiles(context As EmitContext) As IEnumerable(Of IFileReference) Return _builder.GetFiles(context) End Function Protected Overrides Sub AddEmbeddedResourcesFromAddedModules(builder As ArrayBuilder(Of Cci.ManagedResource), diagnostics As DiagnosticBag) End Sub Friend Overrides ReadOnly Property AllowOmissionOfConditionalCalls As Boolean Get Return True End Get End Property Private ReadOnly Property Identity As AssemblyIdentity Implements IAssemblyReference.Identity Get Return DirectCast(_builder, IAssemblyReference).Identity End Get End Property Private ReadOnly Property AssemblyVersionPattern As Version Implements IAssemblyReference.AssemblyVersionPattern Get Return DirectCast(_builder, IAssemblyReference).AssemblyVersionPattern End Get End Property End Class 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.Reflection.Metadata Imports System.Reflection.PortableExecutable Imports Microsoft.Cci Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.CodeGen Imports Microsoft.CodeAnalysis.Emit Imports Microsoft.CodeAnalysis.ExpressionEvaluator Imports Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Symbols Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.Emit Imports Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests Imports Microsoft.DiaSymReader Imports Microsoft.VisualStudio.Debugger.Evaluation Imports Roslyn.Test.PdbUtilities Imports Roslyn.Test.Utilities Imports Xunit Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator.UnitTests Public Class ReferencedModulesTests Inherits ExpressionCompilerTestBase ''' <summary> ''' MakeAssemblyReferences should drop unreferenced assemblies. ''' </summary> <Fact> Public Sub UnreferencedAssemblies() Const sourceA1 = "Public Class A1 Private Shared Sub M() End Sub End Class" Const sourceA2 = "Public Class A2 Private Shared Sub M() End Sub End Class" Const sourceB1 = "Public Class B1 Inherits A1 Private Shared Sub M() End Sub End Class" Const sourceB2 = "Public Class B2 Inherits A1 Private Shared Sub M() End Sub End Class" Const sourceC = "Class C1 Inherits B2 Private Shared Sub M() End Sub End Class Class C2 Inherits A2 End Class" Dim moduleMscorlib = (Identity:=MscorlibRef.GetAssemblyIdentity(), [Module]:=MscorlibRef.ToModuleInstance()) Dim moduleIntrinsic = (Identity:=ExpressionCompilerTestHelpers.IntrinsicAssemblyReference.GetAssemblyIdentity(), [Module]:=ExpressionCompilerTestHelpers.IntrinsicAssemblyReference.ToModuleInstance()) Dim moduleA1 = Compile("A1", sourceA1) Dim moduleA2 = Compile("A2", sourceA2) Dim moduleB1 = Compile("B1", sourceB1, moduleA1.Reference) Dim moduleB2 = Compile("B2", sourceB2, moduleA1.Reference) Dim moduleC = Compile("C", sourceC, moduleA1.Reference, moduleA2.Reference, moduleB2.Reference) Using runtime = CreateRuntimeInstance({moduleMscorlib.Module, moduleA1.Module, moduleA2.Module, moduleB1.Module, moduleB2.Module, moduleC.Module}) Dim stateB2 = GetContextState(runtime, "B2.M") ' B2.M with missing A1. Dim context = CreateMethodContext( New AppDomain(), ImmutableArray.Create(moduleMscorlib.Module, moduleA2.Module, moduleB1.Module, moduleB2.Module, moduleC.Module).SelectAsArray(Function(m) m.MetadataBlock), stateB2) Dim resultProperties As ResultProperties = Nothing Dim errorMessage As String = Nothing Dim testData = New CompilationTestData() Dim missingAssemblyIdentities As ImmutableArray(Of AssemblyIdentity) = Nothing context.CompileExpression( "New B2()", DkmEvaluationFlags.TreatAsExpression, NoAliases, DebuggerDiagnosticFormatter.Instance, resultProperties, errorMessage, missingAssemblyIdentities, EnsureEnglishUICulture.PreferredOrNull, testData) Assert.Equal("error BC30652: Reference required to assembly 'A1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' containing the type 'A1'. Add one to your project.", errorMessage) AssertEx.Equal({moduleA1.Identity}, missingAssemblyIdentities) VerifyResolutionRequests(context, (moduleA1.Identity, Nothing, 1)) ' B2.M with all assemblies. context = CreateMethodContext( New AppDomain(), ImmutableArray.Create(moduleMscorlib.Module, moduleA1.Module, moduleA2.Module, moduleB1.Module, moduleB2.Module, moduleC.Module).SelectAsArray(Function(m) m.MetadataBlock), stateB2) testData = New CompilationTestData() context.CompileExpression("New B2()", errorMessage, testData) testData.GetMethodData("<>x.<>m0").VerifyIL( "{ // Code size 6 (0x6) .maxstack 1 IL_0000: newobj ""Sub B2..ctor()"" IL_0005: ret }") VerifyResolutionRequests(context, (moduleA1.Identity, moduleA1.Identity, 1)) ' B2.M with all assemblies in reverse order. context = CreateMethodContext( New AppDomain(), ImmutableArray.Create(moduleC.Module, moduleB2.Module, moduleB1.Module, moduleA2.Module, moduleA1.Module, moduleMscorlib.Module, moduleIntrinsic.Module).SelectAsArray(Function(m) m.MetadataBlock), stateB2) testData = New CompilationTestData() context.CompileExpression("New B2()", errorMessage, testData) testData.GetMethodData("<>x.<>m0").VerifyIL( "{ // Code size 6 (0x6) .maxstack 1 IL_0000: newobj ""Sub B2..ctor()"" IL_0005: ret }") VerifyResolutionRequests(context, (moduleA1.Identity, moduleA1.Identity, 1)) ' A1.M with all assemblies. Dim stateA1 = GetContextState(runtime, "A1.M") context = CreateMethodContext( New AppDomain(), ImmutableArray.Create(moduleMscorlib.Module, moduleA1.Module, moduleA2.Module, moduleB1.Module, moduleB2.Module, moduleC.Module).SelectAsArray(Function(m) m.MetadataBlock), stateA1) testData = New CompilationTestData() context.CompileExpression("New A1()", errorMessage, testData) testData.GetMethodData("<>x.<>m0").VerifyIL( "{ // Code size 6 (0x6) .maxstack 1 IL_0000: newobj ""Sub A1..ctor()"" IL_0005: ret }") VerifyResolutionRequests(context) ' B1.M with all assemblies. Dim stateB1 = GetContextState(runtime, "B1.M") context = CreateMethodContext( New AppDomain(), ImmutableArray.Create(moduleMscorlib.Module, moduleA1.Module, moduleA2.Module, moduleB1.Module, moduleB2.Module, moduleC.Module).SelectAsArray(Function(m) m.MetadataBlock), stateB1) testData = New CompilationTestData() context.CompileExpression("New B1()", errorMessage, testData) testData.GetMethodData("<>x.<>m0").VerifyIL( "{ // Code size 6 (0x6) .maxstack 1 IL_0000: newobj ""Sub B1..ctor()"" IL_0005: ret }") VerifyResolutionRequests(context, (moduleA1.Identity, moduleA1.Identity, 1)) ' C1.M with all assemblies. Dim stateC = GetContextState(runtime, "C1.M") context = CreateMethodContext( New AppDomain(), ImmutableArray.Create(moduleMscorlib.Module, moduleA1.Module, moduleA2.Module, moduleB1.Module, moduleB2.Module, moduleC.Module).SelectAsArray(Function(m) m.MetadataBlock), stateC) testData = New CompilationTestData() context.CompileExpression("New C1()", errorMessage, testData) testData.GetMethodData("<>x.<>m0").VerifyIL( "{ // Code size 6 (0x6) .maxstack 1 IL_0000: newobj ""Sub C1..ctor()"" IL_0005: ret }") VerifyResolutionRequests(context, (moduleB2.Identity, moduleB2.Identity, 1), (moduleA1.Identity, moduleA1.Identity, 1), (moduleA2.Identity, moduleA2.Identity, 1)) ' Other EvaluationContext.CreateMethodContext overload. ' A1.M with all assemblies. Dim allBlocks = ImmutableArray.Create(moduleMscorlib.Module, moduleA1.Module, moduleA2.Module, moduleB1.Module, moduleB2.Module, moduleC.Module).SelectAsArray(Function(m) m.MetadataBlock) context = EvaluationContext.CreateMethodContext( New VisualBasicMetadataContext(), allBlocks, MakeDummyLazyAssemblyReaders(), stateA1.SymReader, stateA1.ModuleVersionId, stateA1.MethodToken, methodVersion:=1, stateA1.ILOffset, stateA1.LocalSignatureToken) testData = New CompilationTestData() context.CompileExpression("New B1()", errorMessage, testData) testData.GetMethodData("<>x.<>m0").VerifyIL( "{ // Code size 6 (0x6) .maxstack 1 IL_0000: newobj ""Sub B1..ctor()"" IL_0005: ret }") ' Other EvaluationContext.CreateMethodContext overload. ' A1.M with all assemblies, offset outside of IL. context = EvaluationContext.CreateMethodContext( New VisualBasicMetadataContext(), allBlocks, MakeDummyLazyAssemblyReaders(), stateA1.SymReader, stateA1.ModuleVersionId, stateA1.MethodToken, methodVersion:=1, UInteger.MaxValue, stateA1.LocalSignatureToken) testData = New CompilationTestData() context.CompileExpression("New C1()", errorMessage, testData) testData.GetMethodData("<>x.<>m0").VerifyIL( "{ // Code size 6 (0x6) .maxstack 1 IL_0000: newobj ""Sub C1..ctor()"" IL_0005: ret }") End Using End Sub ''' <summary> ''' Reuse compilation across evaluations unless current assembly changes. ''' </summary> <Fact> Public Sub ReuseCompilation() Const sourceA1 = "Public Class A1 Private Shared Sub M() End Sub End Class" Const sourceA2 = "Public Class A2 Private Shared Sub M() End Sub End Class Public Class A3 Private Shared Sub M() End Sub End Class" Const sourceB1 = "Public Class B1 Inherits A1 Private Shared Sub M() End Sub End Class Public Class B2 Private Shared Sub M() End Sub End Class" Dim moduleMscorlib = (Identity:=MscorlibRef.GetAssemblyIdentity(), [Module]:=MscorlibRef.ToModuleInstance()) Dim moduleIntrinsic = (Identity:=ExpressionCompilerTestHelpers.IntrinsicAssemblyReference.GetAssemblyIdentity(), [Module]:=ExpressionCompilerTestHelpers.IntrinsicAssemblyReference.ToModuleInstance()) Dim moduleA1 = Compile("A1", sourceA1) Dim moduleA2 = Compile("A2", sourceA2) Dim moduleB1 = Compile("B1", sourceB1, moduleA1.Reference) Using runtime = CreateRuntimeInstance({moduleMscorlib.Module, moduleA1.Module, moduleA2.Module, moduleB1.Module}) Dim blocks = runtime.Modules.SelectAsArray(Function(m) m.MetadataBlock) Dim stateA1 = GetContextState(runtime, "A1.M") Dim stateA2 = GetContextState(runtime, "A2.M") Dim stateA3 = GetContextState(runtime, "A3.M") Dim stateB1 = GetContextState(runtime, "B1.M") Dim stateB2 = GetContextState(runtime, "B2.M") Dim mvidA1 = stateA1.ModuleVersionId Dim mvidA2 = stateA2.ModuleVersionId Dim mvidB1 = stateB1.ModuleVersionId Dim context As EvaluationContext Dim previous As MetadataContext(Of VisualBasicMetadataContext) ' B1 -> B2 -> A1 -> A2 -> A3 ' B1.M: Dim appDomain = New AppDomain() previous = appDomain.GetMetadataContext() context = CreateMethodContext(appDomain, blocks, stateB1) VerifyResolutionRequests(context, (moduleA1.Identity, moduleA1.Identity, 1)) VerifyAppDomainMetadataContext(appDomain, mvidB1) ' B2.M: previous = appDomain.GetMetadataContext() context = CreateMethodContext(appDomain, blocks, stateB2) Assert.NotSame(context, GetMetadataContext(previous, mvidB1).EvaluationContext) Assert.Same(context.Compilation, GetMetadataContext(previous, mvidB1).Compilation) VerifyResolutionRequests(context, (moduleA1.Identity, moduleA1.Identity, 1)) VerifyAppDomainMetadataContext(appDomain, mvidB1) ' A1.M: previous = appDomain.GetMetadataContext() context = CreateMethodContext(appDomain, blocks, stateA1) Assert.NotSame(context, GetMetadataContext(previous, mvidB1).EvaluationContext) Assert.NotSame(context.Compilation, GetMetadataContext(previous, mvidB1).Compilation) VerifyResolutionRequests(context) VerifyAppDomainMetadataContext(appDomain, mvidB1, mvidA1) ' A2.M: previous = appDomain.GetMetadataContext() context = CreateMethodContext(appDomain, blocks, stateA2) Assert.NotSame(context, GetMetadataContext(previous, mvidA1).EvaluationContext) Assert.NotSame(context.Compilation, GetMetadataContext(previous, mvidA1).Compilation) VerifyResolutionRequests(context) VerifyAppDomainMetadataContext(appDomain, mvidB1, mvidA1, mvidA2) ' A3.M: previous = appDomain.GetMetadataContext() context = CreateMethodContext(appDomain, blocks, stateA3) Assert.NotSame(context, GetMetadataContext(previous, mvidA2).EvaluationContext) Assert.Same(context.Compilation, GetMetadataContext(previous, mvidA2).Compilation) VerifyResolutionRequests(context) VerifyAppDomainMetadataContext(appDomain, mvidB1, mvidA1, mvidA2) ' A1 -> A2 -> A3 -> B1 -> B2 ' A1.M: appDomain = New AppDomain() previous = appDomain.GetMetadataContext() context = CreateMethodContext(appDomain, blocks, stateA1) VerifyResolutionRequests(context) VerifyAppDomainMetadataContext(appDomain, mvidA1) ' A2.M: previous = appDomain.GetMetadataContext() context = CreateMethodContext(appDomain, blocks, stateA2) Assert.NotSame(context, GetMetadataContext(previous, mvidA1).EvaluationContext) Assert.NotSame(context.Compilation, GetMetadataContext(previous, mvidA1).Compilation) VerifyResolutionRequests(context) VerifyAppDomainMetadataContext(appDomain, mvidA1, mvidA2) ' A3.M: previous = appDomain.GetMetadataContext() context = CreateMethodContext(appDomain, blocks, stateA3) Assert.NotSame(context, GetMetadataContext(previous, mvidA2).EvaluationContext) Assert.Same(context.Compilation, GetMetadataContext(previous, mvidA2).Compilation) VerifyResolutionRequests(context) VerifyAppDomainMetadataContext(appDomain, mvidA1, mvidA2) ' B1.M: previous = appDomain.GetMetadataContext() context = CreateMethodContext(appDomain, blocks, stateB1) Assert.NotSame(context, GetMetadataContext(previous, mvidA2).EvaluationContext) Assert.NotSame(context.Compilation, GetMetadataContext(previous, mvidA2).Compilation) VerifyResolutionRequests(context, (moduleA1.Identity, moduleA1.Identity, 1)) VerifyAppDomainMetadataContext(appDomain, mvidA1, mvidA2, mvidB1) ' B2.M: previous = appDomain.GetMetadataContext() context = CreateMethodContext(appDomain, blocks, stateB2) Assert.NotSame(context, GetMetadataContext(previous, mvidB1).EvaluationContext) Assert.Same(context.Compilation, GetMetadataContext(previous, mvidB1).Compilation) VerifyResolutionRequests(context, (moduleA1.Identity, moduleA1.Identity, 1)) VerifyAppDomainMetadataContext(appDomain, mvidA1, mvidA2, mvidB1) End Using End Sub Private Shared Sub VerifyAppDomainMetadataContext(appDomain As AppDomain, ParamArray moduleVersionIds As Guid()) ExpressionCompilerTestHelpers.VerifyAppDomainMetadataContext(appDomain.GetMetadataContext(), moduleVersionIds) End Sub <WorkItem(1141029, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1141029")> <Fact> Public Sub AssemblyDuplicateReferences() Const sourceA = "Public Class A End Class" Const sourceB = "Public Class B Public F As New A() End Class" Const sourceC = "Class C Public F As New B() Shared Sub M() End Sub End Class" ' Assembly A, multiple versions, strong name. Dim assemblyNameA = ExpressionCompilerUtilities.GenerateUniqueName() Dim publicKeyA = ImmutableArray.CreateRange(Of Byte)({&H0, &H24, &H0, &H0, &H4, &H80, &H0, &H0, &H94, &H0, &H0, &H0, &H6, &H2, &H0, &H0, &H0, &H24, &H0, &H0, &H52, &H53, &H41, &H31, &H0, &H4, &H0, &H0, &H1, &H0, &H1, &H0, &HED, &HD3, &H22, &HCB, &H6B, &HF8, &HD4, &HA2, &HFC, &HCC, &H87, &H37, &H4, &H6, &H4, &HCE, &HE7, &HB2, &HA6, &HF8, &H4A, &HEE, &HF3, &H19, &HDF, &H5B, &H95, &HE3, &H7A, &H6A, &H28, &H24, &HA4, &HA, &H83, &H83, &HBD, &HBA, &HF2, &HF2, &H52, &H20, &HE9, &HAA, &H3B, &HD1, &HDD, &HE4, &H9A, &H9A, &H9C, &HC0, &H30, &H8F, &H1, &H40, &H6, &HE0, &H2B, &H95, &H62, &H89, &H2A, &H34, &H75, &H22, &H68, &H64, &H6E, &H7C, &H2E, &H83, &H50, &H5A, &HCE, &H7B, &HB, &HE8, &HF8, &H71, &HE6, &HF7, &H73, &H8E, &HEB, &H84, &HD2, &H73, &H5D, &H9D, &HBE, &H5E, &HF5, &H90, &HF9, &HAB, &HA, &H10, &H7E, &H23, &H48, &HF4, &HAD, &H70, &H2E, &HF7, &HD4, &H51, &HD5, &H8B, &H3A, &HF7, &HCA, &H90, &H4C, &HDC, &H80, &H19, &H26, &H65, &HC9, &H37, &HBD, &H52, &H81, &HF1, &H8B, &HCD}) Dim compilationAS1 = CreateEmptyCompilation( New AssemblyIdentity(assemblyNameA, New Version(1, 1, 1, 1), cultureName:="", publicKeyOrToken:=publicKeyA, hasPublicKey:=True), {sourceA}, references:={MscorlibRef}, options:=TestOptions.DebugDll.WithDelaySign(True)) Dim referenceAS1 = compilationAS1.EmitToImageReference() Dim identityAS1 = referenceAS1.GetAssemblyIdentity() Dim compilationAS2 = CreateEmptyCompilation( New AssemblyIdentity(assemblyNameA, New Version(2, 1, 1, 1), cultureName:="", publicKeyOrToken:=publicKeyA, hasPublicKey:=True), {sourceA}, references:={MscorlibRef}, options:=TestOptions.DebugDll.WithDelaySign(True)) Dim referenceAS2 = compilationAS2.EmitToImageReference() Dim identityAS2 = referenceAS2.GetAssemblyIdentity() ' Assembly B, multiple versions, strong name. Dim assemblyNameB = ExpressionCompilerUtilities.GenerateUniqueName() Dim publicKeyB = ImmutableArray.CreateRange(Of Byte)({&H0, &H24, &H0, &H0, &H4, &H80, &H0, &H0, &H94, &H0, &H0, &H0, &H6, &H2, &H0, &H0, &H0, &H24, &H0, &H0, &H53, &H52, &H41, &H31, &H0, &H4, &H0, &H0, &H1, &H0, &H1, &H0, &HED, &HD3, &H22, &HCB, &H6B, &HF8, &HD4, &HA2, &HFC, &HCC, &H87, &H37, &H4, &H6, &H4, &HCE, &HE7, &HB2, &HA6, &HF8, &H4A, &HEE, &HF3, &H19, &HDF, &H5B, &H95, &HE3, &H7A, &H6A, &H28, &H24, &HA4, &HA, &H83, &H83, &HBD, &HBA, &HF2, &HF2, &H52, &H20, &HE9, &HAA, &H3B, &HD1, &HDD, &HE4, &H9A, &H9A, &H9C, &HC0, &H30, &H8F, &H1, &H40, &H6, &HE0, &H2B, &H95, &H62, &H89, &H2A, &H34, &H75, &H22, &H68, &H64, &H6E, &H7C, &H2E, &H83, &H50, &H5A, &HCE, &H7B, &HB, &HE8, &HF8, &H71, &HE6, &HF7, &H73, &H8E, &HEB, &H84, &HD2, &H73, &H5D, &H9D, &HBE, &H5E, &HF5, &H90, &HF9, &HAB, &HA, &H10, &H7E, &H23, &H48, &HF4, &HAD, &H70, &H2E, &HF7, &HD4, &H51, &HD5, &H8B, &H3A, &HF7, &HCA, &H90, &H4C, &HDC, &H80, &H19, &H26, &H65, &HC9, &H37, &HBD, &H52, &H81, &HF1, &H8B, &HCD}) Dim compilationBS1 = CreateEmptyCompilation( New AssemblyIdentity(assemblyNameB, New Version(1, 1, 1, 1), cultureName:="", publicKeyOrToken:=publicKeyB, hasPublicKey:=True), {sourceB}, references:={MscorlibRef, referenceAS1}, options:=TestOptions.DebugDll.WithDelaySign(True)) Dim referenceBS1 = compilationBS1.EmitToImageReference() Dim identityBS1 = referenceBS1.GetAssemblyIdentity() Dim compilationBS2 = CreateEmptyCompilation( New AssemblyIdentity(assemblyNameB, New Version(2, 2, 2, 1), cultureName:="", publicKeyOrToken:=publicKeyB, hasPublicKey:=True), {sourceB}, references:={MscorlibRef, referenceAS2}, options:=TestOptions.DebugDll.WithDelaySign(True)) Dim referenceBS2 = compilationBS2.EmitToImageReference() Dim identityBS2 = referenceBS2.GetAssemblyIdentity() ' Assembly C, multiple versions, not strong name. Dim compilationCN1 = CreateEmptyCompilation( New AssemblyIdentity("C", New Version(1, 1, 1, 1)), {sourceC}, references:={MscorlibRef, referenceBS1}, options:=TestOptions.DebugDll) ' Duplicate assemblies, target module referencing BS1. WithRuntimeInstance(compilationCN1, {MscorlibRef, referenceAS1, referenceAS2, referenceBS2, referenceBS1, referenceBS2}, Sub(runtime) Dim typeBlocks As ImmutableArray(Of MetadataBlock) = Nothing Dim methodBlocks As ImmutableArray(Of MetadataBlock) = Nothing Dim moduleVersionId As Guid = Nothing Dim symReader As ISymUnmanagedReader = Nothing Dim typeToken = 0 Dim methodToken = 0 Dim localSignatureToken = 0 GetContextState(runtime, "C", typeBlocks, moduleVersionId, symReader, typeToken, localSignatureToken) GetContextState(runtime, "C.M", methodBlocks, moduleVersionId, symReader, methodToken, localSignatureToken) ' Compile expression with type context. Dim appDomain = New AppDomain() Dim context = CreateTypeContext( appDomain, typeBlocks, moduleVersionId, typeToken, MakeAssemblyReferencesKind.AllAssemblies) ' If VB supported extern aliases, the following would be true: ' Assert.Equal(identityAS2, context.Compilation.GlobalNamespace.GetMembers("A").OfType(Of INamedTypeSymbol)().Single().ContainingAssembly.Identity) ' Assert.Equal(identityBS2, context.Compilation.GlobalNamespace.GetMembers("B").OfType(Of INamedTypeSymbol)().Single().ContainingAssembly.Identity) Dim errorMessage As String = Nothing ' A is ambiguous since there were no explicit references to AS1 or AS2. context.CompileExpression("New A()", errorMessage) Assert.Equal(errorMessage, "error BC30554: 'A' is ambiguous.") ' Ideally, B should be resolved to BS1. context.CompileExpression("New B()", errorMessage) Assert.Equal(errorMessage, "error BC30554: 'B' is ambiguous.") ' Compile expression with method context. appDomain.SetMetadataContext( SetMetadataContext( New MetadataContext(Of VisualBasicMetadataContext)(typeBlocks, ImmutableDictionary(Of MetadataContextId, VisualBasicMetadataContext).Empty), New VisualBasicMetadataContext(context.Compilation))) Dim previous = appDomain.GetMetadataContext() context = CreateMethodContext( appDomain, methodBlocks, MakeDummyLazyAssemblyReaders(), symReader, moduleVersionId, methodToken, methodVersion:=1, ilOffset:=0, localSignatureToken:=localSignatureToken, kind:=MakeAssemblyReferencesKind.AllAssemblies) Assert.NotSame(GetMetadataContext(previous).EvaluationContext, context) Assert.Same(GetMetadataContext(previous).Compilation, context.Compilation) ' re-use type context compilation ' Ideally, B should be resolved to BS1. context.CompileExpression("New B()", errorMessage) Assert.Equal(errorMessage, "error BC30554: 'B' is ambiguous.") End Sub) End Sub Private Shared Function Compile(assemblyName As String, source As String, ParamArray references As MetadataReference()) As (Identity As AssemblyIdentity, [Module] As ModuleInstance, Reference As MetadataReference) Dim comp = CreateCompilationWithMscorlib40(source, references, options:=TestOptions.DebugDll, assemblyName:=assemblyName) comp.AssertNoDiagnostics() Dim [module] = comp.ToModuleInstance() Return (comp.Assembly.Identity, [module], [module].GetReference()) End Function Private Shared Sub VerifyResolutionRequests(context As EvaluationContext, ParamArray expectedResults As (AssemblyIdentity, AssemblyIdentity, Integer)()) ExpressionCompilerTestHelpers.VerifyResolutionRequests( DirectCast(context.Compilation.Options.MetadataReferenceResolver, EEMetadataReferenceResolver), expectedResults) End Sub <Fact> Public Sub DuplicateTypesAndMethodsDifferentAssemblies() Const sourceA = "Option Strict On Imports System.Runtime.CompilerServices Imports N Namespace N Class C1 End Class Public Module E <Extension> Public Function F(o As A) As A Return o End Function End Module End Namespace Class C2 End Class Public Class A Public Shared Sub M() Dim x As New A() Dim y As Object = x.F() End Sub End Class" Const sourceB = "Option Strict On Imports System.Runtime.CompilerServices Imports N Namespace N Class C1 End Class Public Module E <Extension> Public Function F(o As A) As Integer Return 2 End Function End Module End Namespace Class C2 End Class Class B Shared Sub Main() Dim x As New A() End Sub End Class" Dim compilationA = CreateEmptyCompilationWithReferences( MakeSources(sourceA), options:=TestOptions.DebugDll, references:={MscorlibRef, SystemRef, MsvbRef, SystemCoreRef}) Dim moduleA = compilationA.ToModuleInstance() Dim identityA = compilationA.Assembly.Identity Dim moduleB = CreateEmptyCompilationWithReferences( MakeSources(sourceB), options:=TestOptions.DebugDll, references:={MscorlibRef, SystemRef, MsvbRef, SystemCoreRef, moduleA.GetReference()}).ToModuleInstance() Dim runtime = CreateRuntimeInstance( { MscorlibRef.ToModuleInstance(), SystemRef.ToModuleInstance(), MsvbRef.ToModuleInstance(), SystemCoreRef.ToModuleInstance(), moduleA, moduleB }) Dim blocks As ImmutableArray(Of MetadataBlock) = Nothing Dim moduleVersionId As Guid = Nothing Dim symReader As ISymUnmanagedReader = Nothing Dim typeToken = 0 Dim methodToken = 0 Dim localSignatureToken = 0 GetContextState(runtime, "B", blocks, moduleVersionId, symReader, typeToken, localSignatureToken) Dim contextFactory = CreateTypeContextFactory(moduleVersionId, typeToken) ' Duplicate type in namespace, at type scope. Dim testData As CompilationTestData = Nothing Dim errorMessage As String = Nothing ExpressionCompilerTestHelpers.CompileExpressionWithRetry(blocks, "New N.C1()", ImmutableArray(Of [Alias]).Empty, contextFactory, getMetaDataBytesPtr:=Nothing, errorMessage:=errorMessage, testData:=testData) Assert.Equal($"error BC30560: { String.Format(VBResources.ERR_AmbiguousInNamespace2, "C1", "N") }", errorMessage) GetContextState(runtime, "B.Main", blocks, moduleVersionId, symReader, methodToken, localSignatureToken) contextFactory = CreateMethodContextFactory(moduleVersionId, symReader, methodToken, localSignatureToken) ' Duplicate type in namespace, at method scope. ExpressionCompilerTestHelpers.CompileExpressionWithRetry(blocks, "New C1()", ImmutableArray(Of [Alias]).Empty, contextFactory, getMetaDataBytesPtr:=Nothing, errorMessage:=errorMessage, testData:=testData) Assert.Equal($"error BC30560: { String.Format(VBResources.ERR_AmbiguousInNamespace2, "C1", "N") }", errorMessage) ' Duplicate type in global namespace, at method scope. ExpressionCompilerTestHelpers.CompileExpressionWithRetry(blocks, "New C2()", ImmutableArray(Of [Alias]).Empty, contextFactory, getMetaDataBytesPtr:=Nothing, errorMessage:=errorMessage, testData:=testData) Assert.Equal($"error BC30554: { String.Format(VBResources.ERR_AmbiguousInUnnamedNamespace1, "C2") }", errorMessage) ' Duplicate extension method, at method scope. ExpressionCompilerTestHelpers.CompileExpressionWithRetry(blocks, "x.F()", ImmutableArray(Of [Alias]).Empty, contextFactory, getMetaDataBytesPtr:=Nothing, errorMessage:=errorMessage, testData:=testData) Assert.True(errorMessage.StartsWith($"error BC30521: { String.Format(VBResources.ERR_NoMostSpecificOverload2, "F", "") }")) ' Same tests as above but in library that does not directly reference duplicates. GetContextState(runtime, "A", blocks, moduleVersionId, symReader, typeToken, localSignatureToken) contextFactory = CreateTypeContextFactory(moduleVersionId, typeToken) ' Duplicate type in namespace, at type scope. ExpressionCompilerTestHelpers.CompileExpressionWithRetry(blocks, "New N.C1()", ImmutableArray(Of [Alias]).Empty, contextFactory, getMetaDataBytesPtr:=Nothing, errorMessage:=errorMessage, testData:=testData) Assert.Null(errorMessage) Dim methodData = testData.GetMethodData("<>x.<>m0") methodData.VerifyIL( "{ // Code size 6 (0x6) .maxstack 1 IL_0000: newobj ""Sub N.C1..ctor()"" IL_0005: ret }") Assert.Equal(methodData.Method.ReturnType.ContainingAssembly.ToDisplayString(), identityA.GetDisplayName()) GetContextState(runtime, "A.M", blocks, moduleVersionId, symReader, methodToken, localSignatureToken) contextFactory = CreateMethodContextFactory(moduleVersionId, symReader, methodToken, localSignatureToken) ' Duplicate type in global namespace, at method scope. ExpressionCompilerTestHelpers.CompileExpressionWithRetry(blocks, "New C2()", ImmutableArray(Of [Alias]).Empty, contextFactory, getMetaDataBytesPtr:=Nothing, errorMessage:=errorMessage, testData:=testData) Assert.Null(errorMessage) methodData = testData.GetMethodData("<>x.<>m0") methodData.VerifyIL( "{ // Code size 6 (0x6) .maxstack 1 .locals init (A V_0, //x Object V_1) //y IL_0000: newobj ""Sub C2..ctor()"" IL_0005: ret }") Assert.Equal(methodData.Method.ReturnType.ContainingAssembly.ToDisplayString(), identityA.GetDisplayName()) ' Duplicate extension method, at method scope. ExpressionCompilerTestHelpers.CompileExpressionWithRetry(blocks, "x.F()", ImmutableArray(Of [Alias]).Empty, contextFactory, getMetaDataBytesPtr:=Nothing, errorMessage:=errorMessage, testData:=testData) Assert.Null(errorMessage) methodData = testData.GetMethodData("<>x.<>m0") methodData.VerifyIL( "{ // Code size 7 (0x7) .maxstack 1 .locals init (A V_0, //x Object V_1) //y IL_0000: ldloc.0 IL_0001: call ""Function N.E.F(A) As A"" IL_0006: ret }") Assert.Equal(methodData.Method.ReturnType.ContainingAssembly.ToDisplayString(), identityA.GetDisplayName()) End Sub <Fact> Public Sub DuplicateTypesAndMethodsDifferentAssemblies_2() Const sourceA = "Namespace N Public Module M Public Function F() Return 1 End Function End Module End Namespace" Const sourceB = "Imports N Class C Shared Sub M() F() End Sub End Class" Dim referenceA1 = CreateEmptyCompilation( New AssemblyIdentity("A", New Version(1, 1, 1, 1)), {sourceA}, options:=TestOptions.DebugDll, references:={MscorlibRef, SystemRef, MsvbRef}).EmitToImageReference() Dim referenceA2 = CreateEmptyCompilation( New AssemblyIdentity("A", New Version(2, 1, 1, 2)), {sourceA}, options:=TestOptions.DebugDll, references:={MscorlibRef, SystemRef, MsvbRef}).EmitToImageReference() Dim compilationB = CreateEmptyCompilation( New AssemblyIdentity("B", New Version(1, 1, 1, 1)), {sourceB}, options:=TestOptions.DebugDll, references:={MscorlibRef, referenceA1}) WithRuntimeInstance(compilationB, {MscorlibRef, SystemRef, MsvbRef, referenceA1, referenceA2}, Sub(runtime) Dim blocks As ImmutableArray(Of MetadataBlock) = Nothing Dim moduleVersionId As Guid = Nothing Dim symReader As ISymUnmanagedReader = Nothing Dim typeToken = 0 Dim methodToken = 0 Dim localSignatureToken = 0 GetContextState(runtime, "C.M", blocks, moduleVersionId, symReader, methodToken, localSignatureToken) Dim context = CreateMethodContext( New AppDomain(), blocks, MakeDummyLazyAssemblyReaders(), symReader, moduleVersionId, methodToken, methodVersion:=1, ilOffset:=0, localSignatureToken:=localSignatureToken, kind:=MakeAssemblyReferencesKind.AllAssemblies) Dim errorMessage As String = Nothing context.CompileExpression("F()", errorMessage) Assert.Equal(errorMessage, "error BC30562: 'F' is ambiguous between declarations in Modules 'N.M, N.M'.") Dim testData As New CompilationTestData() Dim contextFactory = CreateMethodContextFactory(moduleVersionId, symReader, methodToken, localSignatureToken) ExpressionCompilerTestHelpers.CompileExpressionWithRetry(blocks, "F()", ImmutableArray(Of [Alias]).Empty, contextFactory, getMetaDataBytesPtr:=Nothing, errorMessage:=errorMessage, testData:=testData) Assert.Null(errorMessage) testData.GetMethodData("<>x.<>m0").VerifyIL( "{ // Code size 6 (0x6) .maxstack 1 IL_0000: call ""Function N.M.F() As Object"" IL_0005: ret }") End Sub) End Sub <WorkItem(1170032, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1170032")> <Fact> Public Sub DuplicateTypesInMscorlib() Const sourceConsole = "Namespace System Public Class Console End Class End Namespace" Const sourceObjectModel = "Namespace System.Collections.ObjectModel Public Class ReadOnlyDictionary(Of K, V) End Class End Namespace" Const source = "Class C Shared Sub Main() Dim t = GetType(System.Console) Dim o = DirectCast(Nothing, System.Collections.ObjectModel.ReadOnlyDictionary(Of Object, Object)) End Sub End Class" Dim systemConsoleComp = CreateCompilationWithMscorlib40({sourceConsole}, options:=TestOptions.DebugDll, assemblyName:="System.Console") Dim systemConsoleRef = systemConsoleComp.EmitToImageReference() Dim systemObjectModelComp = CreateCompilationWithMscorlib40({sourceObjectModel}, options:=TestOptions.DebugDll, assemblyName:="System.ObjectModel") Dim systemObjectModelRef = systemObjectModelComp.EmitToImageReference() Dim identityObjectModel = systemObjectModelRef.GetAssemblyIdentity() ' At runtime System.Runtime.dll contract assembly is replaced ' by mscorlib.dll and System.Runtime.dll facade assemblies; ' System.Console.dll and System.ObjectModel.dll are not replaced. ' Test different ordering of modules containing duplicates: ' { System.Console, mscorlib } and { mscorlib, System.ObjectModel }. Dim contractReferences = ImmutableArray.Create(systemConsoleRef, SystemRuntimePP7Ref, systemObjectModelRef) Dim runtimeReferences = ImmutableArray.Create(systemConsoleRef, MscorlibFacadeRef, SystemRuntimeFacadeRef, systemObjectModelRef) ' Verify the compiler reports duplicate types with facade assemblies. Dim compilation = CreateEmptyCompilationWithReferences(MakeSources(source), references:=runtimeReferences, options:=TestOptions.DebugDll) compilation.VerifyDiagnostics( Diagnostic(ERRID.ERR_AmbiguousInNamespace2, "System.Console").WithArguments("Console", "System").WithLocation(3, 25), Diagnostic(ERRID.ERR_AmbiguousInNamespace2, "System.Collections.ObjectModel.ReadOnlyDictionary(Of Object, Object)").WithArguments("ReadOnlyDictionary", "System.Collections.ObjectModel").WithLocation(4, 37)) ' EE should not report duplicate type when the original source ' is compiled with contract assemblies and the EE expression ' is compiled with facade assemblies. compilation = CreateEmptyCompilationWithReferences(MakeSources(source), references:=contractReferences, options:=TestOptions.DebugDll) WithRuntimeInstance(compilation, runtimeReferences, Sub(runtime) Dim context = CreateMethodContext(runtime, "C.Main") Dim errorMessage As String = Nothing ' { System.Console, mscorlib } Dim testData = New CompilationTestData() context.CompileExpression("GetType(System.Console)", errorMessage, testData) Dim methodData = testData.GetMethodData("<>x.<>m0") methodData.VerifyIL( "{ // Code size 11 (0xb) .maxstack 1 .locals init (System.Type V_0, //t System.Collections.ObjectModel.ReadOnlyDictionary(Of Object, Object) V_1) //o IL_0000: ldtoken ""System.Console"" IL_0005: call ""Function System.Type.GetTypeFromHandle(System.RuntimeTypeHandle) As System.Type"" IL_000a: ret }") ' { mscorlib, System.ObjectModel } testData = New CompilationTestData() context.CompileExpression("DirectCast(Nothing, System.Collections.ObjectModel.ReadOnlyDictionary(Of Object, Object))", errorMessage, testData) methodData = testData.GetMethodData("<>x.<>m0") methodData.VerifyIL( "{ // Code size 2 (0x2) .maxstack 1 .locals init (System.Type V_0, //t System.Collections.ObjectModel.ReadOnlyDictionary(Of Object, Object) V_1) //o IL_0000: ldnull IL_0001: ret }") Assert.Equal(methodData.Method.ReturnType.ContainingAssembly.ToDisplayString(), identityObjectModel.GetDisplayName()) End Sub) End Sub Private Const CorLibAssemblyName = "System.Private.CoreLib" ' An assembly with the expected corlib name and with System.Object should ' be considered the corlib, even with references to external assemblies. <WorkItem(13275, "https://github.com/dotnet/roslyn/issues/13275")> <Fact> Public Sub CorLibWithAssemblyReferences() Const sourceLib = "Public Class Private1 End Class Public Class Private2 End Class" Dim compLib = CreateCompilationWithMscorlib40( {sourceLib}, options:=TestOptions.ReleaseDll, assemblyName:="System.Private.Library") compLib.VerifyDiagnostics() Dim refLib = compLib.EmitToImageReference() Const sourceCorLib = "Imports System.Runtime.CompilerServices <Assembly: TypeForwardedTo(GetType(Private2))> Namespace System Public Class [Object] Public Function F() As Private1 Return Nothing End Function End Class Public Class Void Inherits [Object] End Class End Namespace" ' Create a custom corlib with a reference to compilation ' above and a reference to the actual mscorlib. Dim compCorLib = CreateEmptyCompilation( {Parse(sourceCorLib)}, options:=TestOptions.ReleaseDll, references:={MscorlibRef, refLib}, assemblyName:=CorLibAssemblyName) compCorLib.VerifyDiagnostics() Dim objectType = compCorLib.SourceAssembly.GlobalNamespace.GetMember(Of NamedTypeSymbol)("System.Object") Assert.NotNull(objectType.BaseType) Dim peBytes As ImmutableArray(Of Byte) = Nothing Dim pdbBytes As ImmutableArray(Of Byte) = Nothing ExpressionCompilerTestHelpers.EmitCorLibWithAssemblyReferences( compCorLib, Nothing, Function(moduleBuilder, emitOptions) New PEAssemblyBuilderWithAdditionalReferences(moduleBuilder, emitOptions, objectType.GetCciAdapter()), peBytes, pdbBytes) Using reader As New PEReader(peBytes) Dim metadata = reader.GetMetadata() Dim [module] = metadata.ToModuleMetadata(ignoreAssemblyRefs:=True) Dim metadataReader = metadata.ToMetadataReader() Dim moduleInstance = Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests.ModuleInstance.Create(metadata, metadataReader.GetModuleVersionIdOrThrow()) ' Verify the module declares System.Object. Assert.True(metadataReader.DeclaresTheObjectClass()) ' Verify the PEModule has no assembly references. Assert.Equal(0, [module].Module.ReferencedAssemblies.Length) ' Verify the underlying metadata has the expected assembly references. Dim actualReferences = metadataReader.AssemblyReferences.Select(Function(r) metadataReader.GetString(metadataReader.GetAssemblyReference(r).Name)).ToImmutableArray() AssertEx.Equal({"mscorlib", "System.Private.Library"}, actualReferences) Const source = "Class C Shared Sub M() End Sub End Class" Dim comp = CreateEmptyCompilation( {Parse(source)}, options:=TestOptions.ReleaseDll, references:={refLib, AssemblyMetadata.Create([module]).GetReference()}) comp.VerifyDiagnostics() Using runtime = RuntimeInstance.Create({comp.ToModuleInstance(), moduleInstance}) Dim errorMessage As String = Nothing Dim context = CreateMethodContext(runtime, "C.M") ' Valid expression. Dim testData = New CompilationTestData() context.CompileExpression("New Object()", errorMessage, testData) Assert.Null(errorMessage) Dim methodData = testData.GetMethodData("<>x.<>m0") methodData.VerifyIL( "{ // Code size 6 (0x6) .maxstack 1 IL_0000: newobj ""Sub Object..ctor()"" IL_0005: ret }") ' Invalid expression: System.Int32 is not defined in corlib above. testData = New CompilationTestData() context.CompileExpression("1", errorMessage, testData) Assert.Equal("error BC30002: Type 'System.Int32' is not defined.", errorMessage) ' Invalid expression: type in method signature from missing referenced assembly. testData = New CompilationTestData() context.CompileExpression("(New Object()).F()", errorMessage, testData) Assert.Equal("error BC30657: 'F' has a return type that is not supported or parameter types that are not supported.", errorMessage) ' Invalid expression: type forwarded to missing referenced assembly. testData = New CompilationTestData() context.CompileExpression("New Private2()", errorMessage, testData) Assert.Equal("error BC30002: Type 'Private2' is not defined.", errorMessage) End Using End Using End Sub Private Shared Function CreateTypeContextFactory( moduleVersionId As Guid, typeToken As Integer) As ExpressionCompiler.CreateContextDelegate Return Function(blocks, useReferencedModulesOnly) Dim compilation = If(useReferencedModulesOnly, blocks.ToCompilationReferencedModulesOnly(moduleVersionId), blocks.ToCompilation()) Return EvaluationContext.CreateTypeContext( compilation, moduleVersionId, typeToken) End Function End Function Private Shared Function CreateMethodContextFactory( moduleVersionId As Guid, symReader As ISymUnmanagedReader, methodToken As Integer, localSignatureToken As Integer) As ExpressionCompiler.CreateContextDelegate Return Function(blocks, useReferencedModulesOnly) Dim compilation = If(useReferencedModulesOnly, blocks.ToCompilationReferencedModulesOnly(moduleVersionId), blocks.ToCompilation()) Return EvaluationContext.CreateMethodContext( compilation, MakeDummyLazyAssemblyReaders(), symReader, moduleVersionId, methodToken, methodVersion:=1, ilOffset:=0, localSignatureToken:=localSignatureToken) End Function End Function Private NotInheritable Class PEAssemblyBuilderWithAdditionalReferences Inherits PEModuleBuilder Implements IAssemblyReference Private ReadOnly _builder As CommonPEModuleBuilder Private ReadOnly _objectType As NamespaceTypeDefinitionNoBase Friend Sub New(builder As CommonPEModuleBuilder, emitOptions As EmitOptions, objectType As INamespaceTypeDefinition) MyBase.New(DirectCast(builder.CommonSourceModule, SourceModuleSymbol), emitOptions, builder.OutputKind, builder.SerializationProperties, builder.ManifestResources) _builder = builder _objectType = New NamespaceTypeDefinitionNoBase(objectType) End Sub Public Overrides Iterator Function GetTopLevelSourceTypeDefinitions(context As EmitContext) As IEnumerable(Of INamespaceTypeDefinition) For Each t In MyBase.GetTopLevelSourceTypeDefinitions(context) Yield If(t Is _objectType.UnderlyingType, _objectType, t) Next End Function Public Overrides ReadOnly Property EncSymbolChanges As SymbolChanges Get Return _builder.EncSymbolChanges End Get End Property Public Overrides ReadOnly Property PreviousGeneration As EmitBaseline Get Return Nothing End Get End Property Public Overrides ReadOnly Property SourceAssemblyOpt As ISourceAssemblySymbolInternal Get Return _builder.SourceAssemblyOpt End Get End Property Public Overrides Function GetFiles(context As EmitContext) As IEnumerable(Of IFileReference) Return _builder.GetFiles(context) End Function Protected Overrides Sub AddEmbeddedResourcesFromAddedModules(builder As ArrayBuilder(Of Cci.ManagedResource), diagnostics As DiagnosticBag) End Sub Friend Overrides ReadOnly Property AllowOmissionOfConditionalCalls As Boolean Get Return True End Get End Property Private ReadOnly Property Identity As AssemblyIdentity Implements IAssemblyReference.Identity Get Return DirectCast(_builder, IAssemblyReference).Identity End Get End Property Private ReadOnly Property AssemblyVersionPattern As Version Implements IAssemblyReference.AssemblyVersionPattern Get Return DirectCast(_builder, IAssemblyReference).AssemblyVersionPattern End Get End Property End Class 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/CSharp/Test/Semantic/Semantics/OverloadResolutionTestBase.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.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.CSharp.UnitTests; using Roslyn.Utilities; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xunit; using Roslyn.Test.Utilities; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public abstract class OverloadResolutionTestBase : CompilingTestBase { internal void TestOverloadResolutionWithDiff(string source, MetadataReference[] additionalRefs = null) { // The mechanism of this test is: we build the bound tree for the code passed in and then extract // from it the nodes that describe the method symbols. We then compare the description of // the symbols given to the comment that follows the call. var mscorlibRef = AssemblyMetadata.CreateFromImage(TestMetadata.ResourcesNet451.mscorlib).GetReference(display: "mscorlib"); var references = new[] { mscorlibRef }.Concat(additionalRefs ?? Array.Empty<MetadataReference>()); var compilation = CreateEmptyCompilation(source, references, TestOptions.ReleaseDll); var method = (SourceMemberMethodSymbol)compilation.GlobalNamespace.GetTypeMembers("C").Single().GetMembers("M").Single(); var diagnostics = new DiagnosticBag(); var block = MethodCompiler.BindMethodBody(method, new TypeCompilationState(method.ContainingType, compilation, null), new BindingDiagnosticBag(diagnostics)); var tree = BoundTreeDumperNodeProducer.MakeTree(block); var results = string.Join("\n", tree.PreorderTraversal().Select(edge => edge.Value) .Where(x => x.Text == "method" && x.Value != null) .Select(x => x.Value) .ToArray()); // var r = string.Join("\n", tree.PreorderTraversal().Select(edge => edge.Value).ToArray(); var expected = string.Join("\n", source .Split(new[] { Environment.NewLine }, System.StringSplitOptions.RemoveEmptyEntries) .Where(x => x.Contains("//-")) .Select(x => x.Substring(x.IndexOf("//-", StringComparison.Ordinal) + 3)) .ToArray()); AssertEx.EqualOrDiff(expected, results); } } }
// 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.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.CSharp.UnitTests; using Roslyn.Utilities; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xunit; using Roslyn.Test.Utilities; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public abstract class OverloadResolutionTestBase : CompilingTestBase { internal void TestOverloadResolutionWithDiff(string source, MetadataReference[] additionalRefs = null) { // The mechanism of this test is: we build the bound tree for the code passed in and then extract // from it the nodes that describe the method symbols. We then compare the description of // the symbols given to the comment that follows the call. var mscorlibRef = AssemblyMetadata.CreateFromImage(TestMetadata.ResourcesNet451.mscorlib).GetReference(display: "mscorlib"); var references = new[] { mscorlibRef }.Concat(additionalRefs ?? Array.Empty<MetadataReference>()); var compilation = CreateEmptyCompilation(source, references, TestOptions.ReleaseDll); var method = (SourceMemberMethodSymbol)compilation.GlobalNamespace.GetTypeMembers("C").Single().GetMembers("M").Single(); var diagnostics = new DiagnosticBag(); var block = MethodCompiler.BindMethodBody(method, new TypeCompilationState(method.ContainingType, compilation, null), new BindingDiagnosticBag(diagnostics)); var tree = BoundTreeDumperNodeProducer.MakeTree(block); var results = string.Join("\n", tree.PreorderTraversal().Select(edge => edge.Value) .Where(x => x.Text == "method" && x.Value != null) .Select(x => x.Value) .ToArray()); // var r = string.Join("\n", tree.PreorderTraversal().Select(edge => edge.Value).ToArray(); var expected = string.Join("\n", source .Split(new[] { Environment.NewLine }, System.StringSplitOptions.RemoveEmptyEntries) .Where(x => x.Contains("//-")) .Select(x => x.Substring(x.IndexOf("//-", StringComparison.Ordinal) + 3)) .ToArray()); AssertEx.EqualOrDiff(expected, results); } } }
-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/Symbol/Compilation/ReferenceManagerTests.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.IO; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; using static Roslyn.Test.Utilities.TestMetadata; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class ReferenceManagerTests : CSharpTestBase { private static readonly CSharpCompilationOptions s_signedDll = TestOptions.ReleaseDll.WithCryptoPublicKey(TestResources.TestKeys.PublicKey_ce65828c82a341f2); [Fact] public void WinRtCompilationReferences() { var ifaceDef = CreateCompilation( @" public interface ITest { }", options: TestOptions.DebugWinMD, assemblyName: "ITest"); ifaceDef.VerifyDiagnostics(); var ifaceImageRef = ifaceDef.EmitToImageReference(); var wimpl = AssemblyMetadata.CreateFromImage(TestResources.WinRt.WImpl).GetReference(display: "WImpl"); var implDef2 = CreateCompilation( @" public class C { public static void Main() { ITest test = new WImpl(); } }", references: new MetadataReference[] { ifaceDef.ToMetadataReference(), wimpl }, options: TestOptions.DebugExe); implDef2.VerifyDiagnostics(); } [Fact] public void VersionUnification_SymbolUsed() { // Identity: C, Version=1.0.0.0, Culture=neutral, PublicKeyToken=374d0c2befcd8cc9 var v1 = AssemblyMetadata.CreateFromImage(TestResources.General.C1).GetReference(display: "C, V1"); // Identity: C, Version=2.0.0.0, Culture=neutral, PublicKeyToken=374d0c2befcd8cc9 var v2 = AssemblyMetadata.CreateFromImage(TestResources.General.C2).GetReference(display: "C, V2"); var refV1 = CreateCompilation("public class D : C { }", new[] { v1 }, assemblyName: "refV1"); var refV2 = CreateCompilation("public class D : C { }", new[] { v2 }, assemblyName: "refV2"); // reference asks for a lower version than available: var testRefV1 = CreateCompilation("public class E : D { }", new MetadataReference[] { new CSharpCompilationReference(refV1), v2 }, assemblyName: "testRefV1"); // reference asks for a higher version than available: var testRefV2 = CreateCompilation("public class E : D { }", new MetadataReference[] { new CSharpCompilationReference(refV2), v1 }, assemblyName: "testRefV2"); // TODO (tomat): we should display paths rather than names "refV1" and "C" testRefV1.VerifyDiagnostics( // warning CS1701: // Assuming assembly reference 'C, Version=1.0.0.0, Culture=neutral, PublicKeyToken=374d0c2befcd8cc9' // used by 'refV1' matches identity 'C, Version=2.0.0.0, Culture=neutral, PublicKeyToken=374d0c2befcd8cc9' of 'C', you may need to supply runtime policy Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin).WithArguments( "C, Version=1.0.0.0, Culture=neutral, PublicKeyToken=374d0c2befcd8cc9", "refV1", "C, Version=2.0.0.0, Culture=neutral, PublicKeyToken=374d0c2befcd8cc9", "C").WithLocation(1, 1)); // TODO (tomat): we should display paths rather than names "refV2" and "C" testRefV2.VerifyDiagnostics( // error CS1705: Assembly 'refV2' with identity 'refV2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' // uses 'C, Version=2.0.0.0, Culture=neutral, PublicKeyToken=374d0c2befcd8cc9' which has a higher version than referenced assembly // 'C' with identity 'C, Version=1.0.0.0, Culture=neutral, PublicKeyToken=374d0c2befcd8cc9' Diagnostic(ErrorCode.ERR_AssemblyMatchBadVersion).WithArguments( "refV2", "refV2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "C, Version=2.0.0.0, Culture=neutral, PublicKeyToken=374d0c2befcd8cc9", "C", "C, Version=1.0.0.0, Culture=neutral, PublicKeyToken=374d0c2befcd8cc9").WithLocation(1, 1)); } [Fact] [WorkItem(546080, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546080")] public void VersionUnification_SymbolNotUsed() { var v1 = MetadataReference.CreateFromImage(TestResources.General.C1); var v2 = MetadataReference.CreateFromImage(TestResources.General.C2); var refV1 = CreateCompilation("public class D : C { }", new[] { v1 }); var refV2 = CreateCompilation("public class D : C { }", new[] { v2 }); // reference asks for a lower version than available: var testRefV1 = CreateCompilation("public class E { }", new MetadataReference[] { new CSharpCompilationReference(refV1), v2 }); // reference asks for a higher version than available: var testRefV2 = CreateCompilation("public class E { }", new MetadataReference[] { new CSharpCompilationReference(refV2), v1 }); testRefV1.VerifyDiagnostics(); testRefV2.VerifyDiagnostics(); } [Fact] public void VersionUnification_MultipleVersions() { string sourceLibV1 = @" [assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public class C {} "; var libV1 = CreateCompilation( sourceLibV1, assemblyName: "Lib", options: s_signedDll); string sourceLibV2 = @" [assembly: System.Reflection.AssemblyVersion(""2.0.0.0"")] public class C {} "; var libV2 = CreateCompilation( sourceLibV2, assemblyName: "Lib", options: s_signedDll); string sourceLibV3 = @" [assembly: System.Reflection.AssemblyVersion(""3.0.0.0"")] public class C {} "; var libV3 = CreateCompilation( sourceLibV3, assemblyName: "Lib", options: s_signedDll); string sourceRefLibV2 = @" using System.Collections.Generic; [assembly: System.Reflection.AssemblyVersion(""2.0.0.0"")] public class R { public C Field; } "; var refLibV2 = CreateCompilation( sourceRefLibV2, assemblyName: "RefLibV2", references: new[] { new CSharpCompilationReference(libV2) }, options: s_signedDll); string sourceMain = @" public class M { public void F() { var x = new R(); System.Console.WriteLine(x.Field); } } "; // higher version should be preferred over lower version regardless of the order of the references var main13 = CreateCompilation( sourceMain, assemblyName: "Main", references: new[] { new CSharpCompilationReference(libV1), new CSharpCompilationReference(libV3), new CSharpCompilationReference(refLibV2) }); // TODO (tomat): we should display paths rather than names "RefLibV2" and "Lib" main13.VerifyDiagnostics( // warning CS1701: Assuming assembly reference 'Lib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' used by 'RefLibV2' matches identity 'Lib, Version=3.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' of 'Lib', you may need to supply runtime policy Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin).WithArguments( "Lib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "RefLibV2", "Lib, Version=3.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "Lib")); var main31 = CreateCompilation( sourceMain, assemblyName: "Main", references: new[] { new CSharpCompilationReference(libV3), new CSharpCompilationReference(libV1), new CSharpCompilationReference(refLibV2) }); // TODO (tomat): we should display paths rather than names "RefLibV2" and "Lib" main31.VerifyDiagnostics( // warning CS1701: Assuming assembly reference 'Lib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' used by 'RefLibV2' matches identity 'Lib, Version=3.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' of 'Lib', you may need to supply runtime policy Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin).WithArguments( "Lib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "RefLibV2", "Lib, Version=3.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "Lib")); } [Fact] [WorkItem(529808, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529808"), WorkItem(530246, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530246")] public void VersionUnification_UseSiteWarnings() { string sourceLibV1 = @" [assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public class C {} public delegate void D(); public interface I {} "; var libV1 = CreateCompilation( sourceLibV1, assemblyName: "Lib", options: s_signedDll); string sourceLibV2 = @" [assembly: System.Reflection.AssemblyVersion(""2.0.0.0"")] public class C {} public delegate void D(); public interface I {} "; var libV2 = CreateCompilation( sourceLibV2, assemblyName: "Lib", options: s_signedDll); string sourceRefLibV1 = @" using System.Collections.Generic; [assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public class R { public R(C c) {} public C Field; public C Property { get; set; } public int this[C arg] { get { return 0; } set {} } public event D Event; public List<C> Method1() { return null; } public void Method2(List<List<C>> c) { } public void GenericMethod<T>() where T : I { } } public class S1 : List<C> { public class Inner {} } public class S2 : I {} public class GenericClass<T> where T : I { public class S {} } "; var refLibV1 = CreateCompilation( sourceRefLibV1, assemblyName: "RefLibV1", references: new[] { new CSharpCompilationReference(libV1) }, options: s_signedDll); string sourceX = @" [assembly: System.Reflection.AssemblyVersion(""2.0.0.0"")] public class P : Q {} public class Q : S2 {} "; var x = CreateCompilation( sourceX, assemblyName: "X", references: new[] { new CSharpCompilationReference(refLibV1), new CSharpCompilationReference(libV1) }, options: s_signedDll); string sourceMain = @" public class M { public void F() { var c = new C(); // ok var r = new R(null); // error: C in parameter var f = r.Field; // error: C in type var a = r.Property; // error: C in return type var b = r[c]; // error: C in parameter r.Event += () => {}; // error: C in type var m = r.Method1(); // error: ~> C in return type r.Method2(null); // error: ~> C in parameter r.GenericMethod<OKImpl>(); // error: ~> I in constraint var g = new GenericClass<OKImpl>.S(); // error: ~> I in constraint -- should report only once, for GenericClass<OKImpl>, not again for S. var s1 = new S1(); // error: ~> C in base var s2 = new S2(); // error: ~> I in implements var s3 = new S1.Inner(); // error: ~> C in base -- should only report once, for S1, not again for Inner. var e = new P(); // error: P -> Q -> S2 ~> I in implements } } public class Z : S2 // error: S2 ~> I in implements { } public class OKImpl : I { } "; var main = CreateCompilation( sourceMain, assemblyName: "Main", references: new[] { new CSharpCompilationReference(refLibV1), new CSharpCompilationReference(libV2), new CSharpCompilationReference(x) }); // TODO (tomat): we should display paths rather than names "RefLibV1" and "Lib" main.VerifyDiagnostics( // warning CS1701: Assuming assembly reference 'Lib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' used by 'RefLibV1' matches identity 'Lib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' of 'Lib', you may need to supply runtime policy Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin).WithArguments("Lib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "RefLibV1", "Lib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "Lib").WithLocation(1, 1), // warning CS1701: Assuming assembly reference 'Lib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' used by 'RefLibV1' matches identity 'Lib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' of 'Lib', you may need to supply runtime policy Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin).WithArguments("Lib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "RefLibV1", "Lib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "Lib").WithLocation(1, 1), // warning CS1701: Assuming assembly reference 'Lib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' used by 'RefLibV1' matches identity 'Lib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' of 'Lib', you may need to supply runtime policy Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin).WithArguments("Lib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "RefLibV1", "Lib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "Lib").WithLocation(1, 1), // warning CS1701: Assuming assembly reference 'Lib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' used by 'RefLibV1' matches identity 'Lib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' of 'Lib', you may need to supply runtime policy Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin).WithArguments("Lib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "RefLibV1", "Lib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "Lib").WithLocation(1, 1), // warning CS1701: Assuming assembly reference 'Lib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' used by 'RefLibV1' matches identity 'Lib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' of 'Lib', you may need to supply runtime policy Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin).WithArguments("Lib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "RefLibV1", "Lib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "Lib").WithLocation(1, 1), // warning CS1701: Assuming assembly reference 'Lib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' used by 'RefLibV1' matches identity 'Lib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' of 'Lib', you may need to supply runtime policy Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin).WithArguments("Lib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "RefLibV1", "Lib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "Lib").WithLocation(1, 1), // warning CS1701: Assuming assembly reference 'Lib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' used by 'RefLibV1' matches identity 'Lib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' of 'Lib', you may need to supply runtime policy Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin).WithArguments("Lib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "RefLibV1", "Lib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "Lib").WithLocation(1, 1), // warning CS1701: Assuming assembly reference 'Lib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' used by 'RefLibV1' matches identity 'Lib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' of 'Lib', you may need to supply runtime policy Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin).WithArguments("Lib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "RefLibV1", "Lib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "Lib").WithLocation(1, 1), // warning CS1701: Assuming assembly reference 'Lib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' used by 'RefLibV1' matches identity 'Lib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' of 'Lib', you may need to supply runtime policy Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin).WithArguments("Lib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "RefLibV1", "Lib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "Lib").WithLocation(1, 1), // warning CS1701: Assuming assembly reference 'Lib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' used by 'RefLibV1' matches identity 'Lib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' of 'Lib', you may need to supply runtime policy Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin).WithArguments("Lib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "RefLibV1", "Lib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "Lib").WithLocation(1, 1), // warning CS1701: Assuming assembly reference 'Lib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' used by 'RefLibV1' matches identity 'Lib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' of 'Lib', you may need to supply runtime policy Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin).WithArguments("Lib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "RefLibV1", "Lib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "Lib").WithLocation(1, 1), // warning CS1701: Assuming assembly reference 'Lib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' used by 'RefLibV1' matches identity 'Lib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' of 'Lib', you may need to supply runtime policy Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin).WithArguments("Lib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "RefLibV1", "Lib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "Lib").WithLocation(1, 1), // warning CS1701: Assuming assembly reference 'Lib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' used by 'RefLibV1' matches identity 'Lib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' of 'Lib', you may need to supply runtime policy Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin).WithArguments("Lib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "RefLibV1", "Lib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "Lib").WithLocation(1, 1), // warning CS1701: Assuming assembly reference 'Lib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' used by 'RefLibV1' matches identity 'Lib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' of 'Lib', you may need to supply runtime policy Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin).WithArguments("Lib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "RefLibV1", "Lib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "Lib").WithLocation(1, 1), // warning CS1701: Assuming assembly reference 'Lib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' used by 'X' matches identity 'Lib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' of 'Lib', you may need to supply runtime policy Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin).WithArguments("Lib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "X", "Lib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "Lib").WithLocation(1, 1)); CompileAndVerify(main, validator: (assembly) => { var reader = assembly.GetMetadataReader(); // Dev11 adds "Lib 1.0" to the references, we don't (see DevDiv #15580) AssertEx.SetEqual(new[] { $"{RuntimeCorLibName.Name} {RuntimeCorLibName.Version.ToString(2)}", "RefLibV1 1.0", "Lib 2.0", "X 2.0" }, reader.DumpAssemblyReferences()); }, // PE verification fails on some platforms. Would need .config file with Lib v1 -> Lib v2 binding redirect verify: Verification.Skipped); } [Fact] [WorkItem(546080, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546080")] public void VersionUnification_UseSiteDiagnostics_Multiple() { string sourceA1 = @" [assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public class A {} "; var a1 = CreateCompilation( sourceA1, assemblyName: "A", options: s_signedDll); string sourceA2 = @" [assembly: System.Reflection.AssemblyVersion(""2.0.0.0"")] public class A {} "; var a2 = CreateCompilation( sourceA2, assemblyName: "A", options: s_signedDll); string sourceB1 = @" [assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public class B {} "; var b1 = CreateCompilation( sourceB1, assemblyName: "B", options: s_signedDll); string sourceB2 = @" [assembly: System.Reflection.AssemblyVersion(""2.0.0.0"")] public class B {} "; var b2 = CreateCompilation( sourceB2, assemblyName: "B", options: s_signedDll); string sourceRefA1B2 = @" using System.Collections.Generic; [assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public class R { public Dictionary<A, B> Dict = new Dictionary<A, B>(); public void Goo(A a, B b) {} } "; var refA1B2 = CreateCompilation( sourceRefA1B2, assemblyName: "RefA1B2", references: new[] { new CSharpCompilationReference(a1), new CSharpCompilationReference(b2) }, options: s_signedDll); string sourceMain = @" public class M { public void F() { var r = new R(); System.Console.WriteLine(r.Dict); // warning & error r.Goo(null, null); // warning & error } } "; var main = CreateCompilation( sourceMain, assemblyName: "Main", references: new[] { new CSharpCompilationReference(refA1B2), new CSharpCompilationReference(a2), new CSharpCompilationReference(b1) }); // TODO (tomat): we should display paths rather than names "RefLibV1" and "Lib" // TODO (tomat): this should include 2 warnings: main.VerifyDiagnostics( // error CS1705: Assembly 'RefA1B2' with identity 'RefA1B2, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' uses // 'B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' which has a higher version than referenced assembly 'B' // with identity 'B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' Diagnostic(ErrorCode.ERR_AssemblyMatchBadVersion).WithArguments( "RefA1B2", "RefA1B2, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "B", "B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2").WithLocation(1, 1), // error CS1705: Assembly 'RefA1B2' with identity 'RefA1B2, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' uses // 'B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' which has a higher version than referenced assembly 'B' // with identity 'B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' Diagnostic(ErrorCode.ERR_AssemblyMatchBadVersion).WithArguments( "RefA1B2", "RefA1B2, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "B", "B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2").WithLocation(1, 1)); } [Fact] public void VersionUnification_UseSiteDiagnostics_OptionalAttributes() { string sourceLibV1 = @" [assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] namespace System.Reflection { [AttributeUsage(AttributeTargets.Assembly, Inherited = false)] public sealed class AssemblyVersionAttribute : Attribute { public AssemblyVersionAttribute(string version) {} public string Version { get; set; } } } public class CGAttribute : System.Attribute { } "; var libV1 = CreateEmptyCompilation( sourceLibV1, assemblyName: "Lib", references: new[] { MinCorlibRef }, options: s_signedDll); libV1.VerifyDiagnostics(); string sourceLibV2 = @" [assembly: System.Reflection.AssemblyVersion(""2.0.0.0"")] namespace System.Reflection { [AttributeUsage(AttributeTargets.Assembly, Inherited = false)] public sealed class AssemblyVersionAttribute : Attribute { public AssemblyVersionAttribute(string version) {} public string Version { get; set; } } } public class CGAttribute : System.Attribute { } "; var libV2 = CreateEmptyCompilation( sourceLibV2, assemblyName: "Lib", references: new[] { MinCorlibRef }, options: s_signedDll); libV2.VerifyDiagnostics(); string sourceRefLibV1 = @" namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.All, Inherited = true)] public sealed class CompilerGeneratedAttribute : CGAttribute { } } "; var refLibV1 = CreateEmptyCompilation( sourceRefLibV1, assemblyName: "RefLibV1", references: new MetadataReference[] { MinCorlibRef, new CSharpCompilationReference(libV1) }, options: s_signedDll); refLibV1.VerifyDiagnostics(); string sourceMain = @" public class C { public int P { get; set; } // error: backing field is marked by CompilerGeneratedAttribute, whose base type is in the unified assembly } "; var main = CreateEmptyCompilation( sourceMain, assemblyName: "Main", references: new MetadataReference[] { MinCorlibRef, new CSharpCompilationReference(refLibV1), new CSharpCompilationReference(libV2) }); // Dev11 reports warning since the base type of CompilerGeneratedAttribute is in unified assembly. // Roslyn doesn't report any use-site diagnostics for optional attributes, it just ignores them main.VerifyDiagnostics(); } [Fact] public void VersionUnification_SymbolEquality() { string sourceLibV1 = @" using System.Reflection; [assembly: AssemblyVersion(""1.0.0.0"")] public interface I {} "; var libV1 = CreateCompilation( sourceLibV1, assemblyName: "Lib", options: s_signedDll); string sourceLibV2 = @" using System.Reflection; [assembly: AssemblyVersion(""2.0.0.0"")] public interface I {} "; var libV2 = CreateCompilation( sourceLibV2, assemblyName: "Lib", options: s_signedDll); string sourceRefLibV1 = @" using System.Reflection; [assembly: AssemblyVersion(""1.0.0.0"")] public class C : I { } "; var refLibV1 = CreateCompilation( sourceRefLibV1, assemblyName: "RefLibV1", references: new[] { new CSharpCompilationReference(libV1) }, options: s_signedDll); string sourceMain = @" public class M { public void F() { I x = new C(); } } "; var main = CreateCompilation( sourceMain, assemblyName: "Main", references: new[] { new CSharpCompilationReference(refLibV1), new CSharpCompilationReference(libV2) }); // TODO (tomat): we should display paths rather than names "RefLibV1" and "Lib" main.VerifyDiagnostics( // warning CS1701: Assuming assembly reference 'Lib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' // used by 'RefLibV1' matches identity 'Lib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' of 'Lib', you may need to supply runtime policy Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin).WithArguments( "Lib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "RefLibV1", "Lib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "Lib")); } [Fact] [WorkItem(546752, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546752")] public void VersionUnification_NoPiaMissingCanonicalTypeSymbol() { string sourceLibV1 = @" [assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public class A {} "; var libV1 = CreateCompilation( sourceLibV1, assemblyName: "Lib", options: s_signedDll); string sourceLibV2 = @" [assembly: System.Reflection.AssemblyVersion(""2.0.0.0"")] public class A {} "; var libV2 = CreateCompilation( sourceLibV2, assemblyName: "Lib", options: s_signedDll); string sourceRefLibV1 = @" using System.Runtime.InteropServices; public class B : A { public void M(IB i) { } } [ComImport] [Guid(""F79F0037-0874-4EE3-BC45-158EDBA3ABA3"")] [TypeIdentifier] public interface IB { } "; var refLibV1 = CreateCompilation( sourceRefLibV1, assemblyName: "RefLibV1", references: new[] { new CSharpCompilationReference(libV1) }, options: TestOptions.ReleaseDll); string sourceMain = @" public class Test { static void Main() { B b = new B(); b.M(null); } } "; // NOTE: We won't get a nopia type unless we use a PE reference (i.e. source won't work). var main = CreateCompilation( sourceMain, assemblyName: "Main", references: new MetadataReference[] { MetadataReference.CreateFromImage(refLibV1.EmitToArray()), new CSharpCompilationReference(libV2) }, options: TestOptions.ReleaseExe); // TODO (tomat): we should display paths rather than names "RefLibV1" and "Lib" main.VerifyDiagnostics( // warning CS1701: Assuming assembly reference 'Lib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' used by 'RefLibV1' matches identity 'Lib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' of 'Lib', you may need to supply runtime policy Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin).WithArguments("Lib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "RefLibV1", "Lib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "Lib"), // warning CS1701: Assuming assembly reference 'Lib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' used by 'RefLibV1' matches identity 'Lib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' of 'Lib', you may need to supply runtime policy Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin).WithArguments("Lib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "RefLibV1", "Lib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "Lib"), // (7,9): error CS1748: Cannot find the interop type that matches the embedded interop type 'IB'. Are you missing an assembly reference? // b.M(null); Diagnostic(ErrorCode.ERR_NoCanonicalView, "b.M").WithArguments("IB")); } [WorkItem(546525, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546525")] [Fact] public void AssemblyReferencesWithAliases() { var source = @"extern alias SysCore; using System.Linq; namespace Microsoft.TeamFoundation.WebAccess.Common { public class CachedRegistry { public static void Main(string[] args) { System.Console.Write('k'); } } }"; var tree = Parse(source); var r1 = AssemblyMetadata.CreateFromImage(ResourcesNet451.SystemCore).GetReference(filePath: @"c:\temp\aa.dll", display: "System.Core.v4_0_30319.dll"); var r2 = AssemblyMetadata.CreateFromImage(ResourcesNet451.SystemCore).GetReference(filePath: @"c:\temp\aa.dll", display: "System.Core.v4_0_30319.dll"); var r2_SysCore = r2.WithAliases(new[] { "SysCore" }); var compilation = CreateEmptyCompilation(tree, new[] { MscorlibRef, r1, r2_SysCore }, TestOptions.DebugExe, assemblyName: "Test"); CompileAndVerify(compilation, expectedOutput: "k"); } [WorkItem(545062, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545062")] [Fact] public void DuplicateReferences() { CSharpCompilation c; string source; var r1 = AssemblyMetadata.CreateFromImage(TestResources.General.C1).GetReference(filePath: @"c:\temp\a.dll", display: "R1"); var r2 = AssemblyMetadata.CreateFromImage(TestResources.General.C1).GetReference(filePath: @"c:\temp\a.dll", display: "R2"); var rGoo = r2.WithAliases(new[] { "goo" }); var rBar = r2.WithAliases(new[] { "bar" }); var rEmbed = r1.WithEmbedInteropTypes(true); source = @" class D { } "; c = createCompilationCore(source, new[] { r1, r2 }); Assert.Null(c.GetReferencedAssemblySymbol(r1)); Assert.NotNull(c.GetReferencedAssemblySymbol(r2)); c.VerifyDiagnostics(); source = @" class D : C { } "; c = createCompilationCore(source, new[] { r1, r2 }); Assert.Null(c.GetReferencedAssemblySymbol(r1)); Assert.NotNull(c.GetReferencedAssemblySymbol(r2)); c.VerifyDiagnostics(); c = createCompilationCore(source, new[] { rGoo, r2 }); Assert.Null(c.GetReferencedAssemblySymbol(rGoo)); Assert.NotNull(c.GetReferencedAssemblySymbol(r2)); AssertEx.SetEqual(new[] { "goo", "global" }, c.ExternAliases); c.VerifyDiagnostics(); // 2 aliases for the same path, aliases not used to qualify name c = createCompilationCore(source, new[] { rGoo, rBar }); Assert.Null(c.GetReferencedAssemblySymbol(rGoo)); Assert.NotNull(c.GetReferencedAssemblySymbol(rBar)); AssertEx.SetEqual(new[] { "goo", "bar" }, c.ExternAliases); c.VerifyDiagnostics( // (2,11): error CS0246: The type or namespace name 'C' could not be found (are you missing a using directive or an assembly reference?) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "C").WithArguments("C")); source = @" class D : C { } "; // /l and /r with the same path c = createCompilationCore(source, new[] { rGoo, rEmbed }); Assert.Null(c.GetReferencedAssemblySymbol(rGoo)); Assert.NotNull(c.GetReferencedAssemblySymbol(rEmbed)); c.VerifyDiagnostics( // error CS1760: Assemblies 'R1' and 'R2' refer to the same metadata but only one is a linked reference (specified using /link option); consider removing one of the references. Diagnostic(ErrorCode.ERR_AssemblySpecifiedForLinkAndRef).WithArguments("R1", "R2"), // error CS1747: Cannot embed interop types from assembly 'C, Version=1.0.0.0, Culture=neutral, PublicKeyToken=374d0c2befcd8cc9' because it is missing the 'System.Runtime.InteropServices.GuidAttribute' attribute. Diagnostic(ErrorCode.ERR_NoPIAAssemblyMissingAttribute).WithArguments("C, Version=1.0.0.0, Culture=neutral, PublicKeyToken=374d0c2befcd8cc9", "System.Runtime.InteropServices.GuidAttribute"), // error CS1759: Cannot embed interop types from assembly 'C, Version=1.0.0.0, Culture=neutral, PublicKeyToken=374d0c2befcd8cc9' because it is missing either the 'System.Runtime.InteropServices.ImportedFromTypeLibAttribute' attribute or the 'System.Runtime.InteropServices.PrimaryInteropAssemblyAttribute' attribute. Diagnostic(ErrorCode.ERR_NoPIAAssemblyMissingAttributes).WithArguments("C, Version=1.0.0.0, Culture=neutral, PublicKeyToken=374d0c2befcd8cc9", "System.Runtime.InteropServices.ImportedFromTypeLibAttribute", "System.Runtime.InteropServices.PrimaryInteropAssemblyAttribute"), // (2,11): error CS1752: Interop type 'C' cannot be embedded. Use the applicable interface instead. // class D : C { } Diagnostic(ErrorCode.ERR_NewCoClassOnLink, "C").WithArguments("C")); source = @" extern alias goo; extern alias bar; public class D : goo::C { } public class E : bar::C { } "; // 2 aliases for the same path, aliases used c = createCompilationCore(source, new[] { rGoo, rBar }); Assert.Null(c.GetReferencedAssemblySymbol(rGoo)); Assert.NotNull(c.GetReferencedAssemblySymbol(rBar)); c.VerifyDiagnostics(); CSharpCompilation createCompilationCore(string s, IEnumerable<MetadataReference> references) { references = TargetFrameworkUtil.StandardReferences.AddRange(references); return CreateEmptyCompilation(s, references); } } // "<path>\x\y.dll" -> "<path>\x\..\x\y.dll" private static string MakeEquivalentPath(string path) { string[] parts = path.Split(Path.DirectorySeparatorChar); Debug.Assert(parts.Length >= 3); int dir = parts.Length - 2; List<string> newParts = new List<string>(parts); newParts.Insert(dir, ".."); newParts.Insert(dir, parts[dir]); return newParts.Join(Path.DirectorySeparatorChar.ToString()); } [Fact] public void DuplicateAssemblyReferences_EquivalentPath() { string p1 = Temp.CreateFile().WriteAllBytes(TestResources.General.MDTestLib1).Path; string p2 = MakeEquivalentPath(p1); string p3 = MakeEquivalentPath(p2); var r1 = MetadataReference.CreateFromFile(p1); var r2 = MetadataReference.CreateFromFile(p2); var r3 = MetadataReference.CreateFromFile(p3); SyntaxTree t1, t2, t3; var compilation = CSharpCompilation.Create("goo", syntaxTrees: new[] { t1 = Parse($"#r \"{p2}\"", options: TestOptions.Script), t2 = Parse($"#r \"{p3}\"", options: TestOptions.Script), t3 = Parse("#r \"Lib\"", options: TestOptions.Script), }, references: new MetadataReference[] { MscorlibRef_v4_0_30316_17626, r1, r2 }, options: TestOptions.ReleaseDll.WithMetadataReferenceResolver( new TestMetadataReferenceResolver( assemblyNames: new Dictionary<string, PortableExecutableReference> { { "Lib", r3 } }, files: new Dictionary<string, PortableExecutableReference> { { p2, r2 }, { p3, r3 } })) ); // no diagnostics expected, all duplicate references should be ignored as they all refer to the same file: compilation.VerifyDiagnostics(); var refs = compilation.ExternalReferences; Assert.Equal(3, refs.Length); Assert.Equal(MscorlibRef_v4_0_30316_17626, refs[0]); Assert.Equal(r1, refs[1]); Assert.Equal(r2, refs[2]); // All #r's resolved are represented in directive references. var dirRefs = compilation.DirectiveReferences; Assert.Equal(1, dirRefs.Length); var as1 = compilation.GetReferencedAssemblySymbol(r2); Assert.Equal("MDTestLib1", as1.Identity.Name); // r1 is a dup of r2: Assert.Null(compilation.GetReferencedAssemblySymbol(r1)); var rd1 = t1.GetCompilationUnitRoot().GetReferenceDirectives().Single(); var rd2 = t2.GetCompilationUnitRoot().GetReferenceDirectives().Single(); var rd3 = t3.GetCompilationUnitRoot().GetReferenceDirectives().Single(); var dr1 = compilation.GetDirectiveReference(rd1) as PortableExecutableReference; var dr2 = compilation.GetDirectiveReference(rd2) as PortableExecutableReference; var dr3 = compilation.GetDirectiveReference(rd3) as PortableExecutableReference; Assert.Equal(MetadataImageKind.Assembly, dr1.Properties.Kind); Assert.Equal(MetadataImageKind.Assembly, dr2.Properties.Kind); Assert.Equal(MetadataImageKind.Assembly, dr3.Properties.Kind); Assert.True(dr1.Properties.Aliases.IsEmpty); Assert.True(dr2.Properties.Aliases.IsEmpty); Assert.True(dr3.Properties.Aliases.IsEmpty); Assert.False(dr1.Properties.EmbedInteropTypes); Assert.False(dr2.Properties.EmbedInteropTypes); Assert.False(dr3.Properties.EmbedInteropTypes); // the paths come from the resolver: Assert.Equal(p2, dr1.FilePath); Assert.Equal(p3, dr2.FilePath); Assert.Equal(p3, dr3.FilePath); } [Fact] public void DuplicateModuleReferences_EquivalentPath() { var dir = Temp.CreateDirectory(); string p1 = dir.CreateFile("netModule1.netmodule").WriteAllBytes(TestResources.SymbolsTests.netModule.netModule1).Path; string p2 = MakeEquivalentPath(p1); var m1 = MetadataReference.CreateFromFile(p1, new MetadataReferenceProperties(MetadataImageKind.Module)); var m2 = MetadataReference.CreateFromFile(p2, new MetadataReferenceProperties(MetadataImageKind.Module)); var compilation = CSharpCompilation.Create("goo", options: TestOptions.ReleaseDll, references: new MetadataReference[] { m1, m2 }); // We don't deduplicate references based on file path on the compilation level. // The host (command line compiler and msbuild workspace) is responsible for such de-duplication, if needed. compilation.VerifyDiagnostics( // error CS8015: Module 'netModule1.netmodule' is already defined in this assembly. Each module must have a unique filename. Diagnostic(ErrorCode.ERR_NetModuleNameMustBeUnique).WithArguments("netModule1.netmodule"), // netModule1.netmodule: error CS0101: The namespace '<global namespace>' already contains a definition for 'Class1' Diagnostic(ErrorCode.ERR_DuplicateNameInNS).WithArguments("Class1", "<global namespace>"), // netModule1.netmodule: error CS0101: The namespace 'NS1' already contains a definition for 'Class4' Diagnostic(ErrorCode.ERR_DuplicateNameInNS).WithArguments("Class4", "NS1"), // netModule1.netmodule: error CS0101: The namespace 'NS1' already contains a definition for 'Class8' Diagnostic(ErrorCode.ERR_DuplicateNameInNS).WithArguments("Class8", "NS1")); var mods = compilation.Assembly.Modules.ToArray(); Assert.Equal(3, mods.Length); Assert.NotNull(compilation.GetReferencedModuleSymbol(m1)); Assert.NotNull(compilation.GetReferencedModuleSymbol(m2)); } /// <summary> /// Two metadata files with the same strong identity referenced twice, with embedInteropTypes=true and embedInteropTypes=false. /// </summary> [Fact] public void DuplicateAssemblyReferences_EquivalentStrongNames_Metadata() { var ref1 = AssemblyMetadata.CreateFromImage(TestResources.General.C2).GetReference(embedInteropTypes: true, filePath: @"R:\A\MTTestLib1.dll"); var ref2 = AssemblyMetadata.CreateFromImage(TestResources.General.C2).GetReference(embedInteropTypes: false, filePath: @"R:\B\MTTestLib1.dll"); var c = CreateEmptyCompilation("class C {}", TargetFrameworkUtil.StandardReferences.AddRange(new[] { ref1, ref2 })); c.VerifyDiagnostics( // error CS1760: Assemblies 'R:\B\MTTestLib1.dll' and 'R:\A\MTTestLib1.dll' refer to the same metadata but only one is a linked reference (specified using /link option); consider removing one of the references. Diagnostic(ErrorCode.ERR_AssemblySpecifiedForLinkAndRef).WithArguments(@"R:\B\MTTestLib1.dll", @"R:\A\MTTestLib1.dll")); } /// <summary> /// Two compilations with the same strong identity referenced twice, with embedInteropTypes=true and embedInteropTypes=false. /// </summary> [Fact] public void DuplicateAssemblyReferences_EquivalentStrongNames_Compilations() { var sourceLib = @" [assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public interface I {}"; var lib1 = CreateCompilation(sourceLib, options: s_signedDll, assemblyName: "Lib"); var lib2 = CreateCompilation(sourceLib, options: s_signedDll, assemblyName: "Lib"); var ref1 = lib1.ToMetadataReference(embedInteropTypes: true); var ref2 = lib2.ToMetadataReference(embedInteropTypes: false); var c = CreateEmptyCompilation("class C {}", TargetFrameworkUtil.StandardReferences.AddRange(new[] { ref1, ref2 })); c.VerifyDiagnostics( // error CS1760: Assemblies 'Lib' and 'Lib' refer to the same metadata but only one is a linked reference (specified using /link option); consider removing one of the references. Diagnostic(ErrorCode.ERR_AssemblySpecifiedForLinkAndRef).WithArguments("Lib", "Lib")); } [Fact] public void DuplicateAssemblyReferences_EquivalentName() { string p1 = Temp.CreateFile().WriteAllBytes(ResourcesNet451.SystemCore).Path; string p2 = Temp.CreateFile().CopyContentFrom(p1).Path; var r1 = MetadataReference.CreateFromFile(p1); var r2 = MetadataReference.CreateFromFile(p2); var compilation = CSharpCompilation.Create("goo", references: new[] { r1, r2 }); var refs = compilation.Assembly.Modules.Select(module => module.GetReferencedAssemblies()).ToArray(); Assert.Equal(1, refs.Length); Assert.Equal(1, refs[0].Length); } /// <summary> /// Two Framework identities with unified versions. /// </summary> [Fact] [WorkItem(546026, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546026"), WorkItem(546169, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546169")] public void CS1703ERR_DuplicateImport() { var p1 = Temp.CreateFile().WriteAllBytes(ResourcesNet451.System).Path; var p2 = Temp.CreateFile().WriteAllBytes(ResourcesNet20.System).Path; var text = @"namespace N {}"; var comp = CSharpCompilation.Create( "DupSignedRefs", new[] { SyntaxFactory.ParseSyntaxTree(text, options: TestOptions.Regular) }, new[] { MetadataReference.CreateFromFile(p1), MetadataReference.CreateFromFile(p2) }, TestOptions.ReleaseDll.WithAssemblyIdentityComparer(DesktopAssemblyIdentityComparer.Default)); comp.VerifyDiagnostics( // error CS1703: Multiple assemblies with equivalent identity have been imported: '...\v4.0.30319\System.dll' and '...\v2.0.50727\System.dll'. Remove one of the duplicate references. Diagnostic(ErrorCode.ERR_DuplicateImport).WithArguments(p1, p2)); } [Fact] public void CS1704ERR_DuplicateImportSimple() { var libSource = @" using System; public class A { }"; var peImage = CreateCompilation(libSource, options: TestOptions.ReleaseDll, assemblyName: "CS1704").EmitToArray(); var dir1 = Temp.CreateDirectory(); var exe1 = dir1.CreateFile("CS1704.dll").WriteAllBytes(peImage); var dir2 = Temp.CreateDirectory(); var exe2 = dir2.CreateFile("CS1704.dll").WriteAllBytes(peImage); var ref1 = AssemblyMetadata.CreateFromFile(exe1.Path).GetReference(aliases: ImmutableArray.Create("A1")); var ref2 = AssemblyMetadata.CreateFromFile(exe2.Path).GetReference(aliases: ImmutableArray.Create("A2")); var source = @" extern alias A1; extern alias A2; class B : A1::A { } class C : A2::A { } "; // Dev12 reports CS1704. An assembly with the same simple name '...' has already been imported. // We consider the second reference a duplicate and ignore it (merging the aliases). CreateEmptyCompilation(source, TargetFrameworkUtil.StandardReferences.AddRange(new[] { ref1, ref2 })).VerifyDiagnostics(); } [Fact] public void WeakIdentitiesWithDifferentVersions() { var sourceLibV1 = @" using System.Reflection; [assembly: AssemblyVersion(""1.0.0.0"")] public class C1 { } "; var sourceLibV2 = @" using System.Reflection; [assembly: AssemblyVersion(""2.0.0.0"")] public class C2 { } "; var sourceRefLibV1 = @" public class P { public C1 x; } "; var sourceMain = @" public class Q { public P x; public C1 y; public C2 z; } "; var libV1 = CreateCompilation(sourceLibV1, assemblyName: "Lib"); var libV2 = CreateCompilation(sourceLibV2, assemblyName: "Lib"); var refLibV1 = CreateCompilation(sourceRefLibV1, new[] { new CSharpCompilationReference(libV1) }, assemblyName: "RefLibV1"); var main = CreateCompilation(sourceMain, new[] { new CSharpCompilationReference(libV1), new CSharpCompilationReference(refLibV1), new CSharpCompilationReference(libV2) }, assemblyName: "Main"); main.VerifyDiagnostics( // error CS1704: An assembly with the same simple name 'Lib' has already been imported. Try removing one of the references (e.g. 'Lib') or sign them to enable side-by-side. Diagnostic(ErrorCode.ERR_DuplicateImportSimple).WithArguments("Lib", "Lib"), // (5,12): error CS0246: The type or namespace name 'C1' could not be found (are you missing a using directive or an assembly reference?) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "C1").WithArguments("C1")); } /// <summary> /// Although the CLR considers all WinRT references equivalent the Dev11 C# and VB compilers still /// compare their identities as if they were regular managed dlls. /// </summary> [Fact] public void WinMd_SameSimpleNames_SameVersions() { var sourceMain = @" public class Q { public C1 y; public C2 z; } "; // W1.dll: (W, Version=255.255.255.255, Culture=null, PKT=null) // W2.dll: (W, Version=255.255.255.255, Culture=null, PKT=null) using (AssemblyMetadata metadataLib1 = AssemblyMetadata.CreateFromImage(TestResources.WinRt.W1), metadataLib2 = AssemblyMetadata.CreateFromImage(TestResources.WinRt.W2)) { var mdRefLib1 = metadataLib1.GetReference(filePath: @"C:\W1.dll"); var mdRefLib2 = metadataLib2.GetReference(filePath: @"C:\W2.dll"); var main = CreateEmptyCompilation(sourceMain, TargetFrameworkUtil.StandardReferences.AddRange(new[] { mdRefLib1, mdRefLib2 })); // Dev12 reports CS1704. An assembly with the same simple name '...' has already been imported. // We consider the second reference a duplicate and ignore it. main.VerifyDiagnostics( // (4,12): error CS0246: The type or namespace name 'C1' could not be found (are you missing a using directive or an assembly reference?) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "C1").WithArguments("C1")); } } /// <summary> /// Although the CLR considers all WinRT references equivalent the Dev11 C# and VB compilers still /// compare their identities as if they were regular managed dlls. /// </summary> [Fact] public void WinMd_DifferentSimpleNames() { var sourceMain = @" public class Q { public C1 y; public CB z; } "; // W1.dll: (W, Version=255.255.255.255, Culture=null, PKT=null) // WB.dll: (WB, Version=255.255.255.255, Culture=null, PKT=null) using (AssemblyMetadata metadataLib1 = AssemblyMetadata.CreateFromImage(TestResources.WinRt.W1), metadataLib2 = AssemblyMetadata.CreateFromImage(TestResources.WinRt.WB)) { var mdRefLib1 = metadataLib1.GetReference(filePath: @"C:\W1.dll"); var mdRefLib2 = metadataLib2.GetReference(filePath: @"C:\WB.dll"); var main = CreateCompilation(sourceMain, new[] { mdRefLib1, mdRefLib2 }); main.VerifyDiagnostics(); } } /// <summary> /// Although the CLR considers all WinRT references equivalent the Dev11 C# and VB compilers still /// compare their identities as if they were regular managed dlls. /// </summary> [Fact] public void WinMd_SameSimpleNames_DifferentVersions() { var sourceMain = @" public class Q { public CB y; public CB_V1 z; } "; // WB.dll: (WB, Version=255.255.255.255, Culture=null, PKT=null) // WB_Version1.dll: (WB, Version=1.0.0.0, Culture=null, PKT=null) using (AssemblyMetadata metadataLib1 = AssemblyMetadata.CreateFromImage(TestResources.WinRt.WB), metadataLib2 = AssemblyMetadata.CreateFromImage(TestResources.WinRt.WB_Version1)) { var mdRefLib1 = metadataLib1.GetReference(filePath: @"C:\WB.dll"); var mdRefLib2 = metadataLib2.GetReference(filePath: @"C:\WB_Version1.dll"); var main = CreateEmptyCompilation(sourceMain, TargetFrameworkUtil.StandardReferences.AddRange(new[] { mdRefLib1, mdRefLib2 })); main.VerifyDiagnostics( // error CS1704: An assembly with the same simple name 'WB' has already been imported. Try removing one of the references (e.g. 'C:\WB.dll') or sign them to enable side-by-side. Diagnostic(ErrorCode.ERR_DuplicateImportSimple).WithArguments("WB", @"C:\WB.dll"), // (4,12): error CS0246: The type or namespace name 'CB' could not be found (are you missing a using directive or an assembly reference?) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "CB").WithArguments("CB")); } } /// <summary> /// We replicate the Dev11 behavior here but is there any real world scenario for this? /// </summary> [Fact] public void MetadataReferencesDifferInCultureOnly() { var arSA = TestReferences.SymbolsTests.Versioning.AR_SA; var enUS = TestReferences.SymbolsTests.Versioning.EN_US; var source = @" public class A { public arSA a = new arSA(); public enUS b = new enUS(); } "; var compilation = CreateEmptyCompilation(source, TargetFrameworkUtil.StandardReferences.AddRange(new[] { arSA, enUS })); var arSA_sym = compilation.GetReferencedAssemblySymbol(arSA); var enUS_sym = compilation.GetReferencedAssemblySymbol(enUS); Assert.Equal("ar-SA", arSA_sym.Identity.CultureName); Assert.Equal("en-US", enUS_sym.Identity.CultureName); compilation.VerifyDiagnostics(); } private class ReferenceResolver1 : MetadataReferenceResolver { public readonly string path1, path2; public bool resolved1, resolved2; public ReferenceResolver1(string path1, string path2) { this.path1 = path1; this.path2 = path2; } public override ImmutableArray<PortableExecutableReference> ResolveReference(string reference, string baseFilePath, MetadataReferenceProperties properties) { switch (reference) { case "1": resolved1 = true; return ImmutableArray.Create(MetadataReference.CreateFromFile(path1)); case "2.dll": resolved2 = true; return ImmutableArray.Create(MetadataReference.CreateFromFile(path2)); default: return ImmutableArray<PortableExecutableReference>.Empty; } } public override bool Equals(object other) => true; public override int GetHashCode() => 1; } [Fact] public void ReferenceResolution1() { var path1 = Temp.CreateFile().WriteAllBytes(TestResources.General.MDTestLib1).Path; var path2 = Temp.CreateFile().WriteAllBytes(TestResources.General.MDTestLib2).Path; var resolver = new ReferenceResolver1(path1, path2); var c1 = CSharpCompilation.Create("c1", syntaxTrees: new[] { Parse("#r \"1\"", options: TestOptions.Script), Parse("#r \"2.dll\"", options: TestOptions.Script), }, options: TestOptions.ReleaseDll.WithMetadataReferenceResolver(resolver)); Assert.NotNull(c1.Assembly); // force creation of SourceAssemblySymbol var dirRefs = c1.DirectiveReferences; var assemblySymbol1 = c1.GetReferencedAssemblySymbol(dirRefs[0]); var assemblySymbol2 = c1.GetReferencedAssemblySymbol(dirRefs[1]); Assert.Equal("MDTestLib1", assemblySymbol1.Name); Assert.Equal("MDTestLib2", assemblySymbol2.Name); Assert.True(resolver.resolved1); Assert.True(resolver.resolved2); } private class TestException : Exception { } private class ErroneousReferenceResolver : TestMetadataReferenceResolver { public ErroneousReferenceResolver() { } public override ImmutableArray<PortableExecutableReference> ResolveReference(string reference, string baseFilePath, MetadataReferenceProperties properties) { switch (reference) { case "throw": throw new TestException(); } return base.ResolveReference(reference, baseFilePath, properties); } } [Fact] public void ReferenceResolution_ExceptionsFromResolver() { var options = TestOptions.ReleaseDll.WithMetadataReferenceResolver(new ErroneousReferenceResolver()); foreach (var tree in new[] { Parse("#r \"throw\"", options: TestOptions.Script), }) { var c = CSharpCompilation.Create("c", syntaxTrees: new[] { tree }, options: options); Assert.Throws<TestException>(() => { var a = c.Assembly; }); } } [Fact] public void ResolvedReferencesCaching() { var c1 = CSharpCompilation.Create("goo", syntaxTrees: new[] { Parse("class C {}") }, references: new[] { MscorlibRef, SystemCoreRef, SystemRef }); var a1 = c1.SourceAssembly; var c2 = c1.AddSyntaxTrees(Parse("class D { }")); var a2 = c2.SourceAssembly; } // TODO: make x-plat (https://github.com/dotnet/roslyn/issues/6465) [ConditionalFact(typeof(WindowsOnly))] public void ReferenceResolution_RelativePaths() { var t1 = Parse(@" #r ""lib.dll"" ", filename: @"C:\A\a.csx", options: TestOptions.Script); var rd1 = (ReferenceDirectiveTriviaSyntax)t1.GetRoot().GetDirectives().Single(); var t2 = Parse(@" #r ""lib.dll"" ", filename: @"C:\B\b.csx", options: TestOptions.Script); var rd2 = (ReferenceDirectiveTriviaSyntax)t2.GetRoot().GetDirectives().Single(); var c = CreateCompilationWithMscorlib45(new[] { t1, t2 }, options: TestOptions.ReleaseDll.WithMetadataReferenceResolver( new TestMetadataReferenceResolver( pathResolver: new VirtualizedRelativePathResolver(new[] { @"C:\A\lib.dll", @"C:\B\lib.dll" }), files: new Dictionary<string, PortableExecutableReference>() { { @"C:\A\lib.dll", Net451.MicrosoftCSharp }, { @"C:\B\lib.dll", Net451.MicrosoftVisualBasic }, }))); c.VerifyDiagnostics(); Assert.Same(Net451.MicrosoftCSharp, c.GetDirectiveReference(rd1)); Assert.Same(Net451.MicrosoftVisualBasic, c.GetDirectiveReference(rd2)); } [Fact] public void CyclesInReferences() { var sourceA = @" public class A { } "; var a = CreateCompilation(sourceA, assemblyName: "A"); var sourceB = @" public class B : A { } public class Goo {} "; var b = CreateCompilation(sourceB, new[] { new CSharpCompilationReference(a) }, assemblyName: "B"); var refB = MetadataReference.CreateFromImage(b.EmitToArray()); var sourceA2 = @" public class A { public Goo x = new Goo(); } "; // construct A2 that has a reference to assembly identity "B". var a2 = CreateCompilation(sourceA2, new[] { refB }, assemblyName: "A"); var refA2 = MetadataReference.CreateFromImage(a2.EmitToArray()); var symbolB = a2.GetReferencedAssemblySymbol(refB); Assert.True(symbolB is Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE.PEAssemblySymbol, "PE symbol expected"); // force A assembly symbol to be added to a metadata cache: var c = CreateCompilation("class C : A {}", new[] { refA2, refB }, assemblyName: "C"); var symbolA2 = c.GetReferencedAssemblySymbol(refA2); Assert.True(symbolA2 is Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE.PEAssemblySymbol, "PE symbol expected"); Assert.Equal(1, ((AssemblyMetadata)refA2.GetMetadataNoCopy()).CachedSymbols.WeakCount); GC.KeepAlive(symbolA2); // Recompile "B" and remove int Goo. The assembly manager should not reuse symbols for A since they are referring to old version of B. var b2 = CreateCompilation(@" public class B : A { public void Bar() { object objX = this.x; } } ", new[] { refA2 }, assemblyName: "B"); // TODO (tomat): Dev11 also reports: // b2.cs(5,28): error CS0570: 'A.x' is not supported by the language b2.VerifyDiagnostics( // (6,28): error CS7068: Reference to type 'Goo' claims it is defined in this assembly, but it is not defined in source or any added modules // object objX = this.x; Diagnostic(ErrorCode.ERR_MissingTypeInSource, "x").WithArguments("Goo")); } [Fact] public void BoundReferenceCaching_CyclesInReferences() { var a = CreateCompilation("public class A { }", assemblyName: "A"); var b = CreateCompilation("public class B : A { } ", new[] { new CSharpCompilationReference(a) }, assemblyName: "B"); var refB = MetadataReference.CreateFromImage(b.EmitToArray()); // construct A2 that has a reference to assembly identity "B". var a2 = CreateCompilation(@"public class A { B B; }", new[] { refB }, assemblyName: "A"); var refA2 = MetadataReference.CreateFromImage(a2.EmitToArray()); var withCircularReference1 = CreateCompilation(@"public class B : A { }", new[] { refA2 }, assemblyName: "B"); var withCircularReference2 = withCircularReference1.WithOptions(TestOptions.ReleaseDll); Assert.NotSame(withCircularReference1, withCircularReference2); // until we try to reuse bound references we share the manager: Assert.True(withCircularReference1.ReferenceManagerEquals(withCircularReference2)); var assembly1 = withCircularReference1.SourceAssembly; Assert.True(withCircularReference1.ReferenceManagerEquals(withCircularReference2)); var assembly2 = withCircularReference2.SourceAssembly; Assert.False(withCircularReference1.ReferenceManagerEquals(withCircularReference2)); var refA2_symbol1 = withCircularReference1.GetReferencedAssemblySymbol(refA2); var refA2_symbol2 = withCircularReference2.GetReferencedAssemblySymbol(refA2); Assert.NotNull(refA2_symbol1); Assert.NotNull(refA2_symbol2); Assert.NotSame(refA2_symbol1, refA2_symbol2); } [WorkItem(546828, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546828")] [Fact] public void MetadataDependsOnSource() { // {0} is the body of the ReachFramework assembly reference. var ilTemplate = @" .assembly extern ReachFramework {{ {0} }} .assembly extern mscorlib {{ .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4.. .ver 4:0:0:0 }} .assembly PresentationFramework {{ .publickey = (00 24 00 00 04 80 00 00 94 00 00 00 06 02 00 00 // .$.............. 00 24 00 00 52 53 41 31 00 04 00 00 01 00 01 00 // .$..RSA1........ B5 FC 90 E7 02 7F 67 87 1E 77 3A 8F DE 89 38 C8 // ......g..w:...8. 1D D4 02 BA 65 B9 20 1D 60 59 3E 96 C4 92 65 1E // ....e. .`Y>...e. 88 9C C1 3F 14 15 EB B5 3F AC 11 31 AE 0B D3 33 // ...?....?..1...3 C5 EE 60 21 67 2D 97 18 EA 31 A8 AE BD 0D A0 07 // ..`!g-...1...... 2F 25 D8 7D BA 6F C9 0F FD 59 8E D4 DA 35 E4 4C // /%.}}.o...Y...5.L 39 8C 45 43 07 E8 E3 3B 84 26 14 3D AE C9 F5 96 // 9.EC...;.&.=.... 83 6F 97 C8 F7 47 50 E5 97 5C 64 E2 18 9F 45 DE // .o...GP..\d...E. F4 6B 2A 2B 12 47 AD C3 65 2B F5 C3 08 05 5D A9 ) // .k*+.G..e+....]. .ver 4:0:0:0 }} .module PresentationFramework.dll // MVID: {{CBA9159C-5BB4-49BC-B41D-AF055BF1C0AB}} .imagebase 0x00400000 .file alignment 0x00000200 .stackreserve 0x00100000 .subsystem 0x0003 // WINDOWS_CUI .corflags 0x00000001 // ILONLY // Image base: 0x04D00000 // =============== CLASS MEMBERS DECLARATION =================== .class public auto ansi System.Windows.Controls.PrintDialog extends [mscorlib]System.Object {{ .method public hidebysig instance class [ReachFramework]System.Printing.PrintTicket Test() cil managed {{ ret }} .method public hidebysig specialname rtspecialname instance void .ctor() cil managed {{ ret }} }} "; var csharp = @" using System.Windows.Controls; namespace System.Printing { public class PrintTicket { } } class Test { static void Main() { var dialog = new PrintDialog(); var p = dialog.Test(); } } "; // ref only specifies name { var il = string.Format(ilTemplate, ""); var ilRef = CompileIL(il, prependDefaultHeader: false); var comp = CreateCompilation(csharp, new[] { ilRef }, assemblyName: "ReachFramework"); comp.VerifyDiagnostics(); } // public key specified by ref, but not def { var il = string.Format(ilTemplate, " .publickeytoken = (31 BF 38 56 AD 36 4E 35 ) // 1.8V.6N5"); var ilRef = CompileIL(il, prependDefaultHeader: false); CreateCompilation(csharp, new[] { ilRef }, assemblyName: "ReachFramework").VerifyDiagnostics(); } // version specified by ref, but not def { var il = string.Format(ilTemplate, " .ver 4:0:0:0"); var ilRef = CompileIL(il, prependDefaultHeader: false); CreateCompilation(csharp, new[] { ilRef }, assemblyName: "ReachFramework").VerifyDiagnostics(); } // culture specified by ref, but not def { var il = string.Format(ilTemplate, " .locale = (65 00 6E 00 2D 00 63 00 61 00 00 00 ) // e.n.-.c.a..."); var ilRef = CompileIL(il, prependDefaultHeader: false); CreateCompilation(csharp, new[] { ilRef }, assemblyName: "ReachFramework").VerifyDiagnostics(); } } [WorkItem(546828, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546828")] [Fact] public void MetadataDependsOnMetadataOrSource() { var il = @" .assembly extern ReachFramework { .ver 4:0:0:0 } .assembly extern mscorlib { .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4.. .ver 4:0:0:0 } .assembly PresentationFramework { .publickey = (00 24 00 00 04 80 00 00 94 00 00 00 06 02 00 00 // .$.............. 00 24 00 00 52 53 41 31 00 04 00 00 01 00 01 00 // .$..RSA1........ B5 FC 90 E7 02 7F 67 87 1E 77 3A 8F DE 89 38 C8 // ......g..w:...8. 1D D4 02 BA 65 B9 20 1D 60 59 3E 96 C4 92 65 1E // ....e. .`Y>...e. 88 9C C1 3F 14 15 EB B5 3F AC 11 31 AE 0B D3 33 // ...?....?..1...3 C5 EE 60 21 67 2D 97 18 EA 31 A8 AE BD 0D A0 07 // ..`!g-...1...... 2F 25 D8 7D BA 6F C9 0F FD 59 8E D4 DA 35 E4 4C // /%.}.o...Y...5.L 39 8C 45 43 07 E8 E3 3B 84 26 14 3D AE C9 F5 96 // 9.EC...;.&.=.... 83 6F 97 C8 F7 47 50 E5 97 5C 64 E2 18 9F 45 DE // .o...GP..\d...E. F4 6B 2A 2B 12 47 AD C3 65 2B F5 C3 08 05 5D A9 ) // .k*+.G..e+....]. .ver 4:0:0:0 } .module PresentationFramework.dll // MVID: {CBA9159C-5BB4-49BC-B41D-AF055BF1C0AB} .imagebase 0x00400000 .file alignment 0x00000200 .stackreserve 0x00100000 .subsystem 0x0003 // WINDOWS_CUI .corflags 0x00000001 // ILONLY // Image base: 0x04D00000 // =============== CLASS MEMBERS DECLARATION =================== .class public auto ansi System.Windows.Controls.PrintDialog extends [mscorlib]System.Object { .method public hidebysig instance class [ReachFramework]System.Printing.PrintTicket Test() cil managed { ret } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } "; var csharp = @" namespace System.Printing { public class PrintTicket { } } "; var oldVersion = @"[assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")]"; var newVersion = @"[assembly: System.Reflection.AssemblyVersion(""4.0.0.0"")]"; var ilRef = CompileIL(il, prependDefaultHeader: false); var oldMetadata = AssemblyMetadata.CreateFromImage(CreateCompilation(oldVersion + csharp, assemblyName: "ReachFramework").EmitToArray()); var oldRef = oldMetadata.GetReference(); var comp = CreateCompilation(newVersion + csharp, new[] { ilRef, oldRef }, assemblyName: "ReachFramework"); comp.VerifyDiagnostics(); var method = comp.GlobalNamespace. GetMember<NamespaceSymbol>("System"). GetMember<NamespaceSymbol>("Windows"). GetMember<NamespaceSymbol>("Controls"). GetMember<NamedTypeSymbol>("PrintDialog"). GetMember<MethodSymbol>("Test"); AssemblyIdentity actualIdentity = method.ReturnType.ContainingAssembly.Identity; // Even though the compilation has the correct version number, the referenced binary is preferred. Assert.Equal(oldMetadata.GetAssembly().Identity, actualIdentity); Assert.NotEqual(comp.Assembly.Identity, actualIdentity); } [Fact] [WorkItem(546900, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546900")] public void MetadataRefersToSourceAssemblyModule() { var srcA = @" .assembly extern b { .ver 0:0:0:0 } .assembly extern mscorlib { .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) .ver 4:0:0:0 } .assembly a { .hash algorithm 0x00008004 .ver 0:0:0:0 } .module a.dll .class public auto ansi beforefieldinit A extends [b]B { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [b]B::.ctor() IL_0006: ret } }"; var aRef = CompileIL(srcA, prependDefaultHeader: false); string srcB = @" public class B { public A A; }"; var b = CreateCompilation(srcB, references: new[] { aRef }, options: TestOptions.ReleaseModule.WithModuleName("mod.netmodule"), assemblyName: "B"); b.VerifyDiagnostics(); } [ConditionalFact(typeof(DesktopOnly))] [WorkItem(530839, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530839")] public void EmbedInteropTypesReferences() { var libSource = @" using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyVersion(""1.0.0.0"")] [assembly: Guid(""49a1950e-3e35-4595-8cb9-920c64c44d67"")] [assembly: PrimaryInteropAssembly(1, 0)] [assembly: ImportedFromTypeLib(""Lib"")] [ComImport()] [Guid(""49a1950e-3e35-4595-8cb9-920c64c44d68"")] public interface I { } "; var mainSource = @" public class C : I { } "; var lib = CreateCompilation(libSource, assemblyName: "lib"); var refLib = ((MetadataImageReference)lib.EmitToImageReference()).WithEmbedInteropTypes(true); var main = CreateCompilation(mainSource, new[] { refLib }, assemblyName: "main"); CompileAndVerify(main, validator: (pe) => { var reader = pe.GetMetadataReader(); AssertEx.SetEqual(new[] { "mscorlib 4.0" }, reader.DumpAssemblyReferences()); }, verify: Verification.Passes); } [WorkItem(531537, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531537")] [Fact] public void ModuleSymbolReuse() { var text1 = @" class C { TypeFromModule M() { } } "; // Doesn't really matter what this text is - just need a delta. var text2 = @" class D { } "; var assemblyMetadata = AssemblyMetadata.CreateFromImage(CreateCompilation("public class TypeDependedOnByModule { }", assemblyName: "lib1").EmitToArray()); var assemblyRef = assemblyMetadata.GetReference(); var moduleRef = CreateCompilation("public class TypeFromModule : TypeDependedOnByModule { }", new[] { assemblyRef }, options: TestOptions.ReleaseModule, assemblyName: "lib2").EmitToImageReference(); var comp1 = CreateCompilation(text1, new MetadataReference[] { moduleRef, assemblyRef, }); var tree1 = comp1.SyntaxTrees.Single(); var moduleSymbol1 = comp1.GetReferencedModuleSymbol(moduleRef); Assert.Equal(comp1.Assembly, moduleSymbol1.ContainingAssembly); var moduleReferences1 = moduleSymbol1.GetReferencedAssemblies(); Assert.Contains(assemblyMetadata.GetAssembly().Identity, moduleReferences1); var moduleTypeSymbol1 = comp1.GlobalNamespace.GetMember<NamedTypeSymbol>("TypeFromModule"); Assert.Equal(moduleSymbol1, moduleTypeSymbol1.ContainingModule); Assert.Equal(comp1.Assembly, moduleTypeSymbol1.ContainingAssembly); var tree2 = tree1.WithInsertAt(text1.Length, text2); var comp2 = comp1.ReplaceSyntaxTree(tree1, tree2); var moduleSymbol2 = comp2.GetReferencedModuleSymbol(moduleRef); Assert.Equal(comp2.Assembly, moduleSymbol2.ContainingAssembly); var moduleReferences2 = moduleSymbol2.GetReferencedAssemblies(); var moduleTypeSymbol2 = comp2.GlobalNamespace.GetMember<NamedTypeSymbol>("TypeFromModule"); Assert.Equal(moduleSymbol2, moduleTypeSymbol2.ContainingModule); Assert.Equal(comp2.Assembly, moduleTypeSymbol2.ContainingAssembly); Assert.NotEqual(moduleSymbol1, moduleSymbol2); Assert.NotEqual(moduleTypeSymbol1, moduleTypeSymbol2); AssertEx.Equal(moduleReferences1, moduleReferences2); } [WorkItem(531537, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531537")] [Fact] public void ModuleSymbolReuse_ImplicitType() { var text1 = @" namespace A { void M() { } "; var text2 = @" } "; // Note: we just need *a* module reference for the repro - we're not depending on its contents, name, etc. var moduleRef = CreateCompilation("public class C { }", options: TestOptions.ReleaseModule, assemblyName: "lib").EmitToImageReference(); var comp1 = CreateCompilation(text1, new MetadataReference[] { moduleRef, }); var tree1 = comp1.SyntaxTrees.Single(); var implicitTypeCount1 = comp1.GlobalNamespace.GetMember<NamespaceSymbol>("A").GetMembers(TypeSymbol.ImplicitTypeName).Length; Assert.Equal(1, implicitTypeCount1); var tree2 = tree1.WithInsertAt(text1.Length, text2); var comp2 = comp1.ReplaceSyntaxTree(tree1, tree2); var implicitTypeCount2 = comp2.GlobalNamespace.GetMember<NamespaceSymbol>("A").GetMembers(TypeSymbol.ImplicitTypeName).Length; Assert.Equal(1, implicitTypeCount2); } [Fact] public void CachingAndVisibility() { var cPublic = CreateCompilation("class C { }", options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Public)); var cInternal = CreateCompilation("class D { }", options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal)); var cAll = CreateCompilation("class E { }", options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All)); var cPublic2 = CreateCompilation("class C { }", options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Public)); var cInternal2 = CreateCompilation("class D { }", options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal)); var cAll2 = CreateCompilation("class E { }", options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All)); Assert.NotSame(cPublic.Assembly.CorLibrary, cInternal.Assembly.CorLibrary); Assert.NotSame(cAll.Assembly.CorLibrary, cInternal.Assembly.CorLibrary); Assert.NotSame(cAll.Assembly.CorLibrary, cPublic.Assembly.CorLibrary); Assert.Same(cPublic.Assembly.CorLibrary, cPublic2.Assembly.CorLibrary); Assert.Same(cInternal.Assembly.CorLibrary, cInternal2.Assembly.CorLibrary); Assert.Same(cAll.Assembly.CorLibrary, cAll2.Assembly.CorLibrary); } [Fact] public void ImportingPrivateNetModuleMembers() { string moduleSource = @" internal class C { private void m() { } } "; string mainSource = @" "; var module = CreateCompilation(moduleSource, options: TestOptions.ReleaseModule); var moduleRef = module.EmitToImageReference(); // All var mainAll = CreateCompilation(mainSource, new[] { moduleRef }, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All)); var mAll = mainAll.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMembers("m"); Assert.Equal(1, mAll.Length); // Internal var mainInternal = CreateCompilation(mainSource, new[] { moduleRef }, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal)); var mInternal = mainInternal.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMembers("m"); Assert.Equal(0, mInternal.Length); // Public var mainPublic = CreateCompilation(mainSource, new[] { moduleRef }, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Public)); var mPublic = mainPublic.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMembers("m"); Assert.Equal(0, mPublic.Length); } [Fact] [WorkItem(531342, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531342"), WorkItem(727122, "DevDiv")] public void PortableLibrary() { var plSource = @"public class C {}"; var pl = CreateEmptyCompilation(plSource, new[] { MscorlibPP7Ref, SystemRuntimePP7Ref }); var r1 = new CSharpCompilationReference(pl); var mainSource = @"public class D : C { }"; // w/o facades: var main = CreateEmptyCompilation(mainSource, new MetadataReference[] { r1, MscorlibFacadeRef }, options: TestOptions.ReleaseDll); main.VerifyDiagnostics( // (1,18): error CS0012: The type 'System.Object' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'. Diagnostic(ErrorCode.ERR_NoTypeDef, "C").WithArguments("System.Object", "System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")); // facade specified: main = CreateEmptyCompilation(mainSource, new MetadataReference[] { r1, MscorlibFacadeRef, SystemRuntimeFacadeRef }); main.VerifyDiagnostics(); } [Fact] [WorkItem(762729, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/762729")] public void OverloadResolutionUseSiteWarning() { var libBTemplate = @" [assembly: System.Reflection.AssemblyVersion(""{0}.0.0.0"")] public class B {{ }} "; var libBv1 = CreateCompilation(string.Format(libBTemplate, "1"), assemblyName: "B", options: s_signedDll); var libBv2 = CreateCompilation(string.Format(libBTemplate, "2"), assemblyName: "B", options: s_signedDll); var libASource = @" [assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public class A { public void M(B b) { } } "; var libAv1 = CreateCompilation( libASource, new[] { new CSharpCompilationReference(libBv1) }, assemblyName: "A", options: s_signedDll); var source = @" public class Source { public void Test() { A a = new A(); a.M(null); } } "; var comp = CreateCompilation(source, new[] { new CSharpCompilationReference(libAv1), new CSharpCompilationReference(libBv2) }); comp.VerifyDiagnostics( // warning CS1701: Assuming assembly reference 'B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' used by 'A' matches identity 'B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' of 'B', you may need to supply runtime policy Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin).WithArguments("B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "A", "B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "B").WithLocation(1, 1)); } [Fact] [WorkItem(762729, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/762729")] public void MethodGroupConversionUseSiteWarning() { var libBTemplate = @" [assembly: System.Reflection.AssemblyVersion(""{0}.0.0.0"")] public class B {{ }} "; var libBv1 = CreateCompilation(string.Format(libBTemplate, "1"), assemblyName: "B", options: s_signedDll); var libBv2 = CreateCompilation(string.Format(libBTemplate, "2"), assemblyName: "B", options: s_signedDll); var libASource = @" [assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public class A { public void M(B b) { } } "; var libAv1 = CreateCompilation( libASource, new[] { new CSharpCompilationReference(libBv1) }, assemblyName: "A", options: s_signedDll); var source = @" public class Source { public void Test() { A a = new A(); System.Action<B> f = a.M; } } "; var comp = CreateCompilation(source, new[] { new CSharpCompilationReference(libAv1), new CSharpCompilationReference(libBv2) }); comp.VerifyDiagnostics( // warning CS1701: Assuming assembly reference 'B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' used by 'A' matches identity 'B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' of 'B', you may need to supply runtime policy Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin).WithArguments("B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "A", "B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "B").WithLocation(1, 1)); } [Fact] [WorkItem(762729, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/762729")] public void IndexerUseSiteWarning() { var libBTemplate = @" [assembly: System.Reflection.AssemblyVersion(""{0}.0.0.0"")] public class B {{ }} "; var libBv1 = CreateCompilation(string.Format(libBTemplate, "1"), assemblyName: "B", options: s_signedDll); var libBv2 = CreateCompilation(string.Format(libBTemplate, "2"), assemblyName: "B", options: s_signedDll); var libASource = @" [assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public class A { public int this[B b] { get { return 0; } } } "; var libAv1 = CreateCompilation(libASource, new[] { new CSharpCompilationReference(libBv1) }, assemblyName: "A", options: s_signedDll); var source = @" public class Source { public void Test() { A a = new A(); int x = a[null]; } } "; var comp = CreateCompilation(source, new[] { new CSharpCompilationReference(libAv1), new CSharpCompilationReference(libBv2) }); comp.VerifyDiagnostics( // warning CS1701: Assuming assembly reference 'B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' used by 'A' matches identity 'B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' of 'B', you may need to supply runtime policy Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin).WithArguments("B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "A", "B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "B").WithLocation(1, 1)); } [Fact] [WorkItem(762729, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/762729")] public void Repro762729() { var libBTemplate = @" [assembly: System.Reflection.AssemblyVersion(""{0}.0.0.0"")] // To be implemented in library A. public interface IGeneric<T> {{ void M(); }} // To be implemented by superclass of class implementing IGeneric<T>. public interface I {{ }} public static class Extensions {{ // To be invoked from the test assembly. public static void Extension<T>(this IGeneric<T> i) {{ i.M(); }} }} "; var libBv1 = CreateCompilationWithMscorlib40AndSystemCore(string.Format(libBTemplate, "1"), assemblyName: "B", options: s_signedDll); var libBv2 = CreateCompilationWithMscorlib40AndSystemCore(string.Format(libBTemplate, "2"), assemblyName: "B", options: s_signedDll); Assert.Equal("B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", libBv1.Assembly.Identity.GetDisplayName()); Assert.Equal("B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", libBv2.Assembly.Identity.GetDisplayName()); libBv1.EmitToImageReference(); libBv2.EmitToImageReference(); var libASource = @" [assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public class ABase : I { } public class A : ABase, IGeneric<AItem> { void IGeneric<AItem>.M() { } } // Type argument for IGeneric<T>. In the current assembly so there are no versioning issues. public class AItem { } "; var libAv1 = CreateCompilation(libASource, new[] { new CSharpCompilationReference(libBv1) }, assemblyName: "A", options: s_signedDll); libAv1.EmitToImageReference(); var source = @" public class Source { public void Test(A a) { a.Extension(); } } "; var comp = CreateCompilation(source, new[] { new CSharpCompilationReference(libAv1), new CSharpCompilationReference(libBv2) }); comp.VerifyEmitDiagnostics( // warning CS1701: Assuming assembly reference 'B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' used by 'A' matches identity 'B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' of 'B', you may need to supply runtime policy Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin).WithArguments("B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "A", "B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "B").WithLocation(1, 1), // warning CS1701: Assuming assembly reference 'B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' used by 'A' matches identity 'B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' of 'B', you may need to supply runtime policy Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin).WithArguments("B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "A", "B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "B").WithLocation(1, 1), // warning CS1701: Assuming assembly reference 'B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' used by 'A' matches identity 'B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' of 'B', you may need to supply runtime policy Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin).WithArguments("B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "A", "B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "B").WithLocation(1, 1)); } [WorkItem(905495, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/905495")] [Fact] public void ReferenceWithNoMetadataSection() { var c = CreateCompilation("", new[] { new TestImageReference(TestResources.Basic.NativeApp, "NativeApp.exe") }); c.VerifyDiagnostics( // error CS0009: Metadata file 'NativeApp.exe' could not be opened -- PE image doesn't contain managed metadata. Diagnostic(ErrorCode.FTL_MetadataCantOpenFile).WithArguments(@"NativeApp.exe", CodeAnalysisResources.PEImageDoesntContainManagedMetadata)); } [WorkItem(2988, "https://github.com/dotnet/roslyn/issues/2988")] [Fact] public void EmptyReference1() { var source = "class C { public static void Main() { } }"; var c = CreateCompilation(source, new[] { AssemblyMetadata.CreateFromImage(new byte[0]).GetReference(display: "Empty.dll") }); c.VerifyDiagnostics( Diagnostic(ErrorCode.FTL_MetadataCantOpenFile).WithArguments(@"Empty.dll", CodeAnalysisResources.PEImageDoesntContainManagedMetadata)); } [WorkItem(2992, "https://github.com/dotnet/roslyn/issues/2992")] [Fact] public void MetadataDisposed() { var md = AssemblyMetadata.CreateFromImage(TestResources.NetFX.Minimal.mincorlib); var compilation = CSharpCompilation.Create("test", references: new[] { md.GetReference() }); // Use the Compilation once to force lazy initialization of the underlying MetadataReader compilation.GetTypeByMetadataName("System.Int32").GetMembers(); md.Dispose(); Assert.Throws<ObjectDisposedException>(() => compilation.GetTypeByMetadataName("System.Int64").GetMembers()); } [WorkItem(43, "https://roslyn.codeplex.com/workitem/43")] [Fact] public void ReusingCorLibManager() { var corlib1 = CreateEmptyCompilation(""); var assembly1 = corlib1.Assembly; var corlib2 = corlib1.Clone(); var assembly2 = corlib2.Assembly; Assert.Same(assembly1.CorLibrary, assembly1); Assert.Same(assembly2.CorLibrary, assembly2); Assert.True(corlib1.ReferenceManagerEquals(corlib2)); } [WorkItem(5138, "https://github.com/dotnet/roslyn/issues/5138")] [Fact] public void AsymmetricUnification() { var vectors40 = CreateCompilation( @"[assembly: System.Reflection.AssemblyVersion(""4.0.0.0"")]", options: TestOptions.ReleaseDll.WithCryptoPublicKey(TestResources.TestKeys.PublicKey_b03f5f7f11d50a3a), assemblyName: "System.Numerics.Vectors"); Assert.Equal("System.Numerics.Vectors, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", vectors40.Assembly.Identity.GetDisplayName()); var vectors41 = CreateCompilation( @"[assembly: System.Reflection.AssemblyVersion(""4.1.0.0"")]", options: TestOptions.ReleaseDll.WithCryptoPublicKey(TestResources.TestKeys.PublicKey_b03f5f7f11d50a3a), assemblyName: "System.Numerics.Vectors"); Assert.Equal("System.Numerics.Vectors, Version=4.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", vectors41.Assembly.Identity.GetDisplayName()); var refVectors40 = vectors40.EmitToImageReference(); var refVectors41 = vectors41.EmitToImageReference(); var c1 = CreateEmptyCompilation("", TargetFrameworkUtil.StandardReferences.AddRange(new[] { refVectors40, refVectors41 }), options: TestOptions.ReleaseDll.WithAssemblyIdentityComparer(DesktopAssemblyIdentityComparer.Default)); c1.VerifyDiagnostics(); var a0 = c1.GetAssemblyOrModuleSymbol(refVectors40); var a1 = c1.GetAssemblyOrModuleSymbol(refVectors41); Assert.Equal("System.Numerics.Vectors, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", ((AssemblySymbol)a0).Identity.GetDisplayName()); Assert.Equal("System.Numerics.Vectors, Version=4.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", ((AssemblySymbol)a1).Identity.GetDisplayName()); var c2 = CreateEmptyCompilation("", TargetFrameworkUtil.StandardReferences.AddRange(new[] { refVectors41, refVectors40 }), options: TestOptions.ReleaseDll.WithAssemblyIdentityComparer(DesktopAssemblyIdentityComparer.Default)); c2.VerifyDiagnostics(); a0 = c2.GetAssemblyOrModuleSymbol(refVectors40); a1 = c2.GetAssemblyOrModuleSymbol(refVectors41); Assert.Equal("System.Numerics.Vectors, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", ((AssemblySymbol)a0).Identity.GetDisplayName()); Assert.Equal("System.Numerics.Vectors, Version=4.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", ((AssemblySymbol)a1).Identity.GetDisplayName()); } [Fact] public void ReferenceSupersession_FxUnification1() { var c = CreateSubmissionWithExactReferences("System.Diagnostics.Process.GetCurrentProcess()", new[] { Net20.mscorlib, Net20.System, Net451.mscorlib, Net451.System, }); c.VerifyDiagnostics(); c.VerifyAssemblyVersionsAndAliases( "mscorlib, Version=2.0.0.0: <superseded>", "System, Version=2.0.0.0: <superseded>", "mscorlib, Version=4.0.0.0", "System, Version=4.0.0.0"); } [Fact] public void ReferenceSupersession_StrongNames1() { var c = CreateSubmissionWithExactReferences("new C()", new[] { MscorlibRef_v4_0_30316_17626, TestReferences.SymbolsTests.Versioning.C2, TestReferences.SymbolsTests.Versioning.C1, }); c.VerifyDiagnostics(); c.VerifyAssemblyVersionsAndAliases( "mscorlib, Version=4.0.0.0", "C, Version=2.0.0.0", "C, Version=1.0.0.0: <superseded>"); } [Fact] public void ReferenceSupersession_WeakNames1() { var c = CreateSubmissionWithExactReferences("new C()", new[] { MscorlibRef_v4_0_30316_17626, CreateEmptyCompilation(@"[assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public class C {}", new[] { MscorlibRef }, assemblyName: "C").EmitToImageReference(), CreateEmptyCompilation(@"[assembly: System.Reflection.AssemblyVersion(""2.0.0.0"")] public class C {}", new[] { MscorlibRef }, assemblyName: "C").ToMetadataReference(), }); c.VerifyDiagnostics(); c.VerifyAssemblyVersionsAndAliases( "mscorlib, Version=4.0.0.0", "C, Version=1.0.0.0: <superseded>", "C, Version=2.0.0.0"); } [Fact] public void ReferenceSupersession_AliasesErased() { var c = CreateSubmissionWithExactReferences("new C()", new[] { MscorlibRef_v4_0_30316_17626, CreateEmptyCompilation(@"[assembly: System.Reflection.AssemblyVersion(""0.0.0.0"")] public class C {}", new[] { MscorlibRef }, assemblyName: "C").ToMetadataReference(), CreateEmptyCompilation(@"[assembly: System.Reflection.AssemblyVersion(""2.0.0.1"")] public class C {}", new[] { MscorlibRef }, assemblyName: "C").ToMetadataReference(), CreateEmptyCompilation(@"[assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public class C {}", new[] { MscorlibRef }, assemblyName: "C").ToMetadataReference(), CreateEmptyCompilation(@"[assembly: System.Reflection.AssemblyVersion(""2.0.0.0"")] public class C {}", new[] { MscorlibRef }, assemblyName: "C").ToMetadataReference(), CreateEmptyCompilation(@"[assembly: System.Reflection.AssemblyVersion(""1.1.0.0"")] public class C {}", new[] { MscorlibRef }, assemblyName: "C").ToMetadataReference(). WithProperties(MetadataReferenceProperties.Assembly.WithAliases(ImmutableArray.Create("Z")).WithRecursiveAliases(true)), }); c.VerifyDiagnostics(); c.VerifyAssemblyVersionsAndAliases( "mscorlib, Version=4.0.0.0: global,Z", "C, Version=0.0.0.0: <superseded>", "C, Version=2.0.0.1", "C, Version=1.0.0.0: <superseded>", "C, Version=2.0.0.0: <superseded>", "C, Version=1.1.0.0: <superseded>"); } [Fact] public void ReferenceSupersession_NoUnaliasedAssembly() { var c = CreateSubmissionWithExactReferences("new C()", new[] { MscorlibRef_v4_0_30316_17626, CreateCompilation(@"[assembly: System.Reflection.AssemblyVersion(""0.0.0.0"")] public class C {}", assemblyName: "C").ToMetadataReference(), CreateCompilation(@"[assembly: System.Reflection.AssemblyVersion(""2.0.0.1"")] public class C {}", assemblyName: "C").ToMetadataReference(aliases: ImmutableArray.Create("X", "Y")), CreateCompilation(@"[assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public class C {}", assemblyName: "C").ToMetadataReference(), CreateCompilation(@"[assembly: System.Reflection.AssemblyVersion(""2.0.0.0"")] public class C {}", assemblyName: "C").ToMetadataReference(), CreateCompilation(@"[assembly: System.Reflection.AssemblyVersion(""1.1.0.0"")] public class C {}", assemblyName: "C").ToMetadataReference(). WithProperties(MetadataReferenceProperties.Assembly.WithAliases(ImmutableArray.Create("Z")).WithRecursiveAliases(true)), }); c.VerifyDiagnostics( // (1,5): error CS0246: The type or namespace name 'C' could not be found (are you missing a using directive or an assembly reference?) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "C").WithArguments("C")); c.VerifyAssemblyVersionsAndAliases( "mscorlib, Version=4.0.0.0: global,Z", "C, Version=0.0.0.0: <superseded>", "C, Version=2.0.0.1: X,Y", "C, Version=1.0.0.0: <superseded>", "C, Version=2.0.0.0: <superseded>", "C, Version=1.1.0.0: <superseded>"); } [Fact] public void ReferenceDirective_RecursiveReferenceWithNoAliases() { // c - b (alias X) // - a (via #r) -> b var bRef = CreateCompilationWithMscorlib45("public class B { }", assemblyName: "B").EmitToImageReference(); var aRef = CreateCompilationWithMscorlib45("public class A : B { }", new[] { bRef }, assemblyName: "A").EmitToImageReference(); var source = @" #r ""a"" new B() "; var c = CreateSubmissionWithExactReferences(source, new[] { MscorlibRef_v4_0_30316_17626, bRef.WithAliases(ImmutableArray.Create("X")), aRef }, TestOptions.ReleaseDll.WithMetadataReferenceResolver( new TestMetadataReferenceResolver(assemblyNames: new Dictionary<string, PortableExecutableReference>() { { "a", (PortableExecutableReference)aRef.WithProperties(MetadataReferenceProperties.Assembly.WithRecursiveAliases(true)) } }))); c.VerifyDiagnostics(); c.VerifyAssemblyAliases( "mscorlib", "B: X,global", "A" ); } [Fact] public void ReferenceDirective_NonRecursiveReferenceWithNoAliases() { // c - b (alias X) // - a (via #r) -> b var bRef = CreateCompilationWithMscorlib45("public class B { }", assemblyName: "B").EmitToImageReference(); var aRef = CreateCompilationWithMscorlib45("public class A : B { }", new[] { bRef }, assemblyName: "A").EmitToImageReference(); var source = @" #r ""a"" new B() "; var c = CreateSubmissionWithExactReferences(source, new[] { MscorlibRef_v4_0_30316_17626, bRef.WithAliases(ImmutableArray.Create("X")), aRef }, TestOptions.ReleaseDll.WithMetadataReferenceResolver( new TestMetadataReferenceResolver(assemblyNames: new Dictionary<string, PortableExecutableReference>() { { "a", (PortableExecutableReference)aRef.WithProperties(MetadataReferenceProperties.Assembly) } }))); c.VerifyDiagnostics( // (3,5): error CS0246: The type or namespace name 'B' could not be found (are you missing a using directive or an assembly reference?) // new B() Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "B").WithArguments("B")); c.VerifyAssemblyAliases( "mscorlib", "B: X", "A"); } [Fact] public void ReferenceDirective_RecursiveReferenceWithAlias1() { // c - b (alias X) // - a // - a (recursive alias Y) -> b var bRef = CreateCompilationWithMscorlib45("public class B { }", assemblyName: "B").EmitToImageReference(); var aRef = CreateCompilationWithMscorlib45("public class A : B { }", new[] { bRef }, assemblyName: "A").EmitToImageReference(); var source = @" extern alias X; extern alias Y; public class P { A a = new Y::A(); X::B b = new Y::B(); } "; var c = CreateEmptyCompilation(source, new[] { bRef.WithAliases(ImmutableArray.Create("X")), aRef, aRef.WithProperties(MetadataReferenceProperties.Assembly.WithAliases(ImmutableArray.Create("Y")).WithRecursiveAliases(true)), MscorlibRef, }, TestOptions.ReleaseDll); c.VerifyDiagnostics(); c.VerifyAssemblyAliases( "B: X,Y", "A: global,Y", "mscorlib: global,Y"); } [Fact] public void ReferenceDirective_RecursiveReferenceWithAlias2() { // c - b (alias X) // - a (recursive alias Y) -> b // - a var bRef = CreateCompilationWithMscorlib45("public class B { }", assemblyName: "B").EmitToImageReference(); var aRef = CreateCompilationWithMscorlib45("public class A : B { }", new[] { bRef }, assemblyName: "A").EmitToImageReference(); var source = @" extern alias X; extern alias Y; public class P { A a = new Y::A(); X::B b = new Y::B(); } "; var c = CreateEmptyCompilation(source, new[] { bRef.WithAliases(ImmutableArray.Create("X")), aRef.WithProperties(MetadataReferenceProperties.Assembly.WithAliases(ImmutableArray.Create("Y")).WithRecursiveAliases(true)), aRef, MscorlibRef, }, TestOptions.ReleaseDll); c.VerifyDiagnostics(); c.VerifyAssemblyAliases( "B: X,Y", "A: global,Y", "mscorlib: global,Y"); } [Fact] public void ReferenceDirective_RecursiveReferenceWithAlias3() { // c - b (alias X) // - a (recursive alias Y) -> b // - a var bRef = CreateCompilationWithMscorlib45("public class B { }", assemblyName: "B").EmitToImageReference(); var aRef = CreateCompilationWithMscorlib45("public class A : B { }", new[] { bRef }, assemblyName: "A").EmitToImageReference(); var source = @" extern alias X; extern alias Y; public class P { A a = new Y::A(); X::B b = new Y::B(); } "; var c = CreateEmptyCompilation(source, new[] { bRef.WithAliases(ImmutableArray.Create("X")), aRef, aRef.WithProperties(MetadataReferenceProperties.Assembly.WithAliases(ImmutableArray.Create("Y")).WithRecursiveAliases(true)), aRef.WithProperties(MetadataReferenceProperties.Assembly.WithAliases(ImmutableArray.Create("Y")).WithRecursiveAliases(true)), aRef, MscorlibRef, }, TestOptions.ReleaseDll); c.VerifyDiagnostics(); c.VerifyAssemblyAliases( "B: X,Y", "A: global,Y", "mscorlib: global,Y"); } [Fact] public void ReferenceDirective_RecursiveReferenceWithAlias4() { // c - b (alias X) // - a (recursive alias Y) -> b // - d (recursive alias Z) -> a var bRef = CreateCompilationWithMscorlib45("public class B { }", assemblyName: "B").EmitToImageReference(); var aRef = CreateCompilationWithMscorlib45("public class A : B { }", new[] { bRef }, assemblyName: "A").EmitToImageReference(); var dRef = CreateCompilationWithMscorlib45("public class D : A { }", new[] { aRef, bRef }, assemblyName: "D").EmitToImageReference(); var source = @" extern alias X; extern alias Y; extern alias Z; public class P { Z::A a = new Y::A(); X::B b = new Y::B(); Z::B d = new X::B(); } "; var c = CreateEmptyCompilation(source, new[] { bRef.WithAliases(ImmutableArray.Create("X")), aRef.WithProperties(MetadataReferenceProperties.Assembly.WithAliases(ImmutableArray.Create("Y", "Y")).WithRecursiveAliases(true)), dRef.WithProperties(MetadataReferenceProperties.Assembly.WithAliases(ImmutableArray.Create("Z")).WithRecursiveAliases(true)), MscorlibRef, }, TestOptions.ReleaseDll); c.VerifyDiagnostics(); c.VerifyAssemblyAliases( "B: X,Y,Y,Z", "A: Y,Y,Z", "D: Z", "mscorlib: global,Y,Y,Z"); } [ConditionalFact(typeof(NoIOperationValidation), typeof(NoUsedAssembliesValidation), Reason = "IOperation adds extra assemblies")] public void MissingAssemblyResolution1() { // c - a -> b var bRef = CreateCompilationWithMscorlib46("public class B { }", assemblyName: "B").EmitToImageReference(); var aRef = CreateCompilationWithMscorlib46("public class A : B { }", new[] { bRef }, assemblyName: "A").EmitToImageReference(); var resolver = new TestMissingMetadataReferenceResolver(new Dictionary<string, MetadataReference> { { "B", bRef } }); var c = CreateCompilationWithMscorlib46("public class C : A { }", new[] { aRef }, TestOptions.ReleaseDll.WithMetadataReferenceResolver(resolver)); c.VerifyEmitDiagnostics(); Assert.Equal("B", ((AssemblySymbol)c.GetAssemblyOrModuleSymbol(bRef)).Name); resolver.VerifyResolutionAttempts( "A -> B, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"); } [ConditionalFact(typeof(NoIOperationValidation), typeof(NoUsedAssembliesValidation))] public void MissingAssemblyResolution_Aliases() { // c - a -> b with alias X var bRef = CreateCompilationWithMscorlib46("public class B { }", assemblyName: "B").EmitToImageReference(); var aRef = CreateCompilationWithMscorlib46("public class A : B { }", new[] { bRef }, assemblyName: "A").EmitToImageReference(); var resolver = new TestMissingMetadataReferenceResolver(new Dictionary<string, MetadataReference> { { "B", bRef.WithAliases(ImmutableArray.Create("X")) } }); var c = CreateCompilationWithMscorlib46(@" extern alias X; public class C : A { X::B F() => null; } ", new[] { aRef }, TestOptions.ReleaseDll.WithMetadataReferenceResolver(resolver)); c.VerifyEmitDiagnostics(); resolver.VerifyResolutionAttempts( "A -> B, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"); } [ConditionalFact(typeof(NoIOperationValidation), typeof(NoUsedAssembliesValidation))] public void MissingAssemblyResolution_AliasesMerge() { // c - a -> "b, V1" resolved to "b, V3" with alias X // - d -> "b, V2" resolved to "b, V3" with alias Y var b1Ref = CreateEmptyCompilation(@"[assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public class B { }", new[] { MscorlibRef }, options: s_signedDll, assemblyName: "B").EmitToImageReference(); var b2Ref = CreateEmptyCompilation(@"[assembly: System.Reflection.AssemblyVersion(""2.0.0.0"")] public class B { }", new[] { MscorlibRef }, options: s_signedDll, assemblyName: "B").EmitToImageReference(); var b3Ref = CreateEmptyCompilation(@"[assembly: System.Reflection.AssemblyVersion(""3.0.0.0"")] public class B { }", new[] { MscorlibRef }, options: s_signedDll, assemblyName: "B").EmitToImageReference(); var aRef = CreateEmptyCompilation("public class A : B { }", new[] { MscorlibRef, b1Ref }, assemblyName: "A").EmitToImageReference(); var dRef = CreateEmptyCompilation("public class D : B { }", new[] { MscorlibRef, b2Ref }, assemblyName: "D").EmitToImageReference(); var b3RefX = b3Ref.WithAliases(ImmutableArray.Create("X")); var b3RefY = b3Ref.WithAliases(ImmutableArray.Create("Y")); var resolver = new TestMissingMetadataReferenceResolver(new Dictionary<string, MetadataReference> { { "B, 1.0.0.0", b3RefX }, { "B, 2.0.0.0", b3RefY }, }); var c = CreateEmptyCompilation(@" extern alias X; extern alias Y; public class C : A { X::B F() => new Y::B(); } ", new[] { MscorlibRef, aRef, dRef }, TestOptions.ReleaseDll.WithMetadataReferenceResolver(resolver)); c.VerifyEmitDiagnostics( // warning CS1701: Assuming assembly reference // 'B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' used by 'A' matches identity // 'B, Version=3.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' of 'B', you may need to supply runtime policy Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin).WithArguments( "B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "A", "B, Version=3.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "B").WithLocation(1, 1)); Assert.Equal("B", ((AssemblySymbol)c.GetAssemblyOrModuleSymbol(b3RefY)).Name); Assert.Null(c.GetAssemblyOrModuleSymbol(b3RefX)); resolver.VerifyResolutionAttempts( "D -> B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "A -> B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2"); c.VerifyAssemblyVersionsAndAliases( "mscorlib, Version=4.0.0.0", "A, Version=0.0.0.0", "D, Version=0.0.0.0", "B, Version=3.0.0.0: Y,X"); } [ConditionalFact(typeof(NoIOperationValidation), typeof(NoUsedAssembliesValidation), Reason = "IOperation adds extra assemblies")] public void MissingAssemblyResolution_WeakIdentities1() { // c - a -> "b,v1,PKT=null" // - d -> "b,v2,PKT=null" var b1Ref = CreateEmptyCompilation(@"[assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public interface B { }", new[] { MscorlibRef }, assemblyName: "B").EmitToImageReference(); var b2Ref = CreateEmptyCompilation(@"[assembly: System.Reflection.AssemblyVersion(""2.0.0.0"")] public interface B { }", new[] { MscorlibRef }, assemblyName: "B").EmitToImageReference(); var b3Ref = CreateEmptyCompilation(@"[assembly: System.Reflection.AssemblyVersion(""3.0.0.0"")] public interface B { }", new[] { MscorlibRef }, assemblyName: "B").EmitToImageReference(); var b4Ref = CreateEmptyCompilation(@"[assembly: System.Reflection.AssemblyVersion(""4.0.0.0"")] public interface B { }", new[] { MscorlibRef }, assemblyName: "B").EmitToImageReference(); var aRef = CreateEmptyCompilation(@"public interface A : B { }", new[] { MscorlibRef, b1Ref }, assemblyName: "A").EmitToImageReference(); var dRef = CreateEmptyCompilation(@"public interface D : B { }", new[] { MscorlibRef, b2Ref }, assemblyName: "D").EmitToImageReference(); var resolver = new TestMissingMetadataReferenceResolver(new Dictionary<string, MetadataReference> { { "B, 1.0.0.0", b1Ref }, { "B, 2.0.0.0", b2Ref }, }); var c = CreateSubmissionWithExactReferences(@"public interface C : A, D { }", new[] { MscorlibRef_v4_0_30316_17626, aRef, dRef }, TestOptions.ReleaseDll.WithMetadataReferenceResolver(resolver)); c.VerifyEmitDiagnostics(); resolver.VerifyResolutionAttempts( "D -> B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null", "A -> B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"); c.VerifyAssemblyVersionsAndAliases( "mscorlib, Version=4.0.0.0", "A, Version=0.0.0.0", "D, Version=0.0.0.0", "B, Version=2.0.0.0", "B, Version=1.0.0.0: <superseded>"); } [ConditionalFact(typeof(NoIOperationValidation), typeof(NoUsedAssembliesValidation), Reason = "IOperation adds extra assemblies")] public void MissingAssemblyResolution_WeakIdentities2() { // c - a -> "b,v1,PKT=null" // - d -> "b,v2,PKT=null" var b1Ref = CreateEmptyCompilation(@"[assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public interface B { }", new[] { MscorlibRef }, assemblyName: "B").EmitToImageReference(); var b2Ref = CreateEmptyCompilation(@"[assembly: System.Reflection.AssemblyVersion(""2.0.0.0"")] public interface B { }", new[] { MscorlibRef }, assemblyName: "B").EmitToImageReference(); var b3Ref = CreateEmptyCompilation(@"[assembly: System.Reflection.AssemblyVersion(""3.0.0.0"")] public interface B { }", new[] { MscorlibRef }, assemblyName: "B").EmitToImageReference(); var b4Ref = CreateEmptyCompilation(@"[assembly: System.Reflection.AssemblyVersion(""4.0.0.0"")] public interface B { }", new[] { MscorlibRef }, assemblyName: "B").EmitToImageReference(); var aRef = CreateEmptyCompilation(@"public interface A : B { }", new[] { MscorlibRef, b1Ref }, assemblyName: "A").EmitToImageReference(); var dRef = CreateEmptyCompilation(@"public interface D : B { }", new[] { MscorlibRef, b2Ref }, assemblyName: "D").EmitToImageReference(); var resolver = new TestMissingMetadataReferenceResolver(new Dictionary<string, MetadataReference> { { "B, 1.0.0.0", b3Ref }, { "B, 2.0.0.0", b4Ref }, }); var c = CreateSubmissionWithExactReferences(@"public interface C : A, D { }", new[] { MscorlibRef_v4_0_30316_17626, aRef, dRef }, TestOptions.ReleaseDll.WithMetadataReferenceResolver(resolver)); c.VerifyEmitDiagnostics(); resolver.VerifyResolutionAttempts( "D -> B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null", "A -> B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"); c.VerifyAssemblyVersionsAndAliases( "mscorlib, Version=4.0.0.0", "A, Version=0.0.0.0", "D, Version=0.0.0.0", "B, Version=4.0.0.0", "B, Version=3.0.0.0: <superseded>"); } [Fact] public void MissingAssemblyResolution_None() { // c - a -> d // - d var dRef = CreateCompilationWithMscorlib46("public interface D { }", assemblyName: "D").EmitToImageReference(); var aRef = CreateCompilationWithMscorlib46("public interface A : D { }", new[] { dRef }, assemblyName: "A").ToMetadataReference(); var resolver = new TestMissingMetadataReferenceResolver(new Dictionary<string, MetadataReference>()); var c = CreateCompilationWithMscorlib46("public interface C : A { }", new[] { aRef, dRef }, TestOptions.ReleaseDll.WithMetadataReferenceResolver(resolver)); c.VerifyDiagnostics(); resolver.VerifyResolutionAttempts(); } [ConditionalFact(typeof(NoIOperationValidation), typeof(NoUsedAssembliesValidation), Reason = "IOperation adds extra assemblies")] public void MissingAssemblyResolution_ActualMissing() { // c - a -> d var dRef = CreateCompilationWithMscorlib46("public interface D { }", assemblyName: "D").EmitToImageReference(); var aRef = CreateCompilationWithMscorlib46("public interface A : D { }", new[] { dRef }, assemblyName: "A").ToMetadataReference(); var resolver = new TestMissingMetadataReferenceResolver(new Dictionary<string, MetadataReference>()); var c = CreateCompilationWithMscorlib46("public interface C : A { }", new[] { aRef }, TestOptions.ReleaseDll.WithMetadataReferenceResolver(resolver)); c.VerifyDiagnostics( // (1,18): error CS0012: The type 'D' is defined in an assembly that is not referenced. You must add a reference to assembly 'D, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Diagnostic(ErrorCode.ERR_NoTypeDef, "C").WithArguments("D", "D, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")); resolver.VerifyResolutionAttempts( "A -> D, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"); } /// <summary> /// Ignore assemblies returned by the resolver that don't match the reference identity. /// </summary> [ConditionalFact(typeof(NoIOperationValidation), typeof(NoUsedAssembliesValidation), Reason = "IOperation adds extra assemblies")] public void MissingAssemblyResolution_MissingDueToResolutionMismatch() { // c - a -> b var bRef = CreateCompilationWithMscorlib46("public interface D { }", assemblyName: "B").EmitToImageReference(); var aRef = CreateCompilationWithMscorlib46("public interface A : D { }", new[] { bRef }, assemblyName: "A").ToMetadataReference(); var eRef = CreateCompilationWithMscorlib46("public interface E { }", assemblyName: "E").ToMetadataReference(); var resolver = new TestMissingMetadataReferenceResolver(new Dictionary<string, MetadataReference> { { "B, 1.0.0.0", eRef }, }); var c = CreateCompilationWithMscorlib46(@"public interface C : A { }", new[] { aRef }, TestOptions.ReleaseDll.WithMetadataReferenceResolver(resolver)); c.VerifyDiagnostics( // (1,18): error CS0012: The type 'D' is defined in an assembly that is not referenced. You must add a reference to assembly 'B, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Diagnostic(ErrorCode.ERR_NoTypeDef, "C").WithArguments("D", "B, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")); resolver.VerifyResolutionAttempts( "A -> B, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"); } [ConditionalFact(typeof(NoIOperationValidation), typeof(NoUsedAssembliesValidation), Reason = "IOperation adds extra assemblies")] public void MissingAssemblyResolution_Multiple() { // c - a -> d // - b -> d var dRef = CreateCompilationWithMscorlib46("public interface D { }", assemblyName: "D").EmitToImageReference(); var aRef = CreateCompilationWithMscorlib46("public interface A : D { }", new[] { dRef }, assemblyName: "A").ToMetadataReference(); var bRef = CreateCompilationWithMscorlib46("public interface B : D { }", new[] { dRef }, assemblyName: "B").ToMetadataReference(); var resolver = new TestMissingMetadataReferenceResolver(new Dictionary<string, MetadataReference> { { "D", dRef } }); var c = CreateCompilationWithMscorlib46("public interface C : A, B { }", new[] { aRef, bRef }, TestOptions.ReleaseDll.WithMetadataReferenceResolver(resolver)); c.VerifyEmitDiagnostics(); Assert.Equal("D", ((AssemblySymbol)c.GetAssemblyOrModuleSymbol(dRef)).Name); resolver.VerifyResolutionAttempts( "B -> D, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"); } [ConditionalFact(typeof(NoIOperationValidation), typeof(NoUsedAssembliesValidation), Reason = "IOperation adds extra assemblies")] public void MissingAssemblyResolution_Modules() { // c - a - d // - module(m) - b // - module(n) - d var bRef = CreateCompilationWithMscorlib46("public interface B { }", assemblyName: "B").EmitToImageReference(); var dRef = CreateCompilationWithMscorlib46("public interface D { }", assemblyName: "D").EmitToImageReference(); var mRef = CreateCompilationWithMscorlib46("public interface M : B { }", new[] { bRef }, options: TestOptions.ReleaseModule.WithModuleName("M.netmodule")).EmitToImageReference(); var nRef = CreateCompilationWithMscorlib46("public interface N : D { }", new[] { dRef }, options: TestOptions.ReleaseModule.WithModuleName("N.netmodule")).EmitToImageReference(); var aRef = CreateCompilationWithMscorlib46("public interface A : D { }", new[] { dRef }, assemblyName: "A").EmitToImageReference(); var resolver = new TestMissingMetadataReferenceResolver(new Dictionary<string, MetadataReference> { { "B", bRef }, { "D", dRef }, }); var c = CreateCompilationWithMscorlib46("public interface C : A { }", new[] { aRef, mRef, nRef }, TestOptions.ReleaseDll.WithMetadataReferenceResolver(resolver)); c.VerifyEmitDiagnostics(); Assert.Equal("B", ((AssemblySymbol)c.GetAssemblyOrModuleSymbol(bRef)).Name); Assert.Equal("D", ((AssemblySymbol)c.GetAssemblyOrModuleSymbol(dRef)).Name); // We don't resolve one assembly reference identity twice, even if the requesting definition is different. resolver.VerifyResolutionAttempts( "A -> D, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "M.netmodule -> B, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"); } /// <summary> /// Don't try to resolve AssemblyRefs that already match explicitly specified definition. /// </summary> [Fact] public void MissingAssemblyResolution_BindingToForExplicitReference1() { // c - a -> "b,v1" // - "b,v3" // var b1Ref = CreateCompilationWithMscorlib46(@"[assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public class B { }", options: s_signedDll, assemblyName: "B").EmitToImageReference(); var b2Ref = CreateCompilationWithMscorlib46(@"[assembly: System.Reflection.AssemblyVersion(""2.0.0.0"")] public class B { }", options: s_signedDll, assemblyName: "B").EmitToImageReference(); var b3Ref = CreateCompilationWithMscorlib46(@"[assembly: System.Reflection.AssemblyVersion(""3.0.0.0"")] public class B { }", options: s_signedDll, assemblyName: "B").EmitToImageReference(); var aRef = CreateCompilationWithMscorlib46(@"[assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public class A : B { }", new[] { b1Ref }, options: s_signedDll, assemblyName: "A").EmitToImageReference(); var resolver = new TestMissingMetadataReferenceResolver(new Dictionary<string, MetadataReference> { // the compiler asked for v1, but we have v2 { "B, 1.0.0.0", b2Ref } }); var c = CreateCompilationWithMscorlib46("public class C : A { }", new[] { aRef, b3Ref }, s_signedDll.WithMetadataReferenceResolver(resolver)); c.VerifyEmitDiagnostics( // warning CS1701: Assuming assembly reference // 'B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' used by 'A' matches identity // 'B, Version=3.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' of 'B', you may need to supply runtime policy Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin).WithArguments( "B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "A", "B, Version=3.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "B").WithLocation(1, 1)); Assert.Equal( "B, Version=3.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", ((AssemblySymbol)c.GetAssemblyOrModuleSymbol(b3Ref)).Identity.GetDisplayName()); Assert.Null((AssemblySymbol)c.GetAssemblyOrModuleSymbol(b2Ref)); resolver.VerifyResolutionAttempts(); } /// <summary> /// Don't try to resolve AssemblyRefs that already match explicitly specified definition. /// </summary> [ConditionalFact(typeof(NoIOperationValidation), typeof(NoUsedAssembliesValidation))] public void MissingAssemblyResolution_BindingToExplicitReference_WorseVersion() { // c - a -> d -> "b,v2" // e -> "b,v1" // - "b,v1" var b1Ref = CreateEmptyCompilation(@"[assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public interface B { }", new[] { MscorlibRef }, options: s_signedDll, assemblyName: "B").EmitToImageReference(); var b2Ref = CreateEmptyCompilation(@"[assembly: System.Reflection.AssemblyVersion(""2.0.0.0"")] public interface B { }", new[] { MscorlibRef }, options: s_signedDll, assemblyName: "B").EmitToImageReference(); var dRef = CreateEmptyCompilation(@"[assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public interface D : B { }", new[] { MscorlibRef, b2Ref }, options: s_signedDll, assemblyName: "D").EmitToImageReference(); var eRef = CreateEmptyCompilation(@"[assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public interface E : B { }", new[] { MscorlibRef, b1Ref }, options: s_signedDll, assemblyName: "E").EmitToImageReference(); var resolverA = new TestMissingMetadataReferenceResolver(new Dictionary<string, MetadataReference> { { "B, 2.0.0.0", b2Ref }, { "B, 1.0.0.0", b1Ref }, }); var aRef = CreateEmptyCompilation(@"[assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public interface A : D, E { }", new[] { MscorlibRef, dRef, eRef }, s_signedDll.WithMetadataReferenceResolver(resolverA), assemblyName: "A").EmitToImageReference(); Assert.Equal(2, resolverA.ResolutionAttempts.Count); var resolverC = new TestMissingMetadataReferenceResolver(new Dictionary<string, MetadataReference> { { "D, 1.0.0.0", dRef }, { "E, 1.0.0.0", eRef }, }); var c = CreateEmptyCompilation("public class C : A { }", new[] { MscorlibRef, aRef, b1Ref }, s_signedDll.WithMetadataReferenceResolver(resolverC)); c.VerifyEmitDiagnostics( // error CS1705: Assembly // 'A' with identity 'A, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' uses // 'B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' which has a higher version than referenced assembly // 'B' with identity 'B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' Diagnostic(ErrorCode.ERR_AssemblyMatchBadVersion).WithArguments( "A", "A, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "B", "B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2").WithLocation(1, 1), // error CS1705: Assembly // 'D' with identity 'D, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' uses // 'B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' which has a higher version than referenced assembly // 'B' with identity 'B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' Diagnostic(ErrorCode.ERR_AssemblyMatchBadVersion).WithArguments( "D", "D, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "B", "B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2").WithLocation(1, 1)); resolverC.VerifyResolutionAttempts( "A -> D, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "A -> E, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2"); c.VerifyAssemblyVersionsAndAliases( "mscorlib, Version=4.0.0.0", "A, Version=1.0.0.0", "B, Version=1.0.0.0", "D, Version=1.0.0.0", "E, Version=1.0.0.0"); } /// <summary> /// Don't try to resolve AssemblyRefs that already match explicitly specified definition. /// </summary> [ConditionalFact(typeof(NoIOperationValidation), typeof(NoUsedAssembliesValidation))] public void MissingAssemblyResolution_BindingToExplicitReference_BetterVersion() { // c - a -> d -> "b,v2" // e -> "b,v1" // - "b,v2" var b1Ref = CreateEmptyCompilation(@"[assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public interface B { }", references: new[] { MscorlibRef }, options: s_signedDll, assemblyName: "B").EmitToImageReference(); var b2Ref = CreateEmptyCompilation(@"[assembly: System.Reflection.AssemblyVersion(""2.0.0.0"")] public interface B { }", references: new[] { MscorlibRef }, options: s_signedDll, assemblyName: "B").EmitToImageReference(); var dRef = CreateEmptyCompilation(@"[assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public interface D : B { }", new[] { MscorlibRef, b2Ref }, options: s_signedDll, assemblyName: "D").EmitToImageReference(); var eRef = CreateEmptyCompilation(@"[assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public interface E : B { }", new[] { MscorlibRef, b1Ref }, options: s_signedDll, assemblyName: "E").EmitToImageReference(); var resolverA = new TestMissingMetadataReferenceResolver(new Dictionary<string, MetadataReference> { { "B, 2.0.0.0", b2Ref }, { "B, 1.0.0.0", b1Ref }, }); var aRef = CreateEmptyCompilation(@"[assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public interface A : D, E { }", new[] { MscorlibRef, dRef, eRef }, s_signedDll.WithMetadataReferenceResolver(resolverA), assemblyName: "A").EmitToImageReference(); Assert.Equal(2, resolverA.ResolutionAttempts.Count); var resolverC = new TestMissingMetadataReferenceResolver(new Dictionary<string, MetadataReference> { { "D, 1.0.0.0", dRef }, { "E, 1.0.0.0", eRef }, }); var c = CreateEmptyCompilation("public class C : A { }", new[] { MscorlibRef, aRef, b2Ref }, s_signedDll.WithMetadataReferenceResolver(resolverC)); c.VerifyEmitDiagnostics( // warning CS1701: Assuming assembly reference // 'B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' used by // 'A' matches identity 'B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' of 'B', you may need to supply runtime policy Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin).WithArguments( "B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "A", "B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "B").WithLocation(1, 1), // warning CS1701: Assuming assembly reference // 'B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' used by 'E' matches identity // 'B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' of 'B', you may need to supply runtime policy Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin).WithArguments( "B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "E", "B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "B").WithLocation(1, 1)); resolverC.VerifyResolutionAttempts( "A -> D, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "A -> E, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2"); c.VerifyAssemblyVersionsAndAliases( "mscorlib, Version=4.0.0.0", "A, Version=1.0.0.0", "B, Version=2.0.0.0", "D, Version=1.0.0.0", "E, Version=1.0.0.0"); } [ConditionalFact(typeof(NoIOperationValidation), typeof(NoUsedAssembliesValidation), Reason = "IOperation adds extra assemblies")] public void MissingAssemblyResolution_BindingToImplicitReference1() { // c - a -> d -> "b,v2" // e -> "b,v1" // "b,v1" // "b,v2" var b1Ref = CreateEmptyCompilation(@"[assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public interface B { }", new[] { MscorlibRef }, options: s_signedDll, assemblyName: "B").EmitToImageReference(); var b2Ref = CreateEmptyCompilation(@"[assembly: System.Reflection.AssemblyVersion(""2.0.0.0"")] public interface B { }", new[] { MscorlibRef }, options: s_signedDll, assemblyName: "B").EmitToImageReference(); var dRef = CreateEmptyCompilation(@"[assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public interface D : B { }", new[] { MscorlibRef, b2Ref }, options: s_signedDll, assemblyName: "D").EmitToImageReference(); var eRef = CreateEmptyCompilation(@"[assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public interface E : B { }", new[] { MscorlibRef, b1Ref }, options: s_signedDll, assemblyName: "E").EmitToImageReference(); var aRef = CreateEmptyCompilation(@"[assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public interface A : D, E { }", new[] { MscorlibRef, dRef, eRef, b1Ref, b2Ref }, s_signedDll, assemblyName: "A").EmitToImageReference(); var resolverC = new TestMissingMetadataReferenceResolver(new Dictionary<string, MetadataReference> { { "D, 1.0.0.0", dRef }, { "E, 1.0.0.0", eRef }, { "B, 1.0.0.0", b1Ref }, { "B, 2.0.0.0", b2Ref }, }); var c = CreateSubmissionWithExactReferences("public class C : A { }", new[] { MscorlibRef_v4_0_30316_17626, aRef }, TestOptions.ReleaseDll.WithMetadataReferenceResolver(resolverC)); c.VerifyEmitDiagnostics(); resolverC.VerifyResolutionAttempts( "A -> D, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "A -> B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "A -> E, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "A -> B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2"); c.VerifyAssemblyVersionsAndAliases( "mscorlib, Version=4.0.0.0", "A, Version=1.0.0.0", "D, Version=1.0.0.0", "B, Version=2.0.0.0", "E, Version=1.0.0.0", "B, Version=1.0.0.0: <superseded>"); } [ConditionalFact(typeof(NoIOperationValidation), typeof(NoUsedAssembliesValidation), Reason = "IOperation adds extra assemblies")] public void MissingAssemblyResolution_BindingToImplicitReference2() { // c - a -> d -> "b,v2" // e -> "b,v1" // "b,v1" // "b,v2" var b1Ref = CreateEmptyCompilation(@"[assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public interface B { }", new[] { MscorlibRef }, options: s_signedDll, assemblyName: "B").EmitToImageReference(); var b2Ref = CreateEmptyCompilation(@"[assembly: System.Reflection.AssemblyVersion(""2.0.0.0"")] public interface B { }", new[] { MscorlibRef }, options: s_signedDll, assemblyName: "B").EmitToImageReference(); var b3Ref = CreateEmptyCompilation(@"[assembly: System.Reflection.AssemblyVersion(""3.0.0.0"")] public interface B { }", new[] { MscorlibRef }, options: s_signedDll, assemblyName: "B").EmitToImageReference(); var b4Ref = CreateEmptyCompilation(@"[assembly: System.Reflection.AssemblyVersion(""4.0.0.0"")] public interface B { }", new[] { MscorlibRef }, options: s_signedDll, assemblyName: "B").EmitToImageReference(); var dRef = CreateEmptyCompilation(@"[assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public interface D : B { }", new[] { MscorlibRef, b2Ref }, options: s_signedDll, assemblyName: "D").EmitToImageReference(); var eRef = CreateEmptyCompilation(@"[assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public interface E : B { }", new[] { MscorlibRef, b1Ref }, options: s_signedDll, assemblyName: "E").EmitToImageReference(); var aRef = CreateEmptyCompilation(@"[assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public interface A : D, E { }", new[] { MscorlibRef, dRef, eRef, b1Ref, b2Ref }, s_signedDll, assemblyName: "A").EmitToImageReference(); var resolverC = new TestMissingMetadataReferenceResolver(new Dictionary<string, MetadataReference> { { "D, 1.0.0.0", dRef }, { "E, 1.0.0.0", eRef }, { "B, 1.0.0.0", b3Ref }, { "B, 2.0.0.0", b4Ref }, }); var c = CreateEmptyCompilation("public class C : A { }", new[] { MscorlibRef, aRef }, s_signedDll.WithMetadataReferenceResolver(resolverC)); c.VerifyEmitDiagnostics( // warning CS1701: Assuming assembly reference // 'B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' used by 'A' matches identity // 'B, Version=3.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' of 'B', you may need to supply runtime policy Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin).WithArguments( "B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "A", "B, Version=3.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "B").WithLocation(1, 1), // warning CS1701: Assuming assembly reference // 'B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' used by 'D' matches identity // 'B, Version=3.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' of 'B', you may need to supply runtime policy Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin).WithArguments( "B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "D", "B, Version=3.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "B").WithLocation(1, 1), // warning CS1701: Assuming assembly reference // 'B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' used by 'E' matches identity // 'B, Version=3.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' of 'B', you may need to supply runtime policy Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin).WithArguments( "B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "E", "B, Version=3.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "B").WithLocation(1, 1)); c.VerifyAssemblyVersionsAndAliases( "mscorlib, Version=4.0.0.0", "A, Version=1.0.0.0", "D, Version=1.0.0.0", "B, Version=4.0.0.0", "E, Version=1.0.0.0", "B, Version=3.0.0.0"); resolverC.VerifyResolutionAttempts( "A -> D, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "A -> B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "A -> E, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "A -> B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2"); } [ConditionalFact(typeof(NoIOperationValidation), typeof(NoUsedAssembliesValidation), Reason = "IOperation adds extra assemblies")] public void MissingAssemblyResolution_BindingToImplicitReference3() { // c - a -> d -> "b,v2" // e -> "b,v1" // "b,v1" // "b,v2" var b1Ref = CreateEmptyCompilation(@"[assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public interface B { }", new[] { MscorlibRef }, options: s_signedDll, assemblyName: "B").EmitToImageReference(); var b2Ref = CreateEmptyCompilation(@"[assembly: System.Reflection.AssemblyVersion(""2.0.0.0"")] public interface B { }", new[] { MscorlibRef }, options: s_signedDll, assemblyName: "B").EmitToImageReference(); var b3Ref = CreateEmptyCompilation(@"[assembly: System.Reflection.AssemblyVersion(""3.0.0.0"")] public interface B { }", new[] { MscorlibRef }, options: s_signedDll, assemblyName: "B").EmitToImageReference(); var b4Ref = CreateEmptyCompilation(@"[assembly: System.Reflection.AssemblyVersion(""4.0.0.0"")] public interface B { }", new[] { MscorlibRef }, options: s_signedDll, assemblyName: "B").EmitToImageReference(); var dRef = CreateEmptyCompilation(@"[assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public interface D : B { }", new[] { MscorlibRef, b2Ref }, options: s_signedDll, assemblyName: "D").EmitToImageReference(); var eRef = CreateEmptyCompilation(@"[assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public interface E : B { }", new[] { MscorlibRef, b1Ref }, options: s_signedDll, assemblyName: "E").EmitToImageReference(); var aRef = CreateEmptyCompilation(@"[assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public interface A : D, E { }", new[] { MscorlibRef, dRef, eRef, b1Ref, b2Ref }, s_signedDll, assemblyName: "A").EmitToImageReference(); var resolverC = new TestMissingMetadataReferenceResolver(new Dictionary<string, MetadataReference> { { "D, 1.0.0.0", dRef }, { "E, 1.0.0.0", eRef }, { "B, 1.0.0.0", b3Ref }, { "B, 2.0.0.0", b4Ref }, }); var c = CreateSubmissionWithExactReferences("public class C : A { }", new[] { MscorlibRef_v4_0_30316_17626, aRef }, TestOptions.ReleaseDll.WithMetadataReferenceResolver(resolverC)); c.VerifyEmitDiagnostics( // warning CS1701: Assuming assembly reference // 'B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' used by 'A' matches identity // 'B, Version=3.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' of 'B', you may need to supply runtime policy Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin).WithArguments( "B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "A", "B, Version=3.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "B").WithLocation(1, 1), // warning CS1701: Assuming assembly reference // 'B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' used by 'D' matches identity // 'B, Version=3.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' of 'B', you may need to supply runtime policy Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin).WithArguments( "B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "D", "B, Version=3.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "B").WithLocation(1, 1), // warning CS1701: Assuming assembly reference // 'B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' used by 'E' matches identity // 'B, Version=3.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' of 'B', you may need to supply runtime policy Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin).WithArguments( "B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "E", "B, Version=3.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "B").WithLocation(1, 1)); c.VerifyAssemblyVersionsAndAliases( "mscorlib, Version=4.0.0.0", "A, Version=1.0.0.0", "D, Version=1.0.0.0", "B, Version=4.0.0.0", "E, Version=1.0.0.0", "B, Version=3.0.0.0: <superseded>"); resolverC.VerifyResolutionAttempts( "A -> D, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "A -> B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "A -> E, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "A -> B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2"); } [ConditionalFact(typeof(NoIOperationValidation), typeof(NoUsedAssembliesValidation), Reason = "IOperation adds extra assemblies")] public void MissingAssemblyResolution_Supersession_FxUnification() { var options = TestOptions.ReleaseDll.WithAssemblyIdentityComparer(DesktopAssemblyIdentityComparer.Default); // c - "mscorlib, v4" // a -> "mscorlib, v2" // "System, v2" // b -> "mscorlib, v4" // "System, v4" var aRef = CreateEmptyCompilation(@"public interface A { System.Diagnostics.Process PA { get; } }", new[] { Net20.mscorlib, Net20.System }, options: options, assemblyName: "A").EmitToImageReference(); var bRef = CreateEmptyCompilation(@"public interface B { System.Diagnostics.Process PB { get; } }", new[] { MscorlibRef_v4_0_30316_17626, Net451.System }, options: options, assemblyName: "B").EmitToImageReference(); var resolverC = new TestMissingMetadataReferenceResolver(new Dictionary<string, MetadataReference> { { "System, 2.0.0.0", Net20.System }, { "System, 4.0.0.0", Net451.System }, }); var c = CreateSubmissionWithExactReferences("public interface C : A, B { System.Diagnostics.Process PC { get; } }", new[] { MscorlibRef_v4_0_30316_17626, aRef, bRef }, options.WithMetadataReferenceResolver(resolverC)); c.VerifyEmitDiagnostics(); resolverC.VerifyResolutionAttempts( "B -> System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "System.dll (net451) -> System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.dll (net451) -> System.Xml, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "A -> System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "System.dll (net20) -> System.Configuration, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.dll (net20) -> System.Xml, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"); c.VerifyAssemblyVersionsAndAliases( "mscorlib, Version=4.0.0.0", "A, Version=0.0.0.0", "B, Version=0.0.0.0", "System, Version=4.0.0.0", "System, Version=2.0.0.0: <superseded>"); } [ConditionalFact(typeof(NoIOperationValidation), typeof(NoUsedAssembliesValidation), Reason = "IOperation adds extra assemblies")] public void MissingAssemblyResolution_Supersession_StrongNames() { var options = TestOptions.ReleaseDll.WithAssemblyIdentityComparer(DesktopAssemblyIdentityComparer.Default); // c - a -> "C, v2" // b -> "C, v1" var aRef = CreateEmptyCompilation(@"public interface A { C CA { get; } }", new[] { MscorlibRef, TestReferences.SymbolsTests.Versioning.C2 }, options: options, assemblyName: "A").EmitToImageReference(); var bRef = CreateEmptyCompilation(@"public interface B { C CB { get; } }", new[] { MscorlibRef, TestReferences.SymbolsTests.Versioning.C1 }, options: options, assemblyName: "B").EmitToImageReference(); var resolverC = new TestMissingMetadataReferenceResolver(new Dictionary<string, MetadataReference> { { "C, 1.0.0.0", TestReferences.SymbolsTests.Versioning.C1 }, { "C, 2.0.0.0", TestReferences.SymbolsTests.Versioning.C2 }, }); var c = CreateSubmissionWithExactReferences("public interface D : A, B { C CC { get; } }", new[] { MscorlibRef_v4_0_30316_17626, aRef, bRef }, options.WithMetadataReferenceResolver(resolverC)); c.VerifyEmitDiagnostics(); resolverC.VerifyResolutionAttempts( "B -> C, Version=1.0.0.0, Culture=neutral, PublicKeyToken=374d0c2befcd8cc9", "A -> C, Version=2.0.0.0, Culture=neutral, PublicKeyToken=374d0c2befcd8cc9"); c.VerifyAssemblyVersionsAndAliases( "mscorlib, Version=4.0.0.0", "A, Version=0.0.0.0", "B, Version=0.0.0.0", "C, Version=1.0.0.0: <superseded>", "C, Version=2.0.0.0"); } } }
// 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.IO; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; using static Roslyn.Test.Utilities.TestMetadata; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class ReferenceManagerTests : CSharpTestBase { private static readonly CSharpCompilationOptions s_signedDll = TestOptions.ReleaseDll.WithCryptoPublicKey(TestResources.TestKeys.PublicKey_ce65828c82a341f2); [Fact] public void WinRtCompilationReferences() { var ifaceDef = CreateCompilation( @" public interface ITest { }", options: TestOptions.DebugWinMD, assemblyName: "ITest"); ifaceDef.VerifyDiagnostics(); var ifaceImageRef = ifaceDef.EmitToImageReference(); var wimpl = AssemblyMetadata.CreateFromImage(TestResources.WinRt.WImpl).GetReference(display: "WImpl"); var implDef2 = CreateCompilation( @" public class C { public static void Main() { ITest test = new WImpl(); } }", references: new MetadataReference[] { ifaceDef.ToMetadataReference(), wimpl }, options: TestOptions.DebugExe); implDef2.VerifyDiagnostics(); } [Fact] public void VersionUnification_SymbolUsed() { // Identity: C, Version=1.0.0.0, Culture=neutral, PublicKeyToken=374d0c2befcd8cc9 var v1 = AssemblyMetadata.CreateFromImage(TestResources.General.C1).GetReference(display: "C, V1"); // Identity: C, Version=2.0.0.0, Culture=neutral, PublicKeyToken=374d0c2befcd8cc9 var v2 = AssemblyMetadata.CreateFromImage(TestResources.General.C2).GetReference(display: "C, V2"); var refV1 = CreateCompilation("public class D : C { }", new[] { v1 }, assemblyName: "refV1"); var refV2 = CreateCompilation("public class D : C { }", new[] { v2 }, assemblyName: "refV2"); // reference asks for a lower version than available: var testRefV1 = CreateCompilation("public class E : D { }", new MetadataReference[] { new CSharpCompilationReference(refV1), v2 }, assemblyName: "testRefV1"); // reference asks for a higher version than available: var testRefV2 = CreateCompilation("public class E : D { }", new MetadataReference[] { new CSharpCompilationReference(refV2), v1 }, assemblyName: "testRefV2"); // TODO (tomat): we should display paths rather than names "refV1" and "C" testRefV1.VerifyDiagnostics( // warning CS1701: // Assuming assembly reference 'C, Version=1.0.0.0, Culture=neutral, PublicKeyToken=374d0c2befcd8cc9' // used by 'refV1' matches identity 'C, Version=2.0.0.0, Culture=neutral, PublicKeyToken=374d0c2befcd8cc9' of 'C', you may need to supply runtime policy Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin).WithArguments( "C, Version=1.0.0.0, Culture=neutral, PublicKeyToken=374d0c2befcd8cc9", "refV1", "C, Version=2.0.0.0, Culture=neutral, PublicKeyToken=374d0c2befcd8cc9", "C").WithLocation(1, 1)); // TODO (tomat): we should display paths rather than names "refV2" and "C" testRefV2.VerifyDiagnostics( // error CS1705: Assembly 'refV2' with identity 'refV2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' // uses 'C, Version=2.0.0.0, Culture=neutral, PublicKeyToken=374d0c2befcd8cc9' which has a higher version than referenced assembly // 'C' with identity 'C, Version=1.0.0.0, Culture=neutral, PublicKeyToken=374d0c2befcd8cc9' Diagnostic(ErrorCode.ERR_AssemblyMatchBadVersion).WithArguments( "refV2", "refV2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "C, Version=2.0.0.0, Culture=neutral, PublicKeyToken=374d0c2befcd8cc9", "C", "C, Version=1.0.0.0, Culture=neutral, PublicKeyToken=374d0c2befcd8cc9").WithLocation(1, 1)); } [Fact] [WorkItem(546080, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546080")] public void VersionUnification_SymbolNotUsed() { var v1 = MetadataReference.CreateFromImage(TestResources.General.C1); var v2 = MetadataReference.CreateFromImage(TestResources.General.C2); var refV1 = CreateCompilation("public class D : C { }", new[] { v1 }); var refV2 = CreateCompilation("public class D : C { }", new[] { v2 }); // reference asks for a lower version than available: var testRefV1 = CreateCompilation("public class E { }", new MetadataReference[] { new CSharpCompilationReference(refV1), v2 }); // reference asks for a higher version than available: var testRefV2 = CreateCompilation("public class E { }", new MetadataReference[] { new CSharpCompilationReference(refV2), v1 }); testRefV1.VerifyDiagnostics(); testRefV2.VerifyDiagnostics(); } [Fact] public void VersionUnification_MultipleVersions() { string sourceLibV1 = @" [assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public class C {} "; var libV1 = CreateCompilation( sourceLibV1, assemblyName: "Lib", options: s_signedDll); string sourceLibV2 = @" [assembly: System.Reflection.AssemblyVersion(""2.0.0.0"")] public class C {} "; var libV2 = CreateCompilation( sourceLibV2, assemblyName: "Lib", options: s_signedDll); string sourceLibV3 = @" [assembly: System.Reflection.AssemblyVersion(""3.0.0.0"")] public class C {} "; var libV3 = CreateCompilation( sourceLibV3, assemblyName: "Lib", options: s_signedDll); string sourceRefLibV2 = @" using System.Collections.Generic; [assembly: System.Reflection.AssemblyVersion(""2.0.0.0"")] public class R { public C Field; } "; var refLibV2 = CreateCompilation( sourceRefLibV2, assemblyName: "RefLibV2", references: new[] { new CSharpCompilationReference(libV2) }, options: s_signedDll); string sourceMain = @" public class M { public void F() { var x = new R(); System.Console.WriteLine(x.Field); } } "; // higher version should be preferred over lower version regardless of the order of the references var main13 = CreateCompilation( sourceMain, assemblyName: "Main", references: new[] { new CSharpCompilationReference(libV1), new CSharpCompilationReference(libV3), new CSharpCompilationReference(refLibV2) }); // TODO (tomat): we should display paths rather than names "RefLibV2" and "Lib" main13.VerifyDiagnostics( // warning CS1701: Assuming assembly reference 'Lib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' used by 'RefLibV2' matches identity 'Lib, Version=3.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' of 'Lib', you may need to supply runtime policy Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin).WithArguments( "Lib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "RefLibV2", "Lib, Version=3.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "Lib")); var main31 = CreateCompilation( sourceMain, assemblyName: "Main", references: new[] { new CSharpCompilationReference(libV3), new CSharpCompilationReference(libV1), new CSharpCompilationReference(refLibV2) }); // TODO (tomat): we should display paths rather than names "RefLibV2" and "Lib" main31.VerifyDiagnostics( // warning CS1701: Assuming assembly reference 'Lib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' used by 'RefLibV2' matches identity 'Lib, Version=3.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' of 'Lib', you may need to supply runtime policy Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin).WithArguments( "Lib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "RefLibV2", "Lib, Version=3.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "Lib")); } [Fact] [WorkItem(529808, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529808"), WorkItem(530246, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530246")] public void VersionUnification_UseSiteWarnings() { string sourceLibV1 = @" [assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public class C {} public delegate void D(); public interface I {} "; var libV1 = CreateCompilation( sourceLibV1, assemblyName: "Lib", options: s_signedDll); string sourceLibV2 = @" [assembly: System.Reflection.AssemblyVersion(""2.0.0.0"")] public class C {} public delegate void D(); public interface I {} "; var libV2 = CreateCompilation( sourceLibV2, assemblyName: "Lib", options: s_signedDll); string sourceRefLibV1 = @" using System.Collections.Generic; [assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public class R { public R(C c) {} public C Field; public C Property { get; set; } public int this[C arg] { get { return 0; } set {} } public event D Event; public List<C> Method1() { return null; } public void Method2(List<List<C>> c) { } public void GenericMethod<T>() where T : I { } } public class S1 : List<C> { public class Inner {} } public class S2 : I {} public class GenericClass<T> where T : I { public class S {} } "; var refLibV1 = CreateCompilation( sourceRefLibV1, assemblyName: "RefLibV1", references: new[] { new CSharpCompilationReference(libV1) }, options: s_signedDll); string sourceX = @" [assembly: System.Reflection.AssemblyVersion(""2.0.0.0"")] public class P : Q {} public class Q : S2 {} "; var x = CreateCompilation( sourceX, assemblyName: "X", references: new[] { new CSharpCompilationReference(refLibV1), new CSharpCompilationReference(libV1) }, options: s_signedDll); string sourceMain = @" public class M { public void F() { var c = new C(); // ok var r = new R(null); // error: C in parameter var f = r.Field; // error: C in type var a = r.Property; // error: C in return type var b = r[c]; // error: C in parameter r.Event += () => {}; // error: C in type var m = r.Method1(); // error: ~> C in return type r.Method2(null); // error: ~> C in parameter r.GenericMethod<OKImpl>(); // error: ~> I in constraint var g = new GenericClass<OKImpl>.S(); // error: ~> I in constraint -- should report only once, for GenericClass<OKImpl>, not again for S. var s1 = new S1(); // error: ~> C in base var s2 = new S2(); // error: ~> I in implements var s3 = new S1.Inner(); // error: ~> C in base -- should only report once, for S1, not again for Inner. var e = new P(); // error: P -> Q -> S2 ~> I in implements } } public class Z : S2 // error: S2 ~> I in implements { } public class OKImpl : I { } "; var main = CreateCompilation( sourceMain, assemblyName: "Main", references: new[] { new CSharpCompilationReference(refLibV1), new CSharpCompilationReference(libV2), new CSharpCompilationReference(x) }); // TODO (tomat): we should display paths rather than names "RefLibV1" and "Lib" main.VerifyDiagnostics( // warning CS1701: Assuming assembly reference 'Lib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' used by 'RefLibV1' matches identity 'Lib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' of 'Lib', you may need to supply runtime policy Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin).WithArguments("Lib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "RefLibV1", "Lib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "Lib").WithLocation(1, 1), // warning CS1701: Assuming assembly reference 'Lib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' used by 'RefLibV1' matches identity 'Lib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' of 'Lib', you may need to supply runtime policy Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin).WithArguments("Lib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "RefLibV1", "Lib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "Lib").WithLocation(1, 1), // warning CS1701: Assuming assembly reference 'Lib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' used by 'RefLibV1' matches identity 'Lib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' of 'Lib', you may need to supply runtime policy Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin).WithArguments("Lib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "RefLibV1", "Lib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "Lib").WithLocation(1, 1), // warning CS1701: Assuming assembly reference 'Lib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' used by 'RefLibV1' matches identity 'Lib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' of 'Lib', you may need to supply runtime policy Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin).WithArguments("Lib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "RefLibV1", "Lib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "Lib").WithLocation(1, 1), // warning CS1701: Assuming assembly reference 'Lib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' used by 'RefLibV1' matches identity 'Lib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' of 'Lib', you may need to supply runtime policy Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin).WithArguments("Lib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "RefLibV1", "Lib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "Lib").WithLocation(1, 1), // warning CS1701: Assuming assembly reference 'Lib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' used by 'RefLibV1' matches identity 'Lib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' of 'Lib', you may need to supply runtime policy Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin).WithArguments("Lib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "RefLibV1", "Lib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "Lib").WithLocation(1, 1), // warning CS1701: Assuming assembly reference 'Lib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' used by 'RefLibV1' matches identity 'Lib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' of 'Lib', you may need to supply runtime policy Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin).WithArguments("Lib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "RefLibV1", "Lib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "Lib").WithLocation(1, 1), // warning CS1701: Assuming assembly reference 'Lib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' used by 'RefLibV1' matches identity 'Lib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' of 'Lib', you may need to supply runtime policy Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin).WithArguments("Lib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "RefLibV1", "Lib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "Lib").WithLocation(1, 1), // warning CS1701: Assuming assembly reference 'Lib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' used by 'RefLibV1' matches identity 'Lib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' of 'Lib', you may need to supply runtime policy Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin).WithArguments("Lib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "RefLibV1", "Lib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "Lib").WithLocation(1, 1), // warning CS1701: Assuming assembly reference 'Lib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' used by 'RefLibV1' matches identity 'Lib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' of 'Lib', you may need to supply runtime policy Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin).WithArguments("Lib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "RefLibV1", "Lib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "Lib").WithLocation(1, 1), // warning CS1701: Assuming assembly reference 'Lib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' used by 'RefLibV1' matches identity 'Lib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' of 'Lib', you may need to supply runtime policy Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin).WithArguments("Lib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "RefLibV1", "Lib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "Lib").WithLocation(1, 1), // warning CS1701: Assuming assembly reference 'Lib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' used by 'RefLibV1' matches identity 'Lib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' of 'Lib', you may need to supply runtime policy Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin).WithArguments("Lib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "RefLibV1", "Lib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "Lib").WithLocation(1, 1), // warning CS1701: Assuming assembly reference 'Lib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' used by 'RefLibV1' matches identity 'Lib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' of 'Lib', you may need to supply runtime policy Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin).WithArguments("Lib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "RefLibV1", "Lib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "Lib").WithLocation(1, 1), // warning CS1701: Assuming assembly reference 'Lib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' used by 'RefLibV1' matches identity 'Lib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' of 'Lib', you may need to supply runtime policy Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin).WithArguments("Lib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "RefLibV1", "Lib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "Lib").WithLocation(1, 1), // warning CS1701: Assuming assembly reference 'Lib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' used by 'X' matches identity 'Lib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' of 'Lib', you may need to supply runtime policy Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin).WithArguments("Lib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "X", "Lib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "Lib").WithLocation(1, 1)); CompileAndVerify(main, validator: (assembly) => { var reader = assembly.GetMetadataReader(); // Dev11 adds "Lib 1.0" to the references, we don't (see DevDiv #15580) AssertEx.SetEqual(new[] { $"{RuntimeCorLibName.Name} {RuntimeCorLibName.Version.ToString(2)}", "RefLibV1 1.0", "Lib 2.0", "X 2.0" }, reader.DumpAssemblyReferences()); }, // PE verification fails on some platforms. Would need .config file with Lib v1 -> Lib v2 binding redirect verify: Verification.Skipped); } [Fact] [WorkItem(546080, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546080")] public void VersionUnification_UseSiteDiagnostics_Multiple() { string sourceA1 = @" [assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public class A {} "; var a1 = CreateCompilation( sourceA1, assemblyName: "A", options: s_signedDll); string sourceA2 = @" [assembly: System.Reflection.AssemblyVersion(""2.0.0.0"")] public class A {} "; var a2 = CreateCompilation( sourceA2, assemblyName: "A", options: s_signedDll); string sourceB1 = @" [assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public class B {} "; var b1 = CreateCompilation( sourceB1, assemblyName: "B", options: s_signedDll); string sourceB2 = @" [assembly: System.Reflection.AssemblyVersion(""2.0.0.0"")] public class B {} "; var b2 = CreateCompilation( sourceB2, assemblyName: "B", options: s_signedDll); string sourceRefA1B2 = @" using System.Collections.Generic; [assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public class R { public Dictionary<A, B> Dict = new Dictionary<A, B>(); public void Goo(A a, B b) {} } "; var refA1B2 = CreateCompilation( sourceRefA1B2, assemblyName: "RefA1B2", references: new[] { new CSharpCompilationReference(a1), new CSharpCompilationReference(b2) }, options: s_signedDll); string sourceMain = @" public class M { public void F() { var r = new R(); System.Console.WriteLine(r.Dict); // warning & error r.Goo(null, null); // warning & error } } "; var main = CreateCompilation( sourceMain, assemblyName: "Main", references: new[] { new CSharpCompilationReference(refA1B2), new CSharpCompilationReference(a2), new CSharpCompilationReference(b1) }); // TODO (tomat): we should display paths rather than names "RefLibV1" and "Lib" // TODO (tomat): this should include 2 warnings: main.VerifyDiagnostics( // error CS1705: Assembly 'RefA1B2' with identity 'RefA1B2, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' uses // 'B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' which has a higher version than referenced assembly 'B' // with identity 'B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' Diagnostic(ErrorCode.ERR_AssemblyMatchBadVersion).WithArguments( "RefA1B2", "RefA1B2, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "B", "B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2").WithLocation(1, 1), // error CS1705: Assembly 'RefA1B2' with identity 'RefA1B2, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' uses // 'B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' which has a higher version than referenced assembly 'B' // with identity 'B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' Diagnostic(ErrorCode.ERR_AssemblyMatchBadVersion).WithArguments( "RefA1B2", "RefA1B2, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "B", "B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2").WithLocation(1, 1)); } [Fact] public void VersionUnification_UseSiteDiagnostics_OptionalAttributes() { string sourceLibV1 = @" [assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] namespace System.Reflection { [AttributeUsage(AttributeTargets.Assembly, Inherited = false)] public sealed class AssemblyVersionAttribute : Attribute { public AssemblyVersionAttribute(string version) {} public string Version { get; set; } } } public class CGAttribute : System.Attribute { } "; var libV1 = CreateEmptyCompilation( sourceLibV1, assemblyName: "Lib", references: new[] { MinCorlibRef }, options: s_signedDll); libV1.VerifyDiagnostics(); string sourceLibV2 = @" [assembly: System.Reflection.AssemblyVersion(""2.0.0.0"")] namespace System.Reflection { [AttributeUsage(AttributeTargets.Assembly, Inherited = false)] public sealed class AssemblyVersionAttribute : Attribute { public AssemblyVersionAttribute(string version) {} public string Version { get; set; } } } public class CGAttribute : System.Attribute { } "; var libV2 = CreateEmptyCompilation( sourceLibV2, assemblyName: "Lib", references: new[] { MinCorlibRef }, options: s_signedDll); libV2.VerifyDiagnostics(); string sourceRefLibV1 = @" namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.All, Inherited = true)] public sealed class CompilerGeneratedAttribute : CGAttribute { } } "; var refLibV1 = CreateEmptyCompilation( sourceRefLibV1, assemblyName: "RefLibV1", references: new MetadataReference[] { MinCorlibRef, new CSharpCompilationReference(libV1) }, options: s_signedDll); refLibV1.VerifyDiagnostics(); string sourceMain = @" public class C { public int P { get; set; } // error: backing field is marked by CompilerGeneratedAttribute, whose base type is in the unified assembly } "; var main = CreateEmptyCompilation( sourceMain, assemblyName: "Main", references: new MetadataReference[] { MinCorlibRef, new CSharpCompilationReference(refLibV1), new CSharpCompilationReference(libV2) }); // Dev11 reports warning since the base type of CompilerGeneratedAttribute is in unified assembly. // Roslyn doesn't report any use-site diagnostics for optional attributes, it just ignores them main.VerifyDiagnostics(); } [Fact] public void VersionUnification_SymbolEquality() { string sourceLibV1 = @" using System.Reflection; [assembly: AssemblyVersion(""1.0.0.0"")] public interface I {} "; var libV1 = CreateCompilation( sourceLibV1, assemblyName: "Lib", options: s_signedDll); string sourceLibV2 = @" using System.Reflection; [assembly: AssemblyVersion(""2.0.0.0"")] public interface I {} "; var libV2 = CreateCompilation( sourceLibV2, assemblyName: "Lib", options: s_signedDll); string sourceRefLibV1 = @" using System.Reflection; [assembly: AssemblyVersion(""1.0.0.0"")] public class C : I { } "; var refLibV1 = CreateCompilation( sourceRefLibV1, assemblyName: "RefLibV1", references: new[] { new CSharpCompilationReference(libV1) }, options: s_signedDll); string sourceMain = @" public class M { public void F() { I x = new C(); } } "; var main = CreateCompilation( sourceMain, assemblyName: "Main", references: new[] { new CSharpCompilationReference(refLibV1), new CSharpCompilationReference(libV2) }); // TODO (tomat): we should display paths rather than names "RefLibV1" and "Lib" main.VerifyDiagnostics( // warning CS1701: Assuming assembly reference 'Lib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' // used by 'RefLibV1' matches identity 'Lib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' of 'Lib', you may need to supply runtime policy Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin).WithArguments( "Lib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "RefLibV1", "Lib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "Lib")); } [Fact] [WorkItem(546752, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546752")] public void VersionUnification_NoPiaMissingCanonicalTypeSymbol() { string sourceLibV1 = @" [assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public class A {} "; var libV1 = CreateCompilation( sourceLibV1, assemblyName: "Lib", options: s_signedDll); string sourceLibV2 = @" [assembly: System.Reflection.AssemblyVersion(""2.0.0.0"")] public class A {} "; var libV2 = CreateCompilation( sourceLibV2, assemblyName: "Lib", options: s_signedDll); string sourceRefLibV1 = @" using System.Runtime.InteropServices; public class B : A { public void M(IB i) { } } [ComImport] [Guid(""F79F0037-0874-4EE3-BC45-158EDBA3ABA3"")] [TypeIdentifier] public interface IB { } "; var refLibV1 = CreateCompilation( sourceRefLibV1, assemblyName: "RefLibV1", references: new[] { new CSharpCompilationReference(libV1) }, options: TestOptions.ReleaseDll); string sourceMain = @" public class Test { static void Main() { B b = new B(); b.M(null); } } "; // NOTE: We won't get a nopia type unless we use a PE reference (i.e. source won't work). var main = CreateCompilation( sourceMain, assemblyName: "Main", references: new MetadataReference[] { MetadataReference.CreateFromImage(refLibV1.EmitToArray()), new CSharpCompilationReference(libV2) }, options: TestOptions.ReleaseExe); // TODO (tomat): we should display paths rather than names "RefLibV1" and "Lib" main.VerifyDiagnostics( // warning CS1701: Assuming assembly reference 'Lib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' used by 'RefLibV1' matches identity 'Lib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' of 'Lib', you may need to supply runtime policy Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin).WithArguments("Lib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "RefLibV1", "Lib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "Lib"), // warning CS1701: Assuming assembly reference 'Lib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' used by 'RefLibV1' matches identity 'Lib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' of 'Lib', you may need to supply runtime policy Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin).WithArguments("Lib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "RefLibV1", "Lib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "Lib"), // (7,9): error CS1748: Cannot find the interop type that matches the embedded interop type 'IB'. Are you missing an assembly reference? // b.M(null); Diagnostic(ErrorCode.ERR_NoCanonicalView, "b.M").WithArguments("IB")); } [WorkItem(546525, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546525")] [Fact] public void AssemblyReferencesWithAliases() { var source = @"extern alias SysCore; using System.Linq; namespace Microsoft.TeamFoundation.WebAccess.Common { public class CachedRegistry { public static void Main(string[] args) { System.Console.Write('k'); } } }"; var tree = Parse(source); var r1 = AssemblyMetadata.CreateFromImage(ResourcesNet451.SystemCore).GetReference(filePath: @"c:\temp\aa.dll", display: "System.Core.v4_0_30319.dll"); var r2 = AssemblyMetadata.CreateFromImage(ResourcesNet451.SystemCore).GetReference(filePath: @"c:\temp\aa.dll", display: "System.Core.v4_0_30319.dll"); var r2_SysCore = r2.WithAliases(new[] { "SysCore" }); var compilation = CreateEmptyCompilation(tree, new[] { MscorlibRef, r1, r2_SysCore }, TestOptions.DebugExe, assemblyName: "Test"); CompileAndVerify(compilation, expectedOutput: "k"); } [WorkItem(545062, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545062")] [Fact] public void DuplicateReferences() { CSharpCompilation c; string source; var r1 = AssemblyMetadata.CreateFromImage(TestResources.General.C1).GetReference(filePath: @"c:\temp\a.dll", display: "R1"); var r2 = AssemblyMetadata.CreateFromImage(TestResources.General.C1).GetReference(filePath: @"c:\temp\a.dll", display: "R2"); var rGoo = r2.WithAliases(new[] { "goo" }); var rBar = r2.WithAliases(new[] { "bar" }); var rEmbed = r1.WithEmbedInteropTypes(true); source = @" class D { } "; c = createCompilationCore(source, new[] { r1, r2 }); Assert.Null(c.GetReferencedAssemblySymbol(r1)); Assert.NotNull(c.GetReferencedAssemblySymbol(r2)); c.VerifyDiagnostics(); source = @" class D : C { } "; c = createCompilationCore(source, new[] { r1, r2 }); Assert.Null(c.GetReferencedAssemblySymbol(r1)); Assert.NotNull(c.GetReferencedAssemblySymbol(r2)); c.VerifyDiagnostics(); c = createCompilationCore(source, new[] { rGoo, r2 }); Assert.Null(c.GetReferencedAssemblySymbol(rGoo)); Assert.NotNull(c.GetReferencedAssemblySymbol(r2)); AssertEx.SetEqual(new[] { "goo", "global" }, c.ExternAliases); c.VerifyDiagnostics(); // 2 aliases for the same path, aliases not used to qualify name c = createCompilationCore(source, new[] { rGoo, rBar }); Assert.Null(c.GetReferencedAssemblySymbol(rGoo)); Assert.NotNull(c.GetReferencedAssemblySymbol(rBar)); AssertEx.SetEqual(new[] { "goo", "bar" }, c.ExternAliases); c.VerifyDiagnostics( // (2,11): error CS0246: The type or namespace name 'C' could not be found (are you missing a using directive or an assembly reference?) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "C").WithArguments("C")); source = @" class D : C { } "; // /l and /r with the same path c = createCompilationCore(source, new[] { rGoo, rEmbed }); Assert.Null(c.GetReferencedAssemblySymbol(rGoo)); Assert.NotNull(c.GetReferencedAssemblySymbol(rEmbed)); c.VerifyDiagnostics( // error CS1760: Assemblies 'R1' and 'R2' refer to the same metadata but only one is a linked reference (specified using /link option); consider removing one of the references. Diagnostic(ErrorCode.ERR_AssemblySpecifiedForLinkAndRef).WithArguments("R1", "R2"), // error CS1747: Cannot embed interop types from assembly 'C, Version=1.0.0.0, Culture=neutral, PublicKeyToken=374d0c2befcd8cc9' because it is missing the 'System.Runtime.InteropServices.GuidAttribute' attribute. Diagnostic(ErrorCode.ERR_NoPIAAssemblyMissingAttribute).WithArguments("C, Version=1.0.0.0, Culture=neutral, PublicKeyToken=374d0c2befcd8cc9", "System.Runtime.InteropServices.GuidAttribute"), // error CS1759: Cannot embed interop types from assembly 'C, Version=1.0.0.0, Culture=neutral, PublicKeyToken=374d0c2befcd8cc9' because it is missing either the 'System.Runtime.InteropServices.ImportedFromTypeLibAttribute' attribute or the 'System.Runtime.InteropServices.PrimaryInteropAssemblyAttribute' attribute. Diagnostic(ErrorCode.ERR_NoPIAAssemblyMissingAttributes).WithArguments("C, Version=1.0.0.0, Culture=neutral, PublicKeyToken=374d0c2befcd8cc9", "System.Runtime.InteropServices.ImportedFromTypeLibAttribute", "System.Runtime.InteropServices.PrimaryInteropAssemblyAttribute"), // (2,11): error CS1752: Interop type 'C' cannot be embedded. Use the applicable interface instead. // class D : C { } Diagnostic(ErrorCode.ERR_NewCoClassOnLink, "C").WithArguments("C")); source = @" extern alias goo; extern alias bar; public class D : goo::C { } public class E : bar::C { } "; // 2 aliases for the same path, aliases used c = createCompilationCore(source, new[] { rGoo, rBar }); Assert.Null(c.GetReferencedAssemblySymbol(rGoo)); Assert.NotNull(c.GetReferencedAssemblySymbol(rBar)); c.VerifyDiagnostics(); CSharpCompilation createCompilationCore(string s, IEnumerable<MetadataReference> references) { references = TargetFrameworkUtil.StandardReferences.AddRange(references); return CreateEmptyCompilation(s, references); } } // "<path>\x\y.dll" -> "<path>\x\..\x\y.dll" private static string MakeEquivalentPath(string path) { string[] parts = path.Split(Path.DirectorySeparatorChar); Debug.Assert(parts.Length >= 3); int dir = parts.Length - 2; List<string> newParts = new List<string>(parts); newParts.Insert(dir, ".."); newParts.Insert(dir, parts[dir]); return newParts.Join(Path.DirectorySeparatorChar.ToString()); } [Fact] public void DuplicateAssemblyReferences_EquivalentPath() { string p1 = Temp.CreateFile().WriteAllBytes(TestResources.General.MDTestLib1).Path; string p2 = MakeEquivalentPath(p1); string p3 = MakeEquivalentPath(p2); var r1 = MetadataReference.CreateFromFile(p1); var r2 = MetadataReference.CreateFromFile(p2); var r3 = MetadataReference.CreateFromFile(p3); SyntaxTree t1, t2, t3; var compilation = CSharpCompilation.Create("goo", syntaxTrees: new[] { t1 = Parse($"#r \"{p2}\"", options: TestOptions.Script), t2 = Parse($"#r \"{p3}\"", options: TestOptions.Script), t3 = Parse("#r \"Lib\"", options: TestOptions.Script), }, references: new MetadataReference[] { MscorlibRef_v4_0_30316_17626, r1, r2 }, options: TestOptions.ReleaseDll.WithMetadataReferenceResolver( new TestMetadataReferenceResolver( assemblyNames: new Dictionary<string, PortableExecutableReference> { { "Lib", r3 } }, files: new Dictionary<string, PortableExecutableReference> { { p2, r2 }, { p3, r3 } })) ); // no diagnostics expected, all duplicate references should be ignored as they all refer to the same file: compilation.VerifyDiagnostics(); var refs = compilation.ExternalReferences; Assert.Equal(3, refs.Length); Assert.Equal(MscorlibRef_v4_0_30316_17626, refs[0]); Assert.Equal(r1, refs[1]); Assert.Equal(r2, refs[2]); // All #r's resolved are represented in directive references. var dirRefs = compilation.DirectiveReferences; Assert.Equal(1, dirRefs.Length); var as1 = compilation.GetReferencedAssemblySymbol(r2); Assert.Equal("MDTestLib1", as1.Identity.Name); // r1 is a dup of r2: Assert.Null(compilation.GetReferencedAssemblySymbol(r1)); var rd1 = t1.GetCompilationUnitRoot().GetReferenceDirectives().Single(); var rd2 = t2.GetCompilationUnitRoot().GetReferenceDirectives().Single(); var rd3 = t3.GetCompilationUnitRoot().GetReferenceDirectives().Single(); var dr1 = compilation.GetDirectiveReference(rd1) as PortableExecutableReference; var dr2 = compilation.GetDirectiveReference(rd2) as PortableExecutableReference; var dr3 = compilation.GetDirectiveReference(rd3) as PortableExecutableReference; Assert.Equal(MetadataImageKind.Assembly, dr1.Properties.Kind); Assert.Equal(MetadataImageKind.Assembly, dr2.Properties.Kind); Assert.Equal(MetadataImageKind.Assembly, dr3.Properties.Kind); Assert.True(dr1.Properties.Aliases.IsEmpty); Assert.True(dr2.Properties.Aliases.IsEmpty); Assert.True(dr3.Properties.Aliases.IsEmpty); Assert.False(dr1.Properties.EmbedInteropTypes); Assert.False(dr2.Properties.EmbedInteropTypes); Assert.False(dr3.Properties.EmbedInteropTypes); // the paths come from the resolver: Assert.Equal(p2, dr1.FilePath); Assert.Equal(p3, dr2.FilePath); Assert.Equal(p3, dr3.FilePath); } [Fact] public void DuplicateModuleReferences_EquivalentPath() { var dir = Temp.CreateDirectory(); string p1 = dir.CreateFile("netModule1.netmodule").WriteAllBytes(TestResources.SymbolsTests.netModule.netModule1).Path; string p2 = MakeEquivalentPath(p1); var m1 = MetadataReference.CreateFromFile(p1, new MetadataReferenceProperties(MetadataImageKind.Module)); var m2 = MetadataReference.CreateFromFile(p2, new MetadataReferenceProperties(MetadataImageKind.Module)); var compilation = CSharpCompilation.Create("goo", options: TestOptions.ReleaseDll, references: new MetadataReference[] { m1, m2 }); // We don't deduplicate references based on file path on the compilation level. // The host (command line compiler and msbuild workspace) is responsible for such de-duplication, if needed. compilation.VerifyDiagnostics( // error CS8015: Module 'netModule1.netmodule' is already defined in this assembly. Each module must have a unique filename. Diagnostic(ErrorCode.ERR_NetModuleNameMustBeUnique).WithArguments("netModule1.netmodule"), // netModule1.netmodule: error CS0101: The namespace '<global namespace>' already contains a definition for 'Class1' Diagnostic(ErrorCode.ERR_DuplicateNameInNS).WithArguments("Class1", "<global namespace>"), // netModule1.netmodule: error CS0101: The namespace 'NS1' already contains a definition for 'Class4' Diagnostic(ErrorCode.ERR_DuplicateNameInNS).WithArguments("Class4", "NS1"), // netModule1.netmodule: error CS0101: The namespace 'NS1' already contains a definition for 'Class8' Diagnostic(ErrorCode.ERR_DuplicateNameInNS).WithArguments("Class8", "NS1")); var mods = compilation.Assembly.Modules.ToArray(); Assert.Equal(3, mods.Length); Assert.NotNull(compilation.GetReferencedModuleSymbol(m1)); Assert.NotNull(compilation.GetReferencedModuleSymbol(m2)); } /// <summary> /// Two metadata files with the same strong identity referenced twice, with embedInteropTypes=true and embedInteropTypes=false. /// </summary> [Fact] public void DuplicateAssemblyReferences_EquivalentStrongNames_Metadata() { var ref1 = AssemblyMetadata.CreateFromImage(TestResources.General.C2).GetReference(embedInteropTypes: true, filePath: @"R:\A\MTTestLib1.dll"); var ref2 = AssemblyMetadata.CreateFromImage(TestResources.General.C2).GetReference(embedInteropTypes: false, filePath: @"R:\B\MTTestLib1.dll"); var c = CreateEmptyCompilation("class C {}", TargetFrameworkUtil.StandardReferences.AddRange(new[] { ref1, ref2 })); c.VerifyDiagnostics( // error CS1760: Assemblies 'R:\B\MTTestLib1.dll' and 'R:\A\MTTestLib1.dll' refer to the same metadata but only one is a linked reference (specified using /link option); consider removing one of the references. Diagnostic(ErrorCode.ERR_AssemblySpecifiedForLinkAndRef).WithArguments(@"R:\B\MTTestLib1.dll", @"R:\A\MTTestLib1.dll")); } /// <summary> /// Two compilations with the same strong identity referenced twice, with embedInteropTypes=true and embedInteropTypes=false. /// </summary> [Fact] public void DuplicateAssemblyReferences_EquivalentStrongNames_Compilations() { var sourceLib = @" [assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public interface I {}"; var lib1 = CreateCompilation(sourceLib, options: s_signedDll, assemblyName: "Lib"); var lib2 = CreateCompilation(sourceLib, options: s_signedDll, assemblyName: "Lib"); var ref1 = lib1.ToMetadataReference(embedInteropTypes: true); var ref2 = lib2.ToMetadataReference(embedInteropTypes: false); var c = CreateEmptyCompilation("class C {}", TargetFrameworkUtil.StandardReferences.AddRange(new[] { ref1, ref2 })); c.VerifyDiagnostics( // error CS1760: Assemblies 'Lib' and 'Lib' refer to the same metadata but only one is a linked reference (specified using /link option); consider removing one of the references. Diagnostic(ErrorCode.ERR_AssemblySpecifiedForLinkAndRef).WithArguments("Lib", "Lib")); } [Fact] public void DuplicateAssemblyReferences_EquivalentName() { string p1 = Temp.CreateFile().WriteAllBytes(ResourcesNet451.SystemCore).Path; string p2 = Temp.CreateFile().CopyContentFrom(p1).Path; var r1 = MetadataReference.CreateFromFile(p1); var r2 = MetadataReference.CreateFromFile(p2); var compilation = CSharpCompilation.Create("goo", references: new[] { r1, r2 }); var refs = compilation.Assembly.Modules.Select(module => module.GetReferencedAssemblies()).ToArray(); Assert.Equal(1, refs.Length); Assert.Equal(1, refs[0].Length); } /// <summary> /// Two Framework identities with unified versions. /// </summary> [Fact] [WorkItem(546026, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546026"), WorkItem(546169, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546169")] public void CS1703ERR_DuplicateImport() { var p1 = Temp.CreateFile().WriteAllBytes(ResourcesNet451.System).Path; var p2 = Temp.CreateFile().WriteAllBytes(ResourcesNet20.System).Path; var text = @"namespace N {}"; var comp = CSharpCompilation.Create( "DupSignedRefs", new[] { SyntaxFactory.ParseSyntaxTree(text, options: TestOptions.Regular) }, new[] { MetadataReference.CreateFromFile(p1), MetadataReference.CreateFromFile(p2) }, TestOptions.ReleaseDll.WithAssemblyIdentityComparer(DesktopAssemblyIdentityComparer.Default)); comp.VerifyDiagnostics( // error CS1703: Multiple assemblies with equivalent identity have been imported: '...\v4.0.30319\System.dll' and '...\v2.0.50727\System.dll'. Remove one of the duplicate references. Diagnostic(ErrorCode.ERR_DuplicateImport).WithArguments(p1, p2)); } [Fact] public void CS1704ERR_DuplicateImportSimple() { var libSource = @" using System; public class A { }"; var peImage = CreateCompilation(libSource, options: TestOptions.ReleaseDll, assemblyName: "CS1704").EmitToArray(); var dir1 = Temp.CreateDirectory(); var exe1 = dir1.CreateFile("CS1704.dll").WriteAllBytes(peImage); var dir2 = Temp.CreateDirectory(); var exe2 = dir2.CreateFile("CS1704.dll").WriteAllBytes(peImage); var ref1 = AssemblyMetadata.CreateFromFile(exe1.Path).GetReference(aliases: ImmutableArray.Create("A1")); var ref2 = AssemblyMetadata.CreateFromFile(exe2.Path).GetReference(aliases: ImmutableArray.Create("A2")); var source = @" extern alias A1; extern alias A2; class B : A1::A { } class C : A2::A { } "; // Dev12 reports CS1704. An assembly with the same simple name '...' has already been imported. // We consider the second reference a duplicate and ignore it (merging the aliases). CreateEmptyCompilation(source, TargetFrameworkUtil.StandardReferences.AddRange(new[] { ref1, ref2 })).VerifyDiagnostics(); } [Fact] public void WeakIdentitiesWithDifferentVersions() { var sourceLibV1 = @" using System.Reflection; [assembly: AssemblyVersion(""1.0.0.0"")] public class C1 { } "; var sourceLibV2 = @" using System.Reflection; [assembly: AssemblyVersion(""2.0.0.0"")] public class C2 { } "; var sourceRefLibV1 = @" public class P { public C1 x; } "; var sourceMain = @" public class Q { public P x; public C1 y; public C2 z; } "; var libV1 = CreateCompilation(sourceLibV1, assemblyName: "Lib"); var libV2 = CreateCompilation(sourceLibV2, assemblyName: "Lib"); var refLibV1 = CreateCompilation(sourceRefLibV1, new[] { new CSharpCompilationReference(libV1) }, assemblyName: "RefLibV1"); var main = CreateCompilation(sourceMain, new[] { new CSharpCompilationReference(libV1), new CSharpCompilationReference(refLibV1), new CSharpCompilationReference(libV2) }, assemblyName: "Main"); main.VerifyDiagnostics( // error CS1704: An assembly with the same simple name 'Lib' has already been imported. Try removing one of the references (e.g. 'Lib') or sign them to enable side-by-side. Diagnostic(ErrorCode.ERR_DuplicateImportSimple).WithArguments("Lib", "Lib"), // (5,12): error CS0246: The type or namespace name 'C1' could not be found (are you missing a using directive or an assembly reference?) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "C1").WithArguments("C1")); } /// <summary> /// Although the CLR considers all WinRT references equivalent the Dev11 C# and VB compilers still /// compare their identities as if they were regular managed dlls. /// </summary> [Fact] public void WinMd_SameSimpleNames_SameVersions() { var sourceMain = @" public class Q { public C1 y; public C2 z; } "; // W1.dll: (W, Version=255.255.255.255, Culture=null, PKT=null) // W2.dll: (W, Version=255.255.255.255, Culture=null, PKT=null) using (AssemblyMetadata metadataLib1 = AssemblyMetadata.CreateFromImage(TestResources.WinRt.W1), metadataLib2 = AssemblyMetadata.CreateFromImage(TestResources.WinRt.W2)) { var mdRefLib1 = metadataLib1.GetReference(filePath: @"C:\W1.dll"); var mdRefLib2 = metadataLib2.GetReference(filePath: @"C:\W2.dll"); var main = CreateEmptyCompilation(sourceMain, TargetFrameworkUtil.StandardReferences.AddRange(new[] { mdRefLib1, mdRefLib2 })); // Dev12 reports CS1704. An assembly with the same simple name '...' has already been imported. // We consider the second reference a duplicate and ignore it. main.VerifyDiagnostics( // (4,12): error CS0246: The type or namespace name 'C1' could not be found (are you missing a using directive or an assembly reference?) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "C1").WithArguments("C1")); } } /// <summary> /// Although the CLR considers all WinRT references equivalent the Dev11 C# and VB compilers still /// compare their identities as if they were regular managed dlls. /// </summary> [Fact] public void WinMd_DifferentSimpleNames() { var sourceMain = @" public class Q { public C1 y; public CB z; } "; // W1.dll: (W, Version=255.255.255.255, Culture=null, PKT=null) // WB.dll: (WB, Version=255.255.255.255, Culture=null, PKT=null) using (AssemblyMetadata metadataLib1 = AssemblyMetadata.CreateFromImage(TestResources.WinRt.W1), metadataLib2 = AssemblyMetadata.CreateFromImage(TestResources.WinRt.WB)) { var mdRefLib1 = metadataLib1.GetReference(filePath: @"C:\W1.dll"); var mdRefLib2 = metadataLib2.GetReference(filePath: @"C:\WB.dll"); var main = CreateCompilation(sourceMain, new[] { mdRefLib1, mdRefLib2 }); main.VerifyDiagnostics(); } } /// <summary> /// Although the CLR considers all WinRT references equivalent the Dev11 C# and VB compilers still /// compare their identities as if they were regular managed dlls. /// </summary> [Fact] public void WinMd_SameSimpleNames_DifferentVersions() { var sourceMain = @" public class Q { public CB y; public CB_V1 z; } "; // WB.dll: (WB, Version=255.255.255.255, Culture=null, PKT=null) // WB_Version1.dll: (WB, Version=1.0.0.0, Culture=null, PKT=null) using (AssemblyMetadata metadataLib1 = AssemblyMetadata.CreateFromImage(TestResources.WinRt.WB), metadataLib2 = AssemblyMetadata.CreateFromImage(TestResources.WinRt.WB_Version1)) { var mdRefLib1 = metadataLib1.GetReference(filePath: @"C:\WB.dll"); var mdRefLib2 = metadataLib2.GetReference(filePath: @"C:\WB_Version1.dll"); var main = CreateEmptyCompilation(sourceMain, TargetFrameworkUtil.StandardReferences.AddRange(new[] { mdRefLib1, mdRefLib2 })); main.VerifyDiagnostics( // error CS1704: An assembly with the same simple name 'WB' has already been imported. Try removing one of the references (e.g. 'C:\WB.dll') or sign them to enable side-by-side. Diagnostic(ErrorCode.ERR_DuplicateImportSimple).WithArguments("WB", @"C:\WB.dll"), // (4,12): error CS0246: The type or namespace name 'CB' could not be found (are you missing a using directive or an assembly reference?) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "CB").WithArguments("CB")); } } /// <summary> /// We replicate the Dev11 behavior here but is there any real world scenario for this? /// </summary> [Fact] public void MetadataReferencesDifferInCultureOnly() { var arSA = TestReferences.SymbolsTests.Versioning.AR_SA; var enUS = TestReferences.SymbolsTests.Versioning.EN_US; var source = @" public class A { public arSA a = new arSA(); public enUS b = new enUS(); } "; var compilation = CreateEmptyCompilation(source, TargetFrameworkUtil.StandardReferences.AddRange(new[] { arSA, enUS })); var arSA_sym = compilation.GetReferencedAssemblySymbol(arSA); var enUS_sym = compilation.GetReferencedAssemblySymbol(enUS); Assert.Equal("ar-SA", arSA_sym.Identity.CultureName); Assert.Equal("en-US", enUS_sym.Identity.CultureName); compilation.VerifyDiagnostics(); } private class ReferenceResolver1 : MetadataReferenceResolver { public readonly string path1, path2; public bool resolved1, resolved2; public ReferenceResolver1(string path1, string path2) { this.path1 = path1; this.path2 = path2; } public override ImmutableArray<PortableExecutableReference> ResolveReference(string reference, string baseFilePath, MetadataReferenceProperties properties) { switch (reference) { case "1": resolved1 = true; return ImmutableArray.Create(MetadataReference.CreateFromFile(path1)); case "2.dll": resolved2 = true; return ImmutableArray.Create(MetadataReference.CreateFromFile(path2)); default: return ImmutableArray<PortableExecutableReference>.Empty; } } public override bool Equals(object other) => true; public override int GetHashCode() => 1; } [Fact] public void ReferenceResolution1() { var path1 = Temp.CreateFile().WriteAllBytes(TestResources.General.MDTestLib1).Path; var path2 = Temp.CreateFile().WriteAllBytes(TestResources.General.MDTestLib2).Path; var resolver = new ReferenceResolver1(path1, path2); var c1 = CSharpCompilation.Create("c1", syntaxTrees: new[] { Parse("#r \"1\"", options: TestOptions.Script), Parse("#r \"2.dll\"", options: TestOptions.Script), }, options: TestOptions.ReleaseDll.WithMetadataReferenceResolver(resolver)); Assert.NotNull(c1.Assembly); // force creation of SourceAssemblySymbol var dirRefs = c1.DirectiveReferences; var assemblySymbol1 = c1.GetReferencedAssemblySymbol(dirRefs[0]); var assemblySymbol2 = c1.GetReferencedAssemblySymbol(dirRefs[1]); Assert.Equal("MDTestLib1", assemblySymbol1.Name); Assert.Equal("MDTestLib2", assemblySymbol2.Name); Assert.True(resolver.resolved1); Assert.True(resolver.resolved2); } private class TestException : Exception { } private class ErroneousReferenceResolver : TestMetadataReferenceResolver { public ErroneousReferenceResolver() { } public override ImmutableArray<PortableExecutableReference> ResolveReference(string reference, string baseFilePath, MetadataReferenceProperties properties) { switch (reference) { case "throw": throw new TestException(); } return base.ResolveReference(reference, baseFilePath, properties); } } [Fact] public void ReferenceResolution_ExceptionsFromResolver() { var options = TestOptions.ReleaseDll.WithMetadataReferenceResolver(new ErroneousReferenceResolver()); foreach (var tree in new[] { Parse("#r \"throw\"", options: TestOptions.Script), }) { var c = CSharpCompilation.Create("c", syntaxTrees: new[] { tree }, options: options); Assert.Throws<TestException>(() => { var a = c.Assembly; }); } } [Fact] public void ResolvedReferencesCaching() { var c1 = CSharpCompilation.Create("goo", syntaxTrees: new[] { Parse("class C {}") }, references: new[] { MscorlibRef, SystemCoreRef, SystemRef }); var a1 = c1.SourceAssembly; var c2 = c1.AddSyntaxTrees(Parse("class D { }")); var a2 = c2.SourceAssembly; } // TODO: make x-plat (https://github.com/dotnet/roslyn/issues/6465) [ConditionalFact(typeof(WindowsOnly))] public void ReferenceResolution_RelativePaths() { var t1 = Parse(@" #r ""lib.dll"" ", filename: @"C:\A\a.csx", options: TestOptions.Script); var rd1 = (ReferenceDirectiveTriviaSyntax)t1.GetRoot().GetDirectives().Single(); var t2 = Parse(@" #r ""lib.dll"" ", filename: @"C:\B\b.csx", options: TestOptions.Script); var rd2 = (ReferenceDirectiveTriviaSyntax)t2.GetRoot().GetDirectives().Single(); var c = CreateCompilationWithMscorlib45(new[] { t1, t2 }, options: TestOptions.ReleaseDll.WithMetadataReferenceResolver( new TestMetadataReferenceResolver( pathResolver: new VirtualizedRelativePathResolver(new[] { @"C:\A\lib.dll", @"C:\B\lib.dll" }), files: new Dictionary<string, PortableExecutableReference>() { { @"C:\A\lib.dll", Net451.MicrosoftCSharp }, { @"C:\B\lib.dll", Net451.MicrosoftVisualBasic }, }))); c.VerifyDiagnostics(); Assert.Same(Net451.MicrosoftCSharp, c.GetDirectiveReference(rd1)); Assert.Same(Net451.MicrosoftVisualBasic, c.GetDirectiveReference(rd2)); } [Fact] public void CyclesInReferences() { var sourceA = @" public class A { } "; var a = CreateCompilation(sourceA, assemblyName: "A"); var sourceB = @" public class B : A { } public class Goo {} "; var b = CreateCompilation(sourceB, new[] { new CSharpCompilationReference(a) }, assemblyName: "B"); var refB = MetadataReference.CreateFromImage(b.EmitToArray()); var sourceA2 = @" public class A { public Goo x = new Goo(); } "; // construct A2 that has a reference to assembly identity "B". var a2 = CreateCompilation(sourceA2, new[] { refB }, assemblyName: "A"); var refA2 = MetadataReference.CreateFromImage(a2.EmitToArray()); var symbolB = a2.GetReferencedAssemblySymbol(refB); Assert.True(symbolB is Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE.PEAssemblySymbol, "PE symbol expected"); // force A assembly symbol to be added to a metadata cache: var c = CreateCompilation("class C : A {}", new[] { refA2, refB }, assemblyName: "C"); var symbolA2 = c.GetReferencedAssemblySymbol(refA2); Assert.True(symbolA2 is Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE.PEAssemblySymbol, "PE symbol expected"); Assert.Equal(1, ((AssemblyMetadata)refA2.GetMetadataNoCopy()).CachedSymbols.WeakCount); GC.KeepAlive(symbolA2); // Recompile "B" and remove int Goo. The assembly manager should not reuse symbols for A since they are referring to old version of B. var b2 = CreateCompilation(@" public class B : A { public void Bar() { object objX = this.x; } } ", new[] { refA2 }, assemblyName: "B"); // TODO (tomat): Dev11 also reports: // b2.cs(5,28): error CS0570: 'A.x' is not supported by the language b2.VerifyDiagnostics( // (6,28): error CS7068: Reference to type 'Goo' claims it is defined in this assembly, but it is not defined in source or any added modules // object objX = this.x; Diagnostic(ErrorCode.ERR_MissingTypeInSource, "x").WithArguments("Goo")); } [Fact] public void BoundReferenceCaching_CyclesInReferences() { var a = CreateCompilation("public class A { }", assemblyName: "A"); var b = CreateCompilation("public class B : A { } ", new[] { new CSharpCompilationReference(a) }, assemblyName: "B"); var refB = MetadataReference.CreateFromImage(b.EmitToArray()); // construct A2 that has a reference to assembly identity "B". var a2 = CreateCompilation(@"public class A { B B; }", new[] { refB }, assemblyName: "A"); var refA2 = MetadataReference.CreateFromImage(a2.EmitToArray()); var withCircularReference1 = CreateCompilation(@"public class B : A { }", new[] { refA2 }, assemblyName: "B"); var withCircularReference2 = withCircularReference1.WithOptions(TestOptions.ReleaseDll); Assert.NotSame(withCircularReference1, withCircularReference2); // until we try to reuse bound references we share the manager: Assert.True(withCircularReference1.ReferenceManagerEquals(withCircularReference2)); var assembly1 = withCircularReference1.SourceAssembly; Assert.True(withCircularReference1.ReferenceManagerEquals(withCircularReference2)); var assembly2 = withCircularReference2.SourceAssembly; Assert.False(withCircularReference1.ReferenceManagerEquals(withCircularReference2)); var refA2_symbol1 = withCircularReference1.GetReferencedAssemblySymbol(refA2); var refA2_symbol2 = withCircularReference2.GetReferencedAssemblySymbol(refA2); Assert.NotNull(refA2_symbol1); Assert.NotNull(refA2_symbol2); Assert.NotSame(refA2_symbol1, refA2_symbol2); } [WorkItem(546828, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546828")] [Fact] public void MetadataDependsOnSource() { // {0} is the body of the ReachFramework assembly reference. var ilTemplate = @" .assembly extern ReachFramework {{ {0} }} .assembly extern mscorlib {{ .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4.. .ver 4:0:0:0 }} .assembly PresentationFramework {{ .publickey = (00 24 00 00 04 80 00 00 94 00 00 00 06 02 00 00 // .$.............. 00 24 00 00 52 53 41 31 00 04 00 00 01 00 01 00 // .$..RSA1........ B5 FC 90 E7 02 7F 67 87 1E 77 3A 8F DE 89 38 C8 // ......g..w:...8. 1D D4 02 BA 65 B9 20 1D 60 59 3E 96 C4 92 65 1E // ....e. .`Y>...e. 88 9C C1 3F 14 15 EB B5 3F AC 11 31 AE 0B D3 33 // ...?....?..1...3 C5 EE 60 21 67 2D 97 18 EA 31 A8 AE BD 0D A0 07 // ..`!g-...1...... 2F 25 D8 7D BA 6F C9 0F FD 59 8E D4 DA 35 E4 4C // /%.}}.o...Y...5.L 39 8C 45 43 07 E8 E3 3B 84 26 14 3D AE C9 F5 96 // 9.EC...;.&.=.... 83 6F 97 C8 F7 47 50 E5 97 5C 64 E2 18 9F 45 DE // .o...GP..\d...E. F4 6B 2A 2B 12 47 AD C3 65 2B F5 C3 08 05 5D A9 ) // .k*+.G..e+....]. .ver 4:0:0:0 }} .module PresentationFramework.dll // MVID: {{CBA9159C-5BB4-49BC-B41D-AF055BF1C0AB}} .imagebase 0x00400000 .file alignment 0x00000200 .stackreserve 0x00100000 .subsystem 0x0003 // WINDOWS_CUI .corflags 0x00000001 // ILONLY // Image base: 0x04D00000 // =============== CLASS MEMBERS DECLARATION =================== .class public auto ansi System.Windows.Controls.PrintDialog extends [mscorlib]System.Object {{ .method public hidebysig instance class [ReachFramework]System.Printing.PrintTicket Test() cil managed {{ ret }} .method public hidebysig specialname rtspecialname instance void .ctor() cil managed {{ ret }} }} "; var csharp = @" using System.Windows.Controls; namespace System.Printing { public class PrintTicket { } } class Test { static void Main() { var dialog = new PrintDialog(); var p = dialog.Test(); } } "; // ref only specifies name { var il = string.Format(ilTemplate, ""); var ilRef = CompileIL(il, prependDefaultHeader: false); var comp = CreateCompilation(csharp, new[] { ilRef }, assemblyName: "ReachFramework"); comp.VerifyDiagnostics(); } // public key specified by ref, but not def { var il = string.Format(ilTemplate, " .publickeytoken = (31 BF 38 56 AD 36 4E 35 ) // 1.8V.6N5"); var ilRef = CompileIL(il, prependDefaultHeader: false); CreateCompilation(csharp, new[] { ilRef }, assemblyName: "ReachFramework").VerifyDiagnostics(); } // version specified by ref, but not def { var il = string.Format(ilTemplate, " .ver 4:0:0:0"); var ilRef = CompileIL(il, prependDefaultHeader: false); CreateCompilation(csharp, new[] { ilRef }, assemblyName: "ReachFramework").VerifyDiagnostics(); } // culture specified by ref, but not def { var il = string.Format(ilTemplate, " .locale = (65 00 6E 00 2D 00 63 00 61 00 00 00 ) // e.n.-.c.a..."); var ilRef = CompileIL(il, prependDefaultHeader: false); CreateCompilation(csharp, new[] { ilRef }, assemblyName: "ReachFramework").VerifyDiagnostics(); } } [WorkItem(546828, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546828")] [Fact] public void MetadataDependsOnMetadataOrSource() { var il = @" .assembly extern ReachFramework { .ver 4:0:0:0 } .assembly extern mscorlib { .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4.. .ver 4:0:0:0 } .assembly PresentationFramework { .publickey = (00 24 00 00 04 80 00 00 94 00 00 00 06 02 00 00 // .$.............. 00 24 00 00 52 53 41 31 00 04 00 00 01 00 01 00 // .$..RSA1........ B5 FC 90 E7 02 7F 67 87 1E 77 3A 8F DE 89 38 C8 // ......g..w:...8. 1D D4 02 BA 65 B9 20 1D 60 59 3E 96 C4 92 65 1E // ....e. .`Y>...e. 88 9C C1 3F 14 15 EB B5 3F AC 11 31 AE 0B D3 33 // ...?....?..1...3 C5 EE 60 21 67 2D 97 18 EA 31 A8 AE BD 0D A0 07 // ..`!g-...1...... 2F 25 D8 7D BA 6F C9 0F FD 59 8E D4 DA 35 E4 4C // /%.}.o...Y...5.L 39 8C 45 43 07 E8 E3 3B 84 26 14 3D AE C9 F5 96 // 9.EC...;.&.=.... 83 6F 97 C8 F7 47 50 E5 97 5C 64 E2 18 9F 45 DE // .o...GP..\d...E. F4 6B 2A 2B 12 47 AD C3 65 2B F5 C3 08 05 5D A9 ) // .k*+.G..e+....]. .ver 4:0:0:0 } .module PresentationFramework.dll // MVID: {CBA9159C-5BB4-49BC-B41D-AF055BF1C0AB} .imagebase 0x00400000 .file alignment 0x00000200 .stackreserve 0x00100000 .subsystem 0x0003 // WINDOWS_CUI .corflags 0x00000001 // ILONLY // Image base: 0x04D00000 // =============== CLASS MEMBERS DECLARATION =================== .class public auto ansi System.Windows.Controls.PrintDialog extends [mscorlib]System.Object { .method public hidebysig instance class [ReachFramework]System.Printing.PrintTicket Test() cil managed { ret } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } "; var csharp = @" namespace System.Printing { public class PrintTicket { } } "; var oldVersion = @"[assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")]"; var newVersion = @"[assembly: System.Reflection.AssemblyVersion(""4.0.0.0"")]"; var ilRef = CompileIL(il, prependDefaultHeader: false); var oldMetadata = AssemblyMetadata.CreateFromImage(CreateCompilation(oldVersion + csharp, assemblyName: "ReachFramework").EmitToArray()); var oldRef = oldMetadata.GetReference(); var comp = CreateCompilation(newVersion + csharp, new[] { ilRef, oldRef }, assemblyName: "ReachFramework"); comp.VerifyDiagnostics(); var method = comp.GlobalNamespace. GetMember<NamespaceSymbol>("System"). GetMember<NamespaceSymbol>("Windows"). GetMember<NamespaceSymbol>("Controls"). GetMember<NamedTypeSymbol>("PrintDialog"). GetMember<MethodSymbol>("Test"); AssemblyIdentity actualIdentity = method.ReturnType.ContainingAssembly.Identity; // Even though the compilation has the correct version number, the referenced binary is preferred. Assert.Equal(oldMetadata.GetAssembly().Identity, actualIdentity); Assert.NotEqual(comp.Assembly.Identity, actualIdentity); } [Fact] [WorkItem(546900, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546900")] public void MetadataRefersToSourceAssemblyModule() { var srcA = @" .assembly extern b { .ver 0:0:0:0 } .assembly extern mscorlib { .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) .ver 4:0:0:0 } .assembly a { .hash algorithm 0x00008004 .ver 0:0:0:0 } .module a.dll .class public auto ansi beforefieldinit A extends [b]B { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [b]B::.ctor() IL_0006: ret } }"; var aRef = CompileIL(srcA, prependDefaultHeader: false); string srcB = @" public class B { public A A; }"; var b = CreateCompilation(srcB, references: new[] { aRef }, options: TestOptions.ReleaseModule.WithModuleName("mod.netmodule"), assemblyName: "B"); b.VerifyDiagnostics(); } [ConditionalFact(typeof(DesktopOnly))] [WorkItem(530839, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530839")] public void EmbedInteropTypesReferences() { var libSource = @" using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyVersion(""1.0.0.0"")] [assembly: Guid(""49a1950e-3e35-4595-8cb9-920c64c44d67"")] [assembly: PrimaryInteropAssembly(1, 0)] [assembly: ImportedFromTypeLib(""Lib"")] [ComImport()] [Guid(""49a1950e-3e35-4595-8cb9-920c64c44d68"")] public interface I { } "; var mainSource = @" public class C : I { } "; var lib = CreateCompilation(libSource, assemblyName: "lib"); var refLib = ((MetadataImageReference)lib.EmitToImageReference()).WithEmbedInteropTypes(true); var main = CreateCompilation(mainSource, new[] { refLib }, assemblyName: "main"); CompileAndVerify(main, validator: (pe) => { var reader = pe.GetMetadataReader(); AssertEx.SetEqual(new[] { "mscorlib 4.0" }, reader.DumpAssemblyReferences()); }, verify: Verification.Passes); } [WorkItem(531537, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531537")] [Fact] public void ModuleSymbolReuse() { var text1 = @" class C { TypeFromModule M() { } } "; // Doesn't really matter what this text is - just need a delta. var text2 = @" class D { } "; var assemblyMetadata = AssemblyMetadata.CreateFromImage(CreateCompilation("public class TypeDependedOnByModule { }", assemblyName: "lib1").EmitToArray()); var assemblyRef = assemblyMetadata.GetReference(); var moduleRef = CreateCompilation("public class TypeFromModule : TypeDependedOnByModule { }", new[] { assemblyRef }, options: TestOptions.ReleaseModule, assemblyName: "lib2").EmitToImageReference(); var comp1 = CreateCompilation(text1, new MetadataReference[] { moduleRef, assemblyRef, }); var tree1 = comp1.SyntaxTrees.Single(); var moduleSymbol1 = comp1.GetReferencedModuleSymbol(moduleRef); Assert.Equal(comp1.Assembly, moduleSymbol1.ContainingAssembly); var moduleReferences1 = moduleSymbol1.GetReferencedAssemblies(); Assert.Contains(assemblyMetadata.GetAssembly().Identity, moduleReferences1); var moduleTypeSymbol1 = comp1.GlobalNamespace.GetMember<NamedTypeSymbol>("TypeFromModule"); Assert.Equal(moduleSymbol1, moduleTypeSymbol1.ContainingModule); Assert.Equal(comp1.Assembly, moduleTypeSymbol1.ContainingAssembly); var tree2 = tree1.WithInsertAt(text1.Length, text2); var comp2 = comp1.ReplaceSyntaxTree(tree1, tree2); var moduleSymbol2 = comp2.GetReferencedModuleSymbol(moduleRef); Assert.Equal(comp2.Assembly, moduleSymbol2.ContainingAssembly); var moduleReferences2 = moduleSymbol2.GetReferencedAssemblies(); var moduleTypeSymbol2 = comp2.GlobalNamespace.GetMember<NamedTypeSymbol>("TypeFromModule"); Assert.Equal(moduleSymbol2, moduleTypeSymbol2.ContainingModule); Assert.Equal(comp2.Assembly, moduleTypeSymbol2.ContainingAssembly); Assert.NotEqual(moduleSymbol1, moduleSymbol2); Assert.NotEqual(moduleTypeSymbol1, moduleTypeSymbol2); AssertEx.Equal(moduleReferences1, moduleReferences2); } [WorkItem(531537, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531537")] [Fact] public void ModuleSymbolReuse_ImplicitType() { var text1 = @" namespace A { void M() { } "; var text2 = @" } "; // Note: we just need *a* module reference for the repro - we're not depending on its contents, name, etc. var moduleRef = CreateCompilation("public class C { }", options: TestOptions.ReleaseModule, assemblyName: "lib").EmitToImageReference(); var comp1 = CreateCompilation(text1, new MetadataReference[] { moduleRef, }); var tree1 = comp1.SyntaxTrees.Single(); var implicitTypeCount1 = comp1.GlobalNamespace.GetMember<NamespaceSymbol>("A").GetMembers(TypeSymbol.ImplicitTypeName).Length; Assert.Equal(1, implicitTypeCount1); var tree2 = tree1.WithInsertAt(text1.Length, text2); var comp2 = comp1.ReplaceSyntaxTree(tree1, tree2); var implicitTypeCount2 = comp2.GlobalNamespace.GetMember<NamespaceSymbol>("A").GetMembers(TypeSymbol.ImplicitTypeName).Length; Assert.Equal(1, implicitTypeCount2); } [Fact] public void CachingAndVisibility() { var cPublic = CreateCompilation("class C { }", options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Public)); var cInternal = CreateCompilation("class D { }", options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal)); var cAll = CreateCompilation("class E { }", options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All)); var cPublic2 = CreateCompilation("class C { }", options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Public)); var cInternal2 = CreateCompilation("class D { }", options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal)); var cAll2 = CreateCompilation("class E { }", options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All)); Assert.NotSame(cPublic.Assembly.CorLibrary, cInternal.Assembly.CorLibrary); Assert.NotSame(cAll.Assembly.CorLibrary, cInternal.Assembly.CorLibrary); Assert.NotSame(cAll.Assembly.CorLibrary, cPublic.Assembly.CorLibrary); Assert.Same(cPublic.Assembly.CorLibrary, cPublic2.Assembly.CorLibrary); Assert.Same(cInternal.Assembly.CorLibrary, cInternal2.Assembly.CorLibrary); Assert.Same(cAll.Assembly.CorLibrary, cAll2.Assembly.CorLibrary); } [Fact] public void ImportingPrivateNetModuleMembers() { string moduleSource = @" internal class C { private void m() { } } "; string mainSource = @" "; var module = CreateCompilation(moduleSource, options: TestOptions.ReleaseModule); var moduleRef = module.EmitToImageReference(); // All var mainAll = CreateCompilation(mainSource, new[] { moduleRef }, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All)); var mAll = mainAll.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMembers("m"); Assert.Equal(1, mAll.Length); // Internal var mainInternal = CreateCompilation(mainSource, new[] { moduleRef }, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal)); var mInternal = mainInternal.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMembers("m"); Assert.Equal(0, mInternal.Length); // Public var mainPublic = CreateCompilation(mainSource, new[] { moduleRef }, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Public)); var mPublic = mainPublic.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMembers("m"); Assert.Equal(0, mPublic.Length); } [Fact] [WorkItem(531342, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531342"), WorkItem(727122, "DevDiv")] public void PortableLibrary() { var plSource = @"public class C {}"; var pl = CreateEmptyCompilation(plSource, new[] { MscorlibPP7Ref, SystemRuntimePP7Ref }); var r1 = new CSharpCompilationReference(pl); var mainSource = @"public class D : C { }"; // w/o facades: var main = CreateEmptyCompilation(mainSource, new MetadataReference[] { r1, MscorlibFacadeRef }, options: TestOptions.ReleaseDll); main.VerifyDiagnostics( // (1,18): error CS0012: The type 'System.Object' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'. Diagnostic(ErrorCode.ERR_NoTypeDef, "C").WithArguments("System.Object", "System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")); // facade specified: main = CreateEmptyCompilation(mainSource, new MetadataReference[] { r1, MscorlibFacadeRef, SystemRuntimeFacadeRef }); main.VerifyDiagnostics(); } [Fact] [WorkItem(762729, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/762729")] public void OverloadResolutionUseSiteWarning() { var libBTemplate = @" [assembly: System.Reflection.AssemblyVersion(""{0}.0.0.0"")] public class B {{ }} "; var libBv1 = CreateCompilation(string.Format(libBTemplate, "1"), assemblyName: "B", options: s_signedDll); var libBv2 = CreateCompilation(string.Format(libBTemplate, "2"), assemblyName: "B", options: s_signedDll); var libASource = @" [assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public class A { public void M(B b) { } } "; var libAv1 = CreateCompilation( libASource, new[] { new CSharpCompilationReference(libBv1) }, assemblyName: "A", options: s_signedDll); var source = @" public class Source { public void Test() { A a = new A(); a.M(null); } } "; var comp = CreateCompilation(source, new[] { new CSharpCompilationReference(libAv1), new CSharpCompilationReference(libBv2) }); comp.VerifyDiagnostics( // warning CS1701: Assuming assembly reference 'B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' used by 'A' matches identity 'B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' of 'B', you may need to supply runtime policy Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin).WithArguments("B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "A", "B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "B").WithLocation(1, 1)); } [Fact] [WorkItem(762729, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/762729")] public void MethodGroupConversionUseSiteWarning() { var libBTemplate = @" [assembly: System.Reflection.AssemblyVersion(""{0}.0.0.0"")] public class B {{ }} "; var libBv1 = CreateCompilation(string.Format(libBTemplate, "1"), assemblyName: "B", options: s_signedDll); var libBv2 = CreateCompilation(string.Format(libBTemplate, "2"), assemblyName: "B", options: s_signedDll); var libASource = @" [assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public class A { public void M(B b) { } } "; var libAv1 = CreateCompilation( libASource, new[] { new CSharpCompilationReference(libBv1) }, assemblyName: "A", options: s_signedDll); var source = @" public class Source { public void Test() { A a = new A(); System.Action<B> f = a.M; } } "; var comp = CreateCompilation(source, new[] { new CSharpCompilationReference(libAv1), new CSharpCompilationReference(libBv2) }); comp.VerifyDiagnostics( // warning CS1701: Assuming assembly reference 'B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' used by 'A' matches identity 'B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' of 'B', you may need to supply runtime policy Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin).WithArguments("B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "A", "B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "B").WithLocation(1, 1)); } [Fact] [WorkItem(762729, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/762729")] public void IndexerUseSiteWarning() { var libBTemplate = @" [assembly: System.Reflection.AssemblyVersion(""{0}.0.0.0"")] public class B {{ }} "; var libBv1 = CreateCompilation(string.Format(libBTemplate, "1"), assemblyName: "B", options: s_signedDll); var libBv2 = CreateCompilation(string.Format(libBTemplate, "2"), assemblyName: "B", options: s_signedDll); var libASource = @" [assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public class A { public int this[B b] { get { return 0; } } } "; var libAv1 = CreateCompilation(libASource, new[] { new CSharpCompilationReference(libBv1) }, assemblyName: "A", options: s_signedDll); var source = @" public class Source { public void Test() { A a = new A(); int x = a[null]; } } "; var comp = CreateCompilation(source, new[] { new CSharpCompilationReference(libAv1), new CSharpCompilationReference(libBv2) }); comp.VerifyDiagnostics( // warning CS1701: Assuming assembly reference 'B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' used by 'A' matches identity 'B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' of 'B', you may need to supply runtime policy Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin).WithArguments("B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "A", "B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "B").WithLocation(1, 1)); } [Fact] [WorkItem(762729, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/762729")] public void Repro762729() { var libBTemplate = @" [assembly: System.Reflection.AssemblyVersion(""{0}.0.0.0"")] // To be implemented in library A. public interface IGeneric<T> {{ void M(); }} // To be implemented by superclass of class implementing IGeneric<T>. public interface I {{ }} public static class Extensions {{ // To be invoked from the test assembly. public static void Extension<T>(this IGeneric<T> i) {{ i.M(); }} }} "; var libBv1 = CreateCompilationWithMscorlib40AndSystemCore(string.Format(libBTemplate, "1"), assemblyName: "B", options: s_signedDll); var libBv2 = CreateCompilationWithMscorlib40AndSystemCore(string.Format(libBTemplate, "2"), assemblyName: "B", options: s_signedDll); Assert.Equal("B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", libBv1.Assembly.Identity.GetDisplayName()); Assert.Equal("B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", libBv2.Assembly.Identity.GetDisplayName()); libBv1.EmitToImageReference(); libBv2.EmitToImageReference(); var libASource = @" [assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public class ABase : I { } public class A : ABase, IGeneric<AItem> { void IGeneric<AItem>.M() { } } // Type argument for IGeneric<T>. In the current assembly so there are no versioning issues. public class AItem { } "; var libAv1 = CreateCompilation(libASource, new[] { new CSharpCompilationReference(libBv1) }, assemblyName: "A", options: s_signedDll); libAv1.EmitToImageReference(); var source = @" public class Source { public void Test(A a) { a.Extension(); } } "; var comp = CreateCompilation(source, new[] { new CSharpCompilationReference(libAv1), new CSharpCompilationReference(libBv2) }); comp.VerifyEmitDiagnostics( // warning CS1701: Assuming assembly reference 'B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' used by 'A' matches identity 'B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' of 'B', you may need to supply runtime policy Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin).WithArguments("B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "A", "B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "B").WithLocation(1, 1), // warning CS1701: Assuming assembly reference 'B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' used by 'A' matches identity 'B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' of 'B', you may need to supply runtime policy Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin).WithArguments("B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "A", "B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "B").WithLocation(1, 1), // warning CS1701: Assuming assembly reference 'B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' used by 'A' matches identity 'B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' of 'B', you may need to supply runtime policy Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin).WithArguments("B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "A", "B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "B").WithLocation(1, 1)); } [WorkItem(905495, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/905495")] [Fact] public void ReferenceWithNoMetadataSection() { var c = CreateCompilation("", new[] { new TestImageReference(TestResources.Basic.NativeApp, "NativeApp.exe") }); c.VerifyDiagnostics( // error CS0009: Metadata file 'NativeApp.exe' could not be opened -- PE image doesn't contain managed metadata. Diagnostic(ErrorCode.FTL_MetadataCantOpenFile).WithArguments(@"NativeApp.exe", CodeAnalysisResources.PEImageDoesntContainManagedMetadata)); } [WorkItem(2988, "https://github.com/dotnet/roslyn/issues/2988")] [Fact] public void EmptyReference1() { var source = "class C { public static void Main() { } }"; var c = CreateCompilation(source, new[] { AssemblyMetadata.CreateFromImage(new byte[0]).GetReference(display: "Empty.dll") }); c.VerifyDiagnostics( Diagnostic(ErrorCode.FTL_MetadataCantOpenFile).WithArguments(@"Empty.dll", CodeAnalysisResources.PEImageDoesntContainManagedMetadata)); } [WorkItem(2992, "https://github.com/dotnet/roslyn/issues/2992")] [Fact] public void MetadataDisposed() { var md = AssemblyMetadata.CreateFromImage(TestResources.NetFX.Minimal.mincorlib); var compilation = CSharpCompilation.Create("test", references: new[] { md.GetReference() }); // Use the Compilation once to force lazy initialization of the underlying MetadataReader compilation.GetTypeByMetadataName("System.Int32").GetMembers(); md.Dispose(); Assert.Throws<ObjectDisposedException>(() => compilation.GetTypeByMetadataName("System.Int64").GetMembers()); } [WorkItem(43, "https://roslyn.codeplex.com/workitem/43")] [Fact] public void ReusingCorLibManager() { var corlib1 = CreateEmptyCompilation(""); var assembly1 = corlib1.Assembly; var corlib2 = corlib1.Clone(); var assembly2 = corlib2.Assembly; Assert.Same(assembly1.CorLibrary, assembly1); Assert.Same(assembly2.CorLibrary, assembly2); Assert.True(corlib1.ReferenceManagerEquals(corlib2)); } [WorkItem(5138, "https://github.com/dotnet/roslyn/issues/5138")] [Fact] public void AsymmetricUnification() { var vectors40 = CreateCompilation( @"[assembly: System.Reflection.AssemblyVersion(""4.0.0.0"")]", options: TestOptions.ReleaseDll.WithCryptoPublicKey(TestResources.TestKeys.PublicKey_b03f5f7f11d50a3a), assemblyName: "System.Numerics.Vectors"); Assert.Equal("System.Numerics.Vectors, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", vectors40.Assembly.Identity.GetDisplayName()); var vectors41 = CreateCompilation( @"[assembly: System.Reflection.AssemblyVersion(""4.1.0.0"")]", options: TestOptions.ReleaseDll.WithCryptoPublicKey(TestResources.TestKeys.PublicKey_b03f5f7f11d50a3a), assemblyName: "System.Numerics.Vectors"); Assert.Equal("System.Numerics.Vectors, Version=4.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", vectors41.Assembly.Identity.GetDisplayName()); var refVectors40 = vectors40.EmitToImageReference(); var refVectors41 = vectors41.EmitToImageReference(); var c1 = CreateEmptyCompilation("", TargetFrameworkUtil.StandardReferences.AddRange(new[] { refVectors40, refVectors41 }), options: TestOptions.ReleaseDll.WithAssemblyIdentityComparer(DesktopAssemblyIdentityComparer.Default)); c1.VerifyDiagnostics(); var a0 = c1.GetAssemblyOrModuleSymbol(refVectors40); var a1 = c1.GetAssemblyOrModuleSymbol(refVectors41); Assert.Equal("System.Numerics.Vectors, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", ((AssemblySymbol)a0).Identity.GetDisplayName()); Assert.Equal("System.Numerics.Vectors, Version=4.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", ((AssemblySymbol)a1).Identity.GetDisplayName()); var c2 = CreateEmptyCompilation("", TargetFrameworkUtil.StandardReferences.AddRange(new[] { refVectors41, refVectors40 }), options: TestOptions.ReleaseDll.WithAssemblyIdentityComparer(DesktopAssemblyIdentityComparer.Default)); c2.VerifyDiagnostics(); a0 = c2.GetAssemblyOrModuleSymbol(refVectors40); a1 = c2.GetAssemblyOrModuleSymbol(refVectors41); Assert.Equal("System.Numerics.Vectors, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", ((AssemblySymbol)a0).Identity.GetDisplayName()); Assert.Equal("System.Numerics.Vectors, Version=4.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", ((AssemblySymbol)a1).Identity.GetDisplayName()); } [Fact] public void ReferenceSupersession_FxUnification1() { var c = CreateSubmissionWithExactReferences("System.Diagnostics.Process.GetCurrentProcess()", new[] { Net20.mscorlib, Net20.System, Net451.mscorlib, Net451.System, }); c.VerifyDiagnostics(); c.VerifyAssemblyVersionsAndAliases( "mscorlib, Version=2.0.0.0: <superseded>", "System, Version=2.0.0.0: <superseded>", "mscorlib, Version=4.0.0.0", "System, Version=4.0.0.0"); } [Fact] public void ReferenceSupersession_StrongNames1() { var c = CreateSubmissionWithExactReferences("new C()", new[] { MscorlibRef_v4_0_30316_17626, TestReferences.SymbolsTests.Versioning.C2, TestReferences.SymbolsTests.Versioning.C1, }); c.VerifyDiagnostics(); c.VerifyAssemblyVersionsAndAliases( "mscorlib, Version=4.0.0.0", "C, Version=2.0.0.0", "C, Version=1.0.0.0: <superseded>"); } [Fact] public void ReferenceSupersession_WeakNames1() { var c = CreateSubmissionWithExactReferences("new C()", new[] { MscorlibRef_v4_0_30316_17626, CreateEmptyCompilation(@"[assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public class C {}", new[] { MscorlibRef }, assemblyName: "C").EmitToImageReference(), CreateEmptyCompilation(@"[assembly: System.Reflection.AssemblyVersion(""2.0.0.0"")] public class C {}", new[] { MscorlibRef }, assemblyName: "C").ToMetadataReference(), }); c.VerifyDiagnostics(); c.VerifyAssemblyVersionsAndAliases( "mscorlib, Version=4.0.0.0", "C, Version=1.0.0.0: <superseded>", "C, Version=2.0.0.0"); } [Fact] public void ReferenceSupersession_AliasesErased() { var c = CreateSubmissionWithExactReferences("new C()", new[] { MscorlibRef_v4_0_30316_17626, CreateEmptyCompilation(@"[assembly: System.Reflection.AssemblyVersion(""0.0.0.0"")] public class C {}", new[] { MscorlibRef }, assemblyName: "C").ToMetadataReference(), CreateEmptyCompilation(@"[assembly: System.Reflection.AssemblyVersion(""2.0.0.1"")] public class C {}", new[] { MscorlibRef }, assemblyName: "C").ToMetadataReference(), CreateEmptyCompilation(@"[assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public class C {}", new[] { MscorlibRef }, assemblyName: "C").ToMetadataReference(), CreateEmptyCompilation(@"[assembly: System.Reflection.AssemblyVersion(""2.0.0.0"")] public class C {}", new[] { MscorlibRef }, assemblyName: "C").ToMetadataReference(), CreateEmptyCompilation(@"[assembly: System.Reflection.AssemblyVersion(""1.1.0.0"")] public class C {}", new[] { MscorlibRef }, assemblyName: "C").ToMetadataReference(). WithProperties(MetadataReferenceProperties.Assembly.WithAliases(ImmutableArray.Create("Z")).WithRecursiveAliases(true)), }); c.VerifyDiagnostics(); c.VerifyAssemblyVersionsAndAliases( "mscorlib, Version=4.0.0.0: global,Z", "C, Version=0.0.0.0: <superseded>", "C, Version=2.0.0.1", "C, Version=1.0.0.0: <superseded>", "C, Version=2.0.0.0: <superseded>", "C, Version=1.1.0.0: <superseded>"); } [Fact] public void ReferenceSupersession_NoUnaliasedAssembly() { var c = CreateSubmissionWithExactReferences("new C()", new[] { MscorlibRef_v4_0_30316_17626, CreateCompilation(@"[assembly: System.Reflection.AssemblyVersion(""0.0.0.0"")] public class C {}", assemblyName: "C").ToMetadataReference(), CreateCompilation(@"[assembly: System.Reflection.AssemblyVersion(""2.0.0.1"")] public class C {}", assemblyName: "C").ToMetadataReference(aliases: ImmutableArray.Create("X", "Y")), CreateCompilation(@"[assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public class C {}", assemblyName: "C").ToMetadataReference(), CreateCompilation(@"[assembly: System.Reflection.AssemblyVersion(""2.0.0.0"")] public class C {}", assemblyName: "C").ToMetadataReference(), CreateCompilation(@"[assembly: System.Reflection.AssemblyVersion(""1.1.0.0"")] public class C {}", assemblyName: "C").ToMetadataReference(). WithProperties(MetadataReferenceProperties.Assembly.WithAliases(ImmutableArray.Create("Z")).WithRecursiveAliases(true)), }); c.VerifyDiagnostics( // (1,5): error CS0246: The type or namespace name 'C' could not be found (are you missing a using directive or an assembly reference?) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "C").WithArguments("C")); c.VerifyAssemblyVersionsAndAliases( "mscorlib, Version=4.0.0.0: global,Z", "C, Version=0.0.0.0: <superseded>", "C, Version=2.0.0.1: X,Y", "C, Version=1.0.0.0: <superseded>", "C, Version=2.0.0.0: <superseded>", "C, Version=1.1.0.0: <superseded>"); } [Fact] public void ReferenceDirective_RecursiveReferenceWithNoAliases() { // c - b (alias X) // - a (via #r) -> b var bRef = CreateCompilationWithMscorlib45("public class B { }", assemblyName: "B").EmitToImageReference(); var aRef = CreateCompilationWithMscorlib45("public class A : B { }", new[] { bRef }, assemblyName: "A").EmitToImageReference(); var source = @" #r ""a"" new B() "; var c = CreateSubmissionWithExactReferences(source, new[] { MscorlibRef_v4_0_30316_17626, bRef.WithAliases(ImmutableArray.Create("X")), aRef }, TestOptions.ReleaseDll.WithMetadataReferenceResolver( new TestMetadataReferenceResolver(assemblyNames: new Dictionary<string, PortableExecutableReference>() { { "a", (PortableExecutableReference)aRef.WithProperties(MetadataReferenceProperties.Assembly.WithRecursiveAliases(true)) } }))); c.VerifyDiagnostics(); c.VerifyAssemblyAliases( "mscorlib", "B: X,global", "A" ); } [Fact] public void ReferenceDirective_NonRecursiveReferenceWithNoAliases() { // c - b (alias X) // - a (via #r) -> b var bRef = CreateCompilationWithMscorlib45("public class B { }", assemblyName: "B").EmitToImageReference(); var aRef = CreateCompilationWithMscorlib45("public class A : B { }", new[] { bRef }, assemblyName: "A").EmitToImageReference(); var source = @" #r ""a"" new B() "; var c = CreateSubmissionWithExactReferences(source, new[] { MscorlibRef_v4_0_30316_17626, bRef.WithAliases(ImmutableArray.Create("X")), aRef }, TestOptions.ReleaseDll.WithMetadataReferenceResolver( new TestMetadataReferenceResolver(assemblyNames: new Dictionary<string, PortableExecutableReference>() { { "a", (PortableExecutableReference)aRef.WithProperties(MetadataReferenceProperties.Assembly) } }))); c.VerifyDiagnostics( // (3,5): error CS0246: The type or namespace name 'B' could not be found (are you missing a using directive or an assembly reference?) // new B() Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "B").WithArguments("B")); c.VerifyAssemblyAliases( "mscorlib", "B: X", "A"); } [Fact] public void ReferenceDirective_RecursiveReferenceWithAlias1() { // c - b (alias X) // - a // - a (recursive alias Y) -> b var bRef = CreateCompilationWithMscorlib45("public class B { }", assemblyName: "B").EmitToImageReference(); var aRef = CreateCompilationWithMscorlib45("public class A : B { }", new[] { bRef }, assemblyName: "A").EmitToImageReference(); var source = @" extern alias X; extern alias Y; public class P { A a = new Y::A(); X::B b = new Y::B(); } "; var c = CreateEmptyCompilation(source, new[] { bRef.WithAliases(ImmutableArray.Create("X")), aRef, aRef.WithProperties(MetadataReferenceProperties.Assembly.WithAliases(ImmutableArray.Create("Y")).WithRecursiveAliases(true)), MscorlibRef, }, TestOptions.ReleaseDll); c.VerifyDiagnostics(); c.VerifyAssemblyAliases( "B: X,Y", "A: global,Y", "mscorlib: global,Y"); } [Fact] public void ReferenceDirective_RecursiveReferenceWithAlias2() { // c - b (alias X) // - a (recursive alias Y) -> b // - a var bRef = CreateCompilationWithMscorlib45("public class B { }", assemblyName: "B").EmitToImageReference(); var aRef = CreateCompilationWithMscorlib45("public class A : B { }", new[] { bRef }, assemblyName: "A").EmitToImageReference(); var source = @" extern alias X; extern alias Y; public class P { A a = new Y::A(); X::B b = new Y::B(); } "; var c = CreateEmptyCompilation(source, new[] { bRef.WithAliases(ImmutableArray.Create("X")), aRef.WithProperties(MetadataReferenceProperties.Assembly.WithAliases(ImmutableArray.Create("Y")).WithRecursiveAliases(true)), aRef, MscorlibRef, }, TestOptions.ReleaseDll); c.VerifyDiagnostics(); c.VerifyAssemblyAliases( "B: X,Y", "A: global,Y", "mscorlib: global,Y"); } [Fact] public void ReferenceDirective_RecursiveReferenceWithAlias3() { // c - b (alias X) // - a (recursive alias Y) -> b // - a var bRef = CreateCompilationWithMscorlib45("public class B { }", assemblyName: "B").EmitToImageReference(); var aRef = CreateCompilationWithMscorlib45("public class A : B { }", new[] { bRef }, assemblyName: "A").EmitToImageReference(); var source = @" extern alias X; extern alias Y; public class P { A a = new Y::A(); X::B b = new Y::B(); } "; var c = CreateEmptyCompilation(source, new[] { bRef.WithAliases(ImmutableArray.Create("X")), aRef, aRef.WithProperties(MetadataReferenceProperties.Assembly.WithAliases(ImmutableArray.Create("Y")).WithRecursiveAliases(true)), aRef.WithProperties(MetadataReferenceProperties.Assembly.WithAliases(ImmutableArray.Create("Y")).WithRecursiveAliases(true)), aRef, MscorlibRef, }, TestOptions.ReleaseDll); c.VerifyDiagnostics(); c.VerifyAssemblyAliases( "B: X,Y", "A: global,Y", "mscorlib: global,Y"); } [Fact] public void ReferenceDirective_RecursiveReferenceWithAlias4() { // c - b (alias X) // - a (recursive alias Y) -> b // - d (recursive alias Z) -> a var bRef = CreateCompilationWithMscorlib45("public class B { }", assemblyName: "B").EmitToImageReference(); var aRef = CreateCompilationWithMscorlib45("public class A : B { }", new[] { bRef }, assemblyName: "A").EmitToImageReference(); var dRef = CreateCompilationWithMscorlib45("public class D : A { }", new[] { aRef, bRef }, assemblyName: "D").EmitToImageReference(); var source = @" extern alias X; extern alias Y; extern alias Z; public class P { Z::A a = new Y::A(); X::B b = new Y::B(); Z::B d = new X::B(); } "; var c = CreateEmptyCompilation(source, new[] { bRef.WithAliases(ImmutableArray.Create("X")), aRef.WithProperties(MetadataReferenceProperties.Assembly.WithAliases(ImmutableArray.Create("Y", "Y")).WithRecursiveAliases(true)), dRef.WithProperties(MetadataReferenceProperties.Assembly.WithAliases(ImmutableArray.Create("Z")).WithRecursiveAliases(true)), MscorlibRef, }, TestOptions.ReleaseDll); c.VerifyDiagnostics(); c.VerifyAssemblyAliases( "B: X,Y,Y,Z", "A: Y,Y,Z", "D: Z", "mscorlib: global,Y,Y,Z"); } [ConditionalFact(typeof(NoIOperationValidation), typeof(NoUsedAssembliesValidation), Reason = "IOperation adds extra assemblies")] public void MissingAssemblyResolution1() { // c - a -> b var bRef = CreateCompilationWithMscorlib46("public class B { }", assemblyName: "B").EmitToImageReference(); var aRef = CreateCompilationWithMscorlib46("public class A : B { }", new[] { bRef }, assemblyName: "A").EmitToImageReference(); var resolver = new TestMissingMetadataReferenceResolver(new Dictionary<string, MetadataReference> { { "B", bRef } }); var c = CreateCompilationWithMscorlib46("public class C : A { }", new[] { aRef }, TestOptions.ReleaseDll.WithMetadataReferenceResolver(resolver)); c.VerifyEmitDiagnostics(); Assert.Equal("B", ((AssemblySymbol)c.GetAssemblyOrModuleSymbol(bRef)).Name); resolver.VerifyResolutionAttempts( "A -> B, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"); } [ConditionalFact(typeof(NoIOperationValidation), typeof(NoUsedAssembliesValidation))] public void MissingAssemblyResolution_Aliases() { // c - a -> b with alias X var bRef = CreateCompilationWithMscorlib46("public class B { }", assemblyName: "B").EmitToImageReference(); var aRef = CreateCompilationWithMscorlib46("public class A : B { }", new[] { bRef }, assemblyName: "A").EmitToImageReference(); var resolver = new TestMissingMetadataReferenceResolver(new Dictionary<string, MetadataReference> { { "B", bRef.WithAliases(ImmutableArray.Create("X")) } }); var c = CreateCompilationWithMscorlib46(@" extern alias X; public class C : A { X::B F() => null; } ", new[] { aRef }, TestOptions.ReleaseDll.WithMetadataReferenceResolver(resolver)); c.VerifyEmitDiagnostics(); resolver.VerifyResolutionAttempts( "A -> B, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"); } [ConditionalFact(typeof(NoIOperationValidation), typeof(NoUsedAssembliesValidation))] public void MissingAssemblyResolution_AliasesMerge() { // c - a -> "b, V1" resolved to "b, V3" with alias X // - d -> "b, V2" resolved to "b, V3" with alias Y var b1Ref = CreateEmptyCompilation(@"[assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public class B { }", new[] { MscorlibRef }, options: s_signedDll, assemblyName: "B").EmitToImageReference(); var b2Ref = CreateEmptyCompilation(@"[assembly: System.Reflection.AssemblyVersion(""2.0.0.0"")] public class B { }", new[] { MscorlibRef }, options: s_signedDll, assemblyName: "B").EmitToImageReference(); var b3Ref = CreateEmptyCompilation(@"[assembly: System.Reflection.AssemblyVersion(""3.0.0.0"")] public class B { }", new[] { MscorlibRef }, options: s_signedDll, assemblyName: "B").EmitToImageReference(); var aRef = CreateEmptyCompilation("public class A : B { }", new[] { MscorlibRef, b1Ref }, assemblyName: "A").EmitToImageReference(); var dRef = CreateEmptyCompilation("public class D : B { }", new[] { MscorlibRef, b2Ref }, assemblyName: "D").EmitToImageReference(); var b3RefX = b3Ref.WithAliases(ImmutableArray.Create("X")); var b3RefY = b3Ref.WithAliases(ImmutableArray.Create("Y")); var resolver = new TestMissingMetadataReferenceResolver(new Dictionary<string, MetadataReference> { { "B, 1.0.0.0", b3RefX }, { "B, 2.0.0.0", b3RefY }, }); var c = CreateEmptyCompilation(@" extern alias X; extern alias Y; public class C : A { X::B F() => new Y::B(); } ", new[] { MscorlibRef, aRef, dRef }, TestOptions.ReleaseDll.WithMetadataReferenceResolver(resolver)); c.VerifyEmitDiagnostics( // warning CS1701: Assuming assembly reference // 'B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' used by 'A' matches identity // 'B, Version=3.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' of 'B', you may need to supply runtime policy Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin).WithArguments( "B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "A", "B, Version=3.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "B").WithLocation(1, 1)); Assert.Equal("B", ((AssemblySymbol)c.GetAssemblyOrModuleSymbol(b3RefY)).Name); Assert.Null(c.GetAssemblyOrModuleSymbol(b3RefX)); resolver.VerifyResolutionAttempts( "D -> B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "A -> B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2"); c.VerifyAssemblyVersionsAndAliases( "mscorlib, Version=4.0.0.0", "A, Version=0.0.0.0", "D, Version=0.0.0.0", "B, Version=3.0.0.0: Y,X"); } [ConditionalFact(typeof(NoIOperationValidation), typeof(NoUsedAssembliesValidation), Reason = "IOperation adds extra assemblies")] public void MissingAssemblyResolution_WeakIdentities1() { // c - a -> "b,v1,PKT=null" // - d -> "b,v2,PKT=null" var b1Ref = CreateEmptyCompilation(@"[assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public interface B { }", new[] { MscorlibRef }, assemblyName: "B").EmitToImageReference(); var b2Ref = CreateEmptyCompilation(@"[assembly: System.Reflection.AssemblyVersion(""2.0.0.0"")] public interface B { }", new[] { MscorlibRef }, assemblyName: "B").EmitToImageReference(); var b3Ref = CreateEmptyCompilation(@"[assembly: System.Reflection.AssemblyVersion(""3.0.0.0"")] public interface B { }", new[] { MscorlibRef }, assemblyName: "B").EmitToImageReference(); var b4Ref = CreateEmptyCompilation(@"[assembly: System.Reflection.AssemblyVersion(""4.0.0.0"")] public interface B { }", new[] { MscorlibRef }, assemblyName: "B").EmitToImageReference(); var aRef = CreateEmptyCompilation(@"public interface A : B { }", new[] { MscorlibRef, b1Ref }, assemblyName: "A").EmitToImageReference(); var dRef = CreateEmptyCompilation(@"public interface D : B { }", new[] { MscorlibRef, b2Ref }, assemblyName: "D").EmitToImageReference(); var resolver = new TestMissingMetadataReferenceResolver(new Dictionary<string, MetadataReference> { { "B, 1.0.0.0", b1Ref }, { "B, 2.0.0.0", b2Ref }, }); var c = CreateSubmissionWithExactReferences(@"public interface C : A, D { }", new[] { MscorlibRef_v4_0_30316_17626, aRef, dRef }, TestOptions.ReleaseDll.WithMetadataReferenceResolver(resolver)); c.VerifyEmitDiagnostics(); resolver.VerifyResolutionAttempts( "D -> B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null", "A -> B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"); c.VerifyAssemblyVersionsAndAliases( "mscorlib, Version=4.0.0.0", "A, Version=0.0.0.0", "D, Version=0.0.0.0", "B, Version=2.0.0.0", "B, Version=1.0.0.0: <superseded>"); } [ConditionalFact(typeof(NoIOperationValidation), typeof(NoUsedAssembliesValidation), Reason = "IOperation adds extra assemblies")] public void MissingAssemblyResolution_WeakIdentities2() { // c - a -> "b,v1,PKT=null" // - d -> "b,v2,PKT=null" var b1Ref = CreateEmptyCompilation(@"[assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public interface B { }", new[] { MscorlibRef }, assemblyName: "B").EmitToImageReference(); var b2Ref = CreateEmptyCompilation(@"[assembly: System.Reflection.AssemblyVersion(""2.0.0.0"")] public interface B { }", new[] { MscorlibRef }, assemblyName: "B").EmitToImageReference(); var b3Ref = CreateEmptyCompilation(@"[assembly: System.Reflection.AssemblyVersion(""3.0.0.0"")] public interface B { }", new[] { MscorlibRef }, assemblyName: "B").EmitToImageReference(); var b4Ref = CreateEmptyCompilation(@"[assembly: System.Reflection.AssemblyVersion(""4.0.0.0"")] public interface B { }", new[] { MscorlibRef }, assemblyName: "B").EmitToImageReference(); var aRef = CreateEmptyCompilation(@"public interface A : B { }", new[] { MscorlibRef, b1Ref }, assemblyName: "A").EmitToImageReference(); var dRef = CreateEmptyCompilation(@"public interface D : B { }", new[] { MscorlibRef, b2Ref }, assemblyName: "D").EmitToImageReference(); var resolver = new TestMissingMetadataReferenceResolver(new Dictionary<string, MetadataReference> { { "B, 1.0.0.0", b3Ref }, { "B, 2.0.0.0", b4Ref }, }); var c = CreateSubmissionWithExactReferences(@"public interface C : A, D { }", new[] { MscorlibRef_v4_0_30316_17626, aRef, dRef }, TestOptions.ReleaseDll.WithMetadataReferenceResolver(resolver)); c.VerifyEmitDiagnostics(); resolver.VerifyResolutionAttempts( "D -> B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null", "A -> B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"); c.VerifyAssemblyVersionsAndAliases( "mscorlib, Version=4.0.0.0", "A, Version=0.0.0.0", "D, Version=0.0.0.0", "B, Version=4.0.0.0", "B, Version=3.0.0.0: <superseded>"); } [Fact] public void MissingAssemblyResolution_None() { // c - a -> d // - d var dRef = CreateCompilationWithMscorlib46("public interface D { }", assemblyName: "D").EmitToImageReference(); var aRef = CreateCompilationWithMscorlib46("public interface A : D { }", new[] { dRef }, assemblyName: "A").ToMetadataReference(); var resolver = new TestMissingMetadataReferenceResolver(new Dictionary<string, MetadataReference>()); var c = CreateCompilationWithMscorlib46("public interface C : A { }", new[] { aRef, dRef }, TestOptions.ReleaseDll.WithMetadataReferenceResolver(resolver)); c.VerifyDiagnostics(); resolver.VerifyResolutionAttempts(); } [ConditionalFact(typeof(NoIOperationValidation), typeof(NoUsedAssembliesValidation), Reason = "IOperation adds extra assemblies")] public void MissingAssemblyResolution_ActualMissing() { // c - a -> d var dRef = CreateCompilationWithMscorlib46("public interface D { }", assemblyName: "D").EmitToImageReference(); var aRef = CreateCompilationWithMscorlib46("public interface A : D { }", new[] { dRef }, assemblyName: "A").ToMetadataReference(); var resolver = new TestMissingMetadataReferenceResolver(new Dictionary<string, MetadataReference>()); var c = CreateCompilationWithMscorlib46("public interface C : A { }", new[] { aRef }, TestOptions.ReleaseDll.WithMetadataReferenceResolver(resolver)); c.VerifyDiagnostics( // (1,18): error CS0012: The type 'D' is defined in an assembly that is not referenced. You must add a reference to assembly 'D, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Diagnostic(ErrorCode.ERR_NoTypeDef, "C").WithArguments("D", "D, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")); resolver.VerifyResolutionAttempts( "A -> D, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"); } /// <summary> /// Ignore assemblies returned by the resolver that don't match the reference identity. /// </summary> [ConditionalFact(typeof(NoIOperationValidation), typeof(NoUsedAssembliesValidation), Reason = "IOperation adds extra assemblies")] public void MissingAssemblyResolution_MissingDueToResolutionMismatch() { // c - a -> b var bRef = CreateCompilationWithMscorlib46("public interface D { }", assemblyName: "B").EmitToImageReference(); var aRef = CreateCompilationWithMscorlib46("public interface A : D { }", new[] { bRef }, assemblyName: "A").ToMetadataReference(); var eRef = CreateCompilationWithMscorlib46("public interface E { }", assemblyName: "E").ToMetadataReference(); var resolver = new TestMissingMetadataReferenceResolver(new Dictionary<string, MetadataReference> { { "B, 1.0.0.0", eRef }, }); var c = CreateCompilationWithMscorlib46(@"public interface C : A { }", new[] { aRef }, TestOptions.ReleaseDll.WithMetadataReferenceResolver(resolver)); c.VerifyDiagnostics( // (1,18): error CS0012: The type 'D' is defined in an assembly that is not referenced. You must add a reference to assembly 'B, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Diagnostic(ErrorCode.ERR_NoTypeDef, "C").WithArguments("D", "B, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")); resolver.VerifyResolutionAttempts( "A -> B, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"); } [ConditionalFact(typeof(NoIOperationValidation), typeof(NoUsedAssembliesValidation), Reason = "IOperation adds extra assemblies")] public void MissingAssemblyResolution_Multiple() { // c - a -> d // - b -> d var dRef = CreateCompilationWithMscorlib46("public interface D { }", assemblyName: "D").EmitToImageReference(); var aRef = CreateCompilationWithMscorlib46("public interface A : D { }", new[] { dRef }, assemblyName: "A").ToMetadataReference(); var bRef = CreateCompilationWithMscorlib46("public interface B : D { }", new[] { dRef }, assemblyName: "B").ToMetadataReference(); var resolver = new TestMissingMetadataReferenceResolver(new Dictionary<string, MetadataReference> { { "D", dRef } }); var c = CreateCompilationWithMscorlib46("public interface C : A, B { }", new[] { aRef, bRef }, TestOptions.ReleaseDll.WithMetadataReferenceResolver(resolver)); c.VerifyEmitDiagnostics(); Assert.Equal("D", ((AssemblySymbol)c.GetAssemblyOrModuleSymbol(dRef)).Name); resolver.VerifyResolutionAttempts( "B -> D, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"); } [ConditionalFact(typeof(NoIOperationValidation), typeof(NoUsedAssembliesValidation), Reason = "IOperation adds extra assemblies")] public void MissingAssemblyResolution_Modules() { // c - a - d // - module(m) - b // - module(n) - d var bRef = CreateCompilationWithMscorlib46("public interface B { }", assemblyName: "B").EmitToImageReference(); var dRef = CreateCompilationWithMscorlib46("public interface D { }", assemblyName: "D").EmitToImageReference(); var mRef = CreateCompilationWithMscorlib46("public interface M : B { }", new[] { bRef }, options: TestOptions.ReleaseModule.WithModuleName("M.netmodule")).EmitToImageReference(); var nRef = CreateCompilationWithMscorlib46("public interface N : D { }", new[] { dRef }, options: TestOptions.ReleaseModule.WithModuleName("N.netmodule")).EmitToImageReference(); var aRef = CreateCompilationWithMscorlib46("public interface A : D { }", new[] { dRef }, assemblyName: "A").EmitToImageReference(); var resolver = new TestMissingMetadataReferenceResolver(new Dictionary<string, MetadataReference> { { "B", bRef }, { "D", dRef }, }); var c = CreateCompilationWithMscorlib46("public interface C : A { }", new[] { aRef, mRef, nRef }, TestOptions.ReleaseDll.WithMetadataReferenceResolver(resolver)); c.VerifyEmitDiagnostics(); Assert.Equal("B", ((AssemblySymbol)c.GetAssemblyOrModuleSymbol(bRef)).Name); Assert.Equal("D", ((AssemblySymbol)c.GetAssemblyOrModuleSymbol(dRef)).Name); // We don't resolve one assembly reference identity twice, even if the requesting definition is different. resolver.VerifyResolutionAttempts( "A -> D, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "M.netmodule -> B, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"); } /// <summary> /// Don't try to resolve AssemblyRefs that already match explicitly specified definition. /// </summary> [Fact] public void MissingAssemblyResolution_BindingToForExplicitReference1() { // c - a -> "b,v1" // - "b,v3" // var b1Ref = CreateCompilationWithMscorlib46(@"[assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public class B { }", options: s_signedDll, assemblyName: "B").EmitToImageReference(); var b2Ref = CreateCompilationWithMscorlib46(@"[assembly: System.Reflection.AssemblyVersion(""2.0.0.0"")] public class B { }", options: s_signedDll, assemblyName: "B").EmitToImageReference(); var b3Ref = CreateCompilationWithMscorlib46(@"[assembly: System.Reflection.AssemblyVersion(""3.0.0.0"")] public class B { }", options: s_signedDll, assemblyName: "B").EmitToImageReference(); var aRef = CreateCompilationWithMscorlib46(@"[assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public class A : B { }", new[] { b1Ref }, options: s_signedDll, assemblyName: "A").EmitToImageReference(); var resolver = new TestMissingMetadataReferenceResolver(new Dictionary<string, MetadataReference> { // the compiler asked for v1, but we have v2 { "B, 1.0.0.0", b2Ref } }); var c = CreateCompilationWithMscorlib46("public class C : A { }", new[] { aRef, b3Ref }, s_signedDll.WithMetadataReferenceResolver(resolver)); c.VerifyEmitDiagnostics( // warning CS1701: Assuming assembly reference // 'B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' used by 'A' matches identity // 'B, Version=3.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' of 'B', you may need to supply runtime policy Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin).WithArguments( "B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "A", "B, Version=3.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "B").WithLocation(1, 1)); Assert.Equal( "B, Version=3.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", ((AssemblySymbol)c.GetAssemblyOrModuleSymbol(b3Ref)).Identity.GetDisplayName()); Assert.Null((AssemblySymbol)c.GetAssemblyOrModuleSymbol(b2Ref)); resolver.VerifyResolutionAttempts(); } /// <summary> /// Don't try to resolve AssemblyRefs that already match explicitly specified definition. /// </summary> [ConditionalFact(typeof(NoIOperationValidation), typeof(NoUsedAssembliesValidation))] public void MissingAssemblyResolution_BindingToExplicitReference_WorseVersion() { // c - a -> d -> "b,v2" // e -> "b,v1" // - "b,v1" var b1Ref = CreateEmptyCompilation(@"[assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public interface B { }", new[] { MscorlibRef }, options: s_signedDll, assemblyName: "B").EmitToImageReference(); var b2Ref = CreateEmptyCompilation(@"[assembly: System.Reflection.AssemblyVersion(""2.0.0.0"")] public interface B { }", new[] { MscorlibRef }, options: s_signedDll, assemblyName: "B").EmitToImageReference(); var dRef = CreateEmptyCompilation(@"[assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public interface D : B { }", new[] { MscorlibRef, b2Ref }, options: s_signedDll, assemblyName: "D").EmitToImageReference(); var eRef = CreateEmptyCompilation(@"[assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public interface E : B { }", new[] { MscorlibRef, b1Ref }, options: s_signedDll, assemblyName: "E").EmitToImageReference(); var resolverA = new TestMissingMetadataReferenceResolver(new Dictionary<string, MetadataReference> { { "B, 2.0.0.0", b2Ref }, { "B, 1.0.0.0", b1Ref }, }); var aRef = CreateEmptyCompilation(@"[assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public interface A : D, E { }", new[] { MscorlibRef, dRef, eRef }, s_signedDll.WithMetadataReferenceResolver(resolverA), assemblyName: "A").EmitToImageReference(); Assert.Equal(2, resolverA.ResolutionAttempts.Count); var resolverC = new TestMissingMetadataReferenceResolver(new Dictionary<string, MetadataReference> { { "D, 1.0.0.0", dRef }, { "E, 1.0.0.0", eRef }, }); var c = CreateEmptyCompilation("public class C : A { }", new[] { MscorlibRef, aRef, b1Ref }, s_signedDll.WithMetadataReferenceResolver(resolverC)); c.VerifyEmitDiagnostics( // error CS1705: Assembly // 'A' with identity 'A, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' uses // 'B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' which has a higher version than referenced assembly // 'B' with identity 'B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' Diagnostic(ErrorCode.ERR_AssemblyMatchBadVersion).WithArguments( "A", "A, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "B", "B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2").WithLocation(1, 1), // error CS1705: Assembly // 'D' with identity 'D, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' uses // 'B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' which has a higher version than referenced assembly // 'B' with identity 'B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' Diagnostic(ErrorCode.ERR_AssemblyMatchBadVersion).WithArguments( "D", "D, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "B", "B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2").WithLocation(1, 1)); resolverC.VerifyResolutionAttempts( "A -> D, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "A -> E, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2"); c.VerifyAssemblyVersionsAndAliases( "mscorlib, Version=4.0.0.0", "A, Version=1.0.0.0", "B, Version=1.0.0.0", "D, Version=1.0.0.0", "E, Version=1.0.0.0"); } /// <summary> /// Don't try to resolve AssemblyRefs that already match explicitly specified definition. /// </summary> [ConditionalFact(typeof(NoIOperationValidation), typeof(NoUsedAssembliesValidation))] public void MissingAssemblyResolution_BindingToExplicitReference_BetterVersion() { // c - a -> d -> "b,v2" // e -> "b,v1" // - "b,v2" var b1Ref = CreateEmptyCompilation(@"[assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public interface B { }", references: new[] { MscorlibRef }, options: s_signedDll, assemblyName: "B").EmitToImageReference(); var b2Ref = CreateEmptyCompilation(@"[assembly: System.Reflection.AssemblyVersion(""2.0.0.0"")] public interface B { }", references: new[] { MscorlibRef }, options: s_signedDll, assemblyName: "B").EmitToImageReference(); var dRef = CreateEmptyCompilation(@"[assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public interface D : B { }", new[] { MscorlibRef, b2Ref }, options: s_signedDll, assemblyName: "D").EmitToImageReference(); var eRef = CreateEmptyCompilation(@"[assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public interface E : B { }", new[] { MscorlibRef, b1Ref }, options: s_signedDll, assemblyName: "E").EmitToImageReference(); var resolverA = new TestMissingMetadataReferenceResolver(new Dictionary<string, MetadataReference> { { "B, 2.0.0.0", b2Ref }, { "B, 1.0.0.0", b1Ref }, }); var aRef = CreateEmptyCompilation(@"[assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public interface A : D, E { }", new[] { MscorlibRef, dRef, eRef }, s_signedDll.WithMetadataReferenceResolver(resolverA), assemblyName: "A").EmitToImageReference(); Assert.Equal(2, resolverA.ResolutionAttempts.Count); var resolverC = new TestMissingMetadataReferenceResolver(new Dictionary<string, MetadataReference> { { "D, 1.0.0.0", dRef }, { "E, 1.0.0.0", eRef }, }); var c = CreateEmptyCompilation("public class C : A { }", new[] { MscorlibRef, aRef, b2Ref }, s_signedDll.WithMetadataReferenceResolver(resolverC)); c.VerifyEmitDiagnostics( // warning CS1701: Assuming assembly reference // 'B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' used by // 'A' matches identity 'B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' of 'B', you may need to supply runtime policy Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin).WithArguments( "B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "A", "B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "B").WithLocation(1, 1), // warning CS1701: Assuming assembly reference // 'B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' used by 'E' matches identity // 'B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' of 'B', you may need to supply runtime policy Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin).WithArguments( "B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "E", "B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "B").WithLocation(1, 1)); resolverC.VerifyResolutionAttempts( "A -> D, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "A -> E, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2"); c.VerifyAssemblyVersionsAndAliases( "mscorlib, Version=4.0.0.0", "A, Version=1.0.0.0", "B, Version=2.0.0.0", "D, Version=1.0.0.0", "E, Version=1.0.0.0"); } [ConditionalFact(typeof(NoIOperationValidation), typeof(NoUsedAssembliesValidation), Reason = "IOperation adds extra assemblies")] public void MissingAssemblyResolution_BindingToImplicitReference1() { // c - a -> d -> "b,v2" // e -> "b,v1" // "b,v1" // "b,v2" var b1Ref = CreateEmptyCompilation(@"[assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public interface B { }", new[] { MscorlibRef }, options: s_signedDll, assemblyName: "B").EmitToImageReference(); var b2Ref = CreateEmptyCompilation(@"[assembly: System.Reflection.AssemblyVersion(""2.0.0.0"")] public interface B { }", new[] { MscorlibRef }, options: s_signedDll, assemblyName: "B").EmitToImageReference(); var dRef = CreateEmptyCompilation(@"[assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public interface D : B { }", new[] { MscorlibRef, b2Ref }, options: s_signedDll, assemblyName: "D").EmitToImageReference(); var eRef = CreateEmptyCompilation(@"[assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public interface E : B { }", new[] { MscorlibRef, b1Ref }, options: s_signedDll, assemblyName: "E").EmitToImageReference(); var aRef = CreateEmptyCompilation(@"[assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public interface A : D, E { }", new[] { MscorlibRef, dRef, eRef, b1Ref, b2Ref }, s_signedDll, assemblyName: "A").EmitToImageReference(); var resolverC = new TestMissingMetadataReferenceResolver(new Dictionary<string, MetadataReference> { { "D, 1.0.0.0", dRef }, { "E, 1.0.0.0", eRef }, { "B, 1.0.0.0", b1Ref }, { "B, 2.0.0.0", b2Ref }, }); var c = CreateSubmissionWithExactReferences("public class C : A { }", new[] { MscorlibRef_v4_0_30316_17626, aRef }, TestOptions.ReleaseDll.WithMetadataReferenceResolver(resolverC)); c.VerifyEmitDiagnostics(); resolverC.VerifyResolutionAttempts( "A -> D, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "A -> B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "A -> E, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "A -> B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2"); c.VerifyAssemblyVersionsAndAliases( "mscorlib, Version=4.0.0.0", "A, Version=1.0.0.0", "D, Version=1.0.0.0", "B, Version=2.0.0.0", "E, Version=1.0.0.0", "B, Version=1.0.0.0: <superseded>"); } [ConditionalFact(typeof(NoIOperationValidation), typeof(NoUsedAssembliesValidation), Reason = "IOperation adds extra assemblies")] public void MissingAssemblyResolution_BindingToImplicitReference2() { // c - a -> d -> "b,v2" // e -> "b,v1" // "b,v1" // "b,v2" var b1Ref = CreateEmptyCompilation(@"[assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public interface B { }", new[] { MscorlibRef }, options: s_signedDll, assemblyName: "B").EmitToImageReference(); var b2Ref = CreateEmptyCompilation(@"[assembly: System.Reflection.AssemblyVersion(""2.0.0.0"")] public interface B { }", new[] { MscorlibRef }, options: s_signedDll, assemblyName: "B").EmitToImageReference(); var b3Ref = CreateEmptyCompilation(@"[assembly: System.Reflection.AssemblyVersion(""3.0.0.0"")] public interface B { }", new[] { MscorlibRef }, options: s_signedDll, assemblyName: "B").EmitToImageReference(); var b4Ref = CreateEmptyCompilation(@"[assembly: System.Reflection.AssemblyVersion(""4.0.0.0"")] public interface B { }", new[] { MscorlibRef }, options: s_signedDll, assemblyName: "B").EmitToImageReference(); var dRef = CreateEmptyCompilation(@"[assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public interface D : B { }", new[] { MscorlibRef, b2Ref }, options: s_signedDll, assemblyName: "D").EmitToImageReference(); var eRef = CreateEmptyCompilation(@"[assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public interface E : B { }", new[] { MscorlibRef, b1Ref }, options: s_signedDll, assemblyName: "E").EmitToImageReference(); var aRef = CreateEmptyCompilation(@"[assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public interface A : D, E { }", new[] { MscorlibRef, dRef, eRef, b1Ref, b2Ref }, s_signedDll, assemblyName: "A").EmitToImageReference(); var resolverC = new TestMissingMetadataReferenceResolver(new Dictionary<string, MetadataReference> { { "D, 1.0.0.0", dRef }, { "E, 1.0.0.0", eRef }, { "B, 1.0.0.0", b3Ref }, { "B, 2.0.0.0", b4Ref }, }); var c = CreateEmptyCompilation("public class C : A { }", new[] { MscorlibRef, aRef }, s_signedDll.WithMetadataReferenceResolver(resolverC)); c.VerifyEmitDiagnostics( // warning CS1701: Assuming assembly reference // 'B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' used by 'A' matches identity // 'B, Version=3.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' of 'B', you may need to supply runtime policy Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin).WithArguments( "B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "A", "B, Version=3.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "B").WithLocation(1, 1), // warning CS1701: Assuming assembly reference // 'B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' used by 'D' matches identity // 'B, Version=3.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' of 'B', you may need to supply runtime policy Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin).WithArguments( "B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "D", "B, Version=3.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "B").WithLocation(1, 1), // warning CS1701: Assuming assembly reference // 'B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' used by 'E' matches identity // 'B, Version=3.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' of 'B', you may need to supply runtime policy Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin).WithArguments( "B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "E", "B, Version=3.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "B").WithLocation(1, 1)); c.VerifyAssemblyVersionsAndAliases( "mscorlib, Version=4.0.0.0", "A, Version=1.0.0.0", "D, Version=1.0.0.0", "B, Version=4.0.0.0", "E, Version=1.0.0.0", "B, Version=3.0.0.0"); resolverC.VerifyResolutionAttempts( "A -> D, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "A -> B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "A -> E, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "A -> B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2"); } [ConditionalFact(typeof(NoIOperationValidation), typeof(NoUsedAssembliesValidation), Reason = "IOperation adds extra assemblies")] public void MissingAssemblyResolution_BindingToImplicitReference3() { // c - a -> d -> "b,v2" // e -> "b,v1" // "b,v1" // "b,v2" var b1Ref = CreateEmptyCompilation(@"[assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public interface B { }", new[] { MscorlibRef }, options: s_signedDll, assemblyName: "B").EmitToImageReference(); var b2Ref = CreateEmptyCompilation(@"[assembly: System.Reflection.AssemblyVersion(""2.0.0.0"")] public interface B { }", new[] { MscorlibRef }, options: s_signedDll, assemblyName: "B").EmitToImageReference(); var b3Ref = CreateEmptyCompilation(@"[assembly: System.Reflection.AssemblyVersion(""3.0.0.0"")] public interface B { }", new[] { MscorlibRef }, options: s_signedDll, assemblyName: "B").EmitToImageReference(); var b4Ref = CreateEmptyCompilation(@"[assembly: System.Reflection.AssemblyVersion(""4.0.0.0"")] public interface B { }", new[] { MscorlibRef }, options: s_signedDll, assemblyName: "B").EmitToImageReference(); var dRef = CreateEmptyCompilation(@"[assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public interface D : B { }", new[] { MscorlibRef, b2Ref }, options: s_signedDll, assemblyName: "D").EmitToImageReference(); var eRef = CreateEmptyCompilation(@"[assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public interface E : B { }", new[] { MscorlibRef, b1Ref }, options: s_signedDll, assemblyName: "E").EmitToImageReference(); var aRef = CreateEmptyCompilation(@"[assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public interface A : D, E { }", new[] { MscorlibRef, dRef, eRef, b1Ref, b2Ref }, s_signedDll, assemblyName: "A").EmitToImageReference(); var resolverC = new TestMissingMetadataReferenceResolver(new Dictionary<string, MetadataReference> { { "D, 1.0.0.0", dRef }, { "E, 1.0.0.0", eRef }, { "B, 1.0.0.0", b3Ref }, { "B, 2.0.0.0", b4Ref }, }); var c = CreateSubmissionWithExactReferences("public class C : A { }", new[] { MscorlibRef_v4_0_30316_17626, aRef }, TestOptions.ReleaseDll.WithMetadataReferenceResolver(resolverC)); c.VerifyEmitDiagnostics( // warning CS1701: Assuming assembly reference // 'B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' used by 'A' matches identity // 'B, Version=3.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' of 'B', you may need to supply runtime policy Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin).WithArguments( "B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "A", "B, Version=3.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "B").WithLocation(1, 1), // warning CS1701: Assuming assembly reference // 'B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' used by 'D' matches identity // 'B, Version=3.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' of 'B', you may need to supply runtime policy Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin).WithArguments( "B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "D", "B, Version=3.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "B").WithLocation(1, 1), // warning CS1701: Assuming assembly reference // 'B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' used by 'E' matches identity // 'B, Version=3.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' of 'B', you may need to supply runtime policy Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin).WithArguments( "B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "E", "B, Version=3.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "B").WithLocation(1, 1)); c.VerifyAssemblyVersionsAndAliases( "mscorlib, Version=4.0.0.0", "A, Version=1.0.0.0", "D, Version=1.0.0.0", "B, Version=4.0.0.0", "E, Version=1.0.0.0", "B, Version=3.0.0.0: <superseded>"); resolverC.VerifyResolutionAttempts( "A -> D, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "A -> B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "A -> E, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "A -> B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2"); } [ConditionalFact(typeof(NoIOperationValidation), typeof(NoUsedAssembliesValidation), Reason = "IOperation adds extra assemblies")] public void MissingAssemblyResolution_Supersession_FxUnification() { var options = TestOptions.ReleaseDll.WithAssemblyIdentityComparer(DesktopAssemblyIdentityComparer.Default); // c - "mscorlib, v4" // a -> "mscorlib, v2" // "System, v2" // b -> "mscorlib, v4" // "System, v4" var aRef = CreateEmptyCompilation(@"public interface A { System.Diagnostics.Process PA { get; } }", new[] { Net20.mscorlib, Net20.System }, options: options, assemblyName: "A").EmitToImageReference(); var bRef = CreateEmptyCompilation(@"public interface B { System.Diagnostics.Process PB { get; } }", new[] { MscorlibRef_v4_0_30316_17626, Net451.System }, options: options, assemblyName: "B").EmitToImageReference(); var resolverC = new TestMissingMetadataReferenceResolver(new Dictionary<string, MetadataReference> { { "System, 2.0.0.0", Net20.System }, { "System, 4.0.0.0", Net451.System }, }); var c = CreateSubmissionWithExactReferences("public interface C : A, B { System.Diagnostics.Process PC { get; } }", new[] { MscorlibRef_v4_0_30316_17626, aRef, bRef }, options.WithMetadataReferenceResolver(resolverC)); c.VerifyEmitDiagnostics(); resolverC.VerifyResolutionAttempts( "B -> System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "System.dll (net451) -> System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.dll (net451) -> System.Xml, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "A -> System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "System.dll (net20) -> System.Configuration, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.dll (net20) -> System.Xml, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"); c.VerifyAssemblyVersionsAndAliases( "mscorlib, Version=4.0.0.0", "A, Version=0.0.0.0", "B, Version=0.0.0.0", "System, Version=4.0.0.0", "System, Version=2.0.0.0: <superseded>"); } [ConditionalFact(typeof(NoIOperationValidation), typeof(NoUsedAssembliesValidation), Reason = "IOperation adds extra assemblies")] public void MissingAssemblyResolution_Supersession_StrongNames() { var options = TestOptions.ReleaseDll.WithAssemblyIdentityComparer(DesktopAssemblyIdentityComparer.Default); // c - a -> "C, v2" // b -> "C, v1" var aRef = CreateEmptyCompilation(@"public interface A { C CA { get; } }", new[] { MscorlibRef, TestReferences.SymbolsTests.Versioning.C2 }, options: options, assemblyName: "A").EmitToImageReference(); var bRef = CreateEmptyCompilation(@"public interface B { C CB { get; } }", new[] { MscorlibRef, TestReferences.SymbolsTests.Versioning.C1 }, options: options, assemblyName: "B").EmitToImageReference(); var resolverC = new TestMissingMetadataReferenceResolver(new Dictionary<string, MetadataReference> { { "C, 1.0.0.0", TestReferences.SymbolsTests.Versioning.C1 }, { "C, 2.0.0.0", TestReferences.SymbolsTests.Versioning.C2 }, }); var c = CreateSubmissionWithExactReferences("public interface D : A, B { C CC { get; } }", new[] { MscorlibRef_v4_0_30316_17626, aRef, bRef }, options.WithMetadataReferenceResolver(resolverC)); c.VerifyEmitDiagnostics(); resolverC.VerifyResolutionAttempts( "B -> C, Version=1.0.0.0, Culture=neutral, PublicKeyToken=374d0c2befcd8cc9", "A -> C, Version=2.0.0.0, Culture=neutral, PublicKeyToken=374d0c2befcd8cc9"); c.VerifyAssemblyVersionsAndAliases( "mscorlib, Version=4.0.0.0", "A, Version=0.0.0.0", "B, Version=0.0.0.0", "C, Version=1.0.0.0: <superseded>", "C, Version=2.0.0.0"); } } }
-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/IntelliSense/CSharpCompletionCommandHandlerTests_AwaitCompletion.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.CSharp Namespace Microsoft.CodeAnalysis.Editor.UnitTests.IntelliSense <UseExportProvider> <Trait(Traits.Feature, Traits.Features.Completion)> Public Class CSharpCompletionCommandHandlerTests_Await <WpfFact> Public Async Function AwaitCompletionAddsAsync_MethodDeclaration() As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System.Threading.Tasks; public class C { public static Task Main() { $$ } } ]]> </Document>) state.SendTypeChars("aw") Await state.AssertSelectedCompletionItem(displayText:="await", isHardSelected:=True, inlineDescription:=FeaturesResources.Make_containing_scope_async) state.SendTab() Assert.Equal(" using System.Threading.Tasks; public class C { public static async Task Main() { await } } ", state.GetDocumentText()) End Using End Function <WpfFact> Public Async Function AwaitCompletionAddsAsync_LocalFunctionDeclaration() As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System.Threading.Tasks; public class C { public static Task Main() { Task LocalFunc() { $$ } } } ]]> </Document>) state.SendTypeChars("aw") Await state.AssertSelectedCompletionItem(displayText:="await", isHardSelected:=True, inlineDescription:=FeaturesResources.Make_containing_scope_async) state.SendTab() Assert.Equal(" using System.Threading.Tasks; public class C { public static Task Main() { async Task LocalFunc() { await } } } ", state.GetDocumentText()) End Using End Function <WpfFact> Public Async Function AwaitCompletionAddsAsync_AnonymousMethodExpression_Void() As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; public class C { public void F() { Action<int> a = static delegate(int i) { $$ }; } } ]]> </Document>) state.SendTypeChars("aw") Await state.AssertSelectedCompletionItem(displayText:="await", isHardSelected:=True, inlineDescription:=FeaturesResources.Make_containing_scope_async) state.SendTab() Assert.Equal(" using System; public class C { public void F() { Action<int> a = static async delegate(int i) { await }; } } ", state.GetDocumentText()) End Using End Function <WpfFact> Public Async Function AwaitCompletionAddsAsync_AnonymousMethodExpression_Task() As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; using System.Threading.Tasks; public class C { public void F() { Func<int, Task> a = static delegate(int i) { $$ }; } } ]]> </Document>) state.SendTypeChars("aw") Await state.AssertSelectedCompletionItem(displayText:="await", isHardSelected:=True, inlineDescription:=FeaturesResources.Make_containing_scope_async) state.SendTab() Assert.Equal(" using System; using System.Threading.Tasks; public class C { public void F() { Func<int, Task> a = static async delegate(int i) { await }; } } ", state.GetDocumentText()) End Using End Function <WpfFact> Public Async Function AwaitCompletionAddsAsync_SimpleLambdaExpression_Void() As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; public class C { public void F() { Action<int> b = static a => { $$ }; } } ]]> </Document>) state.SendTypeChars("aw") Await state.AssertSelectedCompletionItem(displayText:="await", isHardSelected:=True, inlineDescription:=FeaturesResources.Make_containing_scope_async) state.SendTab() Assert.Equal(" using System; public class C { public void F() { Action<int> b = static async a => { await }; } } ", state.GetDocumentText()) End Using End Function <WpfFact> Public Async Function AwaitCompletionAddsAsync_SimpleLambdaExpression_Task() As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; using System.Threading.Tasks; public class C { public void F() { Func<int, Task> b = static a => { $$ }; } } ]]> </Document>) state.SendTypeChars("aw") Await state.AssertSelectedCompletionItem(displayText:="await", isHardSelected:=True, inlineDescription:=FeaturesResources.Make_containing_scope_async) state.SendTab() Assert.Equal(" using System; using System.Threading.Tasks; public class C { public void F() { Func<int, Task> b = static async a => { await }; } } ", state.GetDocumentText()) End Using End Function <WpfFact> Public Async Function AwaitCompletionAddsAsync_ParenthesizedLambdaExpression_Void() As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; public class C { public void F() { Action<int> c = static (a) => { $$ }; } } ]]> </Document>) state.SendTypeChars("aw") Await state.AssertSelectedCompletionItem(displayText:="await", isHardSelected:=True, inlineDescription:=FeaturesResources.Make_containing_scope_async) state.SendTab() Assert.Equal(" using System; public class C { public void F() { Action<int> c = static async (a) => { await }; } } ", state.GetDocumentText()) End Using End Function <WpfFact> Public Async Function AwaitCompletionAddsAsync_ParenthesizedLambdaExpression_Task() As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; using System.Threading.Tasks; public class C { public void F() { Func<int, Task> c = static (a) => { $$ }; } } ]]> </Document>) state.SendTypeChars("aw") Await state.AssertSelectedCompletionItem(displayText:="await", isHardSelected:=True, inlineDescription:=FeaturesResources.Make_containing_scope_async) state.SendTab() Assert.Equal(" using System; using System.Threading.Tasks; public class C { public void F() { Func<int, Task> c = static async (a) => { await }; } } ", state.GetDocumentText()) End Using End Function <WpfFact> Public Async Function AwaitCompletionAddsAsync_ParenthesizedLambdaExpression_ExplicitType() As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; using System.Threading.Tasks; public class C { public void F() { Func<int, Task> c = static Task (a) => { $$ }; } } ]]> </Document>) state.SendTypeChars("aw") Await state.AssertSelectedCompletionItem(displayText:="await", isHardSelected:=True, inlineDescription:=FeaturesResources.Make_containing_scope_async) state.SendTab() Assert.Equal(" using System; using System.Threading.Tasks; public class C { public void F() { Func<int, Task> c = static async Task (a) => { await }; } } ", state.GetDocumentText()) End Using End Function <WpfFact> Public Async Function AwaitCompletionDoesNotAddAsync_NotTask() As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System.Threading.Tasks; public class C { public static void Main() { $$ } } ]]> </Document>) state.SendTypeChars("aw") Await state.AssertSelectedCompletionItem(displayText:="await", isHardSelected:=True, inlineDescription:=FeaturesResources.Make_containing_scope_async) state.SendTab() Assert.Equal(" using System.Threading.Tasks; public class C { public static async void Main() { await } } ", state.GetDocumentText()) End Using End Function <WpfFact> Public Async Function AwaitCompletionAddsAsync_Trivia() As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System.Threading.Tasks; public class C { public /*after public*/ static /*after static*/ Task /*after task*/ Main() { $$ } } ]]> </Document>) state.SendTypeChars("aw") Await state.AssertSelectedCompletionItem(displayText:="await", isHardSelected:=True, inlineDescription:=FeaturesResources.Make_containing_scope_async) state.SendTab() Assert.Equal(" using System.Threading.Tasks; public class C { public /*after public*/ static /*after static*/ async Task /*after task*/ Main() { await } } ", state.GetDocumentText()) 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.CSharp Namespace Microsoft.CodeAnalysis.Editor.UnitTests.IntelliSense <UseExportProvider> <Trait(Traits.Feature, Traits.Features.Completion)> Public Class CSharpCompletionCommandHandlerTests_Await <WpfFact> Public Async Function AwaitCompletionAddsAsync_MethodDeclaration() As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System.Threading.Tasks; public class C { public static Task Main() { $$ } } ]]> </Document>) state.SendTypeChars("aw") Await state.AssertSelectedCompletionItem(displayText:="await", isHardSelected:=True, inlineDescription:=FeaturesResources.Make_containing_scope_async) state.SendTab() Assert.Equal(" using System.Threading.Tasks; public class C { public static async Task Main() { await } } ", state.GetDocumentText()) End Using End Function <WpfFact> Public Async Function AwaitCompletionAddsAsync_LocalFunctionDeclaration() As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System.Threading.Tasks; public class C { public static Task Main() { Task LocalFunc() { $$ } } } ]]> </Document>) state.SendTypeChars("aw") Await state.AssertSelectedCompletionItem(displayText:="await", isHardSelected:=True, inlineDescription:=FeaturesResources.Make_containing_scope_async) state.SendTab() Assert.Equal(" using System.Threading.Tasks; public class C { public static Task Main() { async Task LocalFunc() { await } } } ", state.GetDocumentText()) End Using End Function <WpfFact> Public Async Function AwaitCompletionAddsAsync_AnonymousMethodExpression_Void() As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; public class C { public void F() { Action<int> a = static delegate(int i) { $$ }; } } ]]> </Document>) state.SendTypeChars("aw") Await state.AssertSelectedCompletionItem(displayText:="await", isHardSelected:=True, inlineDescription:=FeaturesResources.Make_containing_scope_async) state.SendTab() Assert.Equal(" using System; public class C { public void F() { Action<int> a = static async delegate(int i) { await }; } } ", state.GetDocumentText()) End Using End Function <WpfFact> Public Async Function AwaitCompletionAddsAsync_AnonymousMethodExpression_Task() As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; using System.Threading.Tasks; public class C { public void F() { Func<int, Task> a = static delegate(int i) { $$ }; } } ]]> </Document>) state.SendTypeChars("aw") Await state.AssertSelectedCompletionItem(displayText:="await", isHardSelected:=True, inlineDescription:=FeaturesResources.Make_containing_scope_async) state.SendTab() Assert.Equal(" using System; using System.Threading.Tasks; public class C { public void F() { Func<int, Task> a = static async delegate(int i) { await }; } } ", state.GetDocumentText()) End Using End Function <WpfFact> Public Async Function AwaitCompletionAddsAsync_SimpleLambdaExpression_Void() As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; public class C { public void F() { Action<int> b = static a => { $$ }; } } ]]> </Document>) state.SendTypeChars("aw") Await state.AssertSelectedCompletionItem(displayText:="await", isHardSelected:=True, inlineDescription:=FeaturesResources.Make_containing_scope_async) state.SendTab() Assert.Equal(" using System; public class C { public void F() { Action<int> b = static async a => { await }; } } ", state.GetDocumentText()) End Using End Function <WpfFact> Public Async Function AwaitCompletionAddsAsync_SimpleLambdaExpression_Task() As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; using System.Threading.Tasks; public class C { public void F() { Func<int, Task> b = static a => { $$ }; } } ]]> </Document>) state.SendTypeChars("aw") Await state.AssertSelectedCompletionItem(displayText:="await", isHardSelected:=True, inlineDescription:=FeaturesResources.Make_containing_scope_async) state.SendTab() Assert.Equal(" using System; using System.Threading.Tasks; public class C { public void F() { Func<int, Task> b = static async a => { await }; } } ", state.GetDocumentText()) End Using End Function <WpfFact> Public Async Function AwaitCompletionAddsAsync_ParenthesizedLambdaExpression_Void() As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; public class C { public void F() { Action<int> c = static (a) => { $$ }; } } ]]> </Document>) state.SendTypeChars("aw") Await state.AssertSelectedCompletionItem(displayText:="await", isHardSelected:=True, inlineDescription:=FeaturesResources.Make_containing_scope_async) state.SendTab() Assert.Equal(" using System; public class C { public void F() { Action<int> c = static async (a) => { await }; } } ", state.GetDocumentText()) End Using End Function <WpfFact> Public Async Function AwaitCompletionAddsAsync_ParenthesizedLambdaExpression_Task() As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; using System.Threading.Tasks; public class C { public void F() { Func<int, Task> c = static (a) => { $$ }; } } ]]> </Document>) state.SendTypeChars("aw") Await state.AssertSelectedCompletionItem(displayText:="await", isHardSelected:=True, inlineDescription:=FeaturesResources.Make_containing_scope_async) state.SendTab() Assert.Equal(" using System; using System.Threading.Tasks; public class C { public void F() { Func<int, Task> c = static async (a) => { await }; } } ", state.GetDocumentText()) End Using End Function <WpfFact> Public Async Function AwaitCompletionAddsAsync_ParenthesizedLambdaExpression_ExplicitType() As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; using System.Threading.Tasks; public class C { public void F() { Func<int, Task> c = static Task (a) => { $$ }; } } ]]> </Document>) state.SendTypeChars("aw") Await state.AssertSelectedCompletionItem(displayText:="await", isHardSelected:=True, inlineDescription:=FeaturesResources.Make_containing_scope_async) state.SendTab() Assert.Equal(" using System; using System.Threading.Tasks; public class C { public void F() { Func<int, Task> c = static async Task (a) => { await }; } } ", state.GetDocumentText()) End Using End Function <WpfFact> Public Async Function AwaitCompletionDoesNotAddAsync_NotTask() As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System.Threading.Tasks; public class C { public static void Main() { $$ } } ]]> </Document>) state.SendTypeChars("aw") Await state.AssertSelectedCompletionItem(displayText:="await", isHardSelected:=True, inlineDescription:=FeaturesResources.Make_containing_scope_async) state.SendTab() Assert.Equal(" using System.Threading.Tasks; public class C { public static async void Main() { await } } ", state.GetDocumentText()) End Using End Function <WpfFact> Public Async Function AwaitCompletionAddsAsync_Trivia() As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System.Threading.Tasks; public class C { public /*after public*/ static /*after static*/ Task /*after task*/ Main() { $$ } } ]]> </Document>) state.SendTypeChars("aw") Await state.AssertSelectedCompletionItem(displayText:="await", isHardSelected:=True, inlineDescription:=FeaturesResources.Make_containing_scope_async) state.SendTab() Assert.Equal(" using System.Threading.Tasks; public class C { public /*after public*/ static /*after static*/ async Task /*after task*/ Main() { await } } ", state.GetDocumentText()) 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/VisualStudio/Core/Impl/Options/OptionLogger.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.Internal.Log; using Microsoft.CodeAnalysis.Options; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Options { internal static class OptionLogger { private const string Name = nameof(Name); private const string Language = nameof(Language); private const string Change = nameof(Change); private const string All = nameof(All); public static void Log(OptionSet oldOptions, OptionSet newOptions) { foreach (var optionKey in newOptions.GetChangedOptions(oldOptions)) { var oldValue = oldOptions.GetOption(optionKey); var currentValue = newOptions.GetOption(optionKey); Logger.Log(FunctionId.Run_Environment_Options, Create(optionKey, oldValue, currentValue)); } } private static KeyValueLogMessage Create(OptionKey optionKey, object oldValue, object currentValue) { return KeyValueLogMessage.Create(m => { m[Name] = optionKey.Option.Name; m[Language] = optionKey.Language ?? All; m[Change] = CreateOptionValue(oldValue, currentValue); }); } private static string CreateOptionValue(object oldValue, object currentValue) { var oldString = GetOptionValue(oldValue); var newString = GetOptionValue(currentValue); return oldString + "->" + newString; } private static string GetOptionValue(object oldValue) => oldValue == null ? "[null]" : oldValue.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. #nullable disable using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Options; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Options { internal static class OptionLogger { private const string Name = nameof(Name); private const string Language = nameof(Language); private const string Change = nameof(Change); private const string All = nameof(All); public static void Log(OptionSet oldOptions, OptionSet newOptions) { foreach (var optionKey in newOptions.GetChangedOptions(oldOptions)) { var oldValue = oldOptions.GetOption(optionKey); var currentValue = newOptions.GetOption(optionKey); Logger.Log(FunctionId.Run_Environment_Options, Create(optionKey, oldValue, currentValue)); } } private static KeyValueLogMessage Create(OptionKey optionKey, object oldValue, object currentValue) { return KeyValueLogMessage.Create(m => { m[Name] = optionKey.Option.Name; m[Language] = optionKey.Language ?? All; m[Change] = CreateOptionValue(oldValue, currentValue); }); } private static string CreateOptionValue(object oldValue, object currentValue) { var oldString = GetOptionValue(oldValue); var newString = GetOptionValue(currentValue); return oldString + "->" + newString; } private static string GetOptionValue(object oldValue) => oldValue == null ? "[null]" : oldValue.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
./azure-pipelines-pr-validation.yml
resources: - repo: self clean: true # Variables defined in yml cannot be overridden at queue time instead overrideable variables must be defined in the web gui. # Commenting out until AzDO supports something like the runtime parameters outlined here: https://github.com/Microsoft/azure-pipelines-yaml/pull/129 #variables: # SignType: test # IbcDrop: 'default' parameters: - name: PRNumber type: number - name: CommitSHA type: string - name: VisualStudioBranchName type: string default: default - name: OptionalTitlePrefix type: string default: '[PR Validation]' - name: InsertToolset type: boolean default: true # The variables `_DotNetArtifactsCategory` and `_DotNetValidationArtifactsCategory` are required for proper publishing of build artifacts. See https://github.com/dotnet/roslyn/pull/38259 variables: - name: _DotNetArtifactsCategory value: .NETCore - name: _DotNetValidationArtifactsCategory value: .NETCoreValidation - group: DotNet-Roslyn-SDLValidation-Params # To retrieve OptProf data we need to authenticate to the VS drop storage. # If the pipeline is running in DevDiv, the account has access to the VS drop storage. # Get $AccessToken-dotnet-build-bot-public-repo from DotNet-GitHub-Versions-Repo-Write - group: DotNet-GitHub-Versions-Repo-Write - name: _DevDivDropAccessToken value: $(System.AccessToken) stages: - stage: build displayName: Build and Test jobs: - job: PRValidationBuild displayName: PR Validation Build timeoutInMinutes: 360 # Conditionally set build pool so we can share this YAML when building with different pipeline pool: name: VSEngSS-MicroBuild2017 demands: - msbuild - visualstudio - DotNetFramework steps: - powershell: Write-Host "##vso[task.setvariable variable=SourceBranchName]$('$(Build.SourceBranch)'.Substring('refs/heads/'.Length))" displayName: Setting SourceBranchName variable condition: succeeded() - task: tagBuildOrRelease@0 displayName: Tag PR validation build inputs: type: 'Build' tags: | PRValidationBuild PRNumber:${{ parameters.PRNumber }} CommitSHA:${{ parameters.CommitSHA }} condition: succeeded() - task: PowerShell@2 displayName: Setup branch for insertion validation inputs: filePath: 'eng\setup-pr-validation.ps1' arguments: '-sourceBranchName $(SourceBranchName) -prNumber ${{ parameters.PRNumber }} -commitSHA ${{ parameters.CommitSHA }}' condition: succeeded() - powershell: Write-Host "##vso[task.setvariable variable=VisualStudio.DropName]Products/$(System.TeamProject)/$(Build.Repository.Name)/$(SourceBranchName)/$(Build.BuildNumber)" displayName: Setting VisualStudio.DropName variable - task: NuGetToolInstaller@0 inputs: versionSpec: '4.9.2' # Authenticate with service connections to be able to publish packages to external nuget feeds. - task: NuGetAuthenticate@0 inputs: nuGetServiceConnections: azure-public/vs-impl, azure-public/vssdk # Needed to restore the Microsoft.DevDiv.Optimization.Data.PowerShell package - task: NuGetCommand@2 displayName: Restore internal tools inputs: command: restore feedsToUse: config restoreSolution: 'eng\common\internal\Tools.csproj' nugetConfigPath: 'NuGet.config' restoreDirectory: '$(Build.SourcesDirectory)\.packages' - task: MicroBuildSigningPlugin@2 inputs: signType: $(SignType) zipSources: false condition: and(succeeded(), in(variables['SignType'], 'test', 'real')) - task: PowerShell@2 displayName: Build inputs: filePath: eng/build.ps1 arguments: -ci -restore -build -pack -sign -publish -binaryLog -configuration $(BuildConfiguration) -officialBuildId $(Build.BuildNumber) -officialSkipTests $(SkipTests) -officialSkipApplyOptimizationData $(SkipApplyOptimizationData) -officialSourceBranchName $(SourceBranchName) -officialIbcDrop $(IbcDrop) -officialVisualStudioDropAccessToken $(_DevDivDropAccessToken) /p:RepositoryName=$(Build.Repository.Name) /p:VisualStudioDropName=$(VisualStudio.DropName) /p:DotNetSignType=$(SignType) /p:DotNetPublishToBlobFeed=false /p:PublishToSymbolServer=false /p:DotNetSymbolServerTokenMsdl=$(microsoft-symbol-server-pat) /p:DotNetSymbolServerTokenSymWeb=$(symweb-symbol-server-pat) /p:DotNetArtifactsCategory=$(_DotNetArtifactsCategory) /p:DotnetPublishUsingPipelines=false /p:IgnoreIbcMergeErrors=true /p:PreReleaseVersionLabel=pr-validation /p:IgnoreIbcMergeErrors=true condition: succeeded() # Publish OptProf generated JSON files as a build artifact. This allows for easy inspection from # a build execution. - task: PublishBuildArtifacts@1 displayName: Publish OptProf Data Files inputs: PathtoPublish: '$(Build.SourcesDirectory)\artifacts\OptProf\$(BuildConfiguration)\Data' ArtifactName: 'OptProf Data Files' condition: succeeded() - task: PublishBuildArtifacts@1 displayName: Publish Logs inputs: PathtoPublish: '$(Build.SourcesDirectory)\artifacts\log\$(BuildConfiguration)' ArtifactName: 'Build Diagnostic Files' publishLocation: Container continueOnError: true condition: succeededOrFailed() - task: PublishBuildArtifacts@1 displayName: Publish Ngen Logs inputs: PathtoPublish: '$(Build.SourcesDirectory)\artifacts\log\$(BuildConfiguration)\ngen' ArtifactName: 'NGen Logs' publishLocation: Container continueOnError: true condition: succeeded() - task: PublishTestResults@2 displayName: Publish xUnit Test Results inputs: testRunner: XUnit testResultsFiles: '$(Build.SourcesDirectory)\artifacts\TestResults\$(BuildConfiguration)\*.xml' mergeTestResults: true testRunTitle: 'Unit Tests' condition: and(succeededOrFailed(), ne(variables['SkipTests'], 'true')) # Publishes setup VSIXes to a drop. # Note: The insertion tool looks for the display name of this task in the logs. - task: ms-vseng.MicroBuildTasks.4305a8de-ba66-4d8b-b2d1-0dc4ecbbf5e8.MicroBuildUploadVstsDropFolder@1 displayName: Upload VSTS Drop inputs: DropName: $(VisualStudio.DropName) DropFolder: 'artifacts\VSSetup\$(BuildConfiguration)\Insertion' AccessToken: $(_DevDivDropAccessToken) condition: succeeded() # Publish insertion packages to CoreXT store. - task: NuGetCommand@2 displayName: Publish CoreXT Packages inputs: command: push packagesToPush: '$(Build.SourcesDirectory)\artifacts\VSSetup\$(BuildConfiguration)\DevDivPackages\**\*.nupkg' allowPackageConflicts: true feedsToUse: config publishVstsFeed: '97a41293-2972-4f48-8c0e-05493ae82010' condition: succeeded() # Publish an artifact that the RoslynInsertionTool is able to find by its name. - task: PublishBuildArtifacts@1 displayName: Publish Artifact VSSetup inputs: PathtoPublish: 'artifacts\VSSetup\$(BuildConfiguration)' ArtifactName: 'VSSetup' condition: succeeded() - task: ms-vseng.MicroBuildTasks.521a94ea-9e68-468a-8167-6dcf361ea776.MicroBuildCleanup@1 displayName: Perform Cleanup Tasks condition: succeededOrFailed() - stage: insert displayName: Create Insertion dependsOn: - build jobs: - job: insert displayName: Insert to VS pool: vmImage: windows-2019 steps: - powershell: Write-Host "##vso[task.setvariable variable=SourceBranchName]$('$(Build.SourceBranch)'.Substring('refs/heads/'.Length))" displayName: Setting SourceBranchName variable condition: succeeded() - template: eng/pipelines/insert.yml parameters: createDraftPR: true autoComplete: false insertToolset: ${{ parameters.InsertToolset }} clientId: $(ClientId) clientSecret: $(ClientSecret) vsBranchName: ${{ parameters.VisualStudioBranchName }} titlePrefix: ${{ parameters.OptionalTitlePrefix }} sourceBranch: $(SourceBranchName) publishDataURI: "https://raw.githubusercontent.com/dotnet/roslyn/main/eng/config/PublishData.json"
resources: - repo: self clean: true # Variables defined in yml cannot be overridden at queue time instead overrideable variables must be defined in the web gui. # Commenting out until AzDO supports something like the runtime parameters outlined here: https://github.com/Microsoft/azure-pipelines-yaml/pull/129 #variables: # SignType: test # IbcDrop: 'default' parameters: - name: PRNumber type: number - name: CommitSHA type: string - name: VisualStudioBranchName type: string default: default - name: OptionalTitlePrefix type: string default: '[PR Validation]' - name: InsertToolset type: boolean default: true # The variables `_DotNetArtifactsCategory` and `_DotNetValidationArtifactsCategory` are required for proper publishing of build artifacts. See https://github.com/dotnet/roslyn/pull/38259 variables: - name: _DotNetArtifactsCategory value: .NETCore - name: _DotNetValidationArtifactsCategory value: .NETCoreValidation - group: DotNet-Roslyn-SDLValidation-Params # To retrieve OptProf data we need to authenticate to the VS drop storage. # If the pipeline is running in DevDiv, the account has access to the VS drop storage. # Get $AccessToken-dotnet-build-bot-public-repo from DotNet-GitHub-Versions-Repo-Write - group: DotNet-GitHub-Versions-Repo-Write - name: _DevDivDropAccessToken value: $(System.AccessToken) stages: - stage: build displayName: Build and Test jobs: - job: PRValidationBuild displayName: PR Validation Build timeoutInMinutes: 360 # Conditionally set build pool so we can share this YAML when building with different pipeline pool: name: VSEngSS-MicroBuild2017 demands: - msbuild - visualstudio - DotNetFramework steps: - powershell: Write-Host "##vso[task.setvariable variable=SourceBranchName]$('$(Build.SourceBranch)'.Substring('refs/heads/'.Length))" displayName: Setting SourceBranchName variable condition: succeeded() - task: tagBuildOrRelease@0 displayName: Tag PR validation build inputs: type: 'Build' tags: | PRValidationBuild PRNumber:${{ parameters.PRNumber }} CommitSHA:${{ parameters.CommitSHA }} condition: succeeded() - task: PowerShell@2 displayName: Setup branch for insertion validation inputs: filePath: 'eng\setup-pr-validation.ps1' arguments: '-sourceBranchName $(SourceBranchName) -prNumber ${{ parameters.PRNumber }} -commitSHA ${{ parameters.CommitSHA }}' condition: succeeded() - powershell: Write-Host "##vso[task.setvariable variable=VisualStudio.DropName]Products/$(System.TeamProject)/$(Build.Repository.Name)/$(SourceBranchName)/$(Build.BuildNumber)" displayName: Setting VisualStudio.DropName variable - task: NuGetToolInstaller@0 inputs: versionSpec: '4.9.2' # Authenticate with service connections to be able to publish packages to external nuget feeds. - task: NuGetAuthenticate@0 inputs: nuGetServiceConnections: azure-public/vs-impl, azure-public/vssdk # Needed to restore the Microsoft.DevDiv.Optimization.Data.PowerShell package - task: NuGetCommand@2 displayName: Restore internal tools inputs: command: restore feedsToUse: config restoreSolution: 'eng\common\internal\Tools.csproj' nugetConfigPath: 'NuGet.config' restoreDirectory: '$(Build.SourcesDirectory)\.packages' - task: MicroBuildSigningPlugin@2 inputs: signType: $(SignType) zipSources: false condition: and(succeeded(), in(variables['SignType'], 'test', 'real')) - task: PowerShell@2 displayName: Build inputs: filePath: eng/build.ps1 arguments: -ci -restore -build -pack -sign -publish -binaryLog -configuration $(BuildConfiguration) -officialBuildId $(Build.BuildNumber) -officialSkipTests $(SkipTests) -officialSkipApplyOptimizationData $(SkipApplyOptimizationData) -officialSourceBranchName $(SourceBranchName) -officialIbcDrop $(IbcDrop) -officialVisualStudioDropAccessToken $(_DevDivDropAccessToken) /p:RepositoryName=$(Build.Repository.Name) /p:VisualStudioDropName=$(VisualStudio.DropName) /p:DotNetSignType=$(SignType) /p:DotNetPublishToBlobFeed=false /p:PublishToSymbolServer=false /p:DotNetSymbolServerTokenMsdl=$(microsoft-symbol-server-pat) /p:DotNetSymbolServerTokenSymWeb=$(symweb-symbol-server-pat) /p:DotNetArtifactsCategory=$(_DotNetArtifactsCategory) /p:DotnetPublishUsingPipelines=false /p:IgnoreIbcMergeErrors=true /p:PreReleaseVersionLabel=pr-validation /p:IgnoreIbcMergeErrors=true condition: succeeded() # Publish OptProf generated JSON files as a build artifact. This allows for easy inspection from # a build execution. - task: PublishBuildArtifacts@1 displayName: Publish OptProf Data Files inputs: PathtoPublish: '$(Build.SourcesDirectory)\artifacts\OptProf\$(BuildConfiguration)\Data' ArtifactName: 'OptProf Data Files' condition: succeeded() - task: PublishBuildArtifacts@1 displayName: Publish Logs inputs: PathtoPublish: '$(Build.SourcesDirectory)\artifacts\log\$(BuildConfiguration)' ArtifactName: 'Build Diagnostic Files' publishLocation: Container continueOnError: true condition: succeededOrFailed() - task: PublishBuildArtifacts@1 displayName: Publish Ngen Logs inputs: PathtoPublish: '$(Build.SourcesDirectory)\artifacts\log\$(BuildConfiguration)\ngen' ArtifactName: 'NGen Logs' publishLocation: Container continueOnError: true condition: succeeded() - task: PublishTestResults@2 displayName: Publish xUnit Test Results inputs: testRunner: XUnit testResultsFiles: '$(Build.SourcesDirectory)\artifacts\TestResults\$(BuildConfiguration)\*.xml' mergeTestResults: true testRunTitle: 'Unit Tests' condition: and(succeededOrFailed(), ne(variables['SkipTests'], 'true')) # Publishes setup VSIXes to a drop. # Note: The insertion tool looks for the display name of this task in the logs. - task: ms-vseng.MicroBuildTasks.4305a8de-ba66-4d8b-b2d1-0dc4ecbbf5e8.MicroBuildUploadVstsDropFolder@1 displayName: Upload VSTS Drop inputs: DropName: $(VisualStudio.DropName) DropFolder: 'artifacts\VSSetup\$(BuildConfiguration)\Insertion' AccessToken: $(_DevDivDropAccessToken) condition: succeeded() # Publish insertion packages to CoreXT store. - task: NuGetCommand@2 displayName: Publish CoreXT Packages inputs: command: push packagesToPush: '$(Build.SourcesDirectory)\artifacts\VSSetup\$(BuildConfiguration)\DevDivPackages\**\*.nupkg' allowPackageConflicts: true feedsToUse: config publishVstsFeed: '97a41293-2972-4f48-8c0e-05493ae82010' condition: succeeded() # Publish an artifact that the RoslynInsertionTool is able to find by its name. - task: PublishBuildArtifacts@1 displayName: Publish Artifact VSSetup inputs: PathtoPublish: 'artifacts\VSSetup\$(BuildConfiguration)' ArtifactName: 'VSSetup' condition: succeeded() - task: ms-vseng.MicroBuildTasks.521a94ea-9e68-468a-8167-6dcf361ea776.MicroBuildCleanup@1 displayName: Perform Cleanup Tasks condition: succeededOrFailed() - stage: insert displayName: Create Insertion dependsOn: - build jobs: - job: insert displayName: Insert to VS pool: vmImage: windows-2019 steps: - powershell: Write-Host "##vso[task.setvariable variable=SourceBranchName]$('$(Build.SourceBranch)'.Substring('refs/heads/'.Length))" displayName: Setting SourceBranchName variable condition: succeeded() - template: eng/pipelines/insert.yml parameters: createDraftPR: true autoComplete: false insertToolset: ${{ parameters.InsertToolset }} clientId: $(ClientId) clientSecret: $(ClientSecret) vsBranchName: ${{ parameters.VisualStudioBranchName }} titlePrefix: ${{ parameters.OptionalTitlePrefix }} sourceBranch: $(SourceBranchName) publishDataURI: "https://raw.githubusercontent.com/dotnet/roslyn/main/eng/config/PublishData.json"
-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/Lowering/LocalRewriter/LocalRewriter_LateAddressOf.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.Diagnostics Imports System.Runtime.InteropServices Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports TypeKind = Microsoft.CodeAnalysis.TypeKind Namespace Microsoft.CodeAnalysis.VisualBasic Partial Friend NotInheritable Class LocalRewriter Public Overrides Function VisitLateAddressOfOperator(node As BoundLateAddressOfOperator) As BoundNode If _inExpressionLambda Then ' just preserve the node to report an error in ExpressionLambdaRewriter Return MyBase.VisitLateAddressOfOperator(node) End If Dim targetType = DirectCast(node.Type, NamedTypeSymbol) Dim lambda = BuildDelegateRelaxationLambda(node.Syntax, targetType, node.MemberAccess, node.Binder, Me._diagnostics) Return Me.VisitExpressionNode(lambda) End Function Private Shared Function BuildDelegateRelaxationLambda( syntaxNode As SyntaxNode, targetType As NamedTypeSymbol, boundMember As BoundLateMemberAccess, binder As Binder, diagnostics As BindingDiagnosticBag ) As BoundExpression Dim delegateInvoke = targetType.DelegateInvokeMethod Debug.Assert(delegateInvoke.MethodKind = MethodKind.DelegateInvoke) ' build lambda symbol parameters matching the invocation method exactly. To do this, ' we'll create a BoundLambdaParameterSymbol for each parameter of the invoke method. Dim delegateInvokeReturnType = delegateInvoke.ReturnType Dim invokeParameters = delegateInvoke.Parameters Dim invokeParameterCount = invokeParameters.Length Dim lambdaSymbolParameters(invokeParameterCount - 1) As BoundLambdaParameterSymbol Dim addressOfLocation As Location = syntaxNode.GetLocation() For parameterIndex = 0 To invokeParameterCount - 1 Dim parameter = invokeParameters(parameterIndex) lambdaSymbolParameters(parameterIndex) = New BoundLambdaParameterSymbol(GeneratedNames.MakeDelegateRelaxationParameterName(parameterIndex), parameter.Ordinal, parameter.Type, parameter.IsByRef, syntaxNode, addressOfLocation) Next ' even if the return value is dropped, we're using the delegate's return type for ' this lambda symbol. Dim lambdaSymbol = New SynthesizedLambdaSymbol(SynthesizedLambdaKind.LateBoundAddressOfLambda, syntaxNode, lambdaSymbolParameters.AsImmutableOrNull, delegateInvokeReturnType, binder) ' the body of the lambda only contains a call to the target (or a return of the return value of ' the call in case of a function) ' for each parameter of the lambda symbol/invoke method we will create a bound parameter, except ' we are implementing a zero argument relaxation. ' These parameters will be used in the method invocation as passed parameters. Dim lambdaBoundParameters(invokeParameterCount - 1) As BoundExpression For parameterIndex = 0 To lambdaSymbolParameters.Length - 1 Dim lambdaSymbolParameter = lambdaSymbolParameters(parameterIndex) Dim boundParameter = New BoundParameter(syntaxNode, lambdaSymbolParameter, lambdaSymbolParameter.Type) boundParameter.SetWasCompilerGenerated() lambdaBoundParameters(parameterIndex) = boundParameter Next 'The invocation of the target method must be bound in the context of the lambda 'The reason is that binding the invoke may introduce local symbols and they need 'to be properly parented to the lambda and not to the outer method. Dim lambdaBinder = New LambdaBodyBinder(lambdaSymbol, binder) ' Dev10 ignores the type characters used in the operand of an AddressOf operator. ' NOTE: we suppress suppressAbstractCallDiagnostics because it ' should have been reported already Dim boundInvocationExpression As BoundExpression = lambdaBinder.BindLateBoundInvocation(syntaxNode, Nothing, boundMember, lambdaBoundParameters.AsImmutableOrNull, Nothing, diagnostics, suppressLateBindingResolutionDiagnostics:=True) boundInvocationExpression.SetWasCompilerGenerated() ' In case of a function target that got assigned to a sub delegate, the return value will be dropped Dim statementList As ImmutableArray(Of BoundStatement) = Nothing If lambdaSymbol.IsSub Then If boundInvocationExpression.IsLateBound() Then boundInvocationExpression = boundInvocationExpression.SetLateBoundAccessKind(LateBoundAccessKind.Call) End If Dim statements(1) As BoundStatement Dim boundStatement As BoundStatement = New BoundExpressionStatement(syntaxNode, boundInvocationExpression) boundStatement.SetWasCompilerGenerated() statements(0) = boundStatement boundStatement = New BoundReturnStatement(syntaxNode, Nothing, Nothing, Nothing) boundStatement.SetWasCompilerGenerated() statements(1) = boundStatement statementList = statements.AsImmutableOrNull Else ' process conversions between the return types of the target and invoke function if needed. boundInvocationExpression = lambdaBinder.ApplyImplicitConversion(syntaxNode, delegateInvokeReturnType, boundInvocationExpression, diagnostics) Dim returnstmt As BoundStatement = New BoundReturnStatement(syntaxNode, boundInvocationExpression, Nothing, Nothing) returnstmt.SetWasCompilerGenerated() statementList = ImmutableArray.Create(returnstmt) End If Dim lambdaBody = New BoundBlock(syntaxNode, Nothing, ImmutableArray(Of LocalSymbol).Empty, statementList) lambdaBody.SetWasCompilerGenerated() Dim boundLambda = New BoundLambda(syntaxNode, lambdaSymbol, lambdaBody, ImmutableBindingDiagnostic(Of AssemblySymbol).Empty, Nothing, ConversionKind.DelegateRelaxationLevelWidening, MethodConversionKind.Identity) boundLambda.SetWasCompilerGenerated() Dim result = New BoundDirectCast(syntaxNode, boundLambda, ConversionKind.DelegateRelaxationLevelWidening, targetType) Return result 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.Diagnostics Imports System.Runtime.InteropServices Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports TypeKind = Microsoft.CodeAnalysis.TypeKind Namespace Microsoft.CodeAnalysis.VisualBasic Partial Friend NotInheritable Class LocalRewriter Public Overrides Function VisitLateAddressOfOperator(node As BoundLateAddressOfOperator) As BoundNode If _inExpressionLambda Then ' just preserve the node to report an error in ExpressionLambdaRewriter Return MyBase.VisitLateAddressOfOperator(node) End If Dim targetType = DirectCast(node.Type, NamedTypeSymbol) Dim lambda = BuildDelegateRelaxationLambda(node.Syntax, targetType, node.MemberAccess, node.Binder, Me._diagnostics) Return Me.VisitExpressionNode(lambda) End Function Private Shared Function BuildDelegateRelaxationLambda( syntaxNode As SyntaxNode, targetType As NamedTypeSymbol, boundMember As BoundLateMemberAccess, binder As Binder, diagnostics As BindingDiagnosticBag ) As BoundExpression Dim delegateInvoke = targetType.DelegateInvokeMethod Debug.Assert(delegateInvoke.MethodKind = MethodKind.DelegateInvoke) ' build lambda symbol parameters matching the invocation method exactly. To do this, ' we'll create a BoundLambdaParameterSymbol for each parameter of the invoke method. Dim delegateInvokeReturnType = delegateInvoke.ReturnType Dim invokeParameters = delegateInvoke.Parameters Dim invokeParameterCount = invokeParameters.Length Dim lambdaSymbolParameters(invokeParameterCount - 1) As BoundLambdaParameterSymbol Dim addressOfLocation As Location = syntaxNode.GetLocation() For parameterIndex = 0 To invokeParameterCount - 1 Dim parameter = invokeParameters(parameterIndex) lambdaSymbolParameters(parameterIndex) = New BoundLambdaParameterSymbol(GeneratedNames.MakeDelegateRelaxationParameterName(parameterIndex), parameter.Ordinal, parameter.Type, parameter.IsByRef, syntaxNode, addressOfLocation) Next ' even if the return value is dropped, we're using the delegate's return type for ' this lambda symbol. Dim lambdaSymbol = New SynthesizedLambdaSymbol(SynthesizedLambdaKind.LateBoundAddressOfLambda, syntaxNode, lambdaSymbolParameters.AsImmutableOrNull, delegateInvokeReturnType, binder) ' the body of the lambda only contains a call to the target (or a return of the return value of ' the call in case of a function) ' for each parameter of the lambda symbol/invoke method we will create a bound parameter, except ' we are implementing a zero argument relaxation. ' These parameters will be used in the method invocation as passed parameters. Dim lambdaBoundParameters(invokeParameterCount - 1) As BoundExpression For parameterIndex = 0 To lambdaSymbolParameters.Length - 1 Dim lambdaSymbolParameter = lambdaSymbolParameters(parameterIndex) Dim boundParameter = New BoundParameter(syntaxNode, lambdaSymbolParameter, lambdaSymbolParameter.Type) boundParameter.SetWasCompilerGenerated() lambdaBoundParameters(parameterIndex) = boundParameter Next 'The invocation of the target method must be bound in the context of the lambda 'The reason is that binding the invoke may introduce local symbols and they need 'to be properly parented to the lambda and not to the outer method. Dim lambdaBinder = New LambdaBodyBinder(lambdaSymbol, binder) ' Dev10 ignores the type characters used in the operand of an AddressOf operator. ' NOTE: we suppress suppressAbstractCallDiagnostics because it ' should have been reported already Dim boundInvocationExpression As BoundExpression = lambdaBinder.BindLateBoundInvocation(syntaxNode, Nothing, boundMember, lambdaBoundParameters.AsImmutableOrNull, Nothing, diagnostics, suppressLateBindingResolutionDiagnostics:=True) boundInvocationExpression.SetWasCompilerGenerated() ' In case of a function target that got assigned to a sub delegate, the return value will be dropped Dim statementList As ImmutableArray(Of BoundStatement) = Nothing If lambdaSymbol.IsSub Then If boundInvocationExpression.IsLateBound() Then boundInvocationExpression = boundInvocationExpression.SetLateBoundAccessKind(LateBoundAccessKind.Call) End If Dim statements(1) As BoundStatement Dim boundStatement As BoundStatement = New BoundExpressionStatement(syntaxNode, boundInvocationExpression) boundStatement.SetWasCompilerGenerated() statements(0) = boundStatement boundStatement = New BoundReturnStatement(syntaxNode, Nothing, Nothing, Nothing) boundStatement.SetWasCompilerGenerated() statements(1) = boundStatement statementList = statements.AsImmutableOrNull Else ' process conversions between the return types of the target and invoke function if needed. boundInvocationExpression = lambdaBinder.ApplyImplicitConversion(syntaxNode, delegateInvokeReturnType, boundInvocationExpression, diagnostics) Dim returnstmt As BoundStatement = New BoundReturnStatement(syntaxNode, boundInvocationExpression, Nothing, Nothing) returnstmt.SetWasCompilerGenerated() statementList = ImmutableArray.Create(returnstmt) End If Dim lambdaBody = New BoundBlock(syntaxNode, Nothing, ImmutableArray(Of LocalSymbol).Empty, statementList) lambdaBody.SetWasCompilerGenerated() Dim boundLambda = New BoundLambda(syntaxNode, lambdaSymbol, lambdaBody, ImmutableBindingDiagnostic(Of AssemblySymbol).Empty, Nothing, ConversionKind.DelegateRelaxationLevelWidening, MethodConversionKind.Identity) boundLambda.SetWasCompilerGenerated() Dim result = New BoundDirectCast(syntaxNode, boundLambda, ConversionKind.DelegateRelaxationLevelWidening, targetType) Return result 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/Scanner/Directives.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 scanner functionality related to Directives and Preprocessor '----------------------------------------------------------------------------- Option Compare Binary Option Strict On Imports System.Collections.Immutable Imports System.Runtime.InteropServices Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Syntax.InternalSyntax Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.SyntaxFacts Namespace Microsoft.CodeAnalysis.VisualBasic.Syntax.InternalSyntax Partial Friend Class Scanner Private _isScanningDirective As Boolean = False Protected _scannerPreprocessorState As PreprocessorState Private Function TryScanDirective(tList As SyntaxListBuilder) As Boolean Debug.Assert(IsAtNewLine()) ' leading whitespace until we see # should be regular whitespace If CanGet() AndAlso IsWhitespace(Peek()) Then Dim ws = ScanWhitespace() tList.Add(ws) End If ' SAVE the lookahead state and clear current token Dim restorePoint = CreateRestorePoint() Me._isScanningDirective = True ' since we do not have lookahead tokens, this just ' resets current token to _lineBufferOffset Me.GetNextTokenInState(ScannerState.VB) Dim currentNonterminal = Me.GetCurrentSyntaxNode() Dim directiveTrivia = TryCast(currentNonterminal, DirectiveTriviaSyntax) ' if we are lucky to get whole directive statement, we can just reuse it. If directiveTrivia IsNot Nothing Then Me.MoveToNextSyntaxNodeInTrivia() ' adjust current token to just after the node ' we need that in case we need to skip some disabled text '(yes we do tokenize disabled text for compatibility reasons) Me.GetNextTokenInState(ScannerState.VB) Else Dim parser As New Parser(Me) directiveTrivia = parser.ParseConditionalCompilationStatement() directiveTrivia = parser.ConsumeStatementTerminatorAfterDirective(directiveTrivia) End If Debug.Assert(directiveTrivia.FullWidth > 0, "should at least get #") ProcessDirective(directiveTrivia, tList) ResetLineBufferOffset() ' RESTORE lookahead state and current token if there were any restorePoint.RestoreTokens(includeLookAhead:=True) Me._isScanningDirective = False Return True End Function ''' <summary> ''' Entry point to directive processing for Scanner. ''' </summary> Private Sub ProcessDirective(directiveTrivia As DirectiveTriviaSyntax, tList As SyntaxListBuilder) Dim disabledCode As CodeAnalysis.Syntax.InternalSyntax.SyntaxList(Of VisualBasicSyntaxNode) = Nothing Dim statement As DirectiveTriviaSyntax = directiveTrivia Dim newState = ApplyDirective(_scannerPreprocessorState, statement) _scannerPreprocessorState = newState ' if we are in a not taken branch, skip text Dim conditionals = newState.ConditionalStack If conditionals.Count <> 0 AndAlso Not conditionals.Peek.BranchTaken = ConditionalState.BranchTakenState.Taken Then ' we should not see #const inside disabled sections Debug.Assert(statement.Kind <> SyntaxKind.ConstDirectiveTrivia) ' skip disabled text disabledCode = SkipConditionalCompilationSection() End If ' Here we add the directive and disabled text that follows it ' (if there is any) to the trivia list ' processing statement could add an error to it, ' so we may need to rebuild the trivia node If statement IsNot directiveTrivia Then directiveTrivia = statement End If ' add the directive trivia to the list tList.Add(directiveTrivia) ' if had disabled code, add that too If disabledCode.Node IsNot Nothing Then tList.AddRange(disabledCode) End If End Sub ''' <summary> ''' Gets an initial preprocessor state and applies all directives from a given node. ''' Entry point for blender ''' </summary> Protected Shared Function ApplyDirectives(preprocessorState As PreprocessorState, node As VisualBasicSyntaxNode) As PreprocessorState If node.ContainsDirectives Then preprocessorState = ApplyDirectivesRecursive(preprocessorState, node) End If Return preprocessorState End Function Private Shared Function ApplyDirectivesRecursive(preprocessorState As PreprocessorState, node As GreenNode) As PreprocessorState Debug.Assert(node.ContainsDirectives, "we should not be processing nodes without Directives") ' node is a directive Dim directive = TryCast(node, DirectiveTriviaSyntax) If directive IsNot Nothing Then Dim statement = directive preprocessorState = ApplyDirective(preprocessorState, statement) Debug.Assert((statement Is directive) OrElse node.ContainsDiagnostics, "since we have no errors, we should not be changing statement") Return preprocessorState End If ' node is nonterminal Dim sCount = node.SlotCount If sCount > 0 Then For i As Integer = 0 To sCount - 1 Dim child = node.GetSlot(i) If child IsNot Nothing AndAlso child.ContainsDirectives Then preprocessorState = ApplyDirectivesRecursive(preprocessorState, child) End If Next Return preprocessorState End If ' node is a token Dim tk = DirectCast(node, SyntaxToken) Dim trivia = tk.GetLeadingTrivia If trivia IsNot Nothing AndAlso trivia.ContainsDirectives Then preprocessorState = ApplyDirectivesRecursive(preprocessorState, trivia) End If trivia = tk.GetTrailingTrivia If trivia IsNot Nothing AndAlso trivia.ContainsDirectives Then preprocessorState = ApplyDirectivesRecursive(preprocessorState, trivia) End If Return preprocessorState End Function ' takes a preprocessor state and applies a directive statement to it Friend Shared Function ApplyDirective(preprocessorState As PreprocessorState, ByRef statement As DirectiveTriviaSyntax) As PreprocessorState Select Case statement.Kind Case SyntaxKind.ConstDirectiveTrivia Dim conditionalsStack = preprocessorState.ConditionalStack If conditionalsStack.Count <> 0 AndAlso Not conditionalsStack.Peek.BranchTaken = ConditionalState.BranchTakenState.Taken Then ' const inside disabled text - do not evaluate Else ' interpret the const preprocessorState = preprocessorState.InterpretConstDirective(statement) End If Case SyntaxKind.IfDirectiveTrivia preprocessorState = preprocessorState.InterpretIfDirective(statement) Case SyntaxKind.ElseIfDirectiveTrivia preprocessorState = preprocessorState.InterpretElseIfDirective(statement) Case SyntaxKind.ElseDirectiveTrivia preprocessorState = preprocessorState.InterpretElseDirective(statement) Case SyntaxKind.EndIfDirectiveTrivia preprocessorState = preprocessorState.InterpretEndIfDirective(statement) Case SyntaxKind.RegionDirectiveTrivia preprocessorState = preprocessorState.InterpretRegionDirective(statement) Case SyntaxKind.EndRegionDirectiveTrivia preprocessorState = preprocessorState.InterpretEndRegionDirective(statement) Case SyntaxKind.ExternalSourceDirectiveTrivia preprocessorState = preprocessorState.InterpretExternalSourceDirective(statement) Case SyntaxKind.EndExternalSourceDirectiveTrivia preprocessorState = preprocessorState.InterpretEndExternalSourceDirective(statement) Case SyntaxKind.ExternalChecksumDirectiveTrivia, SyntaxKind.BadDirectiveTrivia, SyntaxKind.EnableWarningDirectiveTrivia, 'TODO: Add support for processing #Enable and #Disable SyntaxKind.DisableWarningDirectiveTrivia, SyntaxKind.ReferenceDirectiveTrivia ' These directives require no processing Case Else Throw ExceptionUtilities.UnexpectedValue(statement.Kind) End Select Return preprocessorState End Function ' represents states of a single conditional frame ' immutable as PreprocessorState so requires Friend Class ConditionalState Public Enum BranchTakenState As Byte NotTaken Taken AlreadyTaken End Enum Private ReadOnly _branchTaken As BranchTakenState Private ReadOnly _elseSeen As Boolean Private ReadOnly _ifDirective As IfDirectiveTriviaSyntax ' branch can be taken only once. ' this state transitions NotTaken -> Taken -> AlreadyTaken... Friend ReadOnly Property BranchTaken As BranchTakenState Get Return _branchTaken End Get End Property Friend ReadOnly Property ElseSeen As Boolean Get Return _elseSeen End Get End Property Friend ReadOnly Property IfDirective As IfDirectiveTriviaSyntax Get Return _ifDirective End Get End Property Friend Sub New(branchTaken As BranchTakenState, elseSeen As Boolean, ifDirective As IfDirectiveTriviaSyntax) _branchTaken = branchTaken _elseSeen = elseSeen _ifDirective = ifDirective End Sub End Class ' The class needs to be immutable ' as its instances can get associated with multiple tokens. Friend NotInheritable Class PreprocessorState Private ReadOnly _symbols As ImmutableDictionary(Of String, CConst) Private ReadOnly _conditionals As ImmutableStack(Of ConditionalState) Private ReadOnly _regionDirectives As ImmutableStack(Of RegionDirectiveTriviaSyntax) Private ReadOnly _haveSeenRegionDirectives As Boolean Private ReadOnly _externalSourceDirective As ExternalSourceDirectiveTriviaSyntax Friend Sub New(symbols As ImmutableDictionary(Of String, CConst)) _symbols = symbols _conditionals = ImmutableStack.Create(Of ConditionalState)() _regionDirectives = ImmutableStack.Create(Of RegionDirectiveTriviaSyntax)() End Sub Private Sub New(symbols As ImmutableDictionary(Of String, CConst), conditionals As ImmutableStack(Of ConditionalState), regionDirectives As ImmutableStack(Of RegionDirectiveTriviaSyntax), haveSeenRegionDirectives As Boolean, externalSourceDirective As ExternalSourceDirectiveTriviaSyntax) Me._symbols = symbols Me._conditionals = conditionals Me._regionDirectives = regionDirectives Me._haveSeenRegionDirectives = haveSeenRegionDirectives Me._externalSourceDirective = externalSourceDirective End Sub Friend ReadOnly Property SymbolsMap As ImmutableDictionary(Of String, CConst) Get Return _symbols End Get End Property Private Function SetSymbol(name As String, value As CConst) As PreprocessorState Dim symbols = Me._symbols symbols = symbols.SetItem(name, value) Return New PreprocessorState(symbols, Me._conditionals, Me._regionDirectives, Me._haveSeenRegionDirectives, Me._externalSourceDirective) End Function Friend ReadOnly Property ConditionalStack As ImmutableStack(Of ConditionalState) Get Return _conditionals End Get End Property Private Function WithConditionals(conditionals As ImmutableStack(Of ConditionalState)) As PreprocessorState Return New PreprocessorState(Me._symbols, conditionals, Me._regionDirectives, Me._haveSeenRegionDirectives, Me._externalSourceDirective) End Function Friend ReadOnly Property RegionDirectiveStack As ImmutableStack(Of RegionDirectiveTriviaSyntax) Get Return _regionDirectives End Get End Property Friend ReadOnly Property HaveSeenRegionDirectives As Boolean Get Return _haveSeenRegionDirectives End Get End Property Private Function WithRegions(regions As ImmutableStack(Of RegionDirectiveTriviaSyntax)) As PreprocessorState Return New PreprocessorState(Me._symbols, Me._conditionals, regions, Me._haveSeenRegionDirectives OrElse regions.Count > 0, Me._externalSourceDirective) End Function Friend ReadOnly Property ExternalSourceDirective As ExternalSourceDirectiveTriviaSyntax Get Return _externalSourceDirective End Get End Property Private Function WithExternalSource(externalSource As ExternalSourceDirectiveTriviaSyntax) As PreprocessorState Return New PreprocessorState(Me._symbols, Me._conditionals, Me._regionDirectives, Me._haveSeenRegionDirectives, externalSource) End Function Friend Function InterpretConstDirective(ByRef statement As DirectiveTriviaSyntax) As PreprocessorState Debug.Assert(statement.Kind = SyntaxKind.ConstDirectiveTrivia) Dim constDirective = DirectCast(statement, ConstDirectiveTriviaSyntax) Dim value = ExpressionEvaluator.EvaluateExpression(constDirective.Value, _symbols) Dim err = value.ErrorId If err <> 0 Then statement = Parser.ReportSyntaxError(statement, err, value.ErrorArgs) End If Return SetSymbol(constDirective.Name.IdentifierText, value) End Function Friend Function InterpretExternalSourceDirective(ByRef statement As DirectiveTriviaSyntax) As PreprocessorState Dim externalSourceDirective = DirectCast(statement, ExternalSourceDirectiveTriviaSyntax) If _externalSourceDirective IsNot Nothing Then statement = Parser.ReportSyntaxError(statement, ERRID.ERR_NestedExternalSource) Return Me Else Return WithExternalSource(externalSourceDirective) End If End Function Friend Function InterpretEndExternalSourceDirective(ByRef statement As DirectiveTriviaSyntax) As PreprocessorState If _externalSourceDirective Is Nothing Then statement = Parser.ReportSyntaxError(statement, ERRID.ERR_EndExternalSource) Return Me Else Return WithExternalSource(Nothing) End If End Function Friend Function InterpretRegionDirective(ByRef statement As DirectiveTriviaSyntax) As PreprocessorState Dim regionDirective = DirectCast(statement, RegionDirectiveTriviaSyntax) Return WithRegions(_regionDirectives.Push(regionDirective)) End Function Friend Function InterpretEndRegionDirective(ByRef statement As DirectiveTriviaSyntax) As PreprocessorState If _regionDirectives.Count = 0 Then statement = Parser.ReportSyntaxError(statement, ERRID.ERR_EndRegionNoRegion) Return Me Else Return WithRegions(_regionDirectives.Pop()) End If End Function ' // Interpret a conditional compilation #if or #elseif. Friend Function InterpretIfDirective(ByRef statement As DirectiveTriviaSyntax) As PreprocessorState Debug.Assert(statement.Kind = SyntaxKind.IfDirectiveTrivia) Dim ifDirective = DirectCast(statement, IfDirectiveTriviaSyntax) ' TODO - Is the following comment still relevant? How should the error be reported? ' Evaluate the expression to detect errors, whether or not ' its result is needed. Dim value = ExpressionEvaluator.EvaluateCondition(ifDirective.Condition, _symbols) Dim err = value.ErrorId If err <> 0 Then statement = Parser.ReportSyntaxError(statement, err, value.ErrorArgs) End If Dim takeThisBranch = If(value.IsBad OrElse value.IsBooleanTrue, ConditionalState.BranchTakenState.Taken, ConditionalState.BranchTakenState.NotTaken) Return WithConditionals(_conditionals.Push(New ConditionalState(takeThisBranch, False, DirectCast(statement, IfDirectiveTriviaSyntax)))) End Function Friend Function InterpretElseIfDirective(ByRef statement As DirectiveTriviaSyntax) As PreprocessorState Dim condition As ConditionalState Dim conditionals = Me._conditionals If conditionals.Count = 0 Then statement = Parser.ReportSyntaxError(statement, ERRID.ERR_LbBadElseif) condition = New ConditionalState(ConditionalState.BranchTakenState.NotTaken, False, Nothing) Else condition = conditionals.Peek conditionals = conditionals.Pop If condition.ElseSeen Then statement = Parser.ReportSyntaxError(statement, ERRID.ERR_LbElseifAfterElse) End If End If ' TODO - Is the following comment still relevant? How should the error be reported? ' Evaluate the expression to detect errors, whether or not ' its result is needed. Dim ifDirective = DirectCast(statement, IfDirectiveTriviaSyntax) Dim value = ExpressionEvaluator.EvaluateCondition(ifDirective.Condition, _symbols) Dim err = value.ErrorId If err <> 0 Then statement = Parser.ReportSyntaxError(statement, err, value.ErrorArgs) End If Dim takeThisBranch = condition.BranchTaken If takeThisBranch = ConditionalState.BranchTakenState.Taken Then takeThisBranch = ConditionalState.BranchTakenState.AlreadyTaken ElseIf takeThisBranch = ConditionalState.BranchTakenState.NotTaken AndAlso Not value.IsBad AndAlso value.IsBooleanTrue Then takeThisBranch = ConditionalState.BranchTakenState.Taken End If condition = New ConditionalState(takeThisBranch, condition.ElseSeen, DirectCast(statement, IfDirectiveTriviaSyntax)) Return WithConditionals(conditionals.Push(condition)) End Function Friend Function InterpretElseDirective(ByRef statement As DirectiveTriviaSyntax) As PreprocessorState Dim conditionals = Me._conditionals If conditionals.Count = 0 Then ' If there has been no preceding #If, give an error and pretend that there ' had been one. statement = Parser.ReportSyntaxError(statement, ERRID.ERR_LbElseNoMatchingIf) Return WithConditionals(conditionals.Push(New ConditionalState(ConditionalState.BranchTakenState.Taken, True, Nothing))) End If Dim condition = conditionals.Peek conditionals = conditionals.Pop If condition.ElseSeen Then statement = Parser.ReportSyntaxError(statement, ERRID.ERR_LbElseNoMatchingIf) End If Dim takeThisBranch = condition.BranchTaken If takeThisBranch = ConditionalState.BranchTakenState.Taken Then takeThisBranch = ConditionalState.BranchTakenState.AlreadyTaken ElseIf takeThisBranch = ConditionalState.BranchTakenState.NotTaken Then takeThisBranch = ConditionalState.BranchTakenState.Taken End If condition = New ConditionalState(takeThisBranch, True, condition.IfDirective) Return WithConditionals(conditionals.Push(condition)) End Function Friend Function InterpretEndIfDirective(ByRef statement As DirectiveTriviaSyntax) As PreprocessorState If _conditionals.Count = 0 Then statement = Parser.ReportSyntaxError(statement, ERRID.ERR_LbNoMatchingIf) Return Me Else Return WithConditionals(_conditionals.Pop()) End If End Function Friend Function IsEquivalentTo(other As PreprocessorState) As Boolean ' for now, we will only consider two are equivalents when there are only regions but no other directives If Me._conditionals.Count > 0 OrElse Me._symbols.Count > 0 OrElse Me._externalSourceDirective IsNot Nothing OrElse other._conditionals.Count > 0 OrElse other._symbols.Count > 0 OrElse other._externalSourceDirective IsNot Nothing Then Return False End If If Me._regionDirectives.Count <> other._regionDirectives.Count Then Return False End If If Me._haveSeenRegionDirectives <> other._haveSeenRegionDirectives Then Return False End If Return True End Function End Class '//------------------------------------------------------------------------------------------------- '// '// Skip all text until the end of the current conditional section. This will also return the '// span of text that was skipped '// '//------------------------------------------------------------------------------------------------- Private Function SkipConditionalCompilationSection() As CodeAnalysis.Syntax.InternalSyntax.SyntaxList(Of VisualBasicSyntaxNode) ' // If skipping encounters a nested #if, it is necessary to skip all of it through its ' // #end. NestedConditionalsToSkip keeps track of how many nested #if constructs ' // need skipping. Dim NestedConditionalsToSkip As Integer = 0 ' Accumulate span of text we're skipping. Dim startSkipped As Integer = -1 ' Start location of skipping Dim lengthSkipped As Integer = 0 ' Length of skipped text. While True Dim skippedSpan = Me.SkipToNextConditionalLine() If startSkipped < 0 Then startSkipped = skippedSpan.Start End If lengthSkipped += skippedSpan.Length Dim curToken = GetCurrentToken() Select Case curToken.Kind Case SyntaxKind.HashToken Dim nextKind = Me.PeekToken(1, ScannerState.VB).Kind Dim nextNextToken = Me.PeekToken(2, ScannerState.VB) If NestedConditionalsToSkip = 0 AndAlso ((nextKind = SyntaxKind.EndKeyword AndAlso Not IsContextualKeyword(nextNextToken, SyntaxKind.ExternalSourceKeyword, SyntaxKind.RegionKeyword)) OrElse nextKind = SyntaxKind.EndIfKeyword OrElse nextKind = SyntaxKind.ElseIfKeyword OrElse nextKind = SyntaxKind.ElseKeyword) Then ' // Finding one of these is sufficient to stop skipping. It is then necessary ' // to process the line as a conditional compilation line. The normal ' // parsing logic will do this. Exit While ElseIf nextKind = SyntaxKind.EndIfKeyword OrElse (nextKind = SyntaxKind.EndKeyword AndAlso Not IsContextualKeyword(nextNextToken, SyntaxKind.ExternalSourceKeyword, SyntaxKind.RegionKeyword)) Then NestedConditionalsToSkip -= 1 ElseIf nextKind = SyntaxKind.IfKeyword Then NestedConditionalsToSkip += 1 End If ' if the line concluded the skip block, return from the loop If NestedConditionalsToSkip < 0 Then Debug.Assert(NestedConditionalsToSkip = -1, "preprocessor skip underflow") Exit While End If ' skip over # token lengthSkipped += GetCurrentToken.FullWidth GetNextTokenInState(ScannerState.VB) ' Skip over terminator token to avoid counting it twice because it is already trivia on current token If nextKind = SyntaxKind.StatementTerminatorToken OrElse nextKind = SyntaxKind.ColonToken Then GetNextTokenInState(ScannerState.VB) End If Case SyntaxKind.DateLiteralToken, SyntaxKind.BadToken 'Dev10 #777522 Do not confuse Date literal with an end of conditional block. ' skip over date literal token lengthSkipped += GetCurrentToken.FullWidth GetNextTokenInState(ScannerState.VB) Dim nextKind = GetCurrentToken().Kind ' Skip over terminator token to avoid counting it twice because it is already trivia on current token If nextKind = SyntaxKind.StatementTerminatorToken OrElse nextKind = SyntaxKind.ColonToken Then GetNextTokenInState(ScannerState.VB) End If Case SyntaxKind.EndOfFileToken Exit While Case Else Throw ExceptionUtilities.UnexpectedValue(curToken.Kind) End Select End While If lengthSkipped > 0 Then Return New CodeAnalysis.Syntax.InternalSyntax.SyntaxList(Of VisualBasicSyntaxNode)(Me.GetDisabledTextAt(New TextSpan(startSkipped, lengthSkipped))) Else Return New CodeAnalysis.Syntax.InternalSyntax.SyntaxList(Of VisualBasicSyntaxNode)(Nothing) End If End Function ' // If compilation ends in the middle of a non-skipped conditional section, ' // produce appropriate diagnostics. Friend Function RecoverFromMissingConditionalEnds(eof As PunctuationSyntax, <Out> ByRef notClosedIfDirectives As ArrayBuilder(Of IfDirectiveTriviaSyntax), <Out> ByRef notClosedRegionDirectives As ArrayBuilder(Of RegionDirectiveTriviaSyntax), <Out> ByRef haveRegionDirectives As Boolean, <Out> ByRef notClosedExternalSourceDirective As ExternalSourceDirectiveTriviaSyntax) As PunctuationSyntax notClosedIfDirectives = Nothing notClosedRegionDirectives = Nothing If Me._scannerPreprocessorState.ConditionalStack.Count > 0 Then For Each state In _scannerPreprocessorState.ConditionalStack Dim ifDirective As IfDirectiveTriviaSyntax = state.IfDirective If ifDirective IsNot Nothing Then If notClosedIfDirectives Is Nothing Then notClosedIfDirectives = ArrayBuilder(Of IfDirectiveTriviaSyntax).GetInstance() End If notClosedIfDirectives.Add(ifDirective) End If Next If notClosedIfDirectives Is Nothing Then ' #If directive is not found eof = Parser.ReportSyntaxError(eof, ERRID.ERR_LbExpectedEndIf) End If End If If Me._scannerPreprocessorState.RegionDirectiveStack.Count > 0 Then notClosedRegionDirectives = ArrayBuilder(Of RegionDirectiveTriviaSyntax).GetInstance() notClosedRegionDirectives.AddRange(Me._scannerPreprocessorState.RegionDirectiveStack) End If haveRegionDirectives = Me._scannerPreprocessorState.HaveSeenRegionDirectives notClosedExternalSourceDirective = Me._scannerPreprocessorState.ExternalSourceDirective Return eof 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 scanner functionality related to Directives and Preprocessor '----------------------------------------------------------------------------- Option Compare Binary Option Strict On Imports System.Collections.Immutable Imports System.Runtime.InteropServices Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Syntax.InternalSyntax Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.SyntaxFacts Namespace Microsoft.CodeAnalysis.VisualBasic.Syntax.InternalSyntax Partial Friend Class Scanner Private _isScanningDirective As Boolean = False Protected _scannerPreprocessorState As PreprocessorState Private Function TryScanDirective(tList As SyntaxListBuilder) As Boolean Debug.Assert(IsAtNewLine()) ' leading whitespace until we see # should be regular whitespace If CanGet() AndAlso IsWhitespace(Peek()) Then Dim ws = ScanWhitespace() tList.Add(ws) End If ' SAVE the lookahead state and clear current token Dim restorePoint = CreateRestorePoint() Me._isScanningDirective = True ' since we do not have lookahead tokens, this just ' resets current token to _lineBufferOffset Me.GetNextTokenInState(ScannerState.VB) Dim currentNonterminal = Me.GetCurrentSyntaxNode() Dim directiveTrivia = TryCast(currentNonterminal, DirectiveTriviaSyntax) ' if we are lucky to get whole directive statement, we can just reuse it. If directiveTrivia IsNot Nothing Then Me.MoveToNextSyntaxNodeInTrivia() ' adjust current token to just after the node ' we need that in case we need to skip some disabled text '(yes we do tokenize disabled text for compatibility reasons) Me.GetNextTokenInState(ScannerState.VB) Else Dim parser As New Parser(Me) directiveTrivia = parser.ParseConditionalCompilationStatement() directiveTrivia = parser.ConsumeStatementTerminatorAfterDirective(directiveTrivia) End If Debug.Assert(directiveTrivia.FullWidth > 0, "should at least get #") ProcessDirective(directiveTrivia, tList) ResetLineBufferOffset() ' RESTORE lookahead state and current token if there were any restorePoint.RestoreTokens(includeLookAhead:=True) Me._isScanningDirective = False Return True End Function ''' <summary> ''' Entry point to directive processing for Scanner. ''' </summary> Private Sub ProcessDirective(directiveTrivia As DirectiveTriviaSyntax, tList As SyntaxListBuilder) Dim disabledCode As CodeAnalysis.Syntax.InternalSyntax.SyntaxList(Of VisualBasicSyntaxNode) = Nothing Dim statement As DirectiveTriviaSyntax = directiveTrivia Dim newState = ApplyDirective(_scannerPreprocessorState, statement) _scannerPreprocessorState = newState ' if we are in a not taken branch, skip text Dim conditionals = newState.ConditionalStack If conditionals.Count <> 0 AndAlso Not conditionals.Peek.BranchTaken = ConditionalState.BranchTakenState.Taken Then ' we should not see #const inside disabled sections Debug.Assert(statement.Kind <> SyntaxKind.ConstDirectiveTrivia) ' skip disabled text disabledCode = SkipConditionalCompilationSection() End If ' Here we add the directive and disabled text that follows it ' (if there is any) to the trivia list ' processing statement could add an error to it, ' so we may need to rebuild the trivia node If statement IsNot directiveTrivia Then directiveTrivia = statement End If ' add the directive trivia to the list tList.Add(directiveTrivia) ' if had disabled code, add that too If disabledCode.Node IsNot Nothing Then tList.AddRange(disabledCode) End If End Sub ''' <summary> ''' Gets an initial preprocessor state and applies all directives from a given node. ''' Entry point for blender ''' </summary> Protected Shared Function ApplyDirectives(preprocessorState As PreprocessorState, node As VisualBasicSyntaxNode) As PreprocessorState If node.ContainsDirectives Then preprocessorState = ApplyDirectivesRecursive(preprocessorState, node) End If Return preprocessorState End Function Private Shared Function ApplyDirectivesRecursive(preprocessorState As PreprocessorState, node As GreenNode) As PreprocessorState Debug.Assert(node.ContainsDirectives, "we should not be processing nodes without Directives") ' node is a directive Dim directive = TryCast(node, DirectiveTriviaSyntax) If directive IsNot Nothing Then Dim statement = directive preprocessorState = ApplyDirective(preprocessorState, statement) Debug.Assert((statement Is directive) OrElse node.ContainsDiagnostics, "since we have no errors, we should not be changing statement") Return preprocessorState End If ' node is nonterminal Dim sCount = node.SlotCount If sCount > 0 Then For i As Integer = 0 To sCount - 1 Dim child = node.GetSlot(i) If child IsNot Nothing AndAlso child.ContainsDirectives Then preprocessorState = ApplyDirectivesRecursive(preprocessorState, child) End If Next Return preprocessorState End If ' node is a token Dim tk = DirectCast(node, SyntaxToken) Dim trivia = tk.GetLeadingTrivia If trivia IsNot Nothing AndAlso trivia.ContainsDirectives Then preprocessorState = ApplyDirectivesRecursive(preprocessorState, trivia) End If trivia = tk.GetTrailingTrivia If trivia IsNot Nothing AndAlso trivia.ContainsDirectives Then preprocessorState = ApplyDirectivesRecursive(preprocessorState, trivia) End If Return preprocessorState End Function ' takes a preprocessor state and applies a directive statement to it Friend Shared Function ApplyDirective(preprocessorState As PreprocessorState, ByRef statement As DirectiveTriviaSyntax) As PreprocessorState Select Case statement.Kind Case SyntaxKind.ConstDirectiveTrivia Dim conditionalsStack = preprocessorState.ConditionalStack If conditionalsStack.Count <> 0 AndAlso Not conditionalsStack.Peek.BranchTaken = ConditionalState.BranchTakenState.Taken Then ' const inside disabled text - do not evaluate Else ' interpret the const preprocessorState = preprocessorState.InterpretConstDirective(statement) End If Case SyntaxKind.IfDirectiveTrivia preprocessorState = preprocessorState.InterpretIfDirective(statement) Case SyntaxKind.ElseIfDirectiveTrivia preprocessorState = preprocessorState.InterpretElseIfDirective(statement) Case SyntaxKind.ElseDirectiveTrivia preprocessorState = preprocessorState.InterpretElseDirective(statement) Case SyntaxKind.EndIfDirectiveTrivia preprocessorState = preprocessorState.InterpretEndIfDirective(statement) Case SyntaxKind.RegionDirectiveTrivia preprocessorState = preprocessorState.InterpretRegionDirective(statement) Case SyntaxKind.EndRegionDirectiveTrivia preprocessorState = preprocessorState.InterpretEndRegionDirective(statement) Case SyntaxKind.ExternalSourceDirectiveTrivia preprocessorState = preprocessorState.InterpretExternalSourceDirective(statement) Case SyntaxKind.EndExternalSourceDirectiveTrivia preprocessorState = preprocessorState.InterpretEndExternalSourceDirective(statement) Case SyntaxKind.ExternalChecksumDirectiveTrivia, SyntaxKind.BadDirectiveTrivia, SyntaxKind.EnableWarningDirectiveTrivia, 'TODO: Add support for processing #Enable and #Disable SyntaxKind.DisableWarningDirectiveTrivia, SyntaxKind.ReferenceDirectiveTrivia ' These directives require no processing Case Else Throw ExceptionUtilities.UnexpectedValue(statement.Kind) End Select Return preprocessorState End Function ' represents states of a single conditional frame ' immutable as PreprocessorState so requires Friend Class ConditionalState Public Enum BranchTakenState As Byte NotTaken Taken AlreadyTaken End Enum Private ReadOnly _branchTaken As BranchTakenState Private ReadOnly _elseSeen As Boolean Private ReadOnly _ifDirective As IfDirectiveTriviaSyntax ' branch can be taken only once. ' this state transitions NotTaken -> Taken -> AlreadyTaken... Friend ReadOnly Property BranchTaken As BranchTakenState Get Return _branchTaken End Get End Property Friend ReadOnly Property ElseSeen As Boolean Get Return _elseSeen End Get End Property Friend ReadOnly Property IfDirective As IfDirectiveTriviaSyntax Get Return _ifDirective End Get End Property Friend Sub New(branchTaken As BranchTakenState, elseSeen As Boolean, ifDirective As IfDirectiveTriviaSyntax) _branchTaken = branchTaken _elseSeen = elseSeen _ifDirective = ifDirective End Sub End Class ' The class needs to be immutable ' as its instances can get associated with multiple tokens. Friend NotInheritable Class PreprocessorState Private ReadOnly _symbols As ImmutableDictionary(Of String, CConst) Private ReadOnly _conditionals As ImmutableStack(Of ConditionalState) Private ReadOnly _regionDirectives As ImmutableStack(Of RegionDirectiveTriviaSyntax) Private ReadOnly _haveSeenRegionDirectives As Boolean Private ReadOnly _externalSourceDirective As ExternalSourceDirectiveTriviaSyntax Friend Sub New(symbols As ImmutableDictionary(Of String, CConst)) _symbols = symbols _conditionals = ImmutableStack.Create(Of ConditionalState)() _regionDirectives = ImmutableStack.Create(Of RegionDirectiveTriviaSyntax)() End Sub Private Sub New(symbols As ImmutableDictionary(Of String, CConst), conditionals As ImmutableStack(Of ConditionalState), regionDirectives As ImmutableStack(Of RegionDirectiveTriviaSyntax), haveSeenRegionDirectives As Boolean, externalSourceDirective As ExternalSourceDirectiveTriviaSyntax) Me._symbols = symbols Me._conditionals = conditionals Me._regionDirectives = regionDirectives Me._haveSeenRegionDirectives = haveSeenRegionDirectives Me._externalSourceDirective = externalSourceDirective End Sub Friend ReadOnly Property SymbolsMap As ImmutableDictionary(Of String, CConst) Get Return _symbols End Get End Property Private Function SetSymbol(name As String, value As CConst) As PreprocessorState Dim symbols = Me._symbols symbols = symbols.SetItem(name, value) Return New PreprocessorState(symbols, Me._conditionals, Me._regionDirectives, Me._haveSeenRegionDirectives, Me._externalSourceDirective) End Function Friend ReadOnly Property ConditionalStack As ImmutableStack(Of ConditionalState) Get Return _conditionals End Get End Property Private Function WithConditionals(conditionals As ImmutableStack(Of ConditionalState)) As PreprocessorState Return New PreprocessorState(Me._symbols, conditionals, Me._regionDirectives, Me._haveSeenRegionDirectives, Me._externalSourceDirective) End Function Friend ReadOnly Property RegionDirectiveStack As ImmutableStack(Of RegionDirectiveTriviaSyntax) Get Return _regionDirectives End Get End Property Friend ReadOnly Property HaveSeenRegionDirectives As Boolean Get Return _haveSeenRegionDirectives End Get End Property Private Function WithRegions(regions As ImmutableStack(Of RegionDirectiveTriviaSyntax)) As PreprocessorState Return New PreprocessorState(Me._symbols, Me._conditionals, regions, Me._haveSeenRegionDirectives OrElse regions.Count > 0, Me._externalSourceDirective) End Function Friend ReadOnly Property ExternalSourceDirective As ExternalSourceDirectiveTriviaSyntax Get Return _externalSourceDirective End Get End Property Private Function WithExternalSource(externalSource As ExternalSourceDirectiveTriviaSyntax) As PreprocessorState Return New PreprocessorState(Me._symbols, Me._conditionals, Me._regionDirectives, Me._haveSeenRegionDirectives, externalSource) End Function Friend Function InterpretConstDirective(ByRef statement As DirectiveTriviaSyntax) As PreprocessorState Debug.Assert(statement.Kind = SyntaxKind.ConstDirectiveTrivia) Dim constDirective = DirectCast(statement, ConstDirectiveTriviaSyntax) Dim value = ExpressionEvaluator.EvaluateExpression(constDirective.Value, _symbols) Dim err = value.ErrorId If err <> 0 Then statement = Parser.ReportSyntaxError(statement, err, value.ErrorArgs) End If Return SetSymbol(constDirective.Name.IdentifierText, value) End Function Friend Function InterpretExternalSourceDirective(ByRef statement As DirectiveTriviaSyntax) As PreprocessorState Dim externalSourceDirective = DirectCast(statement, ExternalSourceDirectiveTriviaSyntax) If _externalSourceDirective IsNot Nothing Then statement = Parser.ReportSyntaxError(statement, ERRID.ERR_NestedExternalSource) Return Me Else Return WithExternalSource(externalSourceDirective) End If End Function Friend Function InterpretEndExternalSourceDirective(ByRef statement As DirectiveTriviaSyntax) As PreprocessorState If _externalSourceDirective Is Nothing Then statement = Parser.ReportSyntaxError(statement, ERRID.ERR_EndExternalSource) Return Me Else Return WithExternalSource(Nothing) End If End Function Friend Function InterpretRegionDirective(ByRef statement As DirectiveTriviaSyntax) As PreprocessorState Dim regionDirective = DirectCast(statement, RegionDirectiveTriviaSyntax) Return WithRegions(_regionDirectives.Push(regionDirective)) End Function Friend Function InterpretEndRegionDirective(ByRef statement As DirectiveTriviaSyntax) As PreprocessorState If _regionDirectives.Count = 0 Then statement = Parser.ReportSyntaxError(statement, ERRID.ERR_EndRegionNoRegion) Return Me Else Return WithRegions(_regionDirectives.Pop()) End If End Function ' // Interpret a conditional compilation #if or #elseif. Friend Function InterpretIfDirective(ByRef statement As DirectiveTriviaSyntax) As PreprocessorState Debug.Assert(statement.Kind = SyntaxKind.IfDirectiveTrivia) Dim ifDirective = DirectCast(statement, IfDirectiveTriviaSyntax) ' TODO - Is the following comment still relevant? How should the error be reported? ' Evaluate the expression to detect errors, whether or not ' its result is needed. Dim value = ExpressionEvaluator.EvaluateCondition(ifDirective.Condition, _symbols) Dim err = value.ErrorId If err <> 0 Then statement = Parser.ReportSyntaxError(statement, err, value.ErrorArgs) End If Dim takeThisBranch = If(value.IsBad OrElse value.IsBooleanTrue, ConditionalState.BranchTakenState.Taken, ConditionalState.BranchTakenState.NotTaken) Return WithConditionals(_conditionals.Push(New ConditionalState(takeThisBranch, False, DirectCast(statement, IfDirectiveTriviaSyntax)))) End Function Friend Function InterpretElseIfDirective(ByRef statement As DirectiveTriviaSyntax) As PreprocessorState Dim condition As ConditionalState Dim conditionals = Me._conditionals If conditionals.Count = 0 Then statement = Parser.ReportSyntaxError(statement, ERRID.ERR_LbBadElseif) condition = New ConditionalState(ConditionalState.BranchTakenState.NotTaken, False, Nothing) Else condition = conditionals.Peek conditionals = conditionals.Pop If condition.ElseSeen Then statement = Parser.ReportSyntaxError(statement, ERRID.ERR_LbElseifAfterElse) End If End If ' TODO - Is the following comment still relevant? How should the error be reported? ' Evaluate the expression to detect errors, whether or not ' its result is needed. Dim ifDirective = DirectCast(statement, IfDirectiveTriviaSyntax) Dim value = ExpressionEvaluator.EvaluateCondition(ifDirective.Condition, _symbols) Dim err = value.ErrorId If err <> 0 Then statement = Parser.ReportSyntaxError(statement, err, value.ErrorArgs) End If Dim takeThisBranch = condition.BranchTaken If takeThisBranch = ConditionalState.BranchTakenState.Taken Then takeThisBranch = ConditionalState.BranchTakenState.AlreadyTaken ElseIf takeThisBranch = ConditionalState.BranchTakenState.NotTaken AndAlso Not value.IsBad AndAlso value.IsBooleanTrue Then takeThisBranch = ConditionalState.BranchTakenState.Taken End If condition = New ConditionalState(takeThisBranch, condition.ElseSeen, DirectCast(statement, IfDirectiveTriviaSyntax)) Return WithConditionals(conditionals.Push(condition)) End Function Friend Function InterpretElseDirective(ByRef statement As DirectiveTriviaSyntax) As PreprocessorState Dim conditionals = Me._conditionals If conditionals.Count = 0 Then ' If there has been no preceding #If, give an error and pretend that there ' had been one. statement = Parser.ReportSyntaxError(statement, ERRID.ERR_LbElseNoMatchingIf) Return WithConditionals(conditionals.Push(New ConditionalState(ConditionalState.BranchTakenState.Taken, True, Nothing))) End If Dim condition = conditionals.Peek conditionals = conditionals.Pop If condition.ElseSeen Then statement = Parser.ReportSyntaxError(statement, ERRID.ERR_LbElseNoMatchingIf) End If Dim takeThisBranch = condition.BranchTaken If takeThisBranch = ConditionalState.BranchTakenState.Taken Then takeThisBranch = ConditionalState.BranchTakenState.AlreadyTaken ElseIf takeThisBranch = ConditionalState.BranchTakenState.NotTaken Then takeThisBranch = ConditionalState.BranchTakenState.Taken End If condition = New ConditionalState(takeThisBranch, True, condition.IfDirective) Return WithConditionals(conditionals.Push(condition)) End Function Friend Function InterpretEndIfDirective(ByRef statement As DirectiveTriviaSyntax) As PreprocessorState If _conditionals.Count = 0 Then statement = Parser.ReportSyntaxError(statement, ERRID.ERR_LbNoMatchingIf) Return Me Else Return WithConditionals(_conditionals.Pop()) End If End Function Friend Function IsEquivalentTo(other As PreprocessorState) As Boolean ' for now, we will only consider two are equivalents when there are only regions but no other directives If Me._conditionals.Count > 0 OrElse Me._symbols.Count > 0 OrElse Me._externalSourceDirective IsNot Nothing OrElse other._conditionals.Count > 0 OrElse other._symbols.Count > 0 OrElse other._externalSourceDirective IsNot Nothing Then Return False End If If Me._regionDirectives.Count <> other._regionDirectives.Count Then Return False End If If Me._haveSeenRegionDirectives <> other._haveSeenRegionDirectives Then Return False End If Return True End Function End Class '//------------------------------------------------------------------------------------------------- '// '// Skip all text until the end of the current conditional section. This will also return the '// span of text that was skipped '// '//------------------------------------------------------------------------------------------------- Private Function SkipConditionalCompilationSection() As CodeAnalysis.Syntax.InternalSyntax.SyntaxList(Of VisualBasicSyntaxNode) ' // If skipping encounters a nested #if, it is necessary to skip all of it through its ' // #end. NestedConditionalsToSkip keeps track of how many nested #if constructs ' // need skipping. Dim NestedConditionalsToSkip As Integer = 0 ' Accumulate span of text we're skipping. Dim startSkipped As Integer = -1 ' Start location of skipping Dim lengthSkipped As Integer = 0 ' Length of skipped text. While True Dim skippedSpan = Me.SkipToNextConditionalLine() If startSkipped < 0 Then startSkipped = skippedSpan.Start End If lengthSkipped += skippedSpan.Length Dim curToken = GetCurrentToken() Select Case curToken.Kind Case SyntaxKind.HashToken Dim nextKind = Me.PeekToken(1, ScannerState.VB).Kind Dim nextNextToken = Me.PeekToken(2, ScannerState.VB) If NestedConditionalsToSkip = 0 AndAlso ((nextKind = SyntaxKind.EndKeyword AndAlso Not IsContextualKeyword(nextNextToken, SyntaxKind.ExternalSourceKeyword, SyntaxKind.RegionKeyword)) OrElse nextKind = SyntaxKind.EndIfKeyword OrElse nextKind = SyntaxKind.ElseIfKeyword OrElse nextKind = SyntaxKind.ElseKeyword) Then ' // Finding one of these is sufficient to stop skipping. It is then necessary ' // to process the line as a conditional compilation line. The normal ' // parsing logic will do this. Exit While ElseIf nextKind = SyntaxKind.EndIfKeyword OrElse (nextKind = SyntaxKind.EndKeyword AndAlso Not IsContextualKeyword(nextNextToken, SyntaxKind.ExternalSourceKeyword, SyntaxKind.RegionKeyword)) Then NestedConditionalsToSkip -= 1 ElseIf nextKind = SyntaxKind.IfKeyword Then NestedConditionalsToSkip += 1 End If ' if the line concluded the skip block, return from the loop If NestedConditionalsToSkip < 0 Then Debug.Assert(NestedConditionalsToSkip = -1, "preprocessor skip underflow") Exit While End If ' skip over # token lengthSkipped += GetCurrentToken.FullWidth GetNextTokenInState(ScannerState.VB) ' Skip over terminator token to avoid counting it twice because it is already trivia on current token If nextKind = SyntaxKind.StatementTerminatorToken OrElse nextKind = SyntaxKind.ColonToken Then GetNextTokenInState(ScannerState.VB) End If Case SyntaxKind.DateLiteralToken, SyntaxKind.BadToken 'Dev10 #777522 Do not confuse Date literal with an end of conditional block. ' skip over date literal token lengthSkipped += GetCurrentToken.FullWidth GetNextTokenInState(ScannerState.VB) Dim nextKind = GetCurrentToken().Kind ' Skip over terminator token to avoid counting it twice because it is already trivia on current token If nextKind = SyntaxKind.StatementTerminatorToken OrElse nextKind = SyntaxKind.ColonToken Then GetNextTokenInState(ScannerState.VB) End If Case SyntaxKind.EndOfFileToken Exit While Case Else Throw ExceptionUtilities.UnexpectedValue(curToken.Kind) End Select End While If lengthSkipped > 0 Then Return New CodeAnalysis.Syntax.InternalSyntax.SyntaxList(Of VisualBasicSyntaxNode)(Me.GetDisabledTextAt(New TextSpan(startSkipped, lengthSkipped))) Else Return New CodeAnalysis.Syntax.InternalSyntax.SyntaxList(Of VisualBasicSyntaxNode)(Nothing) End If End Function ' // If compilation ends in the middle of a non-skipped conditional section, ' // produce appropriate diagnostics. Friend Function RecoverFromMissingConditionalEnds(eof As PunctuationSyntax, <Out> ByRef notClosedIfDirectives As ArrayBuilder(Of IfDirectiveTriviaSyntax), <Out> ByRef notClosedRegionDirectives As ArrayBuilder(Of RegionDirectiveTriviaSyntax), <Out> ByRef haveRegionDirectives As Boolean, <Out> ByRef notClosedExternalSourceDirective As ExternalSourceDirectiveTriviaSyntax) As PunctuationSyntax notClosedIfDirectives = Nothing notClosedRegionDirectives = Nothing If Me._scannerPreprocessorState.ConditionalStack.Count > 0 Then For Each state In _scannerPreprocessorState.ConditionalStack Dim ifDirective As IfDirectiveTriviaSyntax = state.IfDirective If ifDirective IsNot Nothing Then If notClosedIfDirectives Is Nothing Then notClosedIfDirectives = ArrayBuilder(Of IfDirectiveTriviaSyntax).GetInstance() End If notClosedIfDirectives.Add(ifDirective) End If Next If notClosedIfDirectives Is Nothing Then ' #If directive is not found eof = Parser.ReportSyntaxError(eof, ERRID.ERR_LbExpectedEndIf) End If End If If Me._scannerPreprocessorState.RegionDirectiveStack.Count > 0 Then notClosedRegionDirectives = ArrayBuilder(Of RegionDirectiveTriviaSyntax).GetInstance() notClosedRegionDirectives.AddRange(Me._scannerPreprocessorState.RegionDirectiveStack) End If haveRegionDirectives = Me._scannerPreprocessorState.HaveSeenRegionDirectives notClosedExternalSourceDirective = Me._scannerPreprocessorState.ExternalSourceDirective Return eof End Function End Class End Namespace
-1