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
unknown
date_merged
unknown
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
56,460
Set CompilerApiVersion in Microsoft.Managed.Core.targets
This allows other targets to understand which compiler will be used. This is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets. Contributes to #52265 FYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803
eerhardt
"2021-09-16T21:47:36Z"
"2021-09-22T00:53:07Z"
a10a3720229de8f4227e98736e884d6f926a9950
aabc2fcbf630ba303e6f17808465349ea9b01a32
Set CompilerApiVersion in Microsoft.Managed.Core.targets. This allows other targets to understand which compiler will be used. This is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets. Contributes to #52265 FYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803
./src/VisualStudio/Core/Def/Telemetry/IVsSQM.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 // WARNING: THIS FILE IS BEING CONSUMED THROUGH INTERNALSVISIBLETO // BY THE RULSET EDITOR. Until you fix that, do not delete this file. /////////////////////////////////////////////////////////////////////////////// // // /////////////////////////////////////////////////////////////////////////////// #pragma warning disable 3001 using System; using System.Runtime.InteropServices; namespace Microsoft.VisualStudio.Shell.Interop { [ComImport()] [ComVisible(false)] [Guid("C1F63D0C-4CAE-4907-BE74-EEB75D386ECB")] [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] internal interface IVsSqm { void GetSessionStartTime( [Out] out System.Runtime.InteropServices.ComTypes.FILETIME time ); void GetFlags( [Out, MarshalAs(UnmanagedType.U4)] out System.UInt32 flags ); void SetFlags( [In, MarshalAs(UnmanagedType.U4)] System.UInt32 flags ); void ClearFlags( [In, MarshalAs(UnmanagedType.U4)] System.UInt32 flags ); void AddItemToStream( [In, MarshalAs(UnmanagedType.U4)] System.UInt32 dataPointID, [In, MarshalAs(UnmanagedType.U4)] System.UInt32 value ); void SetDatapoint( [In, MarshalAs(UnmanagedType.U4)] System.UInt32 dataPointID, [In, MarshalAs(UnmanagedType.U4)] System.UInt32 value ); // OBSOLETE IN SQMAPI.DLL. DO NOT CALL. void GetDatapoint( [In, MarshalAs(UnmanagedType.U4)] System.UInt32 dataPointID, [Out, MarshalAs(UnmanagedType.U4)] out System.UInt32 value ); void EnterTaggedAssert( [In, MarshalAs(UnmanagedType.U4)] System.UInt32 dwTag, [In, MarshalAs(UnmanagedType.U4)] System.UInt32 dwPossibleBuild, [In, MarshalAs(UnmanagedType.U4)] System.UInt32 dwActualBuild ); void RecordCmdData( [In] ref Guid pguidCmdGroup, [In, MarshalAs(UnmanagedType.U4)] System.UInt32 dataPointID, [In, MarshalAs(UnmanagedType.U4)] System.UInt32 value ); void GetHashOfGuid( [In] ref Guid hashGuid, [Out, MarshalAs(UnmanagedType.U4)] out System.UInt32 resultantHash ); void GetHashOfString( [In, MarshalAs(UnmanagedType.BStr)] string hashString, [Out, MarshalAs(UnmanagedType.U4)] out System.UInt32 resultantHash ); void IncrementDatapoint( [In, MarshalAs(UnmanagedType.U4)] System.UInt32 dataPointID, [In, MarshalAs(UnmanagedType.U4)] System.UInt32 value ); void SetDatapointBits( [In, MarshalAs(UnmanagedType.U4)] System.UInt32 dataPointID, [In, MarshalAs(UnmanagedType.U4)] System.UInt32 value ); void SetDatapointIfMax( [In, MarshalAs(UnmanagedType.U4)] System.UInt32 dataPointID, [In, MarshalAs(UnmanagedType.U4)] System.UInt32 value ); void SetDatapointIfMin( [In, MarshalAs(UnmanagedType.U4)] System.UInt32 dataPointID, [In, MarshalAs(UnmanagedType.U4)] System.UInt32 value ); void AddToDatapointAverage( [In, MarshalAs(UnmanagedType.U4)] System.UInt32 dataPointID, [In, MarshalAs(UnmanagedType.U4)] System.UInt32 value ); void StartDatapointTimer( [In, MarshalAs(UnmanagedType.U4)] System.UInt32 dataPointID ); void RecordDatapointTimer( [In, MarshalAs(UnmanagedType.U4)] System.UInt32 dataPointID ); void AccumulateDatapointTimer( [In, MarshalAs(UnmanagedType.U4)] System.UInt32 dataPointID ); void AddTimerToDatapointAverage( [In, MarshalAs(UnmanagedType.U4)] System.UInt32 dataPointID ); void AddArrayToStream( [In, MarshalAs(UnmanagedType.U4)] System.UInt32 dataPointID, [In, MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.U4, SizeParamIndex = 2)] System.UInt32[] data, [In, MarshalAs(UnmanagedType.I4)] int count ); } [ComImport()] [ComVisible(false)] [Guid("BE5F55EB-F02D-4217-BCB6-A290800AF6C4")] [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] internal interface IVsSqm2 { void SetBoolDatapoint( [In, MarshalAs(UnmanagedType.U4)] System.UInt32 dataPointID, [In, MarshalAs(UnmanagedType.U4)] System.UInt32 fValue ); void SetStringDatapoint( [In, MarshalAs(UnmanagedType.U4)] System.UInt32 dataPointID, [In, MarshalAs(UnmanagedType.BStr)] string strValue ); void AddToStreamDWord( [In, MarshalAs(UnmanagedType.U4)] System.UInt32 dataPointID, [In, MarshalAs(UnmanagedType.U4)] System.UInt32 cTuple, [In, MarshalAs(UnmanagedType.U4)] System.UInt32 value ); void AddToStreamString( [In, MarshalAs(UnmanagedType.U4)] System.UInt32 dataPointID, [In, MarshalAs(UnmanagedType.U4)] System.UInt32 cTuple, [In, MarshalAs(UnmanagedType.BStr)] string strValue ); void GetObfuscatedString( [In, MarshalAs(UnmanagedType.BStr)] string input, [Out, MarshalAs(UnmanagedType.BStr)] out string output ); } [ComImport()] [ComVisible(false)] [Guid("B17A7D4A-C1A3-45A2-B916-826C3ABA067E")] [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] internal interface IVsSqmMulti { #pragma warning disable CS0618 // Type or member is obsolete [return: MarshalAs(UnmanagedType.VariantBool)] #pragma warning restore CS0618 // Type or member is obsolete bool GetOptInStatus(); void UnloadSessions( ); void EndAllSessionsAndAbortUploads( ); void BeginSession( [In, MarshalAs(UnmanagedType.U4)] System.UInt32 sessionType, #pragma warning disable CS0618 // Type or member is obsolete [In, MarshalAs(UnmanagedType.VariantBool)] System.Boolean alwaysSend, #pragma warning restore CS0618 // Type or member is obsolete [Out, MarshalAs(UnmanagedType.U4)] out System.UInt32 sessionHandle ); void EndSession( [In, MarshalAs(UnmanagedType.U4)] System.UInt32 sessionHandle ); void RegisterSessionHandle( [In] ref Guid sessionIdentifier, [In, MarshalAs(UnmanagedType.U4)] System.UInt32 dwSessionHandle ); [return: MarshalAs(UnmanagedType.U4)] int GetSessionHandleByIdentifier( [In] ref Guid sessionIdentifier ); void GetSessionStartTime( [In, MarshalAs(UnmanagedType.U4)] System.UInt32 sessionHandle, [Out] out System.Runtime.InteropServices.ComTypes.FILETIME time ); Guid GetGlobalSessionGuid(); [return: MarshalAs(UnmanagedType.U4)] int GetGlobalSessionHandle(); void SetGlobalSessionGuid( [In] ref Guid pguidSessionGuid ); void GetFlags( [In, MarshalAs(UnmanagedType.U4)] System.UInt32 sessionHandle, [Out, MarshalAs(UnmanagedType.U4)] out System.UInt32 flags ); void SetFlags( [In, MarshalAs(UnmanagedType.U4)] System.UInt32 sessionHandle, [In, MarshalAs(UnmanagedType.U4)] System.UInt32 flags ); void ClearFlags( [In, MarshalAs(UnmanagedType.U4)] System.UInt32 sessionHandle, [In, MarshalAs(UnmanagedType.U4)] System.UInt32 flags ); void SetDatapoint( [In, MarshalAs(UnmanagedType.U4)] System.UInt32 sessionHandle, [In, MarshalAs(UnmanagedType.U4)] System.UInt32 dataPointID, [In, MarshalAs(UnmanagedType.U4)] System.UInt32 value ); void SetBoolDatapoint( [In, MarshalAs(UnmanagedType.U4)] System.UInt32 sessionHandle, [In, MarshalAs(UnmanagedType.U4)] System.UInt32 dataPointID, [In, MarshalAs(UnmanagedType.U4)] System.UInt32 fValue ); void SetStringDatapoint( [In, MarshalAs(UnmanagedType.U4)] System.UInt32 sessionHandle, [In, MarshalAs(UnmanagedType.U4)] System.UInt32 dataPointID, [In, MarshalAs(UnmanagedType.BStr)] string strValue ); void SetDatapointBits( [In, MarshalAs(UnmanagedType.U4)] System.UInt32 sessionHandle, [In, MarshalAs(UnmanagedType.U4)] System.UInt32 dataPointID, [In, MarshalAs(UnmanagedType.U4)] System.UInt32 value ); void IncrementDatapoint( [In, MarshalAs(UnmanagedType.U4)] System.UInt32 sessionHandle, [In, MarshalAs(UnmanagedType.U4)] System.UInt32 dataPointID, [In, MarshalAs(UnmanagedType.U4)] System.UInt32 value ); void SetDatapointIfMax( [In, MarshalAs(UnmanagedType.U4)] System.UInt32 sessionHandle, [In, MarshalAs(UnmanagedType.U4)] System.UInt32 dataPointID, [In, MarshalAs(UnmanagedType.U4)] System.UInt32 value ); void SetDatapointIfMin( [In, MarshalAs(UnmanagedType.U4)] System.UInt32 sessionHandle, [In, MarshalAs(UnmanagedType.U4)] System.UInt32 dataPointID, [In, MarshalAs(UnmanagedType.U4)] System.UInt32 value ); void AddToDatapointAverage( [In, MarshalAs(UnmanagedType.U4)] System.UInt32 sessionHandle, [In, MarshalAs(UnmanagedType.U4)] System.UInt32 dataPointID, [In, MarshalAs(UnmanagedType.U4)] System.UInt32 value ); void StartDatapointTimer( [In, MarshalAs(UnmanagedType.U4)] System.UInt32 sessionHandle, [In, MarshalAs(UnmanagedType.U4)] System.UInt32 dataPointID ); void RecordDatapointTimer( [In, MarshalAs(UnmanagedType.U4)] System.UInt32 sessionHandle, [In, MarshalAs(UnmanagedType.U4)] System.UInt32 dataPointID ); void AccumulateDatapointTimer( [In, MarshalAs(UnmanagedType.U4)] System.UInt32 sessionHandle, [In, MarshalAs(UnmanagedType.U4)] System.UInt32 dataPointID ); void AddTimerToDatapointAverage( [In, MarshalAs(UnmanagedType.U4)] System.UInt32 sessionHandle, [In, MarshalAs(UnmanagedType.U4)] System.UInt32 dataPointID ); void AddItemToStream( [In, MarshalAs(UnmanagedType.U4)] System.UInt32 sessionHandle, [In, MarshalAs(UnmanagedType.U4)] System.UInt32 dataPointID, [In, MarshalAs(UnmanagedType.U4)] System.UInt32 value ); void AddArrayToStream( [In, MarshalAs(UnmanagedType.U4)] System.UInt32 sessionHandle, [In, MarshalAs(UnmanagedType.U4)] System.UInt32 dataPointID, [In, MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.U4, SizeParamIndex = 2)] System.UInt32[] data, [In, MarshalAs(UnmanagedType.I4)] int count ); void AddToStreamDWord( [In, MarshalAs(UnmanagedType.U4)] System.UInt32 sessionHandle, [In, MarshalAs(UnmanagedType.U4)] System.UInt32 dataPointID, [In, MarshalAs(UnmanagedType.U4)] System.UInt32 cTuple, [In, MarshalAs(UnmanagedType.U4)] System.UInt32 value ); void AddToStreamString( [In, MarshalAs(UnmanagedType.U4)] System.UInt32 sessionHandle, [In, MarshalAs(UnmanagedType.U4)] System.UInt32 dataPointID, [In, MarshalAs(UnmanagedType.U4)] System.UInt32 cTuple, [In, MarshalAs(UnmanagedType.BStr)] string strValue ); void RecordCmdData( [In, MarshalAs(UnmanagedType.U4)] System.UInt32 sessionHandle, [In] ref Guid pguidCmdGroup, [In, MarshalAs(UnmanagedType.U4)] System.UInt32 dataPointID, [In, MarshalAs(UnmanagedType.U4)] System.UInt32 value ); void GetHashOfGuid( [In] ref Guid hashGuid, [Out, MarshalAs(UnmanagedType.U4)] out System.UInt32 resultantHash ); void GetHashOfString( [In, MarshalAs(UnmanagedType.BStr)] string hashString, [Out, MarshalAs(UnmanagedType.U4)] out System.UInt32 resultantHash ); void SetProperty( [In, MarshalAs(UnmanagedType.U4)] System.UInt32 propid, [In] ref Guid varKey, [In] object varValue ); void Get64BitHashOfString( [In, MarshalAs(UnmanagedType.BStr)] string hashString, [Out, MarshalAs(UnmanagedType.U8)] out System.UInt64 resultantHash ); } [ComImport()] [ComVisible(false)] [Guid("16be4288-950b-4265-b0dc-280b89ca9979")] [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] internal interface IVsSqmOptinManager { void GetOptinStatus( [Out, MarshalAs(UnmanagedType.U4)] out System.UInt32 optinStatus, [Out, MarshalAs(UnmanagedType.U4)] out System.UInt32 preferences ); void SetOptinStatus( [In, MarshalAs(UnmanagedType.U4)] System.UInt32 optinStatus ); } [ComImport()] [ComVisible(false)] [Guid("2508FDF0-EF80-4366-878E-C9F024B8D981")] internal interface SVsLog { } }
// Licensed to the .NET Foundation under one or more 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 // WARNING: THIS FILE IS BEING CONSUMED THROUGH INTERNALSVISIBLETO // BY THE RULSET EDITOR. Until you fix that, do not delete this file. /////////////////////////////////////////////////////////////////////////////// // // /////////////////////////////////////////////////////////////////////////////// #pragma warning disable 3001 using System; using System.Runtime.InteropServices; namespace Microsoft.VisualStudio.Shell.Interop { [ComImport()] [ComVisible(false)] [Guid("C1F63D0C-4CAE-4907-BE74-EEB75D386ECB")] [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] internal interface IVsSqm { void GetSessionStartTime( [Out] out System.Runtime.InteropServices.ComTypes.FILETIME time ); void GetFlags( [Out, MarshalAs(UnmanagedType.U4)] out System.UInt32 flags ); void SetFlags( [In, MarshalAs(UnmanagedType.U4)] System.UInt32 flags ); void ClearFlags( [In, MarshalAs(UnmanagedType.U4)] System.UInt32 flags ); void AddItemToStream( [In, MarshalAs(UnmanagedType.U4)] System.UInt32 dataPointID, [In, MarshalAs(UnmanagedType.U4)] System.UInt32 value ); void SetDatapoint( [In, MarshalAs(UnmanagedType.U4)] System.UInt32 dataPointID, [In, MarshalAs(UnmanagedType.U4)] System.UInt32 value ); // OBSOLETE IN SQMAPI.DLL. DO NOT CALL. void GetDatapoint( [In, MarshalAs(UnmanagedType.U4)] System.UInt32 dataPointID, [Out, MarshalAs(UnmanagedType.U4)] out System.UInt32 value ); void EnterTaggedAssert( [In, MarshalAs(UnmanagedType.U4)] System.UInt32 dwTag, [In, MarshalAs(UnmanagedType.U4)] System.UInt32 dwPossibleBuild, [In, MarshalAs(UnmanagedType.U4)] System.UInt32 dwActualBuild ); void RecordCmdData( [In] ref Guid pguidCmdGroup, [In, MarshalAs(UnmanagedType.U4)] System.UInt32 dataPointID, [In, MarshalAs(UnmanagedType.U4)] System.UInt32 value ); void GetHashOfGuid( [In] ref Guid hashGuid, [Out, MarshalAs(UnmanagedType.U4)] out System.UInt32 resultantHash ); void GetHashOfString( [In, MarshalAs(UnmanagedType.BStr)] string hashString, [Out, MarshalAs(UnmanagedType.U4)] out System.UInt32 resultantHash ); void IncrementDatapoint( [In, MarshalAs(UnmanagedType.U4)] System.UInt32 dataPointID, [In, MarshalAs(UnmanagedType.U4)] System.UInt32 value ); void SetDatapointBits( [In, MarshalAs(UnmanagedType.U4)] System.UInt32 dataPointID, [In, MarshalAs(UnmanagedType.U4)] System.UInt32 value ); void SetDatapointIfMax( [In, MarshalAs(UnmanagedType.U4)] System.UInt32 dataPointID, [In, MarshalAs(UnmanagedType.U4)] System.UInt32 value ); void SetDatapointIfMin( [In, MarshalAs(UnmanagedType.U4)] System.UInt32 dataPointID, [In, MarshalAs(UnmanagedType.U4)] System.UInt32 value ); void AddToDatapointAverage( [In, MarshalAs(UnmanagedType.U4)] System.UInt32 dataPointID, [In, MarshalAs(UnmanagedType.U4)] System.UInt32 value ); void StartDatapointTimer( [In, MarshalAs(UnmanagedType.U4)] System.UInt32 dataPointID ); void RecordDatapointTimer( [In, MarshalAs(UnmanagedType.U4)] System.UInt32 dataPointID ); void AccumulateDatapointTimer( [In, MarshalAs(UnmanagedType.U4)] System.UInt32 dataPointID ); void AddTimerToDatapointAverage( [In, MarshalAs(UnmanagedType.U4)] System.UInt32 dataPointID ); void AddArrayToStream( [In, MarshalAs(UnmanagedType.U4)] System.UInt32 dataPointID, [In, MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.U4, SizeParamIndex = 2)] System.UInt32[] data, [In, MarshalAs(UnmanagedType.I4)] int count ); } [ComImport()] [ComVisible(false)] [Guid("BE5F55EB-F02D-4217-BCB6-A290800AF6C4")] [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] internal interface IVsSqm2 { void SetBoolDatapoint( [In, MarshalAs(UnmanagedType.U4)] System.UInt32 dataPointID, [In, MarshalAs(UnmanagedType.U4)] System.UInt32 fValue ); void SetStringDatapoint( [In, MarshalAs(UnmanagedType.U4)] System.UInt32 dataPointID, [In, MarshalAs(UnmanagedType.BStr)] string strValue ); void AddToStreamDWord( [In, MarshalAs(UnmanagedType.U4)] System.UInt32 dataPointID, [In, MarshalAs(UnmanagedType.U4)] System.UInt32 cTuple, [In, MarshalAs(UnmanagedType.U4)] System.UInt32 value ); void AddToStreamString( [In, MarshalAs(UnmanagedType.U4)] System.UInt32 dataPointID, [In, MarshalAs(UnmanagedType.U4)] System.UInt32 cTuple, [In, MarshalAs(UnmanagedType.BStr)] string strValue ); void GetObfuscatedString( [In, MarshalAs(UnmanagedType.BStr)] string input, [Out, MarshalAs(UnmanagedType.BStr)] out string output ); } [ComImport()] [ComVisible(false)] [Guid("B17A7D4A-C1A3-45A2-B916-826C3ABA067E")] [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] internal interface IVsSqmMulti { #pragma warning disable CS0618 // Type or member is obsolete [return: MarshalAs(UnmanagedType.VariantBool)] #pragma warning restore CS0618 // Type or member is obsolete bool GetOptInStatus(); void UnloadSessions( ); void EndAllSessionsAndAbortUploads( ); void BeginSession( [In, MarshalAs(UnmanagedType.U4)] System.UInt32 sessionType, #pragma warning disable CS0618 // Type or member is obsolete [In, MarshalAs(UnmanagedType.VariantBool)] System.Boolean alwaysSend, #pragma warning restore CS0618 // Type or member is obsolete [Out, MarshalAs(UnmanagedType.U4)] out System.UInt32 sessionHandle ); void EndSession( [In, MarshalAs(UnmanagedType.U4)] System.UInt32 sessionHandle ); void RegisterSessionHandle( [In] ref Guid sessionIdentifier, [In, MarshalAs(UnmanagedType.U4)] System.UInt32 dwSessionHandle ); [return: MarshalAs(UnmanagedType.U4)] int GetSessionHandleByIdentifier( [In] ref Guid sessionIdentifier ); void GetSessionStartTime( [In, MarshalAs(UnmanagedType.U4)] System.UInt32 sessionHandle, [Out] out System.Runtime.InteropServices.ComTypes.FILETIME time ); Guid GetGlobalSessionGuid(); [return: MarshalAs(UnmanagedType.U4)] int GetGlobalSessionHandle(); void SetGlobalSessionGuid( [In] ref Guid pguidSessionGuid ); void GetFlags( [In, MarshalAs(UnmanagedType.U4)] System.UInt32 sessionHandle, [Out, MarshalAs(UnmanagedType.U4)] out System.UInt32 flags ); void SetFlags( [In, MarshalAs(UnmanagedType.U4)] System.UInt32 sessionHandle, [In, MarshalAs(UnmanagedType.U4)] System.UInt32 flags ); void ClearFlags( [In, MarshalAs(UnmanagedType.U4)] System.UInt32 sessionHandle, [In, MarshalAs(UnmanagedType.U4)] System.UInt32 flags ); void SetDatapoint( [In, MarshalAs(UnmanagedType.U4)] System.UInt32 sessionHandle, [In, MarshalAs(UnmanagedType.U4)] System.UInt32 dataPointID, [In, MarshalAs(UnmanagedType.U4)] System.UInt32 value ); void SetBoolDatapoint( [In, MarshalAs(UnmanagedType.U4)] System.UInt32 sessionHandle, [In, MarshalAs(UnmanagedType.U4)] System.UInt32 dataPointID, [In, MarshalAs(UnmanagedType.U4)] System.UInt32 fValue ); void SetStringDatapoint( [In, MarshalAs(UnmanagedType.U4)] System.UInt32 sessionHandle, [In, MarshalAs(UnmanagedType.U4)] System.UInt32 dataPointID, [In, MarshalAs(UnmanagedType.BStr)] string strValue ); void SetDatapointBits( [In, MarshalAs(UnmanagedType.U4)] System.UInt32 sessionHandle, [In, MarshalAs(UnmanagedType.U4)] System.UInt32 dataPointID, [In, MarshalAs(UnmanagedType.U4)] System.UInt32 value ); void IncrementDatapoint( [In, MarshalAs(UnmanagedType.U4)] System.UInt32 sessionHandle, [In, MarshalAs(UnmanagedType.U4)] System.UInt32 dataPointID, [In, MarshalAs(UnmanagedType.U4)] System.UInt32 value ); void SetDatapointIfMax( [In, MarshalAs(UnmanagedType.U4)] System.UInt32 sessionHandle, [In, MarshalAs(UnmanagedType.U4)] System.UInt32 dataPointID, [In, MarshalAs(UnmanagedType.U4)] System.UInt32 value ); void SetDatapointIfMin( [In, MarshalAs(UnmanagedType.U4)] System.UInt32 sessionHandle, [In, MarshalAs(UnmanagedType.U4)] System.UInt32 dataPointID, [In, MarshalAs(UnmanagedType.U4)] System.UInt32 value ); void AddToDatapointAverage( [In, MarshalAs(UnmanagedType.U4)] System.UInt32 sessionHandle, [In, MarshalAs(UnmanagedType.U4)] System.UInt32 dataPointID, [In, MarshalAs(UnmanagedType.U4)] System.UInt32 value ); void StartDatapointTimer( [In, MarshalAs(UnmanagedType.U4)] System.UInt32 sessionHandle, [In, MarshalAs(UnmanagedType.U4)] System.UInt32 dataPointID ); void RecordDatapointTimer( [In, MarshalAs(UnmanagedType.U4)] System.UInt32 sessionHandle, [In, MarshalAs(UnmanagedType.U4)] System.UInt32 dataPointID ); void AccumulateDatapointTimer( [In, MarshalAs(UnmanagedType.U4)] System.UInt32 sessionHandle, [In, MarshalAs(UnmanagedType.U4)] System.UInt32 dataPointID ); void AddTimerToDatapointAverage( [In, MarshalAs(UnmanagedType.U4)] System.UInt32 sessionHandle, [In, MarshalAs(UnmanagedType.U4)] System.UInt32 dataPointID ); void AddItemToStream( [In, MarshalAs(UnmanagedType.U4)] System.UInt32 sessionHandle, [In, MarshalAs(UnmanagedType.U4)] System.UInt32 dataPointID, [In, MarshalAs(UnmanagedType.U4)] System.UInt32 value ); void AddArrayToStream( [In, MarshalAs(UnmanagedType.U4)] System.UInt32 sessionHandle, [In, MarshalAs(UnmanagedType.U4)] System.UInt32 dataPointID, [In, MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.U4, SizeParamIndex = 2)] System.UInt32[] data, [In, MarshalAs(UnmanagedType.I4)] int count ); void AddToStreamDWord( [In, MarshalAs(UnmanagedType.U4)] System.UInt32 sessionHandle, [In, MarshalAs(UnmanagedType.U4)] System.UInt32 dataPointID, [In, MarshalAs(UnmanagedType.U4)] System.UInt32 cTuple, [In, MarshalAs(UnmanagedType.U4)] System.UInt32 value ); void AddToStreamString( [In, MarshalAs(UnmanagedType.U4)] System.UInt32 sessionHandle, [In, MarshalAs(UnmanagedType.U4)] System.UInt32 dataPointID, [In, MarshalAs(UnmanagedType.U4)] System.UInt32 cTuple, [In, MarshalAs(UnmanagedType.BStr)] string strValue ); void RecordCmdData( [In, MarshalAs(UnmanagedType.U4)] System.UInt32 sessionHandle, [In] ref Guid pguidCmdGroup, [In, MarshalAs(UnmanagedType.U4)] System.UInt32 dataPointID, [In, MarshalAs(UnmanagedType.U4)] System.UInt32 value ); void GetHashOfGuid( [In] ref Guid hashGuid, [Out, MarshalAs(UnmanagedType.U4)] out System.UInt32 resultantHash ); void GetHashOfString( [In, MarshalAs(UnmanagedType.BStr)] string hashString, [Out, MarshalAs(UnmanagedType.U4)] out System.UInt32 resultantHash ); void SetProperty( [In, MarshalAs(UnmanagedType.U4)] System.UInt32 propid, [In] ref Guid varKey, [In] object varValue ); void Get64BitHashOfString( [In, MarshalAs(UnmanagedType.BStr)] string hashString, [Out, MarshalAs(UnmanagedType.U8)] out System.UInt64 resultantHash ); } [ComImport()] [ComVisible(false)] [Guid("16be4288-950b-4265-b0dc-280b89ca9979")] [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] internal interface IVsSqmOptinManager { void GetOptinStatus( [Out, MarshalAs(UnmanagedType.U4)] out System.UInt32 optinStatus, [Out, MarshalAs(UnmanagedType.U4)] out System.UInt32 preferences ); void SetOptinStatus( [In, MarshalAs(UnmanagedType.U4)] System.UInt32 optinStatus ); } [ComImport()] [ComVisible(false)] [Guid("2508FDF0-EF80-4366-878E-C9F024B8D981")] internal interface SVsLog { } }
-1
dotnet/roslyn
56,460
Set CompilerApiVersion in Microsoft.Managed.Core.targets
This allows other targets to understand which compiler will be used. This is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets. Contributes to #52265 FYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803
eerhardt
"2021-09-16T21:47:36Z"
"2021-09-22T00:53:07Z"
a10a3720229de8f4227e98736e884d6f926a9950
aabc2fcbf630ba303e6f17808465349ea9b01a32
Set CompilerApiVersion in Microsoft.Managed.Core.targets. This allows other targets to understand which compiler will be used. This is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets. Contributes to #52265 FYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803
./src/Workspaces/Core/Portable/Options/PerLanguageOption2_operators.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.Diagnostics.CodeAnalysis; namespace Microsoft.CodeAnalysis.Options { internal partial class PerLanguageOption2<T> { [return: NotNullIfNotNull("option")] public static explicit operator PerLanguageOption<T>?(PerLanguageOption2<T>? option) { if (option is null) { return null; } return new PerLanguageOption<T>(option.OptionDefinition, option.StorageLocations.As<OptionStorageLocation>()); } } }
// Licensed to the .NET Foundation under one or more 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.Diagnostics.CodeAnalysis; namespace Microsoft.CodeAnalysis.Options { internal partial class PerLanguageOption2<T> { [return: NotNullIfNotNull("option")] public static explicit operator PerLanguageOption<T>?(PerLanguageOption2<T>? option) { if (option is null) { return null; } return new PerLanguageOption<T>(option.OptionDefinition, option.StorageLocations.As<OptionStorageLocation>()); } } }
-1
dotnet/roslyn
56,460
Set CompilerApiVersion in Microsoft.Managed.Core.targets
This allows other targets to understand which compiler will be used. This is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets. Contributes to #52265 FYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803
eerhardt
"2021-09-16T21:47:36Z"
"2021-09-22T00:53:07Z"
a10a3720229de8f4227e98736e884d6f926a9950
aabc2fcbf630ba303e6f17808465349ea9b01a32
Set CompilerApiVersion in Microsoft.Managed.Core.targets. This allows other targets to understand which compiler will be used. This is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets. Contributes to #52265 FYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803
./src/Features/Core/Portable/Intents/IIntentProviderMetadata.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.Features.Intents { internal interface IIntentProviderMetadata { public string IntentName { get; } public string LanguageName { 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. namespace Microsoft.CodeAnalysis.Features.Intents { internal interface IIntentProviderMetadata { public string IntentName { get; } public string LanguageName { get; } } }
-1
dotnet/roslyn
56,460
Set CompilerApiVersion in Microsoft.Managed.Core.targets
This allows other targets to understand which compiler will be used. This is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets. Contributes to #52265 FYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803
eerhardt
"2021-09-16T21:47:36Z"
"2021-09-22T00:53:07Z"
a10a3720229de8f4227e98736e884d6f926a9950
aabc2fcbf630ba303e6f17808465349ea9b01a32
Set CompilerApiVersion in Microsoft.Managed.Core.targets. This allows other targets to understand which compiler will be used. This is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets. Contributes to #52265 FYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803
./src/Tools/Source/CompilerGeneratorTools/Source/CSharpSyntaxGenerator/SourceGenerator.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. // We only build the Source Generator in the netstandard target #if NETSTANDARD #nullable enable using System; using System.Collections.Immutable; using System.IO; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using System.Threading; using System.Xml; using System.Xml.Serialization; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Text; namespace CSharpSyntaxGenerator { [Generator] public sealed class SourceGenerator : CachingSourceGenerator { private static readonly DiagnosticDescriptor s_MissingSyntaxXml = new DiagnosticDescriptor( "CSSG1001", title: "Syntax.xml is missing", messageFormat: "The Syntax.xml file was not included in the project, so we are not generating source.", category: "SyntaxGenerator", defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true); private static readonly DiagnosticDescriptor s_UnableToReadSyntaxXml = new DiagnosticDescriptor( "CSSG1002", title: "Syntax.xml could not be read", messageFormat: "The Syntax.xml file could not even be read. Does it exist?", category: "SyntaxGenerator", defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true); private static readonly DiagnosticDescriptor s_SyntaxXmlError = new DiagnosticDescriptor( "CSSG1003", title: "Syntax.xml has a syntax error", messageFormat: "{0}", category: "SyntaxGenerator", defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true); protected override bool TryGetRelevantInput(in GeneratorExecutionContext context, out AdditionalText? input, out SourceText? inputText) { input = context.AdditionalFiles.SingleOrDefault(a => Path.GetFileName(a.Path) == "Syntax.xml"); if (input == null) { context.ReportDiagnostic(Diagnostic.Create(s_MissingSyntaxXml, location: null)); inputText = null; return false; } inputText = input.GetText(); if (inputText == null) { context.ReportDiagnostic(Diagnostic.Create(s_UnableToReadSyntaxXml, location: null)); return false; } return true; } protected override bool TryGenerateSources( AdditionalText input, SourceText inputText, out ImmutableArray<(string hintName, SourceText sourceText)> sources, out ImmutableArray<Diagnostic> diagnostics, CancellationToken cancellationToken) { Tree tree; var reader = XmlReader.Create(new SourceTextReader(inputText), new XmlReaderSettings { DtdProcessing = DtdProcessing.Prohibit }); try { var serializer = new XmlSerializer(typeof(Tree)); tree = (Tree)serializer.Deserialize(reader); } catch (InvalidOperationException ex) when (ex.InnerException is XmlException) { var xmlException = (XmlException)ex.InnerException; var line = inputText.Lines[xmlException.LineNumber - 1]; // LineNumber is one-based. int offset = xmlException.LinePosition - 1; // LinePosition is one-based var position = line.Start + offset; var span = new TextSpan(position, 0); var lineSpan = inputText.Lines.GetLinePositionSpan(span); sources = default; diagnostics = ImmutableArray.Create( Diagnostic.Create( s_SyntaxXmlError, location: Location.Create(input.Path, span, lineSpan), xmlException.Message)); return false; } TreeFlattening.FlattenChildren(tree); var sourcesBuilder = ImmutableArray.CreateBuilder<(string hintName, SourceText sourceText)>(); addResult(writer => SourceWriter.WriteMain(writer, tree, cancellationToken), "Syntax.xml.Main.Generated.cs"); addResult(writer => SourceWriter.WriteInternal(writer, tree, cancellationToken), "Syntax.xml.Internal.Generated.cs"); addResult(writer => SourceWriter.WriteSyntax(writer, tree, cancellationToken), "Syntax.xml.Syntax.Generated.cs"); sources = sourcesBuilder.ToImmutable(); diagnostics = ImmutableArray<Diagnostic>.Empty; return true; void addResult(Action<TextWriter> writeFunction, string hintName) { // Write out the contents to a StringBuilder to avoid creating a single large string // in memory var stringBuilder = new StringBuilder(); using (var textWriter = new StringWriter(stringBuilder)) { writeFunction(textWriter); } // And create a SourceText from the StringBuilder, once again avoiding allocating a single massive string var sourceText = SourceText.From(new StringBuilderReader(stringBuilder), stringBuilder.Length, encoding: Encoding.UTF8); sourcesBuilder.Add((hintName, sourceText)); } } private sealed class SourceTextReader : TextReader { private readonly SourceText _sourceText; private int _position; public SourceTextReader(SourceText sourceText) { _sourceText = sourceText; _position = 0; } public override int Peek() { if (_position == _sourceText.Length) { return -1; } return _sourceText[_position]; } public override int Read() { if (_position == _sourceText.Length) { return -1; } return _sourceText[_position++]; } public override int Read(char[] buffer, int index, int count) { var charsToCopy = Math.Min(count, _sourceText.Length - _position); _sourceText.CopyTo(_position, buffer, index, charsToCopy); _position += charsToCopy; return charsToCopy; } } private sealed class StringBuilderReader : TextReader { private readonly StringBuilder _stringBuilder; private int _position; public StringBuilderReader(StringBuilder stringBuilder) { _stringBuilder = stringBuilder; _position = 0; } public override int Peek() { if (_position == _stringBuilder.Length) { return -1; } return _stringBuilder[_position]; } public override int Read() { if (_position == _stringBuilder.Length) { return -1; } return _stringBuilder[_position++]; } public override int Read(char[] buffer, int index, int count) { var charsToCopy = Math.Min(count, _stringBuilder.Length - _position); _stringBuilder.CopyTo(_position, buffer, index, charsToCopy); _position += charsToCopy; return charsToCopy; } } } } #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. // We only build the Source Generator in the netstandard target #if NETSTANDARD #nullable enable using System; using System.Collections.Immutable; using System.IO; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using System.Threading; using System.Xml; using System.Xml.Serialization; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Text; namespace CSharpSyntaxGenerator { [Generator] public sealed class SourceGenerator : CachingSourceGenerator { private static readonly DiagnosticDescriptor s_MissingSyntaxXml = new DiagnosticDescriptor( "CSSG1001", title: "Syntax.xml is missing", messageFormat: "The Syntax.xml file was not included in the project, so we are not generating source.", category: "SyntaxGenerator", defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true); private static readonly DiagnosticDescriptor s_UnableToReadSyntaxXml = new DiagnosticDescriptor( "CSSG1002", title: "Syntax.xml could not be read", messageFormat: "The Syntax.xml file could not even be read. Does it exist?", category: "SyntaxGenerator", defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true); private static readonly DiagnosticDescriptor s_SyntaxXmlError = new DiagnosticDescriptor( "CSSG1003", title: "Syntax.xml has a syntax error", messageFormat: "{0}", category: "SyntaxGenerator", defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true); protected override bool TryGetRelevantInput(in GeneratorExecutionContext context, out AdditionalText? input, out SourceText? inputText) { input = context.AdditionalFiles.SingleOrDefault(a => Path.GetFileName(a.Path) == "Syntax.xml"); if (input == null) { context.ReportDiagnostic(Diagnostic.Create(s_MissingSyntaxXml, location: null)); inputText = null; return false; } inputText = input.GetText(); if (inputText == null) { context.ReportDiagnostic(Diagnostic.Create(s_UnableToReadSyntaxXml, location: null)); return false; } return true; } protected override bool TryGenerateSources( AdditionalText input, SourceText inputText, out ImmutableArray<(string hintName, SourceText sourceText)> sources, out ImmutableArray<Diagnostic> diagnostics, CancellationToken cancellationToken) { Tree tree; var reader = XmlReader.Create(new SourceTextReader(inputText), new XmlReaderSettings { DtdProcessing = DtdProcessing.Prohibit }); try { var serializer = new XmlSerializer(typeof(Tree)); tree = (Tree)serializer.Deserialize(reader); } catch (InvalidOperationException ex) when (ex.InnerException is XmlException) { var xmlException = (XmlException)ex.InnerException; var line = inputText.Lines[xmlException.LineNumber - 1]; // LineNumber is one-based. int offset = xmlException.LinePosition - 1; // LinePosition is one-based var position = line.Start + offset; var span = new TextSpan(position, 0); var lineSpan = inputText.Lines.GetLinePositionSpan(span); sources = default; diagnostics = ImmutableArray.Create( Diagnostic.Create( s_SyntaxXmlError, location: Location.Create(input.Path, span, lineSpan), xmlException.Message)); return false; } TreeFlattening.FlattenChildren(tree); var sourcesBuilder = ImmutableArray.CreateBuilder<(string hintName, SourceText sourceText)>(); addResult(writer => SourceWriter.WriteMain(writer, tree, cancellationToken), "Syntax.xml.Main.Generated.cs"); addResult(writer => SourceWriter.WriteInternal(writer, tree, cancellationToken), "Syntax.xml.Internal.Generated.cs"); addResult(writer => SourceWriter.WriteSyntax(writer, tree, cancellationToken), "Syntax.xml.Syntax.Generated.cs"); sources = sourcesBuilder.ToImmutable(); diagnostics = ImmutableArray<Diagnostic>.Empty; return true; void addResult(Action<TextWriter> writeFunction, string hintName) { // Write out the contents to a StringBuilder to avoid creating a single large string // in memory var stringBuilder = new StringBuilder(); using (var textWriter = new StringWriter(stringBuilder)) { writeFunction(textWriter); } // And create a SourceText from the StringBuilder, once again avoiding allocating a single massive string var sourceText = SourceText.From(new StringBuilderReader(stringBuilder), stringBuilder.Length, encoding: Encoding.UTF8); sourcesBuilder.Add((hintName, sourceText)); } } private sealed class SourceTextReader : TextReader { private readonly SourceText _sourceText; private int _position; public SourceTextReader(SourceText sourceText) { _sourceText = sourceText; _position = 0; } public override int Peek() { if (_position == _sourceText.Length) { return -1; } return _sourceText[_position]; } public override int Read() { if (_position == _sourceText.Length) { return -1; } return _sourceText[_position++]; } public override int Read(char[] buffer, int index, int count) { var charsToCopy = Math.Min(count, _sourceText.Length - _position); _sourceText.CopyTo(_position, buffer, index, charsToCopy); _position += charsToCopy; return charsToCopy; } } private sealed class StringBuilderReader : TextReader { private readonly StringBuilder _stringBuilder; private int _position; public StringBuilderReader(StringBuilder stringBuilder) { _stringBuilder = stringBuilder; _position = 0; } public override int Peek() { if (_position == _stringBuilder.Length) { return -1; } return _stringBuilder[_position]; } public override int Read() { if (_position == _stringBuilder.Length) { return -1; } return _stringBuilder[_position++]; } public override int Read(char[] buffer, int index, int count) { var charsToCopy = Math.Min(count, _stringBuilder.Length - _position); _stringBuilder.CopyTo(_position, buffer, index, charsToCopy); _position += charsToCopy; return charsToCopy; } } } } #endif
-1
dotnet/roslyn
56,460
Set CompilerApiVersion in Microsoft.Managed.Core.targets
This allows other targets to understand which compiler will be used. This is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets. Contributes to #52265 FYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803
eerhardt
"2021-09-16T21:47:36Z"
"2021-09-22T00:53:07Z"
a10a3720229de8f4227e98736e884d6f926a9950
aabc2fcbf630ba303e6f17808465349ea9b01a32
Set CompilerApiVersion in Microsoft.Managed.Core.targets. This allows other targets to understand which compiler will be used. This is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets. Contributes to #52265 FYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803
./src/Workspaces/Core/Portable/CodeCleanup/Providers/FormatCodeCleanupProvider.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 System.Threading.Tasks; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CodeCleanup.Providers { internal class FormatCodeCleanupProvider : ICodeCleanupProvider { public string Name => PredefinedCodeCleanupProviderNames.Format; public async Task<Document> CleanupAsync(Document document, ImmutableArray<TextSpan> spans, CancellationToken cancellationToken) { // If the old text already exists, use the fast path for formatting. if (document.TryGetText(out var oldText)) { var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var textChanges = Formatter.GetFormattedTextChanges(root, spans, document.Project.Solution.Workspace, cancellationToken: cancellationToken); if (textChanges.Count == 0) { return document; } var newText = oldText.WithChanges(textChanges); return document.WithText(newText); } return await Formatter.FormatAsync(document, spans, cancellationToken: cancellationToken).ConfigureAwait(false); } public async Task<SyntaxNode> CleanupAsync(SyntaxNode root, ImmutableArray<TextSpan> spans, Workspace workspace, CancellationToken cancellationToken) { // If the old text already exists, use the fast path for formatting. if (root.SyntaxTree != null && root.SyntaxTree.TryGetText(out var oldText)) { var changes = Formatter.GetFormattedTextChanges(root, spans, workspace, cancellationToken: cancellationToken); if (changes.Count == 0) { return root; } return await root.SyntaxTree.WithChangedText(oldText.WithChanges(changes)).GetRootAsync(cancellationToken).ConfigureAwait(false); } return Formatter.Format(root, spans, workspace, 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.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CodeCleanup.Providers { internal class FormatCodeCleanupProvider : ICodeCleanupProvider { public string Name => PredefinedCodeCleanupProviderNames.Format; public async Task<Document> CleanupAsync(Document document, ImmutableArray<TextSpan> spans, CancellationToken cancellationToken) { // If the old text already exists, use the fast path for formatting. if (document.TryGetText(out var oldText)) { var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var textChanges = Formatter.GetFormattedTextChanges(root, spans, document.Project.Solution.Workspace, cancellationToken: cancellationToken); if (textChanges.Count == 0) { return document; } var newText = oldText.WithChanges(textChanges); return document.WithText(newText); } return await Formatter.FormatAsync(document, spans, cancellationToken: cancellationToken).ConfigureAwait(false); } public async Task<SyntaxNode> CleanupAsync(SyntaxNode root, ImmutableArray<TextSpan> spans, Workspace workspace, CancellationToken cancellationToken) { // If the old text already exists, use the fast path for formatting. if (root.SyntaxTree != null && root.SyntaxTree.TryGetText(out var oldText)) { var changes = Formatter.GetFormattedTextChanges(root, spans, workspace, cancellationToken: cancellationToken); if (changes.Count == 0) { return root; } return await root.SyntaxTree.WithChangedText(oldText.WithChanges(changes)).GetRootAsync(cancellationToken).ConfigureAwait(false); } return Formatter.Format(root, spans, workspace, cancellationToken: cancellationToken); } } }
-1
dotnet/roslyn
56,460
Set CompilerApiVersion in Microsoft.Managed.Core.targets
This allows other targets to understand which compiler will be used. This is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets. Contributes to #52265 FYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803
eerhardt
"2021-09-16T21:47:36Z"
"2021-09-22T00:53:07Z"
a10a3720229de8f4227e98736e884d6f926a9950
aabc2fcbf630ba303e6f17808465349ea9b01a32
Set CompilerApiVersion in Microsoft.Managed.Core.targets. This allows other targets to understand which compiler will be used. This is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets. Contributes to #52265 FYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803
./src/VisualStudio/Core/Impl/CodeModel/Collections/BasesCollection.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.Diagnostics; using System.Linq; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Collections { [ComVisible(true)] [ComDefaultInterface(typeof(ICodeElements))] public sealed class BasesCollection : AbstractCodeElementCollection { private readonly bool _interfaces; internal static EnvDTE.CodeElements Create( CodeModelState state, object parent, FileCodeModel fileCodeModel, SyntaxNodeKey nodeKey, bool interfaces) { var collection = new BasesCollection(state, parent, fileCodeModel, nodeKey, interfaces); return (EnvDTE.CodeElements)ComAggregate.CreateAggregatedObject(collection); } private readonly ComHandle<EnvDTE.FileCodeModel, FileCodeModel> _fileCodeModel; private readonly SyntaxNodeKey _nodeKey; private BasesCollection( CodeModelState state, object parent, FileCodeModel fileCodeModel, SyntaxNodeKey nodeKey, bool interfaces) : base(state, parent) { Debug.Assert(fileCodeModel != null); _fileCodeModel = new ComHandle<EnvDTE.FileCodeModel, FileCodeModel>(fileCodeModel); _nodeKey = nodeKey; _interfaces = interfaces; } private FileCodeModel FileCodeModel { get { return _fileCodeModel.Object; } } private SyntaxNode LookupNode() => FileCodeModel.LookupNode(_nodeKey); private ITypeSymbol LookupSymbol() { var node = LookupNode(); var semanticModel = FileCodeModel.GetSemanticModel(); return semanticModel.GetDeclaredSymbol(node) as ITypeSymbol; } private IEnumerable<ITypeSymbol> GetBaseTypes() { var symbol = LookupSymbol(); if (symbol == null) { throw Exceptions.ThrowEFail(); } if (symbol.TypeKind == TypeKind.Interface || _interfaces) { return symbol.Interfaces; } else { return SpecializedCollections.SingletonEnumerable<ITypeSymbol>(symbol.BaseType); } } protected override bool TryGetItemByIndex(int index, out EnvDTE.CodeElement element) { var baseTypes = GetBaseTypes(); if (index < baseTypes.Count()) { var child = baseTypes.ElementAt(index); var projectId = FileCodeModel.GetProjectId(); element = CodeModelService.CreateCodeType(this.State, projectId, child); return true; } element = null; return false; } protected override bool TryGetItemByName(string name, out EnvDTE.CodeElement element) { if (name != null) { // When searching by name it may or may not be the fully qualified named, // but we need the fully qualified name for comparison. var node = LookupNode(); var semanticModel = FileCodeModel.GetSemanticModel(); name = CodeModelService.GetFullyQualifiedName(name, node.SpanStart, semanticModel); } foreach (var child in GetBaseTypes()) { var childName = child.GetEscapedFullName(); if (childName == name) { var projectId = FileCodeModel.GetProjectId(); element = CodeModelService.CreateCodeType(this.State, projectId, child); return true; } } element = null; return false; } public override int Count { get { var symbol = LookupSymbol(); if (symbol == null) { throw Exceptions.ThrowEFail(); } if (symbol.TypeKind == TypeKind.Interface || _interfaces) { return symbol.Interfaces.Length; } else { return 1; } } } } }
// Licensed to the .NET Foundation under one or more 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.Diagnostics; using System.Linq; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Collections { [ComVisible(true)] [ComDefaultInterface(typeof(ICodeElements))] public sealed class BasesCollection : AbstractCodeElementCollection { private readonly bool _interfaces; internal static EnvDTE.CodeElements Create( CodeModelState state, object parent, FileCodeModel fileCodeModel, SyntaxNodeKey nodeKey, bool interfaces) { var collection = new BasesCollection(state, parent, fileCodeModel, nodeKey, interfaces); return (EnvDTE.CodeElements)ComAggregate.CreateAggregatedObject(collection); } private readonly ComHandle<EnvDTE.FileCodeModel, FileCodeModel> _fileCodeModel; private readonly SyntaxNodeKey _nodeKey; private BasesCollection( CodeModelState state, object parent, FileCodeModel fileCodeModel, SyntaxNodeKey nodeKey, bool interfaces) : base(state, parent) { Debug.Assert(fileCodeModel != null); _fileCodeModel = new ComHandle<EnvDTE.FileCodeModel, FileCodeModel>(fileCodeModel); _nodeKey = nodeKey; _interfaces = interfaces; } private FileCodeModel FileCodeModel { get { return _fileCodeModel.Object; } } private SyntaxNode LookupNode() => FileCodeModel.LookupNode(_nodeKey); private ITypeSymbol LookupSymbol() { var node = LookupNode(); var semanticModel = FileCodeModel.GetSemanticModel(); return semanticModel.GetDeclaredSymbol(node) as ITypeSymbol; } private IEnumerable<ITypeSymbol> GetBaseTypes() { var symbol = LookupSymbol(); if (symbol == null) { throw Exceptions.ThrowEFail(); } if (symbol.TypeKind == TypeKind.Interface || _interfaces) { return symbol.Interfaces; } else { return SpecializedCollections.SingletonEnumerable<ITypeSymbol>(symbol.BaseType); } } protected override bool TryGetItemByIndex(int index, out EnvDTE.CodeElement element) { var baseTypes = GetBaseTypes(); if (index < baseTypes.Count()) { var child = baseTypes.ElementAt(index); var projectId = FileCodeModel.GetProjectId(); element = CodeModelService.CreateCodeType(this.State, projectId, child); return true; } element = null; return false; } protected override bool TryGetItemByName(string name, out EnvDTE.CodeElement element) { if (name != null) { // When searching by name it may or may not be the fully qualified named, // but we need the fully qualified name for comparison. var node = LookupNode(); var semanticModel = FileCodeModel.GetSemanticModel(); name = CodeModelService.GetFullyQualifiedName(name, node.SpanStart, semanticModel); } foreach (var child in GetBaseTypes()) { var childName = child.GetEscapedFullName(); if (childName == name) { var projectId = FileCodeModel.GetProjectId(); element = CodeModelService.CreateCodeType(this.State, projectId, child); return true; } } element = null; return false; } public override int Count { get { var symbol = LookupSymbol(); if (symbol == null) { throw Exceptions.ThrowEFail(); } if (symbol.TypeKind == TypeKind.Interface || _interfaces) { return symbol.Interfaces.Length; } else { return 1; } } } } }
-1
dotnet/roslyn
56,460
Set CompilerApiVersion in Microsoft.Managed.Core.targets
This allows other targets to understand which compiler will be used. This is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets. Contributes to #52265 FYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803
eerhardt
"2021-09-16T21:47:36Z"
"2021-09-22T00:53:07Z"
a10a3720229de8f4227e98736e884d6f926a9950
aabc2fcbf630ba303e6f17808465349ea9b01a32
Set CompilerApiVersion in Microsoft.Managed.Core.targets. This allows other targets to understand which compiler will be used. This is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets. Contributes to #52265 FYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803
./src/EditorFeatures/Core/Implementation/InlineRename/CommandHandlers/AbstractRenameCommandHandler_TabHandler.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.Editor.Shared.Extensions; using Microsoft.VisualStudio.Commanding; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor.Commanding.Commands; namespace Microsoft.CodeAnalysis.Editor.Implementation.InlineRename { internal abstract partial class AbstractRenameCommandHandler : IChainedCommandHandler<TabKeyCommandArgs>, IChainedCommandHandler<BackTabKeyCommandArgs> { public CommandState GetCommandState(TabKeyCommandArgs args, Func<CommandState> nextHandler) => GetCommandState(nextHandler); public void ExecuteCommand(TabKeyCommandArgs args, Action nextHandler, CommandExecutionContext context) { // If the Dashboard is focused, just navigate through its UI. if (DashboardShouldReceiveKeyboardNavigation(args.TextView)) { SetDashboardFocusToNextElement(args.TextView); return; } HandlePossibleTypingCommand(args, nextHandler, (activeSession, span) => { var spans = new NormalizedSnapshotSpanCollection( activeSession.GetBufferManager(args.SubjectBuffer) .GetEditableSpansForSnapshot(args.SubjectBuffer.CurrentSnapshot)); for (var i = 0; i < spans.Count; i++) { if (span == spans[i]) { var selectNext = i < spans.Count - 1 ? i + 1 : 0; var newSelection = spans[selectNext]; args.TextView.TryMoveCaretToAndEnsureVisible(newSelection.Start); args.TextView.SetSelection(newSelection); break; } } }); } public CommandState GetCommandState(BackTabKeyCommandArgs args, Func<CommandState> nextHandler) => GetCommandState(nextHandler); public void ExecuteCommand(BackTabKeyCommandArgs args, Action nextHandler, CommandExecutionContext context) { // If the Dashboard is focused, just navigate through its UI. if (DashboardShouldReceiveKeyboardNavigation(args.TextView)) { SetDashboardFocusToPreviousElement(args.TextView); return; } else { nextHandler(); } } } }
// Licensed to the .NET Foundation under one or more 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.Editor.Shared.Extensions; using Microsoft.VisualStudio.Commanding; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor.Commanding.Commands; namespace Microsoft.CodeAnalysis.Editor.Implementation.InlineRename { internal abstract partial class AbstractRenameCommandHandler : IChainedCommandHandler<TabKeyCommandArgs>, IChainedCommandHandler<BackTabKeyCommandArgs> { public CommandState GetCommandState(TabKeyCommandArgs args, Func<CommandState> nextHandler) => GetCommandState(nextHandler); public void ExecuteCommand(TabKeyCommandArgs args, Action nextHandler, CommandExecutionContext context) { // If the Dashboard is focused, just navigate through its UI. if (DashboardShouldReceiveKeyboardNavigation(args.TextView)) { SetDashboardFocusToNextElement(args.TextView); return; } HandlePossibleTypingCommand(args, nextHandler, (activeSession, span) => { var spans = new NormalizedSnapshotSpanCollection( activeSession.GetBufferManager(args.SubjectBuffer) .GetEditableSpansForSnapshot(args.SubjectBuffer.CurrentSnapshot)); for (var i = 0; i < spans.Count; i++) { if (span == spans[i]) { var selectNext = i < spans.Count - 1 ? i + 1 : 0; var newSelection = spans[selectNext]; args.TextView.TryMoveCaretToAndEnsureVisible(newSelection.Start); args.TextView.SetSelection(newSelection); break; } } }); } public CommandState GetCommandState(BackTabKeyCommandArgs args, Func<CommandState> nextHandler) => GetCommandState(nextHandler); public void ExecuteCommand(BackTabKeyCommandArgs args, Action nextHandler, CommandExecutionContext context) { // If the Dashboard is focused, just navigate through its UI. if (DashboardShouldReceiveKeyboardNavigation(args.TextView)) { SetDashboardFocusToPreviousElement(args.TextView); return; } else { nextHandler(); } } } }
-1
dotnet/roslyn
56,460
Set CompilerApiVersion in Microsoft.Managed.Core.targets
This allows other targets to understand which compiler will be used. This is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets. Contributes to #52265 FYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803
eerhardt
"2021-09-16T21:47:36Z"
"2021-09-22T00:53:07Z"
a10a3720229de8f4227e98736e884d6f926a9950
aabc2fcbf630ba303e6f17808465349ea9b01a32
Set CompilerApiVersion in Microsoft.Managed.Core.targets. This allows other targets to understand which compiler will be used. This is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets. Contributes to #52265 FYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803
./src/Compilers/VisualBasic/Portable/Emit/AttributeDataAdapter.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.CodeGen Imports Microsoft.CodeAnalysis.Emit Imports Microsoft.CodeAnalysis.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Emit Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols Partial Friend Class VisualBasicAttributeData Implements Cci.ICustomAttribute Private Function GetArguments1(context As EmitContext) As ImmutableArray(Of Cci.IMetadataExpression) Implements Cci.ICustomAttribute.GetArguments Return CommonConstructorArguments.SelectAsArray(Function(arg) CreateMetadataExpression(arg, context)) End Function Private Function Constructor1(context As EmitContext, reportDiagnostics As Boolean) As Cci.IMethodReference Implements Cci.ICustomAttribute.Constructor If Me.AttributeConstructor.IsDefaultValueTypeConstructor() Then ' Parameter constructors for structs exist in symbol table, but are not emitted. ' Produce an error since we cannot use it (instead of crashing): ' Details: https://github.com/dotnet/roslyn/issues/19394 If reportDiagnostics Then context.Diagnostics.Add(ERRID.ERR_AttributeMustBeClassNotStruct1, If(context.SyntaxNode?.GetLocation(), NoLocation.Singleton), Me.AttributeClass) End If Return Nothing End If Dim moduleBeingBuilt As PEModuleBuilder = DirectCast(context.Module, PEModuleBuilder) Return moduleBeingBuilt.Translate(AttributeConstructor, needDeclaration:=False, syntaxNodeOpt:=DirectCast(context.SyntaxNode, VisualBasicSyntaxNode), diagnostics:=context.Diagnostics) End Function Private Function GetNamedArguments1(context As EmitContext) As ImmutableArray(Of Cci.IMetadataNamedArgument) Implements Cci.ICustomAttribute.GetNamedArguments Return CommonNamedArguments.SelectAsArray(Function(namedArgument) CreateMetadataNamedArgument(namedArgument.Key, namedArgument.Value, context)) End Function Private ReadOnly Property ArgumentCount As Integer Implements Cci.ICustomAttribute.ArgumentCount Get Return CommonConstructorArguments.Length End Get End Property Private ReadOnly Property NamedArgumentCount As UShort Implements Cci.ICustomAttribute.NamedArgumentCount Get Return CType(CommonNamedArguments.Length, UShort) End Get End Property Private Function GetType1(context As EmitContext) As Cci.ITypeReference Implements Cci.ICustomAttribute.GetType Dim moduleBeingBuilt As PEModuleBuilder = DirectCast(context.Module, PEModuleBuilder) Return moduleBeingBuilt.Translate(AttributeClass, syntaxNodeOpt:=DirectCast(context.SyntaxNode, VisualBasicSyntaxNode), diagnostics:=context.Diagnostics) End Function Private ReadOnly Property AllowMultiple1 As Boolean Implements Cci.ICustomAttribute.AllowMultiple Get Return Me.AttributeClass.GetAttributeUsageInfo().AllowMultiple End Get End Property Private Function CreateMetadataExpression(argument As TypedConstant, context As EmitContext) As Cci.IMetadataExpression If argument.IsNull Then Return CreateMetadataConstant(argument.TypeInternal, Nothing, context) End If Select Case argument.Kind Case TypedConstantKind.Array Return CreateMetadataArray(argument, context) Case TypedConstantKind.Type Return CreateType(argument, context) Case Else Return CreateMetadataConstant(argument.TypeInternal, argument.ValueInternal, context) End Select End Function Private Function CreateMetadataArray(argument As TypedConstant, context As EmitContext) As MetadataCreateArray Debug.Assert(Not argument.Values.IsDefault) Dim values = argument.Values Dim moduleBeingBuilt = DirectCast(context.Module, PEModuleBuilder) Dim arrayType = moduleBeingBuilt.Translate(DirectCast(argument.TypeInternal, ArrayTypeSymbol)) If values.Length = 0 Then Return New MetadataCreateArray(arrayType, arrayType.GetElementType(context), ImmutableArray(Of Cci.IMetadataExpression).Empty) End If Dim metadataExprs = New Cci.IMetadataExpression(values.Length - 1) {} For i = 0 To values.Length - 1 metadataExprs(i) = CreateMetadataExpression(values(i), context) Next Return New MetadataCreateArray(arrayType, arrayType.GetElementType(context), metadataExprs.AsImmutableOrNull) End Function Private Function CreateType(argument As TypedConstant, context As EmitContext) As MetadataTypeOf Debug.Assert(argument.ValueInternal IsNot Nothing) Dim moduleBeingBuilt = DirectCast(context.Module, PEModuleBuilder) Dim syntaxNodeOpt = DirectCast(context.SyntaxNode, VisualBasicSyntaxNode) Dim diagnostics = context.Diagnostics Return New MetadataTypeOf(moduleBeingBuilt.Translate(DirectCast(argument.ValueInternal, TypeSymbol), syntaxNodeOpt, diagnostics), moduleBeingBuilt.Translate(DirectCast(argument.TypeInternal, TypeSymbol), syntaxNodeOpt, diagnostics)) End Function Private Function CreateMetadataConstant(type As ITypeSymbolInternal, value As Object, context As EmitContext) As MetadataConstant Dim moduleBeingBuilt = DirectCast(context.Module, PEModuleBuilder) Return moduleBeingBuilt.CreateConstant(DirectCast(type, TypeSymbol), value, syntaxNodeOpt:=DirectCast(context.SyntaxNode, VisualBasicSyntaxNode), diagnostics:=context.Diagnostics) End Function Private Function CreateMetadataNamedArgument(name As String, argument As TypedConstant, context As EmitContext) As Cci.IMetadataNamedArgument Dim sym = LookupName(name) Dim value = CreateMetadataExpression(argument, context) Dim type As TypeSymbol Dim fieldSymbol = TryCast(sym, FieldSymbol) If fieldSymbol IsNot Nothing Then type = fieldSymbol.Type Else type = DirectCast(sym, PropertySymbol).Type End If Dim moduleBeingBuilt = DirectCast(context.Module, PEModuleBuilder) Return New MetadataNamedArgument(sym, moduleBeingBuilt.Translate(type, syntaxNodeOpt:=DirectCast(context.SyntaxNode, VisualBasicSyntaxNode), diagnostics:=context.Diagnostics), value) End Function Private Function LookupName(name As String) As Symbol Dim type = AttributeClass Do For Each member In type.GetMembers(name) If member.DeclaredAccessibility = Accessibility.Public Then Return member End If Next type = type.BaseTypeNoUseSiteDiagnostics Loop While type IsNot Nothing Debug.Assert(False, "Name does not match an attribute field or a property. How can that be?") Return ErrorTypeSymbol.UnknownResultType 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.CodeGen Imports Microsoft.CodeAnalysis.Emit Imports Microsoft.CodeAnalysis.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Emit Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols Partial Friend Class VisualBasicAttributeData Implements Cci.ICustomAttribute Private Function GetArguments1(context As EmitContext) As ImmutableArray(Of Cci.IMetadataExpression) Implements Cci.ICustomAttribute.GetArguments Return CommonConstructorArguments.SelectAsArray(Function(arg) CreateMetadataExpression(arg, context)) End Function Private Function Constructor1(context As EmitContext, reportDiagnostics As Boolean) As Cci.IMethodReference Implements Cci.ICustomAttribute.Constructor If Me.AttributeConstructor.IsDefaultValueTypeConstructor() Then ' Parameter constructors for structs exist in symbol table, but are not emitted. ' Produce an error since we cannot use it (instead of crashing): ' Details: https://github.com/dotnet/roslyn/issues/19394 If reportDiagnostics Then context.Diagnostics.Add(ERRID.ERR_AttributeMustBeClassNotStruct1, If(context.SyntaxNode?.GetLocation(), NoLocation.Singleton), Me.AttributeClass) End If Return Nothing End If Dim moduleBeingBuilt As PEModuleBuilder = DirectCast(context.Module, PEModuleBuilder) Return moduleBeingBuilt.Translate(AttributeConstructor, needDeclaration:=False, syntaxNodeOpt:=DirectCast(context.SyntaxNode, VisualBasicSyntaxNode), diagnostics:=context.Diagnostics) End Function Private Function GetNamedArguments1(context As EmitContext) As ImmutableArray(Of Cci.IMetadataNamedArgument) Implements Cci.ICustomAttribute.GetNamedArguments Return CommonNamedArguments.SelectAsArray(Function(namedArgument) CreateMetadataNamedArgument(namedArgument.Key, namedArgument.Value, context)) End Function Private ReadOnly Property ArgumentCount As Integer Implements Cci.ICustomAttribute.ArgumentCount Get Return CommonConstructorArguments.Length End Get End Property Private ReadOnly Property NamedArgumentCount As UShort Implements Cci.ICustomAttribute.NamedArgumentCount Get Return CType(CommonNamedArguments.Length, UShort) End Get End Property Private Function GetType1(context As EmitContext) As Cci.ITypeReference Implements Cci.ICustomAttribute.GetType Dim moduleBeingBuilt As PEModuleBuilder = DirectCast(context.Module, PEModuleBuilder) Return moduleBeingBuilt.Translate(AttributeClass, syntaxNodeOpt:=DirectCast(context.SyntaxNode, VisualBasicSyntaxNode), diagnostics:=context.Diagnostics) End Function Private ReadOnly Property AllowMultiple1 As Boolean Implements Cci.ICustomAttribute.AllowMultiple Get Return Me.AttributeClass.GetAttributeUsageInfo().AllowMultiple End Get End Property Private Function CreateMetadataExpression(argument As TypedConstant, context As EmitContext) As Cci.IMetadataExpression If argument.IsNull Then Return CreateMetadataConstant(argument.TypeInternal, Nothing, context) End If Select Case argument.Kind Case TypedConstantKind.Array Return CreateMetadataArray(argument, context) Case TypedConstantKind.Type Return CreateType(argument, context) Case Else Return CreateMetadataConstant(argument.TypeInternal, argument.ValueInternal, context) End Select End Function Private Function CreateMetadataArray(argument As TypedConstant, context As EmitContext) As MetadataCreateArray Debug.Assert(Not argument.Values.IsDefault) Dim values = argument.Values Dim moduleBeingBuilt = DirectCast(context.Module, PEModuleBuilder) Dim arrayType = moduleBeingBuilt.Translate(DirectCast(argument.TypeInternal, ArrayTypeSymbol)) If values.Length = 0 Then Return New MetadataCreateArray(arrayType, arrayType.GetElementType(context), ImmutableArray(Of Cci.IMetadataExpression).Empty) End If Dim metadataExprs = New Cci.IMetadataExpression(values.Length - 1) {} For i = 0 To values.Length - 1 metadataExprs(i) = CreateMetadataExpression(values(i), context) Next Return New MetadataCreateArray(arrayType, arrayType.GetElementType(context), metadataExprs.AsImmutableOrNull) End Function Private Function CreateType(argument As TypedConstant, context As EmitContext) As MetadataTypeOf Debug.Assert(argument.ValueInternal IsNot Nothing) Dim moduleBeingBuilt = DirectCast(context.Module, PEModuleBuilder) Dim syntaxNodeOpt = DirectCast(context.SyntaxNode, VisualBasicSyntaxNode) Dim diagnostics = context.Diagnostics Return New MetadataTypeOf(moduleBeingBuilt.Translate(DirectCast(argument.ValueInternal, TypeSymbol), syntaxNodeOpt, diagnostics), moduleBeingBuilt.Translate(DirectCast(argument.TypeInternal, TypeSymbol), syntaxNodeOpt, diagnostics)) End Function Private Function CreateMetadataConstant(type As ITypeSymbolInternal, value As Object, context As EmitContext) As MetadataConstant Dim moduleBeingBuilt = DirectCast(context.Module, PEModuleBuilder) Return moduleBeingBuilt.CreateConstant(DirectCast(type, TypeSymbol), value, syntaxNodeOpt:=DirectCast(context.SyntaxNode, VisualBasicSyntaxNode), diagnostics:=context.Diagnostics) End Function Private Function CreateMetadataNamedArgument(name As String, argument As TypedConstant, context As EmitContext) As Cci.IMetadataNamedArgument Dim sym = LookupName(name) Dim value = CreateMetadataExpression(argument, context) Dim type As TypeSymbol Dim fieldSymbol = TryCast(sym, FieldSymbol) If fieldSymbol IsNot Nothing Then type = fieldSymbol.Type Else type = DirectCast(sym, PropertySymbol).Type End If Dim moduleBeingBuilt = DirectCast(context.Module, PEModuleBuilder) Return New MetadataNamedArgument(sym, moduleBeingBuilt.Translate(type, syntaxNodeOpt:=DirectCast(context.SyntaxNode, VisualBasicSyntaxNode), diagnostics:=context.Diagnostics), value) End Function Private Function LookupName(name As String) As Symbol Dim type = AttributeClass Do For Each member In type.GetMembers(name) If member.DeclaredAccessibility = Accessibility.Public Then Return member End If Next type = type.BaseTypeNoUseSiteDiagnostics Loop While type IsNot Nothing Debug.Assert(False, "Name does not match an attribute field or a property. How can that be?") Return ErrorTypeSymbol.UnknownResultType End Function End Class End Namespace
-1
dotnet/roslyn
56,460
Set CompilerApiVersion in Microsoft.Managed.Core.targets
This allows other targets to understand which compiler will be used. This is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets. Contributes to #52265 FYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803
eerhardt
"2021-09-16T21:47:36Z"
"2021-09-22T00:53:07Z"
a10a3720229de8f4227e98736e884d6f926a9950
aabc2fcbf630ba303e6f17808465349ea9b01a32
Set CompilerApiVersion in Microsoft.Managed.Core.targets. This allows other targets to understand which compiler will be used. This is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets. Contributes to #52265 FYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803
./src/Compilers/CSharp/Portable/Binder/LocalInProgressBinder.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.Syntax; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// This binder keeps track of the local variable (if any) that is currently being evaluated /// so that it can be passed into the next call to LocalSymbol.GetConstantValue (and /// its callers). /// </summary> internal sealed class LocalInProgressBinder : Binder { private readonly LocalSymbol _inProgress; internal LocalInProgressBinder(LocalSymbol inProgress, Binder next) : base(next) { _inProgress = inProgress; } internal override LocalSymbol LocalInProgress { get { return _inProgress; } } } }
// Licensed to the .NET Foundation under one or more 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.Syntax; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// This binder keeps track of the local variable (if any) that is currently being evaluated /// so that it can be passed into the next call to LocalSymbol.GetConstantValue (and /// its callers). /// </summary> internal sealed class LocalInProgressBinder : Binder { private readonly LocalSymbol _inProgress; internal LocalInProgressBinder(LocalSymbol inProgress, Binder next) : base(next) { _inProgress = inProgress; } internal override LocalSymbol LocalInProgress { get { return _inProgress; } } } }
-1
dotnet/roslyn
56,460
Set CompilerApiVersion in Microsoft.Managed.Core.targets
This allows other targets to understand which compiler will be used. This is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets. Contributes to #52265 FYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803
eerhardt
"2021-09-16T21:47:36Z"
"2021-09-22T00:53:07Z"
a10a3720229de8f4227e98736e884d6f926a9950
aabc2fcbf630ba303e6f17808465349ea9b01a32
Set CompilerApiVersion in Microsoft.Managed.Core.targets. This allows other targets to understand which compiler will be used. This is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets. Contributes to #52265 FYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803
./src/EditorFeatures/CSharpTest/Completion/CompletionProviders/AbstractCSharpCompletionProviderTests.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.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Completion; using Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.AsyncCompletion; using Microsoft.CodeAnalysis.Editor.UnitTests.Completion; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion.Data; using Xunit; using RoslynTrigger = Microsoft.CodeAnalysis.Completion.CompletionTrigger; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Completion.CompletionProviders { public abstract class AbstractCSharpCompletionProviderTests : AbstractCSharpCompletionProviderTests<CSharpTestWorkspaceFixture> { } public abstract class AbstractCSharpCompletionProviderTests<TWorkspaceFixture> : AbstractCompletionProviderTests<TWorkspaceFixture> where TWorkspaceFixture : TestWorkspaceFixture, new() { protected const string NonBreakingSpaceString = "\x00A0"; protected static string GetMarkup(string source, LanguageVersion languageVersion) => $@"<Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"" LanguageVersion=""{languageVersion.ToDisplayString()}""> <Document FilePath=""Test2.cs""> {source} </Document> </Project> </Workspace>"; protected override TestWorkspace CreateWorkspace(string fileContents) => TestWorkspace.CreateCSharp(fileContents, exportProvider: ExportProvider); internal override CompletionServiceWithProviders GetCompletionService(Project project) => Assert.IsType<CSharpCompletionService>(base.GetCompletionService(project)); private protected override Task BaseVerifyWorkerAsync( string code, int position, string expectedItemOrNull, string expectedDescriptionOrNull, SourceCodeKind sourceCodeKind, bool usePreviousCharAsTrigger, bool checkForAbsence, int? glyph, int? matchPriority, bool? hasSuggestionItem, string displayTextSuffix, string displayTextPrefix, string inlineDescription = null, bool? isComplexTextEdit = null, List<CompletionFilter> matchingFilters = null, CompletionItemFlags? flags = null) { return base.VerifyWorkerAsync( code, position, expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind, usePreviousCharAsTrigger, checkForAbsence, glyph, matchPriority, hasSuggestionItem, displayTextSuffix, displayTextPrefix, inlineDescription, isComplexTextEdit, matchingFilters, flags); } private protected override async Task VerifyWorkerAsync( string code, int position, string expectedItemOrNull, string expectedDescriptionOrNull, SourceCodeKind sourceCodeKind, bool usePreviousCharAsTrigger, bool checkForAbsence, int? glyph, int? matchPriority, bool? hasSuggestionItem, string displayTextSuffix, string displayTextPrefix, string inlineDescription = null, bool? isComplexTextEdit = null, List<CompletionFilter> matchingFilters = null, CompletionItemFlags? flags = null) { await VerifyAtPositionAsync(code, position, usePreviousCharAsTrigger, expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind, checkForAbsence, glyph, matchPriority, hasSuggestionItem, displayTextSuffix, displayTextPrefix, inlineDescription, isComplexTextEdit, matchingFilters); await VerifyInFrontOfCommentAsync(code, position, usePreviousCharAsTrigger, expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind, checkForAbsence, glyph, matchPriority, hasSuggestionItem, displayTextSuffix, displayTextPrefix, inlineDescription, isComplexTextEdit, matchingFilters); await VerifyAtEndOfFileAsync(code, position, usePreviousCharAsTrigger, expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind, checkForAbsence, glyph, matchPriority, hasSuggestionItem, displayTextSuffix, displayTextPrefix, inlineDescription, isComplexTextEdit, matchingFilters); // Items cannot be partially written if we're checking for their absence, // or if we're verifying that the list will show up (without specifying an actual item) if (!checkForAbsence && expectedItemOrNull != null) { await VerifyAtPosition_ItemPartiallyWrittenAsync(code, position, usePreviousCharAsTrigger, expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind, checkForAbsence, glyph, matchPriority, hasSuggestionItem, displayTextSuffix, displayTextPrefix, inlineDescription, isComplexTextEdit, matchingFilters); await VerifyInFrontOfComment_ItemPartiallyWrittenAsync(code, position, usePreviousCharAsTrigger, expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind, checkForAbsence, glyph, matchPriority, hasSuggestionItem, displayTextSuffix, displayTextPrefix, inlineDescription, isComplexTextEdit, matchingFilters); await VerifyAtEndOfFile_ItemPartiallyWrittenAsync(code, position, usePreviousCharAsTrigger, expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind, checkForAbsence, glyph, matchPriority, hasSuggestionItem, displayTextSuffix, displayTextPrefix, inlineDescription, isComplexTextEdit, matchingFilters); } } protected override string ItemPartiallyWritten(string expectedItemOrNull) => expectedItemOrNull[0] == '@' ? expectedItemOrNull.Substring(1, 1) : expectedItemOrNull.Substring(0, 1); private Task VerifyInFrontOfCommentAsync( string code, int position, string insertText, bool usePreviousCharAsTrigger, string expectedItemOrNull, string expectedDescriptionOrNull, SourceCodeKind sourceCodeKind, bool checkForAbsence, int? glyph, int? matchPriority, bool? hasSuggestionItem, string displayTextSuffix, string displayTextPrefix, string inlineDescription, bool? isComplexTextEdit, List<CompletionFilter> matchingFilters) { code = code.Substring(0, position) + insertText + "/**/" + code.Substring(position); position += insertText.Length; return base.VerifyWorkerAsync( code, position, expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind, usePreviousCharAsTrigger, checkForAbsence, glyph, matchPriority, hasSuggestionItem, displayTextSuffix, displayTextPrefix, inlineDescription, isComplexTextEdit, matchingFilters, flags: null); } private Task VerifyInFrontOfCommentAsync( string code, int position, bool usePreviousCharAsTrigger, string expectedItemOrNull, string expectedDescriptionOrNull, SourceCodeKind sourceCodeKind, bool checkForAbsence, int? glyph, int? matchPriority, bool? hasSuggestionItem, string displayTextSuffix, string displayTextPrefix, string inlineDescription, bool? isComplexTextEdit, List<CompletionFilter> matchingFilters) { return VerifyInFrontOfCommentAsync( code, position, string.Empty, usePreviousCharAsTrigger, expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind, checkForAbsence, glyph, matchPriority, hasSuggestionItem, displayTextSuffix, displayTextPrefix, inlineDescription, isComplexTextEdit, matchingFilters); } private protected Task VerifyInFrontOfComment_ItemPartiallyWrittenAsync( string code, int position, bool usePreviousCharAsTrigger, string expectedItemOrNull, string expectedDescriptionOrNull, SourceCodeKind sourceCodeKind, bool checkForAbsence, int? glyph, int? matchPriority, bool? hasSuggestionItem, string displayTextSuffix, string displayTextPrefix, string inlineDescription, bool? isComplexTextEdit, List<CompletionFilter> matchingFilters) { return VerifyInFrontOfCommentAsync( code, position, ItemPartiallyWritten(expectedItemOrNull), usePreviousCharAsTrigger, expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind, checkForAbsence, glyph, matchPriority, hasSuggestionItem, displayTextSuffix, displayTextPrefix, inlineDescription, isComplexTextEdit, matchingFilters); } protected static string AddInsideMethod(string text) { return @"class C { void F() { " + text + @" } }"; } protected static string AddUsingDirectives(string usingDirectives, string text) { return usingDirectives + @" " + text; } protected async Task VerifySendEnterThroughToEnterAsync(string initialMarkup, string textTypedSoFar, EnterKeyRule sendThroughEnterOption, bool expected) { using var workspace = CreateWorkspace(initialMarkup); var hostDocument = workspace.DocumentWithCursor; var documentId = workspace.GetDocumentId(hostDocument); var document = workspace.CurrentSolution.GetDocument(documentId); var position = hostDocument.CursorPosition.Value; workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options .WithChangedOption( CompletionOptions.EnterKeyBehavior, LanguageNames.CSharp, sendThroughEnterOption))); var service = GetCompletionService(document.Project); var completionList = await GetCompletionListAsync(service, document, position, RoslynTrigger.Invoke); var item = completionList.Items.First(i => (i.DisplayText + i.DisplayTextSuffix).StartsWith(textTypedSoFar)); Assert.Equal(expected, CommitManager.SendEnterThroughToEditor(service.GetRules(), item, textTypedSoFar)); } protected void TestCommonIsTextualTriggerCharacter() { var alwaysTriggerList = new[] { "goo$$.", }; foreach (var markup in alwaysTriggerList) { VerifyTextualTriggerCharacter(markup, shouldTriggerWithTriggerOnLettersEnabled: true, shouldTriggerWithTriggerOnLettersDisabled: true); } var triggerOnlyWithLettersList = new[] { "$$a", "$$_" }; foreach (var markup in triggerOnlyWithLettersList) { VerifyTextualTriggerCharacter(markup, shouldTriggerWithTriggerOnLettersEnabled: true, shouldTriggerWithTriggerOnLettersDisabled: false); } var neverTriggerList = new[] { "goo$$x", "goo$$_" }; foreach (var markup in neverTriggerList) { VerifyTextualTriggerCharacter(markup, shouldTriggerWithTriggerOnLettersEnabled: false, shouldTriggerWithTriggerOnLettersDisabled: 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.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Completion; using Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.AsyncCompletion; using Microsoft.CodeAnalysis.Editor.UnitTests.Completion; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion.Data; using Xunit; using RoslynTrigger = Microsoft.CodeAnalysis.Completion.CompletionTrigger; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Completion.CompletionProviders { public abstract class AbstractCSharpCompletionProviderTests : AbstractCSharpCompletionProviderTests<CSharpTestWorkspaceFixture> { } public abstract class AbstractCSharpCompletionProviderTests<TWorkspaceFixture> : AbstractCompletionProviderTests<TWorkspaceFixture> where TWorkspaceFixture : TestWorkspaceFixture, new() { protected const string NonBreakingSpaceString = "\x00A0"; protected static string GetMarkup(string source, LanguageVersion languageVersion) => $@"<Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"" LanguageVersion=""{languageVersion.ToDisplayString()}""> <Document FilePath=""Test2.cs""> {source} </Document> </Project> </Workspace>"; protected override TestWorkspace CreateWorkspace(string fileContents) => TestWorkspace.CreateCSharp(fileContents, exportProvider: ExportProvider); internal override CompletionServiceWithProviders GetCompletionService(Project project) => Assert.IsType<CSharpCompletionService>(base.GetCompletionService(project)); private protected override Task BaseVerifyWorkerAsync( string code, int position, string expectedItemOrNull, string expectedDescriptionOrNull, SourceCodeKind sourceCodeKind, bool usePreviousCharAsTrigger, bool checkForAbsence, int? glyph, int? matchPriority, bool? hasSuggestionItem, string displayTextSuffix, string displayTextPrefix, string inlineDescription = null, bool? isComplexTextEdit = null, List<CompletionFilter> matchingFilters = null, CompletionItemFlags? flags = null) { return base.VerifyWorkerAsync( code, position, expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind, usePreviousCharAsTrigger, checkForAbsence, glyph, matchPriority, hasSuggestionItem, displayTextSuffix, displayTextPrefix, inlineDescription, isComplexTextEdit, matchingFilters, flags); } private protected override async Task VerifyWorkerAsync( string code, int position, string expectedItemOrNull, string expectedDescriptionOrNull, SourceCodeKind sourceCodeKind, bool usePreviousCharAsTrigger, bool checkForAbsence, int? glyph, int? matchPriority, bool? hasSuggestionItem, string displayTextSuffix, string displayTextPrefix, string inlineDescription = null, bool? isComplexTextEdit = null, List<CompletionFilter> matchingFilters = null, CompletionItemFlags? flags = null) { await VerifyAtPositionAsync(code, position, usePreviousCharAsTrigger, expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind, checkForAbsence, glyph, matchPriority, hasSuggestionItem, displayTextSuffix, displayTextPrefix, inlineDescription, isComplexTextEdit, matchingFilters); await VerifyInFrontOfCommentAsync(code, position, usePreviousCharAsTrigger, expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind, checkForAbsence, glyph, matchPriority, hasSuggestionItem, displayTextSuffix, displayTextPrefix, inlineDescription, isComplexTextEdit, matchingFilters); await VerifyAtEndOfFileAsync(code, position, usePreviousCharAsTrigger, expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind, checkForAbsence, glyph, matchPriority, hasSuggestionItem, displayTextSuffix, displayTextPrefix, inlineDescription, isComplexTextEdit, matchingFilters); // Items cannot be partially written if we're checking for their absence, // or if we're verifying that the list will show up (without specifying an actual item) if (!checkForAbsence && expectedItemOrNull != null) { await VerifyAtPosition_ItemPartiallyWrittenAsync(code, position, usePreviousCharAsTrigger, expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind, checkForAbsence, glyph, matchPriority, hasSuggestionItem, displayTextSuffix, displayTextPrefix, inlineDescription, isComplexTextEdit, matchingFilters); await VerifyInFrontOfComment_ItemPartiallyWrittenAsync(code, position, usePreviousCharAsTrigger, expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind, checkForAbsence, glyph, matchPriority, hasSuggestionItem, displayTextSuffix, displayTextPrefix, inlineDescription, isComplexTextEdit, matchingFilters); await VerifyAtEndOfFile_ItemPartiallyWrittenAsync(code, position, usePreviousCharAsTrigger, expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind, checkForAbsence, glyph, matchPriority, hasSuggestionItem, displayTextSuffix, displayTextPrefix, inlineDescription, isComplexTextEdit, matchingFilters); } } protected override string ItemPartiallyWritten(string expectedItemOrNull) => expectedItemOrNull[0] == '@' ? expectedItemOrNull.Substring(1, 1) : expectedItemOrNull.Substring(0, 1); private Task VerifyInFrontOfCommentAsync( string code, int position, string insertText, bool usePreviousCharAsTrigger, string expectedItemOrNull, string expectedDescriptionOrNull, SourceCodeKind sourceCodeKind, bool checkForAbsence, int? glyph, int? matchPriority, bool? hasSuggestionItem, string displayTextSuffix, string displayTextPrefix, string inlineDescription, bool? isComplexTextEdit, List<CompletionFilter> matchingFilters) { code = code.Substring(0, position) + insertText + "/**/" + code.Substring(position); position += insertText.Length; return base.VerifyWorkerAsync( code, position, expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind, usePreviousCharAsTrigger, checkForAbsence, glyph, matchPriority, hasSuggestionItem, displayTextSuffix, displayTextPrefix, inlineDescription, isComplexTextEdit, matchingFilters, flags: null); } private Task VerifyInFrontOfCommentAsync( string code, int position, bool usePreviousCharAsTrigger, string expectedItemOrNull, string expectedDescriptionOrNull, SourceCodeKind sourceCodeKind, bool checkForAbsence, int? glyph, int? matchPriority, bool? hasSuggestionItem, string displayTextSuffix, string displayTextPrefix, string inlineDescription, bool? isComplexTextEdit, List<CompletionFilter> matchingFilters) { return VerifyInFrontOfCommentAsync( code, position, string.Empty, usePreviousCharAsTrigger, expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind, checkForAbsence, glyph, matchPriority, hasSuggestionItem, displayTextSuffix, displayTextPrefix, inlineDescription, isComplexTextEdit, matchingFilters); } private protected Task VerifyInFrontOfComment_ItemPartiallyWrittenAsync( string code, int position, bool usePreviousCharAsTrigger, string expectedItemOrNull, string expectedDescriptionOrNull, SourceCodeKind sourceCodeKind, bool checkForAbsence, int? glyph, int? matchPriority, bool? hasSuggestionItem, string displayTextSuffix, string displayTextPrefix, string inlineDescription, bool? isComplexTextEdit, List<CompletionFilter> matchingFilters) { return VerifyInFrontOfCommentAsync( code, position, ItemPartiallyWritten(expectedItemOrNull), usePreviousCharAsTrigger, expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind, checkForAbsence, glyph, matchPriority, hasSuggestionItem, displayTextSuffix, displayTextPrefix, inlineDescription, isComplexTextEdit, matchingFilters); } protected static string AddInsideMethod(string text) { return @"class C { void F() { " + text + @" } }"; } protected static string AddUsingDirectives(string usingDirectives, string text) { return usingDirectives + @" " + text; } protected async Task VerifySendEnterThroughToEnterAsync(string initialMarkup, string textTypedSoFar, EnterKeyRule sendThroughEnterOption, bool expected) { using var workspace = CreateWorkspace(initialMarkup); var hostDocument = workspace.DocumentWithCursor; var documentId = workspace.GetDocumentId(hostDocument); var document = workspace.CurrentSolution.GetDocument(documentId); var position = hostDocument.CursorPosition.Value; workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options .WithChangedOption( CompletionOptions.EnterKeyBehavior, LanguageNames.CSharp, sendThroughEnterOption))); var service = GetCompletionService(document.Project); var completionList = await GetCompletionListAsync(service, document, position, RoslynTrigger.Invoke); var item = completionList.Items.First(i => (i.DisplayText + i.DisplayTextSuffix).StartsWith(textTypedSoFar)); Assert.Equal(expected, CommitManager.SendEnterThroughToEditor(service.GetRules(), item, textTypedSoFar)); } protected void TestCommonIsTextualTriggerCharacter() { var alwaysTriggerList = new[] { "goo$$.", }; foreach (var markup in alwaysTriggerList) { VerifyTextualTriggerCharacter(markup, shouldTriggerWithTriggerOnLettersEnabled: true, shouldTriggerWithTriggerOnLettersDisabled: true); } var triggerOnlyWithLettersList = new[] { "$$a", "$$_" }; foreach (var markup in triggerOnlyWithLettersList) { VerifyTextualTriggerCharacter(markup, shouldTriggerWithTriggerOnLettersEnabled: true, shouldTriggerWithTriggerOnLettersDisabled: false); } var neverTriggerList = new[] { "goo$$x", "goo$$_" }; foreach (var markup in neverTriggerList) { VerifyTextualTriggerCharacter(markup, shouldTriggerWithTriggerOnLettersEnabled: false, shouldTriggerWithTriggerOnLettersDisabled: false); } } } }
-1
dotnet/roslyn
56,460
Set CompilerApiVersion in Microsoft.Managed.Core.targets
This allows other targets to understand which compiler will be used. This is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets. Contributes to #52265 FYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803
eerhardt
"2021-09-16T21:47:36Z"
"2021-09-22T00:53:07Z"
a10a3720229de8f4227e98736e884d6f926a9950
aabc2fcbf630ba303e6f17808465349ea9b01a32
Set CompilerApiVersion in Microsoft.Managed.Core.targets. This allows other targets to understand which compiler will be used. This is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets. Contributes to #52265 FYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803
./src/EditorFeatures/VisualBasicTest/ChangeSignature/AddParameterTests.OptionalParameter.Omit.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.ChangeSignature Imports Microsoft.CodeAnalysis.Editor.UnitTests.ChangeSignature Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions Imports Microsoft.CodeAnalysis.Test.Utilities.ChangeSignature Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.ChangeSignature Partial Public Class ChangeSignatureTests Inherits AbstractChangeSignatureTests <WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function AddOptionalParameter_ToEmptySignature_CallsiteOmitted() As Task Dim markup = <Text><![CDATA[ Class C Sub M$$() M() End Sub End Class]]></Text>.NormalizedValue() Dim updatedSignature As AddedParameterOrExistingIndex() = { AddedParameterOrExistingIndex.CreateAdded("System.Int32", "a", CallSiteKind.Omitted, isRequired:=False, defaultValue:="1")} Dim updatedCode = <Text><![CDATA[ Class C Sub M(Optional a As Integer = 1) M() End Sub End Class]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=updatedCode) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function AddOptionalParameter_AfterRequiredParameter_CallsiteOmitted() As Task Dim markup = <Text><![CDATA[ Class C Sub M$$(x As Integer) M(1) End Sub End Class]]></Text>.NormalizedValue() Dim updatedSignature As AddedParameterOrExistingIndex() = { New AddedParameterOrExistingIndex(0), AddedParameterOrExistingIndex.CreateAdded("System.Int32", "a", CallSiteKind.Omitted, isRequired:=False, defaultValue:="1")} Dim updatedCode = <Text><![CDATA[ Class C Sub M(x As Integer, Optional a As Integer = 1) M(1) End Sub End Class]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=updatedCode) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function AddOptionalParameter_BeforeOptionalParameter_CallsiteOmitted() As Task Dim markup = <Text><![CDATA[ Class C Sub M$$(Optional x As Integer = 2) M() M(2) M(x:=2) End Sub End Class]]></Text>.NormalizedValue() Dim updatedSignature As AddedParameterOrExistingIndex() = { AddedParameterOrExistingIndex.CreateAdded("System.Int32", "a", CallSiteKind.Omitted, isRequired:=False, defaultValue:="1"), New AddedParameterOrExistingIndex(0)} Dim updatedCode = <Text><![CDATA[ Class C Sub M(Optional a As Integer = 1, Optional x As Integer = 2) M() M(x:=2) M(x:=2) End Sub End Class]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=updatedCode) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function AddOptionalParameter_BeforeExpandedParamsArray_CallsiteOmitted() As Task Dim markup = <Text><![CDATA[ Class C Sub M$$(ParamArray p As Integer()) M() M(1) M(1, 2) M(1, 2, 3) End Sub End Class]]></Text>.NormalizedValue() ' This is an illegal configuration in VB, but can happen if cascaded from the legal C# ' version of this configuration. We reinterpret OMIT as TODO in this case. Dim updatedSignature As AddedParameterOrExistingIndex() = { AddedParameterOrExistingIndex.CreateAdded("System.Int32", "a", CallSiteKind.Omitted, isRequired:=False, defaultValue:="1"), New AddedParameterOrExistingIndex(0)} Dim updatedCode = <Text><![CDATA[ Class C Sub M(Optional a As Integer = 1, ParamArray p As Integer()) M(TODO) M(TODO, 1) M(TODO, 1, 2) M(TODO, 1, 2, 3) End Sub End Class]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=updatedCode) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function AddOptionalParameterWithOmittedCallsiteToAttributeConstructor() As Task Dim markup = <Text><![CDATA[ <Some(1, 2, 4)> Class SomeAttribute Inherits System.Attribute Sub New$$(a As Integer, b As Integer, Optional y As Integer = 4) End Sub End Class]]></Text>.NormalizedValue() Dim permutation = { New AddedParameterOrExistingIndex(0), New AddedParameterOrExistingIndex(1), AddedParameterOrExistingIndex.CreateAdded("Integer", "x", CallSiteKind.Omitted, isRequired:=False, defaultValue:="3"), New AddedParameterOrExistingIndex(2)} Dim updatedCode = <Text><![CDATA[ <Some(1, 2, y:=4)> Class SomeAttribute Inherits System.Attribute Sub New(a As Integer, b As Integer, Optional x As Integer = 3, Optional y As Integer = 4) End Sub End Class]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=permutation, expectedUpdatedInvocationDocumentCode:=updatedCode) 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.ChangeSignature Imports Microsoft.CodeAnalysis.Editor.UnitTests.ChangeSignature Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions Imports Microsoft.CodeAnalysis.Test.Utilities.ChangeSignature Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.ChangeSignature Partial Public Class ChangeSignatureTests Inherits AbstractChangeSignatureTests <WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function AddOptionalParameter_ToEmptySignature_CallsiteOmitted() As Task Dim markup = <Text><![CDATA[ Class C Sub M$$() M() End Sub End Class]]></Text>.NormalizedValue() Dim updatedSignature As AddedParameterOrExistingIndex() = { AddedParameterOrExistingIndex.CreateAdded("System.Int32", "a", CallSiteKind.Omitted, isRequired:=False, defaultValue:="1")} Dim updatedCode = <Text><![CDATA[ Class C Sub M(Optional a As Integer = 1) M() End Sub End Class]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=updatedCode) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function AddOptionalParameter_AfterRequiredParameter_CallsiteOmitted() As Task Dim markup = <Text><![CDATA[ Class C Sub M$$(x As Integer) M(1) End Sub End Class]]></Text>.NormalizedValue() Dim updatedSignature As AddedParameterOrExistingIndex() = { New AddedParameterOrExistingIndex(0), AddedParameterOrExistingIndex.CreateAdded("System.Int32", "a", CallSiteKind.Omitted, isRequired:=False, defaultValue:="1")} Dim updatedCode = <Text><![CDATA[ Class C Sub M(x As Integer, Optional a As Integer = 1) M(1) End Sub End Class]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=updatedCode) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function AddOptionalParameter_BeforeOptionalParameter_CallsiteOmitted() As Task Dim markup = <Text><![CDATA[ Class C Sub M$$(Optional x As Integer = 2) M() M(2) M(x:=2) End Sub End Class]]></Text>.NormalizedValue() Dim updatedSignature As AddedParameterOrExistingIndex() = { AddedParameterOrExistingIndex.CreateAdded("System.Int32", "a", CallSiteKind.Omitted, isRequired:=False, defaultValue:="1"), New AddedParameterOrExistingIndex(0)} Dim updatedCode = <Text><![CDATA[ Class C Sub M(Optional a As Integer = 1, Optional x As Integer = 2) M() M(x:=2) M(x:=2) End Sub End Class]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=updatedCode) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function AddOptionalParameter_BeforeExpandedParamsArray_CallsiteOmitted() As Task Dim markup = <Text><![CDATA[ Class C Sub M$$(ParamArray p As Integer()) M() M(1) M(1, 2) M(1, 2, 3) End Sub End Class]]></Text>.NormalizedValue() ' This is an illegal configuration in VB, but can happen if cascaded from the legal C# ' version of this configuration. We reinterpret OMIT as TODO in this case. Dim updatedSignature As AddedParameterOrExistingIndex() = { AddedParameterOrExistingIndex.CreateAdded("System.Int32", "a", CallSiteKind.Omitted, isRequired:=False, defaultValue:="1"), New AddedParameterOrExistingIndex(0)} Dim updatedCode = <Text><![CDATA[ Class C Sub M(Optional a As Integer = 1, ParamArray p As Integer()) M(TODO) M(TODO, 1) M(TODO, 1, 2) M(TODO, 1, 2, 3) End Sub End Class]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=updatedCode) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)> Public Async Function AddOptionalParameterWithOmittedCallsiteToAttributeConstructor() As Task Dim markup = <Text><![CDATA[ <Some(1, 2, 4)> Class SomeAttribute Inherits System.Attribute Sub New$$(a As Integer, b As Integer, Optional y As Integer = 4) End Sub End Class]]></Text>.NormalizedValue() Dim permutation = { New AddedParameterOrExistingIndex(0), New AddedParameterOrExistingIndex(1), AddedParameterOrExistingIndex.CreateAdded("Integer", "x", CallSiteKind.Omitted, isRequired:=False, defaultValue:="3"), New AddedParameterOrExistingIndex(2)} Dim updatedCode = <Text><![CDATA[ <Some(1, 2, y:=4)> Class SomeAttribute Inherits System.Attribute Sub New(a As Integer, b As Integer, Optional x As Integer = 3, Optional y As Integer = 4) End Sub End Class]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=permutation, expectedUpdatedInvocationDocumentCode:=updatedCode) End Function End Class End Namespace
-1
dotnet/roslyn
56,460
Set CompilerApiVersion in Microsoft.Managed.Core.targets
This allows other targets to understand which compiler will be used. This is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets. Contributes to #52265 FYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803
eerhardt
"2021-09-16T21:47:36Z"
"2021-09-22T00:53:07Z"
a10a3720229de8f4227e98736e884d6f926a9950
aabc2fcbf630ba303e6f17808465349ea9b01a32
Set CompilerApiVersion in Microsoft.Managed.Core.targets. This allows other targets to understand which compiler will be used. This is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets. Contributes to #52265 FYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803
./src/Compilers/Core/Portable/DiaSymReader/Writer/ISymUnmanagedDocumentWriter.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 #pragma warning disable 436 // SuppressUnmanagedCodeSecurityAttribute defined in source and mscorlib using System; using System.Runtime.InteropServices; using System.Security; namespace Microsoft.DiaSymReader { [ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("B01FAFEB-C450-3A4D-BEEC-B4CEEC01E006"), SuppressUnmanagedCodeSecurity] internal unsafe interface ISymUnmanagedDocumentWriter { void SetSource(uint sourceSize, byte* source); void SetCheckSum(Guid algorithmId, uint checkSumSize, byte* checkSum); } }
// Licensed to the .NET Foundation under one or more 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 #pragma warning disable 436 // SuppressUnmanagedCodeSecurityAttribute defined in source and mscorlib using System; using System.Runtime.InteropServices; using System.Security; namespace Microsoft.DiaSymReader { [ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("B01FAFEB-C450-3A4D-BEEC-B4CEEC01E006"), SuppressUnmanagedCodeSecurity] internal unsafe interface ISymUnmanagedDocumentWriter { void SetSource(uint sourceSize, byte* source); void SetCheckSum(Guid algorithmId, uint checkSumSize, byte* checkSum); } }
-1
dotnet/roslyn
56,460
Set CompilerApiVersion in Microsoft.Managed.Core.targets
This allows other targets to understand which compiler will be used. This is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets. Contributes to #52265 FYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803
eerhardt
"2021-09-16T21:47:36Z"
"2021-09-22T00:53:07Z"
a10a3720229de8f4227e98736e884d6f926a9950
aabc2fcbf630ba303e6f17808465349ea9b01a32
Set CompilerApiVersion in Microsoft.Managed.Core.targets. This allows other targets to understand which compiler will be used. This is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets. Contributes to #52265 FYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803
./src/ExpressionEvaluator/Core/Source/ResultProvider/Portable/xlf/Resources.ru.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="ru" original="../Resources.resx"> <body> <trans-unit id="DynamicView"> <source>Dynamic View</source> <target state="translated">Динамическое представление</target> <note>IDynamicMetaObjectProvider and System.__ComObject expansion</note> </trans-unit> <trans-unit id="DynamicViewNotDynamic"> <source>Only COM or Dynamic objects can have Dynamic View</source> <target state="translated">Только динамические объекты и объекты COM могут иметь динамическое представление</target> <note>Cannot use "dynamic" format specifier on a non-dynamic type</note> </trans-unit> <trans-unit id="DynamicViewValueWarning"> <source>Expanding the Dynamic View will get the dynamic members for the object</source> <target state="translated">При раскрытии динамического представления будут отображены динамические члены объекта</target> <note>Warning reported in Dynamic View value</note> </trans-unit> <trans-unit id="ErrorName"> <source>Error</source> <target state="translated">Ошибка</target> <note>Error result name</note> </trans-unit> <trans-unit id="ExceptionThrown"> <source>'{0}' threw an exception of type '{1}'</source> <target state="translated">"{0}" выдал исключение типа "{1}"</target> <note>Threw an exception while evaluating a value.</note> </trans-unit> <trans-unit id="HostValueNotFound"> <source>Cannot provide the value: host value not found</source> <target state="translated">Предоставить значение невозможно: значение узла не найдено.</target> <note /> </trans-unit> <trans-unit id="InvalidPointerDereference"> <source>Cannot dereference '{0}'. The pointer is not valid.</source> <target state="translated">Не удается разыменовать "{0}". Недопустимый указатель.</target> <note>Invalid pointer dereference</note> </trans-unit> <trans-unit id="NativeView"> <source>Native View</source> <target state="translated">Представление машинного кода</target> <note>Native COM object expansion</note> </trans-unit> <trans-unit id="NativeViewNotNativeDebugging"> <source>To inspect the native object, enable native code debugging.</source> <target state="translated">Чтобы изучить объект машинного кода, включите отладку машинного кода.</target> <note>Display value of Native View node when native debugging is not enabled</note> </trans-unit> <trans-unit id="NonPublicMembers"> <source>Non-Public members</source> <target state="translated">Члены, не являющиеся открытыми</target> <note>Non-public type members</note> </trans-unit> <trans-unit id="RawView"> <source>Raw View</source> <target state="translated">Базовое представление</target> <note>DebuggerTypeProxy "Raw View"</note> </trans-unit> <trans-unit id="ResultsView"> <source>Results View</source> <target state="translated">Представление результатов</target> <note>IEnumerable results expansion</note> </trans-unit> <trans-unit id="ResultsViewNoSystemCore"> <source>Results View requires System.Core.dll to be referenced</source> <target state="translated">Представление результатов требует наличия ссылки на System.Core.dll</target> <note>"results" format specifier requires System.Core.dll</note> </trans-unit> <trans-unit id="ResultsViewNotEnumerable"> <source>Only Enumerable types can have Results View</source> <target state="translated">Только перечислимые типы могут иметь представление результатов</target> <note>Cannot use "results" format specifier on non-enumerable type</note> </trans-unit> <trans-unit id="ResultsViewValueWarning"> <source>Expanding the Results View will enumerate the IEnumerable</source> <target state="translated">Раскрытие представления результатов вызовет перечисление IEnumerable</target> <note>Warning reported in Results View value</note> </trans-unit> <trans-unit id="SharedMembers"> <source>Shared members</source> <target state="translated">Общие члены</target> <note>Shared type members (VB only)</note> </trans-unit> <trans-unit id="StaticMembers"> <source>Static members</source> <target state="translated">Статические члены</target> <note>Static type members (C# only)</note> </trans-unit> <trans-unit id="TypeVariablesName"> <source>Type variables</source> <target state="translated">Переменные типа</target> <note>Type variables result name</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="ru" original="../Resources.resx"> <body> <trans-unit id="DynamicView"> <source>Dynamic View</source> <target state="translated">Динамическое представление</target> <note>IDynamicMetaObjectProvider and System.__ComObject expansion</note> </trans-unit> <trans-unit id="DynamicViewNotDynamic"> <source>Only COM or Dynamic objects can have Dynamic View</source> <target state="translated">Только динамические объекты и объекты COM могут иметь динамическое представление</target> <note>Cannot use "dynamic" format specifier on a non-dynamic type</note> </trans-unit> <trans-unit id="DynamicViewValueWarning"> <source>Expanding the Dynamic View will get the dynamic members for the object</source> <target state="translated">При раскрытии динамического представления будут отображены динамические члены объекта</target> <note>Warning reported in Dynamic View value</note> </trans-unit> <trans-unit id="ErrorName"> <source>Error</source> <target state="translated">Ошибка</target> <note>Error result name</note> </trans-unit> <trans-unit id="ExceptionThrown"> <source>'{0}' threw an exception of type '{1}'</source> <target state="translated">"{0}" выдал исключение типа "{1}"</target> <note>Threw an exception while evaluating a value.</note> </trans-unit> <trans-unit id="HostValueNotFound"> <source>Cannot provide the value: host value not found</source> <target state="translated">Предоставить значение невозможно: значение узла не найдено.</target> <note /> </trans-unit> <trans-unit id="InvalidPointerDereference"> <source>Cannot dereference '{0}'. The pointer is not valid.</source> <target state="translated">Не удается разыменовать "{0}". Недопустимый указатель.</target> <note>Invalid pointer dereference</note> </trans-unit> <trans-unit id="NativeView"> <source>Native View</source> <target state="translated">Представление машинного кода</target> <note>Native COM object expansion</note> </trans-unit> <trans-unit id="NativeViewNotNativeDebugging"> <source>To inspect the native object, enable native code debugging.</source> <target state="translated">Чтобы изучить объект машинного кода, включите отладку машинного кода.</target> <note>Display value of Native View node when native debugging is not enabled</note> </trans-unit> <trans-unit id="NonPublicMembers"> <source>Non-Public members</source> <target state="translated">Члены, не являющиеся открытыми</target> <note>Non-public type members</note> </trans-unit> <trans-unit id="RawView"> <source>Raw View</source> <target state="translated">Базовое представление</target> <note>DebuggerTypeProxy "Raw View"</note> </trans-unit> <trans-unit id="ResultsView"> <source>Results View</source> <target state="translated">Представление результатов</target> <note>IEnumerable results expansion</note> </trans-unit> <trans-unit id="ResultsViewNoSystemCore"> <source>Results View requires System.Core.dll to be referenced</source> <target state="translated">Представление результатов требует наличия ссылки на System.Core.dll</target> <note>"results" format specifier requires System.Core.dll</note> </trans-unit> <trans-unit id="ResultsViewNotEnumerable"> <source>Only Enumerable types can have Results View</source> <target state="translated">Только перечислимые типы могут иметь представление результатов</target> <note>Cannot use "results" format specifier on non-enumerable type</note> </trans-unit> <trans-unit id="ResultsViewValueWarning"> <source>Expanding the Results View will enumerate the IEnumerable</source> <target state="translated">Раскрытие представления результатов вызовет перечисление IEnumerable</target> <note>Warning reported in Results View value</note> </trans-unit> <trans-unit id="SharedMembers"> <source>Shared members</source> <target state="translated">Общие члены</target> <note>Shared type members (VB only)</note> </trans-unit> <trans-unit id="StaticMembers"> <source>Static members</source> <target state="translated">Статические члены</target> <note>Static type members (C# only)</note> </trans-unit> <trans-unit id="TypeVariablesName"> <source>Type variables</source> <target state="translated">Переменные типа</target> <note>Type variables result name</note> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
56,460
Set CompilerApiVersion in Microsoft.Managed.Core.targets
This allows other targets to understand which compiler will be used. This is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets. Contributes to #52265 FYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803
eerhardt
"2021-09-16T21:47:36Z"
"2021-09-22T00:53:07Z"
a10a3720229de8f4227e98736e884d6f926a9950
aabc2fcbf630ba303e6f17808465349ea9b01a32
Set CompilerApiVersion in Microsoft.Managed.Core.targets. This allows other targets to understand which compiler will be used. This is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets. Contributes to #52265 FYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803
./src/Features/VisualBasic/Portable/Completion/KeywordRecommenders/Declarations/StructureKeywordRecommender.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 "Structure" keyword in type declaration contexts ''' </summary> Friend Class StructureKeywordRecommender Inherits AbstractKeywordRecommender Private Shared ReadOnly s_keywords As ImmutableArray(Of RecommendedKeyword) = ImmutableArray.Create(New RecommendedKeyword("Structure", VBFeaturesResources.Declares_the_name_of_a_structure_and_introduces_the_definition_of_the_variables_properties_events_and_procedures_that_make_up_the_structure)) 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.Structure) 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 "Structure" keyword in type declaration contexts ''' </summary> Friend Class StructureKeywordRecommender Inherits AbstractKeywordRecommender Private Shared ReadOnly s_keywords As ImmutableArray(Of RecommendedKeyword) = ImmutableArray.Create(New RecommendedKeyword("Structure", VBFeaturesResources.Declares_the_name_of_a_structure_and_introduces_the_definition_of_the_variables_properties_events_and_procedures_that_make_up_the_structure)) 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.Structure) Then Return s_keywords End If End If Return ImmutableArray(Of RecommendedKeyword).Empty End Function End Class End Namespace
-1
dotnet/roslyn
56,460
Set CompilerApiVersion in Microsoft.Managed.Core.targets
This allows other targets to understand which compiler will be used. This is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets. Contributes to #52265 FYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803
eerhardt
"2021-09-16T21:47:36Z"
"2021-09-22T00:53:07Z"
a10a3720229de8f4227e98736e884d6f926a9950
aabc2fcbf630ba303e6f17808465349ea9b01a32
Set CompilerApiVersion in Microsoft.Managed.Core.targets. This allows other targets to understand which compiler will be used. This is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets. Contributes to #52265 FYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803
./src/EditorFeatures/DiagnosticsTestUtilities/CodeActions/AbstractCodeActionTest.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.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.Editor.Implementation.Preview; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.PickMembers; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions { public abstract partial class AbstractCodeActionTest : AbstractCodeActionOrUserDiagnosticTest { protected abstract CodeRefactoringProvider CreateCodeRefactoringProvider( Workspace workspace, TestParameters parameters); protected override async Task<(ImmutableArray<CodeAction>, CodeAction actionToInvoke)> GetCodeActionsAsync( TestWorkspace workspace, TestParameters parameters) { var refactoring = await GetCodeRefactoringAsync(workspace, parameters); var actions = refactoring == null ? ImmutableArray<CodeAction>.Empty : refactoring.CodeActions.Select(n => n.action).AsImmutable(); actions = MassageActions(actions); return (actions, actions.IsDefaultOrEmpty ? null : actions[parameters.index]); } protected override Task<ImmutableArray<Diagnostic>> GetDiagnosticsWorkerAsync(TestWorkspace workspace, TestParameters parameters) => SpecializedTasks.EmptyImmutableArray<Diagnostic>(); internal async Task<CodeRefactoring> GetCodeRefactoringAsync( TestWorkspace workspace, TestParameters parameters) { return (await GetCodeRefactoringsAsync(workspace, parameters)).FirstOrDefault(); } private async Task<IEnumerable<CodeRefactoring>> GetCodeRefactoringsAsync( TestWorkspace workspace, TestParameters parameters) { var provider = CreateCodeRefactoringProvider(workspace, parameters); return SpecializedCollections.SingletonEnumerable( await GetCodeRefactoringAsync(provider, workspace)); } private static async Task<CodeRefactoring> GetCodeRefactoringAsync( CodeRefactoringProvider provider, TestWorkspace workspace) { var documentsWithSelections = workspace.Documents.Where(d => !d.IsLinkFile && d.SelectedSpans.Count == 1); Debug.Assert(documentsWithSelections.Count() == 1, "One document must have a single span annotation"); var span = documentsWithSelections.Single().SelectedSpans.Single(); var actions = ArrayBuilder<(CodeAction, TextSpan?)>.GetInstance(); var document = workspace.CurrentSolution.GetDocument(documentsWithSelections.Single().Id); var context = new CodeRefactoringContext(document, span, (a, t) => actions.Add((a, t)), isBlocking: false, CancellationToken.None); await provider.ComputeRefactoringsAsync(context); var result = actions.Count > 0 ? new CodeRefactoring(provider, actions.ToImmutable()) : null; actions.Free(); return result; } protected async Task TestActionOnLinkedFiles( TestWorkspace workspace, string expectedText, CodeAction action, string expectedPreviewContents = null) { var operations = await VerifyActionAndGetOperationsAsync(workspace, action, default); await VerifyPreviewContents(workspace, expectedPreviewContents, operations); var applyChangesOperation = operations.OfType<ApplyChangesOperation>().First(); applyChangesOperation.TryApply(workspace, new ProgressTracker(), CancellationToken.None); foreach (var document in workspace.Documents) { var fixedRoot = await workspace.CurrentSolution.GetDocument(document.Id).GetSyntaxRootAsync(); var actualText = fixedRoot.ToFullString(); Assert.Equal(expectedText, actualText); } } private static async Task VerifyPreviewContents( TestWorkspace workspace, string expectedPreviewContents, ImmutableArray<CodeActionOperation> operations) { if (expectedPreviewContents != null) { var editHandler = workspace.ExportProvider.GetExportedValue<ICodeActionEditHandlerService>(); var previews = await editHandler.GetPreviewsAsync(workspace, operations, CancellationToken.None); var content = (await previews.GetPreviewsAsync())[0]; var diffView = content as DifferenceViewerPreview; Assert.NotNull(diffView.Viewer); var previewContents = diffView.Viewer.RightView.TextBuffer.AsTextContainer().CurrentText.ToString(); diffView.Dispose(); Assert.Equal(expectedPreviewContents, previewContents); } } protected static Document GetDocument(TestWorkspace workspace) => workspace.CurrentSolution.GetDocument(workspace.Documents.First().Id); internal static void EnableOptions( ImmutableArray<PickMembersOption> options, params string[] ids) { foreach (var id in ids) { EnableOption(options, id); } } internal static void EnableOption(ImmutableArray<PickMembersOption> options, string id) { var option = options.FirstOrDefault(o => o.Id == id); if (option != null) { option.Value = true; } } internal Task TestWithPickMembersDialogAsync( string initialMarkup, string expectedMarkup, string[] chosenSymbols, Action<ImmutableArray<PickMembersOption>> optionsCallback = null, int index = 0, TestParameters parameters = default) { var pickMembersService = new TestPickMembersService(chosenSymbols.AsImmutableOrNull(), optionsCallback); return TestInRegularAndScript1Async( initialMarkup, expectedMarkup, index, parameters.WithFixProviderData(pickMembersService)); } } [ExportWorkspaceService(typeof(IPickMembersService), ServiceLayer.Host), Shared, PartNotDiscoverable] internal class TestPickMembersService : IPickMembersService { public ImmutableArray<string> MemberNames; public Action<ImmutableArray<PickMembersOption>> OptionsCallback; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public TestPickMembersService() { } #pragma warning disable RS0034 // Exported parts should be marked with 'ImportingConstructorAttribute' public TestPickMembersService( ImmutableArray<string> memberNames, Action<ImmutableArray<PickMembersOption>> optionsCallback) { MemberNames = memberNames; OptionsCallback = optionsCallback; } #pragma warning restore RS0034 // Exported parts should be marked with 'ImportingConstructorAttribute' public PickMembersResult PickMembers( string title, ImmutableArray<ISymbol> members, ImmutableArray<PickMembersOption> options, bool selectAll) { OptionsCallback?.Invoke(options); return new PickMembersResult( MemberNames.IsDefault ? members : MemberNames.SelectAsArray(n => members.Single(m => m.Name == n)), options, selectAll); } } }
// Licensed to the .NET Foundation under one or more 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.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.Editor.Implementation.Preview; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.PickMembers; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions { public abstract partial class AbstractCodeActionTest : AbstractCodeActionOrUserDiagnosticTest { protected abstract CodeRefactoringProvider CreateCodeRefactoringProvider( Workspace workspace, TestParameters parameters); protected override async Task<(ImmutableArray<CodeAction>, CodeAction actionToInvoke)> GetCodeActionsAsync( TestWorkspace workspace, TestParameters parameters) { var refactoring = await GetCodeRefactoringAsync(workspace, parameters); var actions = refactoring == null ? ImmutableArray<CodeAction>.Empty : refactoring.CodeActions.Select(n => n.action).AsImmutable(); actions = MassageActions(actions); return (actions, actions.IsDefaultOrEmpty ? null : actions[parameters.index]); } protected override Task<ImmutableArray<Diagnostic>> GetDiagnosticsWorkerAsync(TestWorkspace workspace, TestParameters parameters) => SpecializedTasks.EmptyImmutableArray<Diagnostic>(); internal async Task<CodeRefactoring> GetCodeRefactoringAsync( TestWorkspace workspace, TestParameters parameters) { return (await GetCodeRefactoringsAsync(workspace, parameters)).FirstOrDefault(); } private async Task<IEnumerable<CodeRefactoring>> GetCodeRefactoringsAsync( TestWorkspace workspace, TestParameters parameters) { var provider = CreateCodeRefactoringProvider(workspace, parameters); return SpecializedCollections.SingletonEnumerable( await GetCodeRefactoringAsync(provider, workspace)); } private static async Task<CodeRefactoring> GetCodeRefactoringAsync( CodeRefactoringProvider provider, TestWorkspace workspace) { var documentsWithSelections = workspace.Documents.Where(d => !d.IsLinkFile && d.SelectedSpans.Count == 1); Debug.Assert(documentsWithSelections.Count() == 1, "One document must have a single span annotation"); var span = documentsWithSelections.Single().SelectedSpans.Single(); var actions = ArrayBuilder<(CodeAction, TextSpan?)>.GetInstance(); var document = workspace.CurrentSolution.GetDocument(documentsWithSelections.Single().Id); var context = new CodeRefactoringContext(document, span, (a, t) => actions.Add((a, t)), isBlocking: false, CancellationToken.None); await provider.ComputeRefactoringsAsync(context); var result = actions.Count > 0 ? new CodeRefactoring(provider, actions.ToImmutable()) : null; actions.Free(); return result; } protected async Task TestActionOnLinkedFiles( TestWorkspace workspace, string expectedText, CodeAction action, string expectedPreviewContents = null) { var operations = await VerifyActionAndGetOperationsAsync(workspace, action, default); await VerifyPreviewContents(workspace, expectedPreviewContents, operations); var applyChangesOperation = operations.OfType<ApplyChangesOperation>().First(); applyChangesOperation.TryApply(workspace, new ProgressTracker(), CancellationToken.None); foreach (var document in workspace.Documents) { var fixedRoot = await workspace.CurrentSolution.GetDocument(document.Id).GetSyntaxRootAsync(); var actualText = fixedRoot.ToFullString(); Assert.Equal(expectedText, actualText); } } private static async Task VerifyPreviewContents( TestWorkspace workspace, string expectedPreviewContents, ImmutableArray<CodeActionOperation> operations) { if (expectedPreviewContents != null) { var editHandler = workspace.ExportProvider.GetExportedValue<ICodeActionEditHandlerService>(); var previews = await editHandler.GetPreviewsAsync(workspace, operations, CancellationToken.None); var content = (await previews.GetPreviewsAsync())[0]; var diffView = content as DifferenceViewerPreview; Assert.NotNull(diffView.Viewer); var previewContents = diffView.Viewer.RightView.TextBuffer.AsTextContainer().CurrentText.ToString(); diffView.Dispose(); Assert.Equal(expectedPreviewContents, previewContents); } } protected static Document GetDocument(TestWorkspace workspace) => workspace.CurrentSolution.GetDocument(workspace.Documents.First().Id); internal static void EnableOptions( ImmutableArray<PickMembersOption> options, params string[] ids) { foreach (var id in ids) { EnableOption(options, id); } } internal static void EnableOption(ImmutableArray<PickMembersOption> options, string id) { var option = options.FirstOrDefault(o => o.Id == id); if (option != null) { option.Value = true; } } internal Task TestWithPickMembersDialogAsync( string initialMarkup, string expectedMarkup, string[] chosenSymbols, Action<ImmutableArray<PickMembersOption>> optionsCallback = null, int index = 0, TestParameters parameters = default) { var pickMembersService = new TestPickMembersService(chosenSymbols.AsImmutableOrNull(), optionsCallback); return TestInRegularAndScript1Async( initialMarkup, expectedMarkup, index, parameters.WithFixProviderData(pickMembersService)); } } [ExportWorkspaceService(typeof(IPickMembersService), ServiceLayer.Host), Shared, PartNotDiscoverable] internal class TestPickMembersService : IPickMembersService { public ImmutableArray<string> MemberNames; public Action<ImmutableArray<PickMembersOption>> OptionsCallback; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public TestPickMembersService() { } #pragma warning disable RS0034 // Exported parts should be marked with 'ImportingConstructorAttribute' public TestPickMembersService( ImmutableArray<string> memberNames, Action<ImmutableArray<PickMembersOption>> optionsCallback) { MemberNames = memberNames; OptionsCallback = optionsCallback; } #pragma warning restore RS0034 // Exported parts should be marked with 'ImportingConstructorAttribute' public PickMembersResult PickMembers( string title, ImmutableArray<ISymbol> members, ImmutableArray<PickMembersOption> options, bool selectAll) { OptionsCallback?.Invoke(options); return new PickMembersResult( MemberNames.IsDefault ? members : MemberNames.SelectAsArray(n => members.Single(m => m.Name == n)), options, selectAll); } } }
-1
dotnet/roslyn
56,460
Set CompilerApiVersion in Microsoft.Managed.Core.targets
This allows other targets to understand which compiler will be used. This is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets. Contributes to #52265 FYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803
eerhardt
"2021-09-16T21:47:36Z"
"2021-09-22T00:53:07Z"
a10a3720229de8f4227e98736e884d6f926a9950
aabc2fcbf630ba303e6f17808465349ea9b01a32
Set CompilerApiVersion in Microsoft.Managed.Core.targets. This allows other targets to understand which compiler will be used. This is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets. Contributes to #52265 FYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803
./src/EditorFeatures/CSharpTest/ExtractMethod/ExtractMethodBase.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.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.ExtractMethod; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.ExtractMethod; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ExtractMethod { [UseExportProvider] public class ExtractMethodBase { protected static async Task ExpectExtractMethodToFailAsync(string codeWithMarker, bool dontPutOutOrRefOnStruct = true, string[] features = null) { ParseOptions parseOptions = null; if (features != null) { var featuresMapped = features.Select(x => new KeyValuePair<string, string>(x, string.Empty)); parseOptions = new CSharpParseOptions().WithFeatures(featuresMapped); } using var workspace = TestWorkspace.CreateCSharp(codeWithMarker, parseOptions: parseOptions); var testDocument = workspace.Documents.First(); var textSpan = testDocument.SelectedSpans.Single(); var treeAfterExtractMethod = await ExtractMethodAsync(workspace, testDocument, succeed: false, dontPutOutOrRefOnStruct: dontPutOutOrRefOnStruct); } protected static async Task ExpectExtractMethodToFailAsync( string codeWithMarker, string expected, bool dontPutOutOrRefOnStruct = true, CSharpParseOptions parseOptions = null) { using var workspace = TestWorkspace.CreateCSharp(codeWithMarker, parseOptions: parseOptions); var testDocument = workspace.Documents.Single(); var subjectBuffer = testDocument.GetTextBuffer(); var tree = await ExtractMethodAsync(workspace, testDocument, succeed: false, dontPutOutOrRefOnStruct: dontPutOutOrRefOnStruct); using (var edit = subjectBuffer.CreateEdit()) { edit.Replace(0, edit.Snapshot.Length, tree.ToFullString()); edit.Apply(); } if (expected == "") Assert.True(false, subjectBuffer.CurrentSnapshot.GetText()); Assert.Equal(expected, subjectBuffer.CurrentSnapshot.GetText()); } protected static async Task NotSupported_ExtractMethodAsync(string codeWithMarker) { using (var workspace = TestWorkspace.CreateCSharp(codeWithMarker)) { Assert.NotNull(await Record.ExceptionAsync(async () => { var testDocument = workspace.Documents.Single(); var tree = await ExtractMethodAsync(workspace, testDocument); })); } } protected static async Task TestExtractMethodAsync( string codeWithMarker, string expected, bool temporaryFailing = false, bool dontPutOutOrRefOnStruct = true, bool allowBestEffort = false, CSharpParseOptions parseOptions = null) { using var workspace = TestWorkspace.CreateCSharp(codeWithMarker, parseOptions: parseOptions); var testDocument = workspace.Documents.Single(); var subjectBuffer = testDocument.GetTextBuffer(); var tree = await ExtractMethodAsync( workspace, testDocument, dontPutOutOrRefOnStruct: dontPutOutOrRefOnStruct, allowBestEffort: allowBestEffort); using (var edit = subjectBuffer.CreateEdit()) { edit.Replace(0, edit.Snapshot.Length, tree.ToFullString()); edit.Apply(); } var actual = subjectBuffer.CurrentSnapshot.GetText(); if (temporaryFailing) { Assert.NotEqual(expected, actual); } else { if (expected != "") { AssertEx.EqualOrDiff(expected, actual); } else { // print out the entire diff to make adding tests simpler. Assert.Equal((object)expected, actual); } } } protected static async Task<SyntaxNode> ExtractMethodAsync( TestWorkspace workspace, TestHostDocument testDocument, bool succeed = true, bool dontPutOutOrRefOnStruct = true, bool allowBestEffort = false) { var document = workspace.CurrentSolution.GetDocument(testDocument.Id); Assert.NotNull(document); var originalOptions = await document.GetOptionsAsync(); var options = originalOptions.WithChangedOption(ExtractMethodOptions.DontPutOutOrRefOnStruct, document.Project.Language, dontPutOutOrRefOnStruct); var semanticDocument = await SemanticDocument.CreateAsync(document, CancellationToken.None); var validator = new CSharpSelectionValidator(semanticDocument, testDocument.SelectedSpans.Single(), options); var selectedCode = await validator.GetValidSelectionAsync(CancellationToken.None); if (!succeed && selectedCode.Status.FailedWithNoBestEffortSuggestion()) { return null; } Assert.True(selectedCode.ContainsValidContext); // extract method var extractor = new CSharpMethodExtractor((CSharpSelectionResult)selectedCode, localFunction: false); var result = await extractor.ExtractMethodAsync(CancellationToken.None); Assert.NotNull(result); Assert.Equal(succeed, result.Succeeded || result.SucceededWithSuggestion || (allowBestEffort && result.Status.HasBestEffort())); var doc = result.Document; return doc == null ? null : await doc.GetSyntaxRootAsync(); } protected static async Task TestSelectionAsync(string codeWithMarker, bool expectedFail = false, CSharpParseOptions parseOptions = null, TextSpan? textSpanOverride = null) { using var workspace = TestWorkspace.CreateCSharp(codeWithMarker, parseOptions: parseOptions); var testDocument = workspace.Documents.Single(); var namedSpans = testDocument.AnnotatedSpans; var document = workspace.CurrentSolution.GetDocument(testDocument.Id); Assert.NotNull(document); var options = await document.GetOptionsAsync(CancellationToken.None); var semanticDocument = await SemanticDocument.CreateAsync(document, CancellationToken.None); var validator = new CSharpSelectionValidator(semanticDocument, textSpanOverride ?? namedSpans["b"].Single(), options); var result = await validator.GetValidSelectionAsync(CancellationToken.None); Assert.True(expectedFail ? result.Status.Failed() : result.Status.Succeeded()); if ((result.Status.Succeeded() || result.Status.Flag.HasBestEffort()) && result.Status.Flag.HasSuggestion()) { Assert.Equal(namedSpans["r"].Single(), result.FinalSpan); } } protected static async Task IterateAllAsync(string code) { using var workspace = TestWorkspace.CreateCSharp(code, CodeAnalysis.CSharp.Test.Utilities.TestOptions.Regular); var document = workspace.CurrentSolution.GetDocument(workspace.Documents.First().Id); Assert.NotNull(document); var semanticDocument = await SemanticDocument.CreateAsync(document, CancellationToken.None); var root = await document.GetSyntaxRootAsync(); var iterator = root.DescendantNodesAndSelf().Cast<SyntaxNode>(); var originalOptions = await document.GetOptionsAsync(); foreach (var node in iterator) { var validator = new CSharpSelectionValidator(semanticDocument, node.Span, originalOptions); var result = await validator.GetValidSelectionAsync(CancellationToken.None); // check the obvious case if (!(node is ExpressionSyntax) && !node.UnderValidContext()) { Assert.True(result.Status.FailedWithNoBestEffortSuggestion()); } } } } }
// Licensed to the .NET Foundation under one or more 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.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.ExtractMethod; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.ExtractMethod; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ExtractMethod { [UseExportProvider] public class ExtractMethodBase { protected static async Task ExpectExtractMethodToFailAsync(string codeWithMarker, bool dontPutOutOrRefOnStruct = true, string[] features = null) { ParseOptions parseOptions = null; if (features != null) { var featuresMapped = features.Select(x => new KeyValuePair<string, string>(x, string.Empty)); parseOptions = new CSharpParseOptions().WithFeatures(featuresMapped); } using var workspace = TestWorkspace.CreateCSharp(codeWithMarker, parseOptions: parseOptions); var testDocument = workspace.Documents.First(); var textSpan = testDocument.SelectedSpans.Single(); var treeAfterExtractMethod = await ExtractMethodAsync(workspace, testDocument, succeed: false, dontPutOutOrRefOnStruct: dontPutOutOrRefOnStruct); } protected static async Task ExpectExtractMethodToFailAsync( string codeWithMarker, string expected, bool dontPutOutOrRefOnStruct = true, CSharpParseOptions parseOptions = null) { using var workspace = TestWorkspace.CreateCSharp(codeWithMarker, parseOptions: parseOptions); var testDocument = workspace.Documents.Single(); var subjectBuffer = testDocument.GetTextBuffer(); var tree = await ExtractMethodAsync(workspace, testDocument, succeed: false, dontPutOutOrRefOnStruct: dontPutOutOrRefOnStruct); using (var edit = subjectBuffer.CreateEdit()) { edit.Replace(0, edit.Snapshot.Length, tree.ToFullString()); edit.Apply(); } if (expected == "") Assert.True(false, subjectBuffer.CurrentSnapshot.GetText()); Assert.Equal(expected, subjectBuffer.CurrentSnapshot.GetText()); } protected static async Task NotSupported_ExtractMethodAsync(string codeWithMarker) { using (var workspace = TestWorkspace.CreateCSharp(codeWithMarker)) { Assert.NotNull(await Record.ExceptionAsync(async () => { var testDocument = workspace.Documents.Single(); var tree = await ExtractMethodAsync(workspace, testDocument); })); } } protected static async Task TestExtractMethodAsync( string codeWithMarker, string expected, bool temporaryFailing = false, bool dontPutOutOrRefOnStruct = true, bool allowBestEffort = false, CSharpParseOptions parseOptions = null) { using var workspace = TestWorkspace.CreateCSharp(codeWithMarker, parseOptions: parseOptions); var testDocument = workspace.Documents.Single(); var subjectBuffer = testDocument.GetTextBuffer(); var tree = await ExtractMethodAsync( workspace, testDocument, dontPutOutOrRefOnStruct: dontPutOutOrRefOnStruct, allowBestEffort: allowBestEffort); using (var edit = subjectBuffer.CreateEdit()) { edit.Replace(0, edit.Snapshot.Length, tree.ToFullString()); edit.Apply(); } var actual = subjectBuffer.CurrentSnapshot.GetText(); if (temporaryFailing) { Assert.NotEqual(expected, actual); } else { if (expected != "") { AssertEx.EqualOrDiff(expected, actual); } else { // print out the entire diff to make adding tests simpler. Assert.Equal((object)expected, actual); } } } protected static async Task<SyntaxNode> ExtractMethodAsync( TestWorkspace workspace, TestHostDocument testDocument, bool succeed = true, bool dontPutOutOrRefOnStruct = true, bool allowBestEffort = false) { var document = workspace.CurrentSolution.GetDocument(testDocument.Id); Assert.NotNull(document); var originalOptions = await document.GetOptionsAsync(); var options = originalOptions.WithChangedOption(ExtractMethodOptions.DontPutOutOrRefOnStruct, document.Project.Language, dontPutOutOrRefOnStruct); var semanticDocument = await SemanticDocument.CreateAsync(document, CancellationToken.None); var validator = new CSharpSelectionValidator(semanticDocument, testDocument.SelectedSpans.Single(), options); var selectedCode = await validator.GetValidSelectionAsync(CancellationToken.None); if (!succeed && selectedCode.Status.FailedWithNoBestEffortSuggestion()) { return null; } Assert.True(selectedCode.ContainsValidContext); // extract method var extractor = new CSharpMethodExtractor((CSharpSelectionResult)selectedCode, localFunction: false); var result = await extractor.ExtractMethodAsync(CancellationToken.None); Assert.NotNull(result); Assert.Equal(succeed, result.Succeeded || result.SucceededWithSuggestion || (allowBestEffort && result.Status.HasBestEffort())); var doc = result.Document; return doc == null ? null : await doc.GetSyntaxRootAsync(); } protected static async Task TestSelectionAsync(string codeWithMarker, bool expectedFail = false, CSharpParseOptions parseOptions = null, TextSpan? textSpanOverride = null) { using var workspace = TestWorkspace.CreateCSharp(codeWithMarker, parseOptions: parseOptions); var testDocument = workspace.Documents.Single(); var namedSpans = testDocument.AnnotatedSpans; var document = workspace.CurrentSolution.GetDocument(testDocument.Id); Assert.NotNull(document); var options = await document.GetOptionsAsync(CancellationToken.None); var semanticDocument = await SemanticDocument.CreateAsync(document, CancellationToken.None); var validator = new CSharpSelectionValidator(semanticDocument, textSpanOverride ?? namedSpans["b"].Single(), options); var result = await validator.GetValidSelectionAsync(CancellationToken.None); Assert.True(expectedFail ? result.Status.Failed() : result.Status.Succeeded()); if ((result.Status.Succeeded() || result.Status.Flag.HasBestEffort()) && result.Status.Flag.HasSuggestion()) { Assert.Equal(namedSpans["r"].Single(), result.FinalSpan); } } protected static async Task IterateAllAsync(string code) { using var workspace = TestWorkspace.CreateCSharp(code, CodeAnalysis.CSharp.Test.Utilities.TestOptions.Regular); var document = workspace.CurrentSolution.GetDocument(workspace.Documents.First().Id); Assert.NotNull(document); var semanticDocument = await SemanticDocument.CreateAsync(document, CancellationToken.None); var root = await document.GetSyntaxRootAsync(); var iterator = root.DescendantNodesAndSelf().Cast<SyntaxNode>(); var originalOptions = await document.GetOptionsAsync(); foreach (var node in iterator) { var validator = new CSharpSelectionValidator(semanticDocument, node.Span, originalOptions); var result = await validator.GetValidSelectionAsync(CancellationToken.None); // check the obvious case if (!(node is ExpressionSyntax) && !node.UnderValidContext()) { Assert.True(result.Status.FailedWithNoBestEffortSuggestion()); } } } } }
-1
dotnet/roslyn
56,460
Set CompilerApiVersion in Microsoft.Managed.Core.targets
This allows other targets to understand which compiler will be used. This is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets. Contributes to #52265 FYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803
eerhardt
"2021-09-16T21:47:36Z"
"2021-09-22T00:53:07Z"
a10a3720229de8f4227e98736e884d6f926a9950
aabc2fcbf630ba303e6f17808465349ea9b01a32
Set CompilerApiVersion in Microsoft.Managed.Core.targets. This allows other targets to understand which compiler will be used. This is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets. Contributes to #52265 FYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803
./src/Analyzers/CSharp/Analyzers/UsePatternMatching/CSharpAsAndNullCheckDiagnosticAnalyzer.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.Diagnostics.CodeAnalysis; using System.Linq; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.UsePatternMatching { /// <summary> /// Looks for code of the forms: /// /// var x = o as Type; /// if (x != null) ... /// /// and converts it to: /// /// if (o is Type x) ... /// /// </summary> [DiagnosticAnalyzer(LanguageNames.CSharp)] internal partial class CSharpAsAndNullCheckDiagnosticAnalyzer : AbstractBuiltInCodeStyleDiagnosticAnalyzer { public CSharpAsAndNullCheckDiagnosticAnalyzer() : base(IDEDiagnosticIds.InlineAsTypeCheckId, EnforceOnBuildValues.InlineAsType, CSharpCodeStyleOptions.PreferPatternMatchingOverAsWithNullCheck, LanguageNames.CSharp, new LocalizableResourceString( nameof(CSharpAnalyzersResources.Use_pattern_matching), CSharpAnalyzersResources.ResourceManager, typeof(CSharpAnalyzersResources))) { } protected override void InitializeWorker(AnalysisContext context) => context.RegisterSyntaxNodeAction(SyntaxNodeAction, SyntaxKind.EqualsExpression, SyntaxKind.NotEqualsExpression, SyntaxKind.IsExpression, SyntaxKind.IsPatternExpression); private void SyntaxNodeAction(SyntaxNodeAnalysisContext syntaxContext) { var node = syntaxContext.Node; var syntaxTree = node.SyntaxTree; // "x is Type y" is only available in C# 7.0 and above. Don't offer this refactoring // in projects targeting a lesser version. if (((CSharpParseOptions)syntaxTree.Options).LanguageVersion < LanguageVersion.CSharp7) { return; } var options = syntaxContext.Options; var cancellationToken = syntaxContext.CancellationToken; var styleOption = options.GetOption(CSharpCodeStyleOptions.PreferPatternMatchingOverAsWithNullCheck, syntaxTree, cancellationToken); if (!styleOption.Value) { // Bail immediately if the user has disabled this feature. return; } var comparison = (ExpressionSyntax)node; var (comparisonLeft, comparisonRight) = comparison switch { BinaryExpressionSyntax binaryExpression => (binaryExpression.Left, (SyntaxNode)binaryExpression.Right), IsPatternExpressionSyntax isPattern => (isPattern.Expression, isPattern.Pattern), _ => throw ExceptionUtilities.Unreachable, }; var operand = GetNullCheckOperand(comparisonLeft, comparison.Kind(), comparisonRight)?.WalkDownParentheses(); if (operand == null) { return; } var semanticModel = syntaxContext.SemanticModel; if (operand.IsKind(SyntaxKind.CastExpression, out CastExpressionSyntax? castExpression)) { // Unwrap object cast var castType = semanticModel.GetTypeInfo(castExpression.Type).Type; if (castType?.SpecialType == SpecialType.System_Object) { operand = castExpression.Expression; } } if (semanticModel.GetSymbolInfo(comparison, cancellationToken).GetAnySymbol().IsUserDefinedOperator()) { return; } if (!TryGetTypeCheckParts(semanticModel, operand, out var declarator, out var asExpression, out var localSymbol)) { return; } var localStatement = declarator.Parent?.Parent; var enclosingBlock = localStatement?.Parent; if (localStatement == null || enclosingBlock == null) { return; } // Don't convert if the as is part of a using statement // eg using (var x = y as MyObject) { } if (localStatement is UsingStatementSyntax) { return; } // Don't convert if the as is part of a local declaration with a using keyword // eg using var x = y as MyObject; if (localStatement is LocalDeclarationStatementSyntax localDecl && localDecl.UsingKeyword != default) { return; } var typeNode = asExpression.Right; var asType = semanticModel.GetTypeInfo(typeNode, cancellationToken).Type; if (asType.IsNullable()) { // Not legal to write "x is int? y" return; } if (asType?.TypeKind == TypeKind.Dynamic) { // Not legal to use dynamic in a pattern. return; } if (!localSymbol.Type.Equals(asType)) { // We have something like: // // BaseType b = x as DerivedType; // if (b != null) { ... } // // It's not necessarily safe to convert this to: // // if (x is DerivedType b) { ... } // // That's because there may be later code that wants to do something like assign a // 'BaseType' into 'b'. As we've now claimed that it must be DerivedType, that // won't work. This might also cause unintended changes like changing overload // resolution. So, we conservatively do not offer the change in a situation like this. return; } // Check if the as operand is ever written up to the point of null check. // // var s = field as string; // field = null; // if (s != null) { ... } // // It's no longer safe to use pattern-matching because 'field is string s' would never be true. // // Additionally, also bail out if the assigned local is referenced (i.e. read/write/nameof) up to the point of null check. // var s = field as string; // MethodCall(flag: s == null); // if (s != null) { ... } // var asOperand = semanticModel.GetSymbolInfo(asExpression.Left, cancellationToken).Symbol; var localStatementStart = localStatement.SpanStart; var comparisonSpanStart = comparison.SpanStart; foreach (var descendentNode in enclosingBlock.DescendantNodes()) { var descendentNodeSpanStart = descendentNode.SpanStart; if (descendentNodeSpanStart <= localStatementStart) { continue; } if (descendentNodeSpanStart >= comparisonSpanStart) { break; } if (descendentNode.IsKind(SyntaxKind.IdentifierName, out IdentifierNameSyntax? identifierName)) { // Check if this is a 'write' to the asOperand. if (identifierName.Identifier.ValueText == asOperand?.Name && asOperand.Equals(semanticModel.GetSymbolInfo(identifierName, cancellationToken).Symbol) && identifierName.IsWrittenTo(semanticModel, cancellationToken)) { return; } // Check is a reference of any sort (i.e. read/write/nameof) to the local. if (identifierName.Identifier.ValueText == localSymbol.Name) { return; } } } if (!Analyzer.CanSafelyConvertToPatternMatching( semanticModel, localSymbol, comparison, operand, localStatement, enclosingBlock, cancellationToken)) { return; } // Looks good! var additionalLocations = ImmutableArray.Create( declarator.GetLocation(), comparison.GetLocation(), asExpression.GetLocation()); // Put a diagnostic with the appropriate severity on the declaration-statement itself. syntaxContext.ReportDiagnostic(DiagnosticHelper.Create( Descriptor, localStatement.GetLocation(), styleOption.Notification.Severity, additionalLocations, properties: null)); } private static bool TryGetTypeCheckParts( SemanticModel semanticModel, SyntaxNode operand, [NotNullWhen(true)] out VariableDeclaratorSyntax? declarator, [NotNullWhen(true)] out BinaryExpressionSyntax? asExpression, [NotNullWhen(true)] out ILocalSymbol? localSymbol) { switch (operand.Kind()) { case SyntaxKind.IdentifierName: { // var x = e as T; // if (x != null) F(x); var identifier = (IdentifierNameSyntax)operand; if (!TryFindVariableDeclarator(semanticModel, identifier, out localSymbol, out declarator)) { break; } var initializerValue = declarator.Initializer?.Value; if (!initializerValue.IsKind(SyntaxKind.AsExpression, out asExpression)) { break; } return true; } case SyntaxKind.SimpleAssignmentExpression: { // T x; // if ((x = e as T) != null) F(x); var assignment = (AssignmentExpressionSyntax)operand; if (!assignment.Right.IsKind(SyntaxKind.AsExpression, out asExpression) || !assignment.Left.IsKind(SyntaxKind.IdentifierName, out IdentifierNameSyntax? identifier)) { break; } if (!TryFindVariableDeclarator(semanticModel, identifier, out localSymbol, out declarator)) { break; } return true; } } declarator = null; asExpression = null; localSymbol = null; return false; } private static bool TryFindVariableDeclarator( SemanticModel semanticModel, IdentifierNameSyntax identifier, [NotNullWhen(true)] out ILocalSymbol? localSymbol, [NotNullWhen(true)] out VariableDeclaratorSyntax? declarator) { localSymbol = semanticModel.GetSymbolInfo(identifier).Symbol as ILocalSymbol; declarator = localSymbol?.DeclaringSyntaxReferences.FirstOrDefault()?.GetSyntax() as VariableDeclaratorSyntax; return localSymbol != null && declarator != null; } private static ExpressionSyntax? GetNullCheckOperand(ExpressionSyntax left, SyntaxKind comparisonKind, SyntaxNode right) { if (left.IsKind(SyntaxKind.NullLiteralExpression)) { // null == x // null != x return (ExpressionSyntax)right; } if (right.IsKind(SyntaxKind.NullLiteralExpression)) { // x == null // x != null return left; } if (right.IsKind(SyntaxKind.PredefinedType, out PredefinedTypeSyntax? predefinedType) && predefinedType.Keyword.IsKind(SyntaxKind.ObjectKeyword) && comparisonKind == SyntaxKind.IsExpression) { // x is object return left; } if (right.IsKind(SyntaxKind.ConstantPattern, out ConstantPatternSyntax? constantPattern) && constantPattern.Expression.IsKind(SyntaxKind.NullLiteralExpression) && comparisonKind == SyntaxKind.IsPatternExpression) { // x is null return left; } return null; } public override DiagnosticAnalyzerCategory GetAnalyzerCategory() => DiagnosticAnalyzerCategory.SemanticSpanAnalysis; } }
// Licensed to the .NET Foundation under one or more 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.Diagnostics.CodeAnalysis; using System.Linq; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.UsePatternMatching { /// <summary> /// Looks for code of the forms: /// /// var x = o as Type; /// if (x != null) ... /// /// and converts it to: /// /// if (o is Type x) ... /// /// </summary> [DiagnosticAnalyzer(LanguageNames.CSharp)] internal partial class CSharpAsAndNullCheckDiagnosticAnalyzer : AbstractBuiltInCodeStyleDiagnosticAnalyzer { public CSharpAsAndNullCheckDiagnosticAnalyzer() : base(IDEDiagnosticIds.InlineAsTypeCheckId, EnforceOnBuildValues.InlineAsType, CSharpCodeStyleOptions.PreferPatternMatchingOverAsWithNullCheck, LanguageNames.CSharp, new LocalizableResourceString( nameof(CSharpAnalyzersResources.Use_pattern_matching), CSharpAnalyzersResources.ResourceManager, typeof(CSharpAnalyzersResources))) { } protected override void InitializeWorker(AnalysisContext context) => context.RegisterSyntaxNodeAction(SyntaxNodeAction, SyntaxKind.EqualsExpression, SyntaxKind.NotEqualsExpression, SyntaxKind.IsExpression, SyntaxKind.IsPatternExpression); private void SyntaxNodeAction(SyntaxNodeAnalysisContext syntaxContext) { var node = syntaxContext.Node; var syntaxTree = node.SyntaxTree; // "x is Type y" is only available in C# 7.0 and above. Don't offer this refactoring // in projects targeting a lesser version. if (((CSharpParseOptions)syntaxTree.Options).LanguageVersion < LanguageVersion.CSharp7) { return; } var options = syntaxContext.Options; var cancellationToken = syntaxContext.CancellationToken; var styleOption = options.GetOption(CSharpCodeStyleOptions.PreferPatternMatchingOverAsWithNullCheck, syntaxTree, cancellationToken); if (!styleOption.Value) { // Bail immediately if the user has disabled this feature. return; } var comparison = (ExpressionSyntax)node; var (comparisonLeft, comparisonRight) = comparison switch { BinaryExpressionSyntax binaryExpression => (binaryExpression.Left, (SyntaxNode)binaryExpression.Right), IsPatternExpressionSyntax isPattern => (isPattern.Expression, isPattern.Pattern), _ => throw ExceptionUtilities.Unreachable, }; var operand = GetNullCheckOperand(comparisonLeft, comparison.Kind(), comparisonRight)?.WalkDownParentheses(); if (operand == null) { return; } var semanticModel = syntaxContext.SemanticModel; if (operand.IsKind(SyntaxKind.CastExpression, out CastExpressionSyntax? castExpression)) { // Unwrap object cast var castType = semanticModel.GetTypeInfo(castExpression.Type).Type; if (castType?.SpecialType == SpecialType.System_Object) { operand = castExpression.Expression; } } if (semanticModel.GetSymbolInfo(comparison, cancellationToken).GetAnySymbol().IsUserDefinedOperator()) { return; } if (!TryGetTypeCheckParts(semanticModel, operand, out var declarator, out var asExpression, out var localSymbol)) { return; } var localStatement = declarator.Parent?.Parent; var enclosingBlock = localStatement?.Parent; if (localStatement == null || enclosingBlock == null) { return; } // Don't convert if the as is part of a using statement // eg using (var x = y as MyObject) { } if (localStatement is UsingStatementSyntax) { return; } // Don't convert if the as is part of a local declaration with a using keyword // eg using var x = y as MyObject; if (localStatement is LocalDeclarationStatementSyntax localDecl && localDecl.UsingKeyword != default) { return; } var typeNode = asExpression.Right; var asType = semanticModel.GetTypeInfo(typeNode, cancellationToken).Type; if (asType.IsNullable()) { // Not legal to write "x is int? y" return; } if (asType?.TypeKind == TypeKind.Dynamic) { // Not legal to use dynamic in a pattern. return; } if (!localSymbol.Type.Equals(asType)) { // We have something like: // // BaseType b = x as DerivedType; // if (b != null) { ... } // // It's not necessarily safe to convert this to: // // if (x is DerivedType b) { ... } // // That's because there may be later code that wants to do something like assign a // 'BaseType' into 'b'. As we've now claimed that it must be DerivedType, that // won't work. This might also cause unintended changes like changing overload // resolution. So, we conservatively do not offer the change in a situation like this. return; } // Check if the as operand is ever written up to the point of null check. // // var s = field as string; // field = null; // if (s != null) { ... } // // It's no longer safe to use pattern-matching because 'field is string s' would never be true. // // Additionally, also bail out if the assigned local is referenced (i.e. read/write/nameof) up to the point of null check. // var s = field as string; // MethodCall(flag: s == null); // if (s != null) { ... } // var asOperand = semanticModel.GetSymbolInfo(asExpression.Left, cancellationToken).Symbol; var localStatementStart = localStatement.SpanStart; var comparisonSpanStart = comparison.SpanStart; foreach (var descendentNode in enclosingBlock.DescendantNodes()) { var descendentNodeSpanStart = descendentNode.SpanStart; if (descendentNodeSpanStart <= localStatementStart) { continue; } if (descendentNodeSpanStart >= comparisonSpanStart) { break; } if (descendentNode.IsKind(SyntaxKind.IdentifierName, out IdentifierNameSyntax? identifierName)) { // Check if this is a 'write' to the asOperand. if (identifierName.Identifier.ValueText == asOperand?.Name && asOperand.Equals(semanticModel.GetSymbolInfo(identifierName, cancellationToken).Symbol) && identifierName.IsWrittenTo(semanticModel, cancellationToken)) { return; } // Check is a reference of any sort (i.e. read/write/nameof) to the local. if (identifierName.Identifier.ValueText == localSymbol.Name) { return; } } } if (!Analyzer.CanSafelyConvertToPatternMatching( semanticModel, localSymbol, comparison, operand, localStatement, enclosingBlock, cancellationToken)) { return; } // Looks good! var additionalLocations = ImmutableArray.Create( declarator.GetLocation(), comparison.GetLocation(), asExpression.GetLocation()); // Put a diagnostic with the appropriate severity on the declaration-statement itself. syntaxContext.ReportDiagnostic(DiagnosticHelper.Create( Descriptor, localStatement.GetLocation(), styleOption.Notification.Severity, additionalLocations, properties: null)); } private static bool TryGetTypeCheckParts( SemanticModel semanticModel, SyntaxNode operand, [NotNullWhen(true)] out VariableDeclaratorSyntax? declarator, [NotNullWhen(true)] out BinaryExpressionSyntax? asExpression, [NotNullWhen(true)] out ILocalSymbol? localSymbol) { switch (operand.Kind()) { case SyntaxKind.IdentifierName: { // var x = e as T; // if (x != null) F(x); var identifier = (IdentifierNameSyntax)operand; if (!TryFindVariableDeclarator(semanticModel, identifier, out localSymbol, out declarator)) { break; } var initializerValue = declarator.Initializer?.Value; if (!initializerValue.IsKind(SyntaxKind.AsExpression, out asExpression)) { break; } return true; } case SyntaxKind.SimpleAssignmentExpression: { // T x; // if ((x = e as T) != null) F(x); var assignment = (AssignmentExpressionSyntax)operand; if (!assignment.Right.IsKind(SyntaxKind.AsExpression, out asExpression) || !assignment.Left.IsKind(SyntaxKind.IdentifierName, out IdentifierNameSyntax? identifier)) { break; } if (!TryFindVariableDeclarator(semanticModel, identifier, out localSymbol, out declarator)) { break; } return true; } } declarator = null; asExpression = null; localSymbol = null; return false; } private static bool TryFindVariableDeclarator( SemanticModel semanticModel, IdentifierNameSyntax identifier, [NotNullWhen(true)] out ILocalSymbol? localSymbol, [NotNullWhen(true)] out VariableDeclaratorSyntax? declarator) { localSymbol = semanticModel.GetSymbolInfo(identifier).Symbol as ILocalSymbol; declarator = localSymbol?.DeclaringSyntaxReferences.FirstOrDefault()?.GetSyntax() as VariableDeclaratorSyntax; return localSymbol != null && declarator != null; } private static ExpressionSyntax? GetNullCheckOperand(ExpressionSyntax left, SyntaxKind comparisonKind, SyntaxNode right) { if (left.IsKind(SyntaxKind.NullLiteralExpression)) { // null == x // null != x return (ExpressionSyntax)right; } if (right.IsKind(SyntaxKind.NullLiteralExpression)) { // x == null // x != null return left; } if (right.IsKind(SyntaxKind.PredefinedType, out PredefinedTypeSyntax? predefinedType) && predefinedType.Keyword.IsKind(SyntaxKind.ObjectKeyword) && comparisonKind == SyntaxKind.IsExpression) { // x is object return left; } if (right.IsKind(SyntaxKind.ConstantPattern, out ConstantPatternSyntax? constantPattern) && constantPattern.Expression.IsKind(SyntaxKind.NullLiteralExpression) && comparisonKind == SyntaxKind.IsPatternExpression) { // x is null return left; } return null; } public override DiagnosticAnalyzerCategory GetAnalyzerCategory() => DiagnosticAnalyzerCategory.SemanticSpanAnalysis; } }
-1
dotnet/roslyn
56,460
Set CompilerApiVersion in Microsoft.Managed.Core.targets
This allows other targets to understand which compiler will be used. This is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets. Contributes to #52265 FYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803
eerhardt
"2021-09-16T21:47:36Z"
"2021-09-22T00:53:07Z"
a10a3720229de8f4227e98736e884d6f926a9950
aabc2fcbf630ba303e6f17808465349ea9b01a32
Set CompilerApiVersion in Microsoft.Managed.Core.targets. This allows other targets to understand which compiler will be used. This is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets. Contributes to #52265 FYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803
./src/Workspaces/CSharp/Portable/xlf/CSharpWorkspaceResources.zh-Hans.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-Hans" original="../CSharpWorkspaceResources.resx"> <body> <trans-unit id="Indentation_preferences"> <source>Indentation preferences</source> <target state="translated">缩进首选项</target> <note /> </trans-unit> <trans-unit id="No_available_location_found_to_add_statements_to"> <source>No available location found to add statements to.</source> <target state="translated">没有找到添加语句的可用位置。</target> <note /> </trans-unit> <trans-unit id="Namespace_can_not_be_added_in_this_destination"> <source>Namespace can not be added in this destination.</source> <target state="translated">不能在此目标中添加命名空间。</target> <note /> </trans-unit> <trans-unit id="Node_does_not_descend_from_root"> <source>Node does not descend from root.</source> <target state="translated">节点并非源自根。</target> <note /> </trans-unit> <trans-unit id="Node_not_in_parent_s_child_list"> <source>Node not in parent's child list</source> <target state="translated">节点不在父级的子列表中</target> <note /> </trans-unit> <trans-unit id="Remove_and_Sort_Usings"> <source>R&amp;emove and Sort Usings</source> <target state="translated">删除 Using 和对其排序(&amp;E)</target> <note /> </trans-unit> <trans-unit id="Sort_Usings"> <source>&amp;Sort Usings</source> <target state="translated">对 using 排序(&amp;S)</target> <note /> </trans-unit> <trans-unit id="Space_preferences"> <source>Space preferences</source> <target state="translated">空格键首选项</target> <note /> </trans-unit> <trans-unit id="Trivia_is_not_associated_with_token"> <source>Trivia is not associated with token</source> <target state="translated">琐事与标记不相关联</target> <note /> </trans-unit> <trans-unit id="Cannot_retrieve_the_Span_of_a_null_syntax_reference"> <source>Cannot retrieve the Span of a null syntax reference.</source> <target state="translated">无法检索一个空语法引用的范围。</target> <note /> </trans-unit> <trans-unit id="Only_attributes_constructor_initializers_expressions_or_statements_can_be_made_explicit"> <source>Only attributes, constructor initializers, expressions or statements can be made explicit</source> <target state="translated">仅属性、构造函数初始值设定项、表达式或语句可为显式</target> <note /> </trans-unit> <trans-unit id="Implement_Interface"> <source>Implement Interface</source> <target state="translated">实现接口</target> <note /> </trans-unit> <trans-unit id="Wrapping_preferences"> <source>Wrapping preferences</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="zh-Hans" original="../CSharpWorkspaceResources.resx"> <body> <trans-unit id="Indentation_preferences"> <source>Indentation preferences</source> <target state="translated">缩进首选项</target> <note /> </trans-unit> <trans-unit id="No_available_location_found_to_add_statements_to"> <source>No available location found to add statements to.</source> <target state="translated">没有找到添加语句的可用位置。</target> <note /> </trans-unit> <trans-unit id="Namespace_can_not_be_added_in_this_destination"> <source>Namespace can not be added in this destination.</source> <target state="translated">不能在此目标中添加命名空间。</target> <note /> </trans-unit> <trans-unit id="Node_does_not_descend_from_root"> <source>Node does not descend from root.</source> <target state="translated">节点并非源自根。</target> <note /> </trans-unit> <trans-unit id="Node_not_in_parent_s_child_list"> <source>Node not in parent's child list</source> <target state="translated">节点不在父级的子列表中</target> <note /> </trans-unit> <trans-unit id="Remove_and_Sort_Usings"> <source>R&amp;emove and Sort Usings</source> <target state="translated">删除 Using 和对其排序(&amp;E)</target> <note /> </trans-unit> <trans-unit id="Sort_Usings"> <source>&amp;Sort Usings</source> <target state="translated">对 using 排序(&amp;S)</target> <note /> </trans-unit> <trans-unit id="Space_preferences"> <source>Space preferences</source> <target state="translated">空格键首选项</target> <note /> </trans-unit> <trans-unit id="Trivia_is_not_associated_with_token"> <source>Trivia is not associated with token</source> <target state="translated">琐事与标记不相关联</target> <note /> </trans-unit> <trans-unit id="Cannot_retrieve_the_Span_of_a_null_syntax_reference"> <source>Cannot retrieve the Span of a null syntax reference.</source> <target state="translated">无法检索一个空语法引用的范围。</target> <note /> </trans-unit> <trans-unit id="Only_attributes_constructor_initializers_expressions_or_statements_can_be_made_explicit"> <source>Only attributes, constructor initializers, expressions or statements can be made explicit</source> <target state="translated">仅属性、构造函数初始值设定项、表达式或语句可为显式</target> <note /> </trans-unit> <trans-unit id="Implement_Interface"> <source>Implement Interface</source> <target state="translated">实现接口</target> <note /> </trans-unit> <trans-unit id="Wrapping_preferences"> <source>Wrapping preferences</source> <target state="translated">包装首选项</target> <note /> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
56,460
Set CompilerApiVersion in Microsoft.Managed.Core.targets
This allows other targets to understand which compiler will be used. This is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets. Contributes to #52265 FYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803
eerhardt
"2021-09-16T21:47:36Z"
"2021-09-22T00:53:07Z"
a10a3720229de8f4227e98736e884d6f926a9950
aabc2fcbf630ba303e6f17808465349ea9b01a32
Set CompilerApiVersion in Microsoft.Managed.Core.targets. This allows other targets to understand which compiler will be used. This is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets. Contributes to #52265 FYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803
./src/Features/Core/Portable/EditAndContinue/EditAndContinueDocumentAnalysesCache.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.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.EditAndContinue { /// <summary> /// Calculates and caches results of changed documents analysis. /// The work is triggered by an incremental analyzer on idle or explicitly when "continue" operation is executed. /// Contains analyses of the latest observed document versions. /// </summary> internal sealed class EditAndContinueDocumentAnalysesCache { private readonly object _guard = new(); private readonly Dictionary<DocumentId, (AsyncLazy<DocumentAnalysisResults> results, Project baseProject, Document document, ImmutableArray<LinePositionSpan> activeStatementSpans)> _analyses = new(); private readonly AsyncLazy<ActiveStatementsMap> _baseActiveStatements; private readonly AsyncLazy<EditAndContinueCapabilities> _capabilities; public EditAndContinueDocumentAnalysesCache(AsyncLazy<ActiveStatementsMap> baseActiveStatements, AsyncLazy<EditAndContinueCapabilities> capabilities) { _baseActiveStatements = baseActiveStatements; _capabilities = capabilities; } public async ValueTask<ImmutableArray<DocumentAnalysisResults>> GetDocumentAnalysesAsync( CommittedSolution oldSolution, IReadOnlyList<(Document? oldDocument, Document newDocument)> documents, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken) { try { if (documents.IsEmpty()) { return ImmutableArray<DocumentAnalysisResults>.Empty; } var tasks = documents.Select(document => Task.Run(() => GetDocumentAnalysisAsync(oldSolution, document.oldDocument, document.newDocument, activeStatementSpanProvider, cancellationToken).AsTask(), cancellationToken)); var allResults = await Task.WhenAll(tasks).ConfigureAwait(false); return allResults.ToImmutableArray(); } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } /// <summary> /// Returns a document analysis or kicks off a new one if one is not available for the specified document snapshot. /// </summary> /// <param name="oldSolution">Committed solution.</param> /// <param name="newDocument">Document snapshot to analyze.</param> /// <param name="activeStatementSpanProvider">Provider of active statement spans tracked by the editor for the solution snapshot of the <paramref name="newDocument"/>.</param> public async ValueTask<DocumentAnalysisResults> GetDocumentAnalysisAsync( CommittedSolution oldSolution, Document? oldDocument, Document newDocument, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken) { try { var unmappedActiveStatementSpans = await GetLatestUnmappedActiveStatementSpansAsync(oldDocument, newDocument, activeStatementSpanProvider, cancellationToken).ConfigureAwait(false); // The base project may have been updated as documents were brought up-to-date in the committed solution. // Get the latest available snapshot of the base project from the committed solution and use it for analyses of all documents, // so that we use a single compilation for the base project (for efficiency). // Note that some other request might be updating documents in the committed solution that were not changed (not in changedOrAddedDocuments) // but are not up-to-date. These documents do not have impact on the analysis unless we read semantic information // from the project compilation. When reading such information we need to be aware of its potential incompleteness // and consult the compiler output binary (see https://github.com/dotnet/roslyn/issues/51261). var oldProject = oldDocument?.Project ?? oldSolution.GetRequiredProject(newDocument.Project.Id); AsyncLazy<DocumentAnalysisResults> lazyResults; lock (_guard) { lazyResults = GetDocumentAnalysisNoLock(oldProject, newDocument, unmappedActiveStatementSpans); } return await lazyResults.GetValueAsync(cancellationToken).ConfigureAwait(false); } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } /// <summary> /// Calculates unmapped active statement spans in the <paramref name="newDocument"/> from spans provided by <paramref name="newActiveStatementSpanProvider"/>. /// </summary> private async Task<ImmutableArray<LinePositionSpan>> GetLatestUnmappedActiveStatementSpansAsync(Document? oldDocument, Document newDocument, ActiveStatementSpanProvider newActiveStatementSpanProvider, CancellationToken cancellationToken) { if (oldDocument == null) { // document has been deleted or is out-of-sync return ImmutableArray<LinePositionSpan>.Empty; } if (newDocument.FilePath == null) { // document has been added, or doesn't have a file path - we do not have tracking spans for it return ImmutableArray<LinePositionSpan>.Empty; } var newTree = await newDocument.GetRequiredSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); var newLineMappings = newTree.GetLineMappings(cancellationToken); // No #line directives -- retrieve the current location of tracking spans directly for this document: if (!newLineMappings.Any()) { var newMappedDocumentSpans = await newActiveStatementSpanProvider(newDocument.Id, newDocument.FilePath, cancellationToken).ConfigureAwait(false); return newMappedDocumentSpans.SelectAsArray(s => s.LineSpan); } // The document has #line directives. In order to determine all active statement spans in the document // we need to find all documents that #line directives in this document map to. // We retrieve the tracking spans for all such documents and then map them back to this document. using var _1 = PooledDictionary<string, ImmutableArray<ActiveStatementSpan>>.GetInstance(out var mappedSpansByDocumentPath); using var _2 = ArrayBuilder<LinePositionSpan>.GetInstance(out var activeStatementSpansBuilder); var baseActiveStatements = await _baseActiveStatements.GetValueAsync(cancellationToken).ConfigureAwait(false); var analyzer = newDocument.Project.LanguageServices.GetRequiredService<IEditAndContinueAnalyzer>(); var oldActiveStatements = await baseActiveStatements.GetOldActiveStatementsAsync(analyzer, oldDocument, cancellationToken).ConfigureAwait(false); foreach (var oldActiveStatement in oldActiveStatements) { var mappedFilePath = oldActiveStatement.Statement.FileSpan.Path; if (!mappedSpansByDocumentPath.TryGetValue(mappedFilePath, out var newMappedDocumentSpans)) { newMappedDocumentSpans = await newActiveStatementSpanProvider((newDocument.FilePath == mappedFilePath) ? newDocument.Id : null, mappedFilePath, cancellationToken).ConfigureAwait(false); mappedSpansByDocumentPath.Add(mappedFilePath, newMappedDocumentSpans); } // Spans not tracked in the document (e.g. the document has been closed): if (newMappedDocumentSpans.IsEmpty) { continue; } // all baseline spans are being tracked in their corresponding mapped documents (if a span is deleted it's still tracked as empty): var newMappedDocumentActiveSpan = newMappedDocumentSpans.GetStatement(oldActiveStatement.Statement.Ordinal); Debug.Assert(newMappedDocumentActiveSpan.UnmappedDocumentId == null || newMappedDocumentActiveSpan.UnmappedDocumentId == newDocument.Id); // TODO: optimize var newLineMappingContainingActiveSpan = newLineMappings.FirstOrDefault(mapping => mapping.MappedSpan.Span.Contains(newMappedDocumentActiveSpan.LineSpan)); var unmappedSpan = newLineMappingContainingActiveSpan.MappedSpan.IsValid ? newLineMappingContainingActiveSpan.Span : default; activeStatementSpansBuilder.Add(unmappedSpan); } return activeStatementSpansBuilder.ToImmutable(); } private AsyncLazy<DocumentAnalysisResults> GetDocumentAnalysisNoLock(Project baseProject, Document document, ImmutableArray<LinePositionSpan> activeStatementSpans) { // Do not reuse an analysis of the document unless its snasphot is exactly the same as was used to calculate the results. // Note that comparing document snapshots in effect compares the entire solution snapshots (when another document is changed a new solution snapshot is created // that creates new document snapshots for all queried documents). // Also check the base project snapshot since the analysis uses semantic information from the base project as well. // // It would be possible to reuse analysis results of documents whose content does not change in between two solution snapshots. // However, we'd need rather sophisticated caching logic. The smantic analysis gathers information from other documents when // calculating results for a specific document. In some cases it's easy to record the set of documents the analysis depends on. // For example, when analyzing a partial class we can record all documents its declaration spans. However, in other cases the analysis // checks for absence of a top-level type symbol. Adding a symbol to any document thus invalidates such analysis. It'd be possible // to keep track of which type symbols an analysis is conditional upon, if it was worth the extra complexity. if (_analyses.TryGetValue(document.Id, out var analysis) && analysis.baseProject == baseProject && analysis.document == document && analysis.activeStatementSpans.SequenceEqual(activeStatementSpans)) { return analysis.results; } var lazyResults = new AsyncLazy<DocumentAnalysisResults>( asynchronousComputeFunction: async cancellationToken => { try { var analyzer = document.Project.LanguageServices.GetRequiredService<IEditAndContinueAnalyzer>(); return await analyzer.AnalyzeDocumentAsync(baseProject, _baseActiveStatements, document, activeStatementSpans, _capabilities, cancellationToken).ConfigureAwait(false); } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } }, cacheResult: true); // Previous results for this document id are discarded as they are no longer relevant. // The only relevant analysis is for the latest base and document snapshots. // Note that the base snapshot may evolve if documents are dicovered that were previously // out-of-sync with the compiled outputs and are now up-to-date. _analyses[document.Id] = (lazyResults, baseProject, document, activeStatementSpans); return lazyResults; } } }
// Licensed to the .NET Foundation under one or more 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.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.EditAndContinue { /// <summary> /// Calculates and caches results of changed documents analysis. /// The work is triggered by an incremental analyzer on idle or explicitly when "continue" operation is executed. /// Contains analyses of the latest observed document versions. /// </summary> internal sealed class EditAndContinueDocumentAnalysesCache { private readonly object _guard = new(); private readonly Dictionary<DocumentId, (AsyncLazy<DocumentAnalysisResults> results, Project baseProject, Document document, ImmutableArray<LinePositionSpan> activeStatementSpans)> _analyses = new(); private readonly AsyncLazy<ActiveStatementsMap> _baseActiveStatements; private readonly AsyncLazy<EditAndContinueCapabilities> _capabilities; public EditAndContinueDocumentAnalysesCache(AsyncLazy<ActiveStatementsMap> baseActiveStatements, AsyncLazy<EditAndContinueCapabilities> capabilities) { _baseActiveStatements = baseActiveStatements; _capabilities = capabilities; } public async ValueTask<ImmutableArray<DocumentAnalysisResults>> GetDocumentAnalysesAsync( CommittedSolution oldSolution, IReadOnlyList<(Document? oldDocument, Document newDocument)> documents, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken) { try { if (documents.IsEmpty()) { return ImmutableArray<DocumentAnalysisResults>.Empty; } var tasks = documents.Select(document => Task.Run(() => GetDocumentAnalysisAsync(oldSolution, document.oldDocument, document.newDocument, activeStatementSpanProvider, cancellationToken).AsTask(), cancellationToken)); var allResults = await Task.WhenAll(tasks).ConfigureAwait(false); return allResults.ToImmutableArray(); } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } /// <summary> /// Returns a document analysis or kicks off a new one if one is not available for the specified document snapshot. /// </summary> /// <param name="oldSolution">Committed solution.</param> /// <param name="newDocument">Document snapshot to analyze.</param> /// <param name="activeStatementSpanProvider">Provider of active statement spans tracked by the editor for the solution snapshot of the <paramref name="newDocument"/>.</param> public async ValueTask<DocumentAnalysisResults> GetDocumentAnalysisAsync( CommittedSolution oldSolution, Document? oldDocument, Document newDocument, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken) { try { var unmappedActiveStatementSpans = await GetLatestUnmappedActiveStatementSpansAsync(oldDocument, newDocument, activeStatementSpanProvider, cancellationToken).ConfigureAwait(false); // The base project may have been updated as documents were brought up-to-date in the committed solution. // Get the latest available snapshot of the base project from the committed solution and use it for analyses of all documents, // so that we use a single compilation for the base project (for efficiency). // Note that some other request might be updating documents in the committed solution that were not changed (not in changedOrAddedDocuments) // but are not up-to-date. These documents do not have impact on the analysis unless we read semantic information // from the project compilation. When reading such information we need to be aware of its potential incompleteness // and consult the compiler output binary (see https://github.com/dotnet/roslyn/issues/51261). var oldProject = oldDocument?.Project ?? oldSolution.GetRequiredProject(newDocument.Project.Id); AsyncLazy<DocumentAnalysisResults> lazyResults; lock (_guard) { lazyResults = GetDocumentAnalysisNoLock(oldProject, newDocument, unmappedActiveStatementSpans); } return await lazyResults.GetValueAsync(cancellationToken).ConfigureAwait(false); } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } /// <summary> /// Calculates unmapped active statement spans in the <paramref name="newDocument"/> from spans provided by <paramref name="newActiveStatementSpanProvider"/>. /// </summary> private async Task<ImmutableArray<LinePositionSpan>> GetLatestUnmappedActiveStatementSpansAsync(Document? oldDocument, Document newDocument, ActiveStatementSpanProvider newActiveStatementSpanProvider, CancellationToken cancellationToken) { if (oldDocument == null) { // document has been deleted or is out-of-sync return ImmutableArray<LinePositionSpan>.Empty; } if (newDocument.FilePath == null) { // document has been added, or doesn't have a file path - we do not have tracking spans for it return ImmutableArray<LinePositionSpan>.Empty; } var newTree = await newDocument.GetRequiredSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); var newLineMappings = newTree.GetLineMappings(cancellationToken); // No #line directives -- retrieve the current location of tracking spans directly for this document: if (!newLineMappings.Any()) { var newMappedDocumentSpans = await newActiveStatementSpanProvider(newDocument.Id, newDocument.FilePath, cancellationToken).ConfigureAwait(false); return newMappedDocumentSpans.SelectAsArray(s => s.LineSpan); } // The document has #line directives. In order to determine all active statement spans in the document // we need to find all documents that #line directives in this document map to. // We retrieve the tracking spans for all such documents and then map them back to this document. using var _1 = PooledDictionary<string, ImmutableArray<ActiveStatementSpan>>.GetInstance(out var mappedSpansByDocumentPath); using var _2 = ArrayBuilder<LinePositionSpan>.GetInstance(out var activeStatementSpansBuilder); var baseActiveStatements = await _baseActiveStatements.GetValueAsync(cancellationToken).ConfigureAwait(false); var analyzer = newDocument.Project.LanguageServices.GetRequiredService<IEditAndContinueAnalyzer>(); var oldActiveStatements = await baseActiveStatements.GetOldActiveStatementsAsync(analyzer, oldDocument, cancellationToken).ConfigureAwait(false); foreach (var oldActiveStatement in oldActiveStatements) { var mappedFilePath = oldActiveStatement.Statement.FileSpan.Path; if (!mappedSpansByDocumentPath.TryGetValue(mappedFilePath, out var newMappedDocumentSpans)) { newMappedDocumentSpans = await newActiveStatementSpanProvider((newDocument.FilePath == mappedFilePath) ? newDocument.Id : null, mappedFilePath, cancellationToken).ConfigureAwait(false); mappedSpansByDocumentPath.Add(mappedFilePath, newMappedDocumentSpans); } // Spans not tracked in the document (e.g. the document has been closed): if (newMappedDocumentSpans.IsEmpty) { continue; } // all baseline spans are being tracked in their corresponding mapped documents (if a span is deleted it's still tracked as empty): var newMappedDocumentActiveSpan = newMappedDocumentSpans.GetStatement(oldActiveStatement.Statement.Ordinal); Debug.Assert(newMappedDocumentActiveSpan.UnmappedDocumentId == null || newMappedDocumentActiveSpan.UnmappedDocumentId == newDocument.Id); // TODO: optimize var newLineMappingContainingActiveSpan = newLineMappings.FirstOrDefault(mapping => mapping.MappedSpan.Span.Contains(newMappedDocumentActiveSpan.LineSpan)); var unmappedSpan = newLineMappingContainingActiveSpan.MappedSpan.IsValid ? newLineMappingContainingActiveSpan.Span : default; activeStatementSpansBuilder.Add(unmappedSpan); } return activeStatementSpansBuilder.ToImmutable(); } private AsyncLazy<DocumentAnalysisResults> GetDocumentAnalysisNoLock(Project baseProject, Document document, ImmutableArray<LinePositionSpan> activeStatementSpans) { // Do not reuse an analysis of the document unless its snasphot is exactly the same as was used to calculate the results. // Note that comparing document snapshots in effect compares the entire solution snapshots (when another document is changed a new solution snapshot is created // that creates new document snapshots for all queried documents). // Also check the base project snapshot since the analysis uses semantic information from the base project as well. // // It would be possible to reuse analysis results of documents whose content does not change in between two solution snapshots. // However, we'd need rather sophisticated caching logic. The smantic analysis gathers information from other documents when // calculating results for a specific document. In some cases it's easy to record the set of documents the analysis depends on. // For example, when analyzing a partial class we can record all documents its declaration spans. However, in other cases the analysis // checks for absence of a top-level type symbol. Adding a symbol to any document thus invalidates such analysis. It'd be possible // to keep track of which type symbols an analysis is conditional upon, if it was worth the extra complexity. if (_analyses.TryGetValue(document.Id, out var analysis) && analysis.baseProject == baseProject && analysis.document == document && analysis.activeStatementSpans.SequenceEqual(activeStatementSpans)) { return analysis.results; } var lazyResults = new AsyncLazy<DocumentAnalysisResults>( asynchronousComputeFunction: async cancellationToken => { try { var analyzer = document.Project.LanguageServices.GetRequiredService<IEditAndContinueAnalyzer>(); return await analyzer.AnalyzeDocumentAsync(baseProject, _baseActiveStatements, document, activeStatementSpans, _capabilities, cancellationToken).ConfigureAwait(false); } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } }, cacheResult: true); // Previous results for this document id are discarded as they are no longer relevant. // The only relevant analysis is for the latest base and document snapshots. // Note that the base snapshot may evolve if documents are dicovered that were previously // out-of-sync with the compiled outputs and are now up-to-date. _analyses[document.Id] = (lazyResults, baseProject, document, activeStatementSpans); return lazyResults; } } }
-1
dotnet/roslyn
56,460
Set CompilerApiVersion in Microsoft.Managed.Core.targets
This allows other targets to understand which compiler will be used. This is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets. Contributes to #52265 FYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803
eerhardt
"2021-09-16T21:47:36Z"
"2021-09-22T00:53:07Z"
a10a3720229de8f4227e98736e884d6f926a9950
aabc2fcbf630ba303e6f17808465349ea9b01a32
Set CompilerApiVersion in Microsoft.Managed.Core.targets. This allows other targets to understand which compiler will be used. This is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets. Contributes to #52265 FYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803
./src/Analyzers/CSharp/Analyzers/PopulateSwitch/CSharpPopulateSwitchExpressionDiagnosticAnalyzer.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; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.PopulateSwitch; namespace Microsoft.CodeAnalysis.CSharp.PopulateSwitch { [DiagnosticAnalyzer(LanguageNames.CSharp)] internal sealed class CSharpPopulateSwitchExpressionDiagnosticAnalyzer : AbstractPopulateSwitchExpressionDiagnosticAnalyzer<SwitchExpressionSyntax> { protected override Location GetDiagnosticLocation(SwitchExpressionSyntax switchBlock) => switchBlock.SwitchKeyword.GetLocation(); } }
// Licensed to the .NET Foundation under one or more 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; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.PopulateSwitch; namespace Microsoft.CodeAnalysis.CSharp.PopulateSwitch { [DiagnosticAnalyzer(LanguageNames.CSharp)] internal sealed class CSharpPopulateSwitchExpressionDiagnosticAnalyzer : AbstractPopulateSwitchExpressionDiagnosticAnalyzer<SwitchExpressionSyntax> { protected override Location GetDiagnosticLocation(SwitchExpressionSyntax switchBlock) => switchBlock.SwitchKeyword.GetLocation(); } }
-1
dotnet/roslyn
56,460
Set CompilerApiVersion in Microsoft.Managed.Core.targets
This allows other targets to understand which compiler will be used. This is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets. Contributes to #52265 FYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803
eerhardt
"2021-09-16T21:47:36Z"
"2021-09-22T00:53:07Z"
a10a3720229de8f4227e98736e884d6f926a9950
aabc2fcbf630ba303e6f17808465349ea9b01a32
Set CompilerApiVersion in Microsoft.Managed.Core.targets. This allows other targets to understand which compiler will be used. This is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets. Contributes to #52265 FYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803
./src/Features/VisualBasic/Portable/IntroduceVariable/VisualBasicIntroduceVariableService.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.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.IntroduceVariable Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports System.Composition Namespace Microsoft.CodeAnalysis.VisualBasic.IntroduceVariable <ExportLanguageService(GetType(IIntroduceVariableService), LanguageNames.VisualBasic), [Shared]> Partial Friend Class VisualBasicIntroduceVariableService Inherits AbstractIntroduceVariableService(Of VisualBasicIntroduceVariableService, ExpressionSyntax, TypeSyntax, TypeBlockSyntax, QueryExpressionSyntax, NameSyntax) <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub Protected Overrides Function GetContainingExecutableBlocks(expression As ExpressionSyntax) As IEnumerable(Of SyntaxNode) Return expression.GetContainingExecutableBlocks() End Function Protected Overrides Function GetInsertionIndices(destination As TypeBlockSyntax, cancellationToken As CancellationToken) As IList(Of Boolean) Return destination.GetInsertionIndices(cancellationToken) End Function Protected Overrides Function IsInAttributeArgumentInitializer(expression As ExpressionSyntax) As Boolean If expression.GetAncestorOrThis(Of ArgumentSyntax)() Is Nothing Then Return False End If If expression.GetAncestorOrThis(Of AttributeSyntax)() Is Nothing Then Return False End If If expression.DepthFirstTraversal.Any(Function(n) n.Kind() = SyntaxKind.ArrayCreationExpression) OrElse expression.DepthFirstTraversal.Any(Function(n) n.Kind() = SyntaxKind.GetTypeExpression) Then Return False End If Dim attributeBlock = expression.GetAncestorOrThis(Of AttributeListSyntax)() If attributeBlock.IsParentKind(SyntaxKind.CompilationUnit) Then Return False End If Return True End Function Protected Overrides Function IsInConstructorInitializer(expression As ExpressionSyntax) As Boolean Dim constructorInitializer = expression.GetAncestorsOrThis(Of StatementSyntax)(). Where(Function(n) n.IsConstructorInitializer()). FirstOrDefault() If constructorInitializer Is Nothing Then Return False End If ' have to make sure we're not inside a lambda inside the constructor initializer. If expression.GetAncestorOrThis(Of LambdaExpressionSyntax)() IsNot Nothing Then Return False End If Return True End Function Protected Overrides Function CanIntroduceVariableFor(expression As ExpressionSyntax) As Boolean expression = expression.WalkUpParentheses() If TypeOf expression.Parent Is CallStatementSyntax Then Return False End If If Not expression.GetImplicitMemberAccessExpressions.All(Function(e) e.IsParentKind(SyntaxKind.WithStatement)) Then Return False End If If expression.IsParentKind(SyntaxKind.EqualsValue) AndAlso expression.Parent.IsParentKind(SyntaxKind.VariableDeclarator) Then Return False End If ' For Nothing Literals, AllOccurrences could introduce semantic errors. If expression.IsKind(SyntaxKind.NothingLiteralExpression) Then Return False End If Return True End Function Protected Overrides Function IsInFieldInitializer(expression As ExpressionSyntax) As Boolean If expression.GetAncestorOrThis(Of VariableDeclaratorSyntax)().GetAncestorOrThis(Of FieldDeclarationSyntax)() IsNot Nothing Then Return True End If Return False End Function Protected Overrides Function IsInNonFirstQueryClause(expression As ExpressionSyntax) As Boolean Dim query = expression.GetAncestor(Of QueryExpressionSyntax)() If query Is Nothing Then Return False End If ' Can't introduce for the first clause in a query. Dim fromClause = expression.GetAncestor(Of FromClauseSyntax)() If fromClause IsNot Nothing AndAlso query.Clauses.First() Is fromClause Then Return False End If Return True End Function Protected Overrides Function IsInParameterInitializer(expression As ExpressionSyntax) As Boolean Return expression.GetAncestorOrThis(Of EqualsValueSyntax)().IsParentKind(SyntaxKind.Parameter) End Function Protected Overrides Function IsInAutoPropertyInitializer(expression As ExpressionSyntax) As Boolean Dim propertyStatement = expression.GetAncestorOrThis(Of PropertyStatementSyntax)() Dim equalsValueStatement = expression.GetAncestorOrThis(Of EqualsValueSyntax) If propertyStatement IsNot Nothing Then Return expression.GetAncestorsOrThis(Of AsClauseSyntax).Contains(propertyStatement.AsClause) OrElse (equalsValueStatement IsNot Nothing AndAlso equalsValueStatement.Contains(propertyStatement.Initializer)) End If Return False End Function Protected Overrides Function IsInExpressionBodiedMember(expression As ExpressionSyntax) As Boolean Return False End Function Protected Overrides Function CanReplace(expression As ExpressionSyntax) As Boolean If expression.CheckParent(Of RangeArgumentSyntax)(Function(n) n.LowerBound Is expression) Then Return False End If Return True End Function Protected Overrides Function IsExpressionInStaticLocalFunction(expression As ExpressionSyntax) As Boolean ' Local functions don't apply to VB. Return False End Function Protected Overrides Function RewriteCore(Of TNode As SyntaxNode)(node As TNode, replacementNode As SyntaxNode, matches As ISet(Of ExpressionSyntax)) As TNode Return DirectCast(Rewriter.Visit(node, replacementNode, matches), TNode) End Function Protected Overrides Function BlockOverlapsHiddenPosition(block As SyntaxNode, cancellationToken As CancellationToken) As Boolean Dim statements = block.GetStatements() If statements.Count = 0 Then Return block.OverlapsHiddenPosition(cancellationToken) End If Dim first = statements.First() Dim last = statements.Last() Return block.OverlapsHiddenPosition(TextSpan.FromBounds(first.SpanStart, last.SpanStart), cancellationToken) 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.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.IntroduceVariable Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports System.Composition Namespace Microsoft.CodeAnalysis.VisualBasic.IntroduceVariable <ExportLanguageService(GetType(IIntroduceVariableService), LanguageNames.VisualBasic), [Shared]> Partial Friend Class VisualBasicIntroduceVariableService Inherits AbstractIntroduceVariableService(Of VisualBasicIntroduceVariableService, ExpressionSyntax, TypeSyntax, TypeBlockSyntax, QueryExpressionSyntax, NameSyntax) <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub Protected Overrides Function GetContainingExecutableBlocks(expression As ExpressionSyntax) As IEnumerable(Of SyntaxNode) Return expression.GetContainingExecutableBlocks() End Function Protected Overrides Function GetInsertionIndices(destination As TypeBlockSyntax, cancellationToken As CancellationToken) As IList(Of Boolean) Return destination.GetInsertionIndices(cancellationToken) End Function Protected Overrides Function IsInAttributeArgumentInitializer(expression As ExpressionSyntax) As Boolean If expression.GetAncestorOrThis(Of ArgumentSyntax)() Is Nothing Then Return False End If If expression.GetAncestorOrThis(Of AttributeSyntax)() Is Nothing Then Return False End If If expression.DepthFirstTraversal.Any(Function(n) n.Kind() = SyntaxKind.ArrayCreationExpression) OrElse expression.DepthFirstTraversal.Any(Function(n) n.Kind() = SyntaxKind.GetTypeExpression) Then Return False End If Dim attributeBlock = expression.GetAncestorOrThis(Of AttributeListSyntax)() If attributeBlock.IsParentKind(SyntaxKind.CompilationUnit) Then Return False End If Return True End Function Protected Overrides Function IsInConstructorInitializer(expression As ExpressionSyntax) As Boolean Dim constructorInitializer = expression.GetAncestorsOrThis(Of StatementSyntax)(). Where(Function(n) n.IsConstructorInitializer()). FirstOrDefault() If constructorInitializer Is Nothing Then Return False End If ' have to make sure we're not inside a lambda inside the constructor initializer. If expression.GetAncestorOrThis(Of LambdaExpressionSyntax)() IsNot Nothing Then Return False End If Return True End Function Protected Overrides Function CanIntroduceVariableFor(expression As ExpressionSyntax) As Boolean expression = expression.WalkUpParentheses() If TypeOf expression.Parent Is CallStatementSyntax Then Return False End If If Not expression.GetImplicitMemberAccessExpressions.All(Function(e) e.IsParentKind(SyntaxKind.WithStatement)) Then Return False End If If expression.IsParentKind(SyntaxKind.EqualsValue) AndAlso expression.Parent.IsParentKind(SyntaxKind.VariableDeclarator) Then Return False End If ' For Nothing Literals, AllOccurrences could introduce semantic errors. If expression.IsKind(SyntaxKind.NothingLiteralExpression) Then Return False End If Return True End Function Protected Overrides Function IsInFieldInitializer(expression As ExpressionSyntax) As Boolean If expression.GetAncestorOrThis(Of VariableDeclaratorSyntax)().GetAncestorOrThis(Of FieldDeclarationSyntax)() IsNot Nothing Then Return True End If Return False End Function Protected Overrides Function IsInNonFirstQueryClause(expression As ExpressionSyntax) As Boolean Dim query = expression.GetAncestor(Of QueryExpressionSyntax)() If query Is Nothing Then Return False End If ' Can't introduce for the first clause in a query. Dim fromClause = expression.GetAncestor(Of FromClauseSyntax)() If fromClause IsNot Nothing AndAlso query.Clauses.First() Is fromClause Then Return False End If Return True End Function Protected Overrides Function IsInParameterInitializer(expression As ExpressionSyntax) As Boolean Return expression.GetAncestorOrThis(Of EqualsValueSyntax)().IsParentKind(SyntaxKind.Parameter) End Function Protected Overrides Function IsInAutoPropertyInitializer(expression As ExpressionSyntax) As Boolean Dim propertyStatement = expression.GetAncestorOrThis(Of PropertyStatementSyntax)() Dim equalsValueStatement = expression.GetAncestorOrThis(Of EqualsValueSyntax) If propertyStatement IsNot Nothing Then Return expression.GetAncestorsOrThis(Of AsClauseSyntax).Contains(propertyStatement.AsClause) OrElse (equalsValueStatement IsNot Nothing AndAlso equalsValueStatement.Contains(propertyStatement.Initializer)) End If Return False End Function Protected Overrides Function IsInExpressionBodiedMember(expression As ExpressionSyntax) As Boolean Return False End Function Protected Overrides Function CanReplace(expression As ExpressionSyntax) As Boolean If expression.CheckParent(Of RangeArgumentSyntax)(Function(n) n.LowerBound Is expression) Then Return False End If Return True End Function Protected Overrides Function IsExpressionInStaticLocalFunction(expression As ExpressionSyntax) As Boolean ' Local functions don't apply to VB. Return False End Function Protected Overrides Function RewriteCore(Of TNode As SyntaxNode)(node As TNode, replacementNode As SyntaxNode, matches As ISet(Of ExpressionSyntax)) As TNode Return DirectCast(Rewriter.Visit(node, replacementNode, matches), TNode) End Function Protected Overrides Function BlockOverlapsHiddenPosition(block As SyntaxNode, cancellationToken As CancellationToken) As Boolean Dim statements = block.GetStatements() If statements.Count = 0 Then Return block.OverlapsHiddenPosition(cancellationToken) End If Dim first = statements.First() Dim last = statements.Last() Return block.OverlapsHiddenPosition(TextSpan.FromBounds(first.SpanStart, last.SpanStart), cancellationToken) End Function End Class End Namespace
-1
dotnet/roslyn
56,460
Set CompilerApiVersion in Microsoft.Managed.Core.targets
This allows other targets to understand which compiler will be used. This is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets. Contributes to #52265 FYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803
eerhardt
"2021-09-16T21:47:36Z"
"2021-09-22T00:53:07Z"
a10a3720229de8f4227e98736e884d6f926a9950
aabc2fcbf630ba303e6f17808465349ea9b01a32
Set CompilerApiVersion in Microsoft.Managed.Core.targets. This allows other targets to understand which compiler will be used. This is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets. Contributes to #52265 FYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803
./src/Workspaces/VisualBasic/Portable/CaseCorrection/VisualBasicCaseCorrectionServiceFactory.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.Composition Imports Microsoft.CodeAnalysis.CaseCorrection Imports Microsoft.CodeAnalysis.Host Imports Microsoft.CodeAnalysis.Host.Mef Namespace Microsoft.CodeAnalysis.VisualBasic.CaseCorrection <ExportLanguageServiceFactory(GetType(ICaseCorrectionService), LanguageNames.VisualBasic), [Shared]> Partial Friend Class VisualBasicCaseCorrectionServiceFactory Implements ILanguageServiceFactory <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub Public Function CreateLanguageService(provider As HostLanguageServices) As ILanguageService Implements ILanguageServiceFactory.CreateLanguageService Return New VisualBasicCaseCorrectionService(provider) 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.Composition Imports Microsoft.CodeAnalysis.CaseCorrection Imports Microsoft.CodeAnalysis.Host Imports Microsoft.CodeAnalysis.Host.Mef Namespace Microsoft.CodeAnalysis.VisualBasic.CaseCorrection <ExportLanguageServiceFactory(GetType(ICaseCorrectionService), LanguageNames.VisualBasic), [Shared]> Partial Friend Class VisualBasicCaseCorrectionServiceFactory Implements ILanguageServiceFactory <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub Public Function CreateLanguageService(provider As HostLanguageServices) As ILanguageService Implements ILanguageServiceFactory.CreateLanguageService Return New VisualBasicCaseCorrectionService(provider) End Function End Class End Namespace
-1
dotnet/roslyn
56,460
Set CompilerApiVersion in Microsoft.Managed.Core.targets
This allows other targets to understand which compiler will be used. This is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets. Contributes to #52265 FYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803
eerhardt
"2021-09-16T21:47:36Z"
"2021-09-22T00:53:07Z"
a10a3720229de8f4227e98736e884d6f926a9950
aabc2fcbf630ba303e6f17808465349ea9b01a32
Set CompilerApiVersion in Microsoft.Managed.Core.targets. This allows other targets to understand which compiler will be used. This is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets. Contributes to #52265 FYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803
./src/Workspaces/CSharp/Portable/SemanticModelReuse/CSharpSemanticModelReuseLanguageService.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.CSharp.CodeGeneration; using Microsoft.CodeAnalysis.CSharp.LanguageServices; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.SemanticModelReuse; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.SemanticModelReuse { [ExportLanguageService(typeof(ISemanticModelReuseLanguageService), LanguageNames.CSharp), Shared] internal class CSharpSemanticModelReuseLanguageService : AbstractSemanticModelReuseLanguageService< MemberDeclarationSyntax, BaseMethodDeclarationSyntax, BasePropertyDeclarationSyntax, AccessorDeclarationSyntax> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpSemanticModelReuseLanguageService() { } protected override ISyntaxFacts SyntaxFacts => CSharpSyntaxFacts.Instance; protected override BasePropertyDeclarationSyntax GetBasePropertyDeclaration(AccessorDeclarationSyntax accessor) { Contract.ThrowIfFalse(accessor.Parent is AccessorListSyntax); Contract.ThrowIfFalse(accessor.Parent.Parent is BasePropertyDeclarationSyntax); return (BasePropertyDeclarationSyntax)accessor.Parent.Parent; } protected override SyntaxList<AccessorDeclarationSyntax> GetAccessors(BasePropertyDeclarationSyntax baseProperty) => baseProperty.AccessorList!.Accessors; public override SyntaxNode? TryGetContainingMethodBodyForSpeculation(SyntaxNode node) { for (SyntaxNode? previous = null, current = node; current != null; previous = current, current = current.Parent) { // These are the exact types that SemanticModel.TryGetSpeculativeSemanticModelForMethodBody accepts. if (current is BaseMethodDeclarationSyntax baseMethod) return previous != null && baseMethod.Body == previous ? baseMethod : null; if (current is AccessorDeclarationSyntax accessor) return previous != null && accessor.Body == previous ? accessor : null; } return null; } protected override async Task<SemanticModel?> TryGetSpeculativeSemanticModelWorkerAsync( SemanticModel previousSemanticModel, SyntaxNode currentBodyNode, CancellationToken cancellationToken) { var previousRoot = await previousSemanticModel.SyntaxTree.GetRootAsync(cancellationToken).ConfigureAwait(false); var currentRoot = await currentBodyNode.SyntaxTree.GetRootAsync(cancellationToken).ConfigureAwait(false); var previousBodyNode = GetPreviousBodyNode(previousRoot, currentRoot, currentBodyNode); if (previousBodyNode is BaseMethodDeclarationSyntax previousBaseMethod && currentBodyNode is BaseMethodDeclarationSyntax currentBaseMethod && previousBaseMethod.Body != null && previousSemanticModel.TryGetSpeculativeSemanticModelForMethodBody(previousBaseMethod.Body.SpanStart, currentBaseMethod, out var speculativeModel)) { return speculativeModel; } if (previousBodyNode is AccessorDeclarationSyntax previousAccessorDeclaration && currentBodyNode is AccessorDeclarationSyntax currentAccessorDeclaration && previousAccessorDeclaration.Body != null && previousSemanticModel.TryGetSpeculativeSemanticModelForMethodBody(previousAccessorDeclaration.Body.SpanStart, currentAccessorDeclaration, out speculativeModel)) { return speculativeModel; } 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. using System; using System.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.CodeGeneration; using Microsoft.CodeAnalysis.CSharp.LanguageServices; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.SemanticModelReuse; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.SemanticModelReuse { [ExportLanguageService(typeof(ISemanticModelReuseLanguageService), LanguageNames.CSharp), Shared] internal class CSharpSemanticModelReuseLanguageService : AbstractSemanticModelReuseLanguageService< MemberDeclarationSyntax, BaseMethodDeclarationSyntax, BasePropertyDeclarationSyntax, AccessorDeclarationSyntax> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpSemanticModelReuseLanguageService() { } protected override ISyntaxFacts SyntaxFacts => CSharpSyntaxFacts.Instance; protected override BasePropertyDeclarationSyntax GetBasePropertyDeclaration(AccessorDeclarationSyntax accessor) { Contract.ThrowIfFalse(accessor.Parent is AccessorListSyntax); Contract.ThrowIfFalse(accessor.Parent.Parent is BasePropertyDeclarationSyntax); return (BasePropertyDeclarationSyntax)accessor.Parent.Parent; } protected override SyntaxList<AccessorDeclarationSyntax> GetAccessors(BasePropertyDeclarationSyntax baseProperty) => baseProperty.AccessorList!.Accessors; public override SyntaxNode? TryGetContainingMethodBodyForSpeculation(SyntaxNode node) { for (SyntaxNode? previous = null, current = node; current != null; previous = current, current = current.Parent) { // These are the exact types that SemanticModel.TryGetSpeculativeSemanticModelForMethodBody accepts. if (current is BaseMethodDeclarationSyntax baseMethod) return previous != null && baseMethod.Body == previous ? baseMethod : null; if (current is AccessorDeclarationSyntax accessor) return previous != null && accessor.Body == previous ? accessor : null; } return null; } protected override async Task<SemanticModel?> TryGetSpeculativeSemanticModelWorkerAsync( SemanticModel previousSemanticModel, SyntaxNode currentBodyNode, CancellationToken cancellationToken) { var previousRoot = await previousSemanticModel.SyntaxTree.GetRootAsync(cancellationToken).ConfigureAwait(false); var currentRoot = await currentBodyNode.SyntaxTree.GetRootAsync(cancellationToken).ConfigureAwait(false); var previousBodyNode = GetPreviousBodyNode(previousRoot, currentRoot, currentBodyNode); if (previousBodyNode is BaseMethodDeclarationSyntax previousBaseMethod && currentBodyNode is BaseMethodDeclarationSyntax currentBaseMethod && previousBaseMethod.Body != null && previousSemanticModel.TryGetSpeculativeSemanticModelForMethodBody(previousBaseMethod.Body.SpanStart, currentBaseMethod, out var speculativeModel)) { return speculativeModel; } if (previousBodyNode is AccessorDeclarationSyntax previousAccessorDeclaration && currentBodyNode is AccessorDeclarationSyntax currentAccessorDeclaration && previousAccessorDeclaration.Body != null && previousSemanticModel.TryGetSpeculativeSemanticModelForMethodBody(previousAccessorDeclaration.Body.SpanStart, currentAccessorDeclaration, out speculativeModel)) { return speculativeModel; } return null; } } }
-1
dotnet/roslyn
56,460
Set CompilerApiVersion in Microsoft.Managed.Core.targets
This allows other targets to understand which compiler will be used. This is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets. Contributes to #52265 FYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803
eerhardt
"2021-09-16T21:47:36Z"
"2021-09-22T00:53:07Z"
a10a3720229de8f4227e98736e884d6f926a9950
aabc2fcbf630ba303e6f17808465349ea9b01a32
Set CompilerApiVersion in Microsoft.Managed.Core.targets. This allows other targets to understand which compiler will be used. This is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets. Contributes to #52265 FYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803
./src/Workspaces/MSBuildTest/Resources/SourceFiles/VisualBasic/Application.myapp
<?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. --> <MyApplicationData xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <MySubMain>false</MySubMain> <SingleInstance>false</SingleInstance> <ShutdownMode>0</ShutdownMode> <EnableVisualStyles>true</EnableVisualStyles> <AuthenticationMode>0</AuthenticationMode> <ApplicationType>1</ApplicationType> <SaveMySettingsOnExit>true</SaveMySettingsOnExit> </MyApplicationData>
<?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. --> <MyApplicationData xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <MySubMain>false</MySubMain> <SingleInstance>false</SingleInstance> <ShutdownMode>0</ShutdownMode> <EnableVisualStyles>true</EnableVisualStyles> <AuthenticationMode>0</AuthenticationMode> <ApplicationType>1</ApplicationType> <SaveMySettingsOnExit>true</SaveMySettingsOnExit> </MyApplicationData>
-1
dotnet/roslyn
56,460
Set CompilerApiVersion in Microsoft.Managed.Core.targets
This allows other targets to understand which compiler will be used. This is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets. Contributes to #52265 FYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803
eerhardt
"2021-09-16T21:47:36Z"
"2021-09-22T00:53:07Z"
a10a3720229de8f4227e98736e884d6f926a9950
aabc2fcbf630ba303e6f17808465349ea9b01a32
Set CompilerApiVersion in Microsoft.Managed.Core.targets. This allows other targets to understand which compiler will be used. This is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets. Contributes to #52265 FYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803
./src/EditorFeatures/Test2/ReferenceHighlighting/CSharpReferenceHighlightingTests.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.Remote.Testing Namespace Microsoft.CodeAnalysis.Editor.UnitTests.ReferenceHighlighting Public Class CSharpReferenceHighlightingTests Inherits AbstractReferenceHighlightingTests <WpfTheory> <CombinatorialData> Public Async Function TestVerifyNoHighlightsWhenOptionDisabled(testHost As TestHost) As Task Await VerifyHighlightsAsync( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class $$Goo { Goo f; } </Document> </Project> </Workspace>, testHost, optionIsEnabled:=False) End Function <WpfTheory> <CombinatorialData> Public Async Function TestVerifyHighlightsForClass(testHost As TestHost) As Task Await VerifyHighlightsAsync( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class {|Definition:$$Goo|} { } </Document> </Project> </Workspace>, testHost) End Function <WpfTheory> <CombinatorialData> Public Async Function TestVerifyHighlightsForScriptReference(testHost As TestHost) As Task Await VerifyHighlightsAsync( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> <ParseOptions Kind="Script"/> void M() { } {|Reference:$$Script|}.M(); </Document> </Project> </Workspace>, testHost) End Function <WpfTheory> <CombinatorialData> Public Async Function TestVerifyHighlightsForCSharpClassWithConstructor(testHost As TestHost) As Task Await VerifyHighlightsAsync( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class {|Definition:$$Goo|} { {|Definition:Goo|}() { {|Reference:var|} x = new {|Reference:Goo|}(); } } </Document> </Project> </Workspace>, testHost) End Function <WorkItem(538721, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538721")> <WpfTheory> <CombinatorialData> Public Async Function TestVerifyHighlightsForCSharpClassWithSynthesizedConstructor(testHost As TestHost) As Task Await VerifyHighlightsAsync( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class {|Definition:Goo|} { void Blah() { var x = new {|Reference:$$Goo|}(); } } </Document> </Project> </Workspace>, testHost) End Function <WpfTheory> <CombinatorialData> <WorkItem(528436, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528436")> Public Async Function TestVerifyHighlightsOnCloseAngleOfGeneric(testHost As TestHost) As Task Await VerifyHighlightsAsync( <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ using System; using System.Collections.Generic; using System.Linq; class {|Definition:Program|} { static void Main(string[] args) { new List<{|Reference:Program$$|}>(); } }]]> </Document> </Project> </Workspace>, testHost) End Function <WpfTheory> <CombinatorialData> <WorkItem(570809, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/570809")> Public Async Function TestVerifyNoHighlightsOnAsyncLambda(testHost As TestHost) As Task Await VerifyHighlightsAsync( <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ using System; using System.Collections.Generic; using System.Linq; class Program { public delegate Task del(); del ft = $$async () => { return await Task.Yield(); }; }]]> </Document> </Project> </Workspace>, testHost) End Function <WorkItem(543768, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543768")> <WpfTheory> <CombinatorialData> Public Async Function TestAlias1(testHost As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> namespace X { using {|Definition:Q|} = System.IO; Class B { public void M() { $${|Reference:Q|}.Directory.Exists(""); } } } </Document> </Project> </Workspace> Await VerifyHighlightsAsync(input, testHost) End Function <WorkItem(543768, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543768")> <WpfTheory> <CombinatorialData> Public Async Function TestAlias2(testHost As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> namespace X { using $${|Definition:Q|} = System.IO; Class B { public void M() { {|Reference:Q|}.Directory.Exists(""); } } } </Document> </Project> </Workspace> Await VerifyHighlightsAsync(input, testHost) End Function <WorkItem(543768, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543768")> <WpfTheory> <CombinatorialData> Public Async Function TestAlias3(testHost As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> namespace X { using Q = System.$${|Reference:IO|}; Class B { public void M() { {|Reference:Q|}.Directory.Exists(""); } } } </Document> </Project> </Workspace> Await VerifyHighlightsAsync(input, testHost) End Function <WorkItem(552000, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/552000")> <WpfTheory> <CombinatorialData> Public Async Function TestAlias4(testHost As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ using C = System.Action; namespace N { using $${|Definition:C|} = A<C>; // select C class A<T> { } class B : {|Reference:C|} { } }]]> </Document> </Project> </Workspace> Await VerifyHighlightsAsync(input, testHost) End Function <WorkItem(542830, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542830")> <WpfTheory> <CombinatorialData> Public Async Function TestHighlightThroughVar1(testHost As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void F() { $${|Reference:var|} i = 1; {|Reference:int|} j = 0; double d; {|Reference:int|} k = 1; } } </Document> </Project> </Workspace> Await VerifyHighlightsAsync(input, testHost) End Function <WorkItem(542830, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542830")> <WpfTheory> <CombinatorialData> Public Async Function TestHighlightThroughVar2(testHost As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void F() { {|Reference:var|} i = 1; $${|Reference:int|} j = 0; double d; {|Reference:int|} k = 1; } } </Document> </Project> </Workspace> Await VerifyHighlightsAsync(input, testHost) End Function <WorkItem(542830, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542830")> <WpfTheory> <CombinatorialData> Public Async Function TestHighlightThroughVar3(testHost As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ using System.Collections.Generic; class C { void F() { $${|Reference:var|} i = new {|Reference:List|}<string>(); int j = 0; double d; {|Reference:var|} k = new {|Reference:List|}<int>(); } } ]]></Document> </Project> </Workspace> Await VerifyHighlightsAsync(input, testHost) End Function <WorkItem(545648, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545648")> <WpfTheory> <CombinatorialData> Public Async Function TestUsingAliasAndTypeWithSameName1(testHost As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using {|Definition:$$X|} = System; class X { } </Document> </Project> </Workspace> Await VerifyHighlightsAsync(input, testHost) End Function <WorkItem(545648, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545648")> <WpfTheory> <CombinatorialData> Public Async Function TestUsingAliasAndTypeWithSameName2(testHost As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using X = System; class {|Definition:$$X|} { } </Document> </Project> </Workspace> Await VerifyHighlightsAsync(input, testHost) End Function <WorkItem(567959, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/567959")> <WpfTheory> <CombinatorialData> Public Async Function TestAccessor1(testHost As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { string P { $$get { return P; } set { P = ""; } } } </Document> </Project> </Workspace> Await VerifyHighlightsAsync(input, testHost) End Function <WorkItem(567959, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/567959")> <WpfTheory> <CombinatorialData> Public Async Function TestAccessor2(testHost As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { string P { get { return P; } $$set { P = ""; } } } </Document> </Project> </Workspace> Await VerifyHighlightsAsync(input, testHost) End Function <WpfTheory(Skip:="604466"), CombinatorialData> <WorkItem(604466, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/604466")> Public Async Function TestThisShouldNotHighlightTypeName(testHost As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void M() { t$$his.M(); } } </Document> </Project> </Workspace> Await VerifyHighlightsAsync(input, testHost) End Function <WorkItem(531620, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531620")> <WpfTheory> <CombinatorialData> Public Async Function TestHighlightDynamicallyBoundMethod(testHost As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { class B { public void {|Definition:Boo|}(int d) { } //Line 1 public void Boo(dynamic d) { } //Line 2 public void Boo(string d) { } //Line 3 } void Aoo() { B b = new B(); dynamic d = 1.5f; b.{|Reference:Boo|}(1); //Line 4 b.$${|Reference:Boo|}(d); //Line 5 b.Boo("d"); //Line 6 } } </Document> </Project> </Workspace> Await VerifyHighlightsAsync(input, testHost) End Function <WorkItem(531624, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531624")> <WpfTheory> <CombinatorialData> Public Async Function TestHighlightParameterizedPropertyParameter(testHost As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { int this[int $${|Definition:i|}] { get { return this[{|Reference:i|}]; } } } </Document> </Project> </Workspace> Await VerifyHighlightsAsync(input, testHost) End Function <WpfTheory> <CombinatorialData> Public Async Function TestInterpolatedString1(testHost As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void M() { var $${|Definition:a|} = "Hello"; var b = "World"; var c = $"{ {|Reference:a|} }, {b}!"; } } </Document> </Project> </Workspace> Await VerifyHighlightsAsync(input, testHost) End Function <WpfTheory> <CombinatorialData> Public Async Function TestInterpolatedString2(testHost As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void M() { var a = "Hello"; var $${|Definition:b|} = "World"; var c = $"{a}, { {|Reference:b|} }!"; } } </Document> </Project> </Workspace> Await VerifyHighlightsAsync(input, testHost) End Function <WpfTheory> <CombinatorialData> Public Async Function TestWrittenReference(testHost As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void M() { var $${|Definition:b|} = "Hello"; {|WrittenReference:b|} = "World"; } } </Document> </Project> </Workspace> Await VerifyHighlightsAsync(input, testHost) End Function <WpfTheory> <CombinatorialData> Public Async Function TestWrittenReference2(testHost As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void M() { int {|Definition:$$y|}; int x = {|WrittenReference:y|} = 7; } } </Document> </Project> </Workspace> Await VerifyHighlightsAsync(input, testHost) End Function <WpfTheory> <CombinatorialData> Public Async Function TestPatternMatchingType1(testHost As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void M() { object o = null; if (o is C $${|Definition:c|}) { var d = {|Reference:c|}; } } } </Document> </Project> </Workspace> Await VerifyHighlightsAsync(input, testHost) End Function <WpfTheory> <CombinatorialData> Public Async Function TestPatternMatchingType2(testHost As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void M() { object o = null; if (o is C {|Definition:c|}) { var d = $${|Reference:c|}; } } } </Document> </Project> </Workspace> Await VerifyHighlightsAsync(input, testHost) End Function <WpfTheory> <CombinatorialData> Public Async Function TestPatternMatchingTypeScoping1(testHost As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Class1 { } class Class2 { } class C { void M() { object o = null; if (o is Class1 {|Definition:c|}) { var d = $${|Reference:c|}; } else if (o is Class2 c) { var d = c; } el } } </Document> </Project> </Workspace> Await VerifyHighlightsAsync(input, testHost) End Function <WpfTheory> <CombinatorialData> Public Async Function TestPatternMatchingTypeScoping2(testHost As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Class1 { } class Class2 { } class C { void M() { object o = null; if (o is Class1 c) { var d = c; } else if (o is Class2 {|Definition:c|}) { var d = $${|Reference:c|}; } el } } </Document> </Project> </Workspace> Await VerifyHighlightsAsync(input, testHost) End Function <WpfTheory> <CombinatorialData> Public Async Function TestRegexReference1(testHost As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using System.Text.RegularExpressions; class C { void Goo() { var r = new Regex(@"{|Reference:(a)|}\0{|Reference:\$$1|}"); } } </Document> </Project> </Workspace> Await VerifyHighlightsAsync(input, testHost) End Function <WpfTheory> <CombinatorialData> Public Async Function TestHighlightParamAndCommentsCursorOnDefinition(testHost As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { /// &lt; summary &gt; /// &lt; paramref name="{|Reference:x|}"/ &gt; /// &lt; /summary &gt; /// &lt; param name="{|Reference:x|}" &gt; &lt; /param &gt; public int this[int $${|Definition:x|}] { get { return 0; } } } </Document> </Project> </Workspace> Await VerifyHighlightsAsync(input, testHost) End Function <WpfTheory> <CombinatorialData> Public Async Function TestHighlightParamAndCommentsCursorOnReference(testHost As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { /// &lt; summary &gt; /// &lt; paramref name="$${|Reference:x|}"/ &gt; /// &lt; /summary &gt; /// &lt; param name="{|Reference:x|}" &gt; &lt; /param &gt; public int this[int {|Definition:x|}] { get { return 0; } } } </Document> </Project> </Workspace> Await VerifyHighlightsAsync(input, testHost) End Function <WpfTheory> <CombinatorialData> Public Async Function TestHighlightParamAndCommentsDefinitionNestedBetweenReferences(testHost As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { /// &lt; summary &gt; /// &lt; paramref name="$${|Reference:x|}"/ &gt; /// &lt; /summary &gt; /// &lt; param name="{|Reference:x|}" &gt; &lt; /param &gt; public int this[int {|Definition:x|}] { get { return {|Reference:x|}; } } } </Document> </Project> </Workspace> Await VerifyHighlightsAsync(input, testHost) End Function <WpfTheory> <CombinatorialData> Public Async Function TestNotOnNewInObjectCreation(testHost As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> namespace X { class B { public void M() { $$new B(); new B(); } } } </Document> </Project> </Workspace> Await VerifyHighlightsAsync(input, testHost) End Function <WpfTheory> <CombinatorialData> Public Async Function TestOnTypeInObjectCreation(testHost As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> namespace X { class {|Definition:B|} { public void M() { new $${|Reference:B|}(); new {|Reference:B|}(); } } } </Document> </Project> </Workspace> Await VerifyHighlightsAsync(input, testHost) 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.Remote.Testing Namespace Microsoft.CodeAnalysis.Editor.UnitTests.ReferenceHighlighting Public Class CSharpReferenceHighlightingTests Inherits AbstractReferenceHighlightingTests <WpfTheory> <CombinatorialData> Public Async Function TestVerifyNoHighlightsWhenOptionDisabled(testHost As TestHost) As Task Await VerifyHighlightsAsync( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class $$Goo { Goo f; } </Document> </Project> </Workspace>, testHost, optionIsEnabled:=False) End Function <WpfTheory> <CombinatorialData> Public Async Function TestVerifyHighlightsForClass(testHost As TestHost) As Task Await VerifyHighlightsAsync( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class {|Definition:$$Goo|} { } </Document> </Project> </Workspace>, testHost) End Function <WpfTheory> <CombinatorialData> Public Async Function TestVerifyHighlightsForScriptReference(testHost As TestHost) As Task Await VerifyHighlightsAsync( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> <ParseOptions Kind="Script"/> void M() { } {|Reference:$$Script|}.M(); </Document> </Project> </Workspace>, testHost) End Function <WpfTheory> <CombinatorialData> Public Async Function TestVerifyHighlightsForCSharpClassWithConstructor(testHost As TestHost) As Task Await VerifyHighlightsAsync( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class {|Definition:$$Goo|} { {|Definition:Goo|}() { {|Reference:var|} x = new {|Reference:Goo|}(); } } </Document> </Project> </Workspace>, testHost) End Function <WorkItem(538721, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538721")> <WpfTheory> <CombinatorialData> Public Async Function TestVerifyHighlightsForCSharpClassWithSynthesizedConstructor(testHost As TestHost) As Task Await VerifyHighlightsAsync( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class {|Definition:Goo|} { void Blah() { var x = new {|Reference:$$Goo|}(); } } </Document> </Project> </Workspace>, testHost) End Function <WpfTheory> <CombinatorialData> <WorkItem(528436, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528436")> Public Async Function TestVerifyHighlightsOnCloseAngleOfGeneric(testHost As TestHost) As Task Await VerifyHighlightsAsync( <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ using System; using System.Collections.Generic; using System.Linq; class {|Definition:Program|} { static void Main(string[] args) { new List<{|Reference:Program$$|}>(); } }]]> </Document> </Project> </Workspace>, testHost) End Function <WpfTheory> <CombinatorialData> <WorkItem(570809, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/570809")> Public Async Function TestVerifyNoHighlightsOnAsyncLambda(testHost As TestHost) As Task Await VerifyHighlightsAsync( <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ using System; using System.Collections.Generic; using System.Linq; class Program { public delegate Task del(); del ft = $$async () => { return await Task.Yield(); }; }]]> </Document> </Project> </Workspace>, testHost) End Function <WorkItem(543768, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543768")> <WpfTheory> <CombinatorialData> Public Async Function TestAlias1(testHost As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> namespace X { using {|Definition:Q|} = System.IO; Class B { public void M() { $${|Reference:Q|}.Directory.Exists(""); } } } </Document> </Project> </Workspace> Await VerifyHighlightsAsync(input, testHost) End Function <WorkItem(543768, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543768")> <WpfTheory> <CombinatorialData> Public Async Function TestAlias2(testHost As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> namespace X { using $${|Definition:Q|} = System.IO; Class B { public void M() { {|Reference:Q|}.Directory.Exists(""); } } } </Document> </Project> </Workspace> Await VerifyHighlightsAsync(input, testHost) End Function <WorkItem(543768, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543768")> <WpfTheory> <CombinatorialData> Public Async Function TestAlias3(testHost As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> namespace X { using Q = System.$${|Reference:IO|}; Class B { public void M() { {|Reference:Q|}.Directory.Exists(""); } } } </Document> </Project> </Workspace> Await VerifyHighlightsAsync(input, testHost) End Function <WorkItem(552000, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/552000")> <WpfTheory> <CombinatorialData> Public Async Function TestAlias4(testHost As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ using C = System.Action; namespace N { using $${|Definition:C|} = A<C>; // select C class A<T> { } class B : {|Reference:C|} { } }]]> </Document> </Project> </Workspace> Await VerifyHighlightsAsync(input, testHost) End Function <WorkItem(542830, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542830")> <WpfTheory> <CombinatorialData> Public Async Function TestHighlightThroughVar1(testHost As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void F() { $${|Reference:var|} i = 1; {|Reference:int|} j = 0; double d; {|Reference:int|} k = 1; } } </Document> </Project> </Workspace> Await VerifyHighlightsAsync(input, testHost) End Function <WorkItem(542830, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542830")> <WpfTheory> <CombinatorialData> Public Async Function TestHighlightThroughVar2(testHost As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void F() { {|Reference:var|} i = 1; $${|Reference:int|} j = 0; double d; {|Reference:int|} k = 1; } } </Document> </Project> </Workspace> Await VerifyHighlightsAsync(input, testHost) End Function <WorkItem(542830, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542830")> <WpfTheory> <CombinatorialData> Public Async Function TestHighlightThroughVar3(testHost As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ using System.Collections.Generic; class C { void F() { $${|Reference:var|} i = new {|Reference:List|}<string>(); int j = 0; double d; {|Reference:var|} k = new {|Reference:List|}<int>(); } } ]]></Document> </Project> </Workspace> Await VerifyHighlightsAsync(input, testHost) End Function <WorkItem(545648, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545648")> <WpfTheory> <CombinatorialData> Public Async Function TestUsingAliasAndTypeWithSameName1(testHost As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using {|Definition:$$X|} = System; class X { } </Document> </Project> </Workspace> Await VerifyHighlightsAsync(input, testHost) End Function <WorkItem(545648, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545648")> <WpfTheory> <CombinatorialData> Public Async Function TestUsingAliasAndTypeWithSameName2(testHost As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using X = System; class {|Definition:$$X|} { } </Document> </Project> </Workspace> Await VerifyHighlightsAsync(input, testHost) End Function <WorkItem(567959, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/567959")> <WpfTheory> <CombinatorialData> Public Async Function TestAccessor1(testHost As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { string P { $$get { return P; } set { P = ""; } } } </Document> </Project> </Workspace> Await VerifyHighlightsAsync(input, testHost) End Function <WorkItem(567959, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/567959")> <WpfTheory> <CombinatorialData> Public Async Function TestAccessor2(testHost As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { string P { get { return P; } $$set { P = ""; } } } </Document> </Project> </Workspace> Await VerifyHighlightsAsync(input, testHost) End Function <WpfTheory(Skip:="604466"), CombinatorialData> <WorkItem(604466, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/604466")> Public Async Function TestThisShouldNotHighlightTypeName(testHost As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void M() { t$$his.M(); } } </Document> </Project> </Workspace> Await VerifyHighlightsAsync(input, testHost) End Function <WorkItem(531620, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531620")> <WpfTheory> <CombinatorialData> Public Async Function TestHighlightDynamicallyBoundMethod(testHost As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { class B { public void {|Definition:Boo|}(int d) { } //Line 1 public void Boo(dynamic d) { } //Line 2 public void Boo(string d) { } //Line 3 } void Aoo() { B b = new B(); dynamic d = 1.5f; b.{|Reference:Boo|}(1); //Line 4 b.$${|Reference:Boo|}(d); //Line 5 b.Boo("d"); //Line 6 } } </Document> </Project> </Workspace> Await VerifyHighlightsAsync(input, testHost) End Function <WorkItem(531624, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531624")> <WpfTheory> <CombinatorialData> Public Async Function TestHighlightParameterizedPropertyParameter(testHost As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { int this[int $${|Definition:i|}] { get { return this[{|Reference:i|}]; } } } </Document> </Project> </Workspace> Await VerifyHighlightsAsync(input, testHost) End Function <WpfTheory> <CombinatorialData> Public Async Function TestInterpolatedString1(testHost As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void M() { var $${|Definition:a|} = "Hello"; var b = "World"; var c = $"{ {|Reference:a|} }, {b}!"; } } </Document> </Project> </Workspace> Await VerifyHighlightsAsync(input, testHost) End Function <WpfTheory> <CombinatorialData> Public Async Function TestInterpolatedString2(testHost As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void M() { var a = "Hello"; var $${|Definition:b|} = "World"; var c = $"{a}, { {|Reference:b|} }!"; } } </Document> </Project> </Workspace> Await VerifyHighlightsAsync(input, testHost) End Function <WpfTheory> <CombinatorialData> Public Async Function TestWrittenReference(testHost As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void M() { var $${|Definition:b|} = "Hello"; {|WrittenReference:b|} = "World"; } } </Document> </Project> </Workspace> Await VerifyHighlightsAsync(input, testHost) End Function <WpfTheory> <CombinatorialData> Public Async Function TestWrittenReference2(testHost As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void M() { int {|Definition:$$y|}; int x = {|WrittenReference:y|} = 7; } } </Document> </Project> </Workspace> Await VerifyHighlightsAsync(input, testHost) End Function <WpfTheory> <CombinatorialData> Public Async Function TestPatternMatchingType1(testHost As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void M() { object o = null; if (o is C $${|Definition:c|}) { var d = {|Reference:c|}; } } } </Document> </Project> </Workspace> Await VerifyHighlightsAsync(input, testHost) End Function <WpfTheory> <CombinatorialData> Public Async Function TestPatternMatchingType2(testHost As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void M() { object o = null; if (o is C {|Definition:c|}) { var d = $${|Reference:c|}; } } } </Document> </Project> </Workspace> Await VerifyHighlightsAsync(input, testHost) End Function <WpfTheory> <CombinatorialData> Public Async Function TestPatternMatchingTypeScoping1(testHost As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Class1 { } class Class2 { } class C { void M() { object o = null; if (o is Class1 {|Definition:c|}) { var d = $${|Reference:c|}; } else if (o is Class2 c) { var d = c; } el } } </Document> </Project> </Workspace> Await VerifyHighlightsAsync(input, testHost) End Function <WpfTheory> <CombinatorialData> Public Async Function TestPatternMatchingTypeScoping2(testHost As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Class1 { } class Class2 { } class C { void M() { object o = null; if (o is Class1 c) { var d = c; } else if (o is Class2 {|Definition:c|}) { var d = $${|Reference:c|}; } el } } </Document> </Project> </Workspace> Await VerifyHighlightsAsync(input, testHost) End Function <WpfTheory> <CombinatorialData> Public Async Function TestRegexReference1(testHost As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using System.Text.RegularExpressions; class C { void Goo() { var r = new Regex(@"{|Reference:(a)|}\0{|Reference:\$$1|}"); } } </Document> </Project> </Workspace> Await VerifyHighlightsAsync(input, testHost) End Function <WpfTheory> <CombinatorialData> Public Async Function TestHighlightParamAndCommentsCursorOnDefinition(testHost As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { /// &lt; summary &gt; /// &lt; paramref name="{|Reference:x|}"/ &gt; /// &lt; /summary &gt; /// &lt; param name="{|Reference:x|}" &gt; &lt; /param &gt; public int this[int $${|Definition:x|}] { get { return 0; } } } </Document> </Project> </Workspace> Await VerifyHighlightsAsync(input, testHost) End Function <WpfTheory> <CombinatorialData> Public Async Function TestHighlightParamAndCommentsCursorOnReference(testHost As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { /// &lt; summary &gt; /// &lt; paramref name="$${|Reference:x|}"/ &gt; /// &lt; /summary &gt; /// &lt; param name="{|Reference:x|}" &gt; &lt; /param &gt; public int this[int {|Definition:x|}] { get { return 0; } } } </Document> </Project> </Workspace> Await VerifyHighlightsAsync(input, testHost) End Function <WpfTheory> <CombinatorialData> Public Async Function TestHighlightParamAndCommentsDefinitionNestedBetweenReferences(testHost As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { /// &lt; summary &gt; /// &lt; paramref name="$${|Reference:x|}"/ &gt; /// &lt; /summary &gt; /// &lt; param name="{|Reference:x|}" &gt; &lt; /param &gt; public int this[int {|Definition:x|}] { get { return {|Reference:x|}; } } } </Document> </Project> </Workspace> Await VerifyHighlightsAsync(input, testHost) End Function <WpfTheory> <CombinatorialData> Public Async Function TestNotOnNewInObjectCreation(testHost As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> namespace X { class B { public void M() { $$new B(); new B(); } } } </Document> </Project> </Workspace> Await VerifyHighlightsAsync(input, testHost) End Function <WpfTheory> <CombinatorialData> Public Async Function TestOnTypeInObjectCreation(testHost As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> namespace X { class {|Definition:B|} { public void M() { new $${|Reference:B|}(); new {|Reference:B|}(); } } } </Document> </Project> </Workspace> Await VerifyHighlightsAsync(input, testHost) End Function End Class End Namespace
-1
dotnet/roslyn
56,460
Set CompilerApiVersion in Microsoft.Managed.Core.targets
This allows other targets to understand which compiler will be used. This is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets. Contributes to #52265 FYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803
eerhardt
"2021-09-16T21:47:36Z"
"2021-09-22T00:53:07Z"
a10a3720229de8f4227e98736e884d6f926a9950
aabc2fcbf630ba303e6f17808465349ea9b01a32
Set CompilerApiVersion in Microsoft.Managed.Core.targets. This allows other targets to understand which compiler will be used. This is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets. Contributes to #52265 FYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803
./src/EditorFeatures/VisualBasicTest/ConvertForEachToFor/ConvertForEachToForTests.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.CodeRefactorings Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeRefactorings Imports Microsoft.CodeAnalysis.VisualBasic.ConvertForEachToFor Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.ConvertForEachToFor Partial Public Class ConvertForEachToForTests Inherits AbstractVisualBasicCodeActionTest Protected Overrides Function CreateCodeRefactoringProvider( workspace As Workspace, parameters As TestParameters) As CodeRefactoringProvider Return New VisualBasicConvertForEachToForCodeRefactoringProvider() End Function <WorkItem(31621, "https://github.com/dotnet/roslyn/issues/31621")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)> Public Async Function EmptyBlockBody() As Task Dim initial = " Class Test Sub Method() Dim array = New Integer() {1, 2, 3} For Each [||] a In array Next End Sub End Class " Dim expected = " Class Test Sub Method() Dim array = New Integer() {1, 2, 3} For {|Rename:i|} = 0 To array.Length - 1 Dim a = array(i) Next End Sub End Class " Await TestInRegularAndScriptAsync(initial, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)> Public Async Function EmptyBody() As Task Dim initial = " Class Test Sub Method() Dim array = New Integer() {1, 2, 3} For Each [||] a In array : Next End Sub End Class " Await TestMissingInRegularAndScriptAsync(initial) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)> Public Async Function Body() As Task Dim initial = " Class Test Sub Method() Dim array = New Integer() {1, 2, 3} For Each [||] a In array : Console.WriteLine(a) : Next End Sub End Class " Await TestMissingInRegularAndScriptAsync(initial) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)> Public Async Function BlockBody() As Task Dim initial = " Class Test Sub Method() Dim array = New Integer() {1, 2, 3} For Each [||] a In array Console.WriteLine(a) Next End Sub End Class " Dim expected = " Class Test Sub Method() Dim array = New Integer() {1, 2, 3} For {|Rename:i|} = 0 To array.Length - 1 Dim a = array(i) Console.WriteLine(a) Next End Sub End Class " Await TestInRegularAndScriptAsync(initial, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)> Public Async Function Comment() As Task Dim initial = " Class Test Sub Method() Dim array = New Integer() {1, 2, 3} ' comment For Each [||] a In array ' comment Console.WriteLine(a) Next End Sub End Class " Dim expected = " Class Test Sub Method() Dim array = New Integer() {1, 2, 3} ' comment For {|Rename:i|} = 0 To array.Length - 1 ' comment Dim a = array(i) Console.WriteLine(a) Next End Sub End Class " Await TestInRegularAndScriptAsync(initial, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)> Public Async Function Comment2() As Task Dim initial = " Class Test Sub Method() Dim array = New Integer() {1, 2, 3} For Each [||] a In array ' comment Console.WriteLine(a) Next ' comment End Sub End Class " Dim expected = " Class Test Sub Method() Dim array = New Integer() {1, 2, 3} For {|Rename:i|} = 0 To array.Length - 1 Dim a = array(i) ' comment Console.WriteLine(a) Next ' comment End Sub End Class " Await TestInRegularAndScriptAsync(initial, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)> Public Async Function Comment3() As Task Dim initial = " Class Test Sub Method() Dim array = New Integer() {1, 2, 3} For Each [||] a In array Console.WriteLine(a) Next a ' comment End Sub End Class " Dim expected = " Class Test Sub Method() Dim array = New Integer() {1, 2, 3} For {|Rename:i|} = 0 To array.Length - 1 Dim a = array(i) Console.WriteLine(a) Next i ' comment End Sub End Class " Await TestInRegularAndScriptAsync(initial, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)> Public Async Function Comment4() As Task Dim initial = " Class Test Sub Method() For Each [||] a In New Integer() {1, 2, 3} ' test Console.WriteLine(a) Next End Sub End Class " Dim expected = " Class Test Sub Method() Dim {|Rename:array|} = New Integer() {1, 2, 3} For {|Rename:i|} = 0 To array.Length - 1 ' test Dim a = array(i) Console.WriteLine(a) Next End Sub End Class " Await TestInRegularAndScriptAsync(initial, expected) End Function <WorkItem(31621, "https://github.com/dotnet/roslyn/issues/31621")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)> Public Async Function Comment7() As Task Dim initial = " Class Test Sub Method() ' test For Each [||] a In New Integer() {1, 2, 3} Next End Sub End Class " Dim expected = " Class Test Sub Method() ' test Dim {|Rename:array|} = New Integer() {1, 2, 3} For {|Rename:i|} = 0 To array.Length - 1 Dim a = array(i) Next End Sub End Class " Await TestInRegularAndScriptAsync(initial, expected) End Function <WorkItem(31621, "https://github.com/dotnet/roslyn/issues/31621")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)> Public Async Function TestCommentsLiveBetweenForEachAndArrayDeclaration() As Task Dim initial = " Class Test Sub Method() For Each [||] a ' test In ' test New Integer() {1, 2, 3} Next End Sub End Class " Dim Expected = " Class Test Sub Method() Dim {|Rename:array|} = New Integer() {1, 2, 3} For {|Rename:i|} = 0 To array.Length - 1 Dim a = array(i) Next End Sub End Class " Await TestInRegularAndScriptAsync(initial, Expected) End Function <WorkItem(31621, "https://github.com/dotnet/roslyn/issues/31621")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)> Public Async Function CommentNotSupportedCommentsAfterLineContinuation() As Task Dim initial = " Class Test Sub Method() For Each [||] a _ ' test In ' test New Integer() {1, 2, 3} Next End Sub End Class " Dim expected = " Class Test Sub Method() Dim {|Rename:array|} = New Integer() {1, 2, 3} For {|Rename:i|} = 0 To array.Length - 1 Dim a = array(i) Next End Sub End Class " Await TestInRegularAndScriptAsync(initial, expected) End Function <WorkItem(31621, "https://github.com/dotnet/roslyn/issues/31621")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)> Public Async Function LineContinuation() As Task Dim initial = " Class Test Sub Method() For Each [||] a _ In New Integer() {1, 2, 3} Next End Sub End Class " Dim expected = " Class Test Sub Method() Dim {|Rename:array|} = New Integer() {1, 2, 3} For {|Rename:i|} = 0 To array.Length - 1 Dim a = array(i) Next End Sub End Class " Await TestInRegularAndScriptAsync(initial, expected) End Function <WorkItem(31621, "https://github.com/dotnet/roslyn/issues/31621")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)> Public Async Function CollectionStatement() As Task Dim initial = " Class Test Sub Method() For Each [||] a In New Integer() {1, 2, 3} Next End Sub End Class " Dim expected = " Class Test Sub Method() Dim {|Rename:array|} = New Integer() {1, 2, 3} For {|Rename:i|} = 0 To array.Length - 1 Dim a = array(i) Next End Sub End Class " Await TestInRegularAndScriptAsync(initial, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)> Public Async Function CollectionConflict() As Task Dim initial = " Class Test Sub Method() Dim array = 1 For Each [||] a In New Integer() {1, 2, 3} Console.WriteLine(a) Next End Sub End Class " Dim expected = " Class Test Sub Method() Dim array = 1 Dim {|Rename:array1|} = New Integer() {1, 2, 3} For {|Rename:i|} = 0 To array1.Length - 1 Dim a = array1(i) Console.WriteLine(a) Next End Sub End Class " Await TestInRegularAndScriptAsync(initial, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)> Public Async Function IndexConflict() As Task Dim initial = " Class Test Sub Method() For Each [||] a In New Integer() {1, 2, 3} Dim i = 1 Console.WriteLine(a) Next End Sub End Class " Dim expected = " Class Test Sub Method() Dim {|Rename:array|} = New Integer() {1, 2, 3} For {|Rename:i1|} = 0 To array.Length - 1 Dim a = array(i1) Dim i = 1 Console.WriteLine(a) Next End Sub End Class " Await TestInRegularAndScriptAsync(initial, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)> Public Async Function VariableWritten() As Task Dim initial = " Class Test Sub Method() For Each [||] a In New Integer() {1, 2, 3} a = 1 Next End Sub End Class " Dim expected = " Class Test Sub Method() Dim {|Rename:array|} = New Integer() {1, 2, 3} For {|Rename:i|} = 0 To array.Length - 1 {|Warning:Dim a = array(i)|} a = 1 Next End Sub End Class " Await TestInRegularAndScriptAsync(initial, expected) End Function Public Async Function StructPropertyReadFromAndAssignedToLocal() As Task Dim initial = " Class Test Sub Method() For Each [||] a In New Integer?() {1, 2, 3} Dim b = a.Value Next End Sub End Class " Dim expected = " Class Test Sub Method() Dim {|Rename:array|} = New Integer?() {1, 2, 3} For {|Rename:i|} = 0 To array.Length - 1 Dim a = array(i) Dim b = a.Value Next End Sub End Class " Await TestInRegularAndScriptAsync(initial, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)> Public Async Function StructPropertyRead() As Task Dim initial = " Class Test Sub Method() For Each [||] a In New Integer?() {1, 2, 3} a.Value Next End Sub End Class " Dim expected = " Class Test Sub Method() Dim {|Rename:array|} = New Integer?() {1, 2, 3} For {|Rename:i|} = 0 To array.Length - 1 Dim a = array(i) a.Value Next End Sub End Class " Await TestInRegularAndScriptAsync(initial, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)> Public Async Function WrongCaretPosition() As Task Dim initial = " Class Test Sub Method() For Each a In New Integer() {1, 2, 3} [||] Next End Sub End Class " Await TestMissingInRegularAndScriptAsync(initial) End Function <WorkItem(31621, "https://github.com/dotnet/roslyn/issues/31621")> <WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)> Public Async Function TestBefore() As Task Dim initial = " Class Test Sub Method() Dim array = New Integer() {1, 2, 3} [||] For Each a In array Next End Sub End Class " Dim expected = " Class Test Sub Method() Dim array = New Integer() {1, 2, 3} For {|Rename:i|} = 0 To array.Length - 1 Dim a = array(i) Next End Sub End Class " Await TestInRegularAndScriptAsync(initial, expected) End Function <WorkItem(31621, "https://github.com/dotnet/roslyn/issues/31621")> <WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)> Public Async Function TestAfter() As Task Dim initial = " Class Test Sub Method() Dim array = New Integer() {1, 2, 3} For Each a In array [||] Next End Sub End Class " Dim expected = " Class Test Sub Method() Dim array = New Integer() {1, 2, 3} For {|Rename:i|} = 0 To array.Length - 1 Dim a = array(i) Next End Sub End Class " Await TestInRegularAndScriptAsync(initial, expected) End Function <WorkItem(31621, "https://github.com/dotnet/roslyn/issues/31621")> <WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)> Public Async Function TestSelection() As Task Dim initial = " Class Test Sub Method() Dim array = New Integer() {1, 2, 3} [|For Each a In array Next|] End Sub End Class " Dim expected = " Class Test Sub Method() Dim array = New Integer() {1, 2, 3} For {|Rename:i|} = 0 To array.Length - 1 Dim a = array(i) Next End Sub End Class " Await TestInRegularAndScriptAsync(initial, expected) End Function <WorkItem(31621, "https://github.com/dotnet/roslyn/issues/31621")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)> Public Async Function Field() As Task Dim initial = " Class Test Dim list As Integer() = New Integer() {1, 2, 3} Sub Method() For Each [||] a In list Next End Sub End Class " Dim expected = " Class Test Dim list As Integer() = New Integer() {1, 2, 3} Sub Method() For {|Rename:i|} = 0 To list.Length - 1 Dim a = list(i) Next End Sub End Class " Await TestInRegularAndScriptAsync(initial, expected) End Function <WorkItem(31621, "https://github.com/dotnet/roslyn/issues/31621")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)> Public Async Function [Interface]() As Task Dim initial = " Imports System.Collections.Generic Class Test Sub Method() Dim list = DirectCast(New Integer() {1, 2, 3}, IList(Of Integer)) For [||] Each a In list Next End Sub End Class " Dim expected = " Imports System.Collections.Generic Class Test Sub Method() Dim list = DirectCast(New Integer() {1, 2, 3}, IList(Of Integer)) For {|Rename:i|} = 0 To list.Count - 1 Dim a = list(i) Next End Sub End Class " Await TestInRegularAndScriptAsync(initial, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)> Public Async Function ExplicitInterface() As Task Dim initial = " Imports System Imports System.Collections Imports System.Collections.Generic Class Test Sub Method() Dim list = New Explicit() For [||] Each a In list Console.WriteLine(a) Next End Sub End Class Class Explicit Implements IReadOnlyList(Of Integer) Default Public ReadOnly Property ItemExplicit(index As Integer) As Integer Implements IReadOnlyList(Of Integer).Item Get Throw New NotImplementedException() End Get End Property Public ReadOnly Property CountExplicit As Integer Implements IReadOnlyCollection(Of Integer).Count Get Throw New NotImplementedException() End Get End Property Public Function GetEnumeratorExplicit() As IEnumerator(Of Integer) Implements IEnumerable(Of Integer).GetEnumerator Throw New NotImplementedException() End Function Private Function IEnumerable_GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator Throw New NotImplementedException() End Function End Class " Dim expected = " Imports System Imports System.Collections Imports System.Collections.Generic Class Test Sub Method() Dim list = New Explicit() Dim {|Rename:list1|} = DirectCast(list, IReadOnlyList(Of Integer)) For {|Rename:i|} = 0 To list1.Count - 1 Dim a = list1(i) Console.WriteLine(a) Next End Sub End Class Class Explicit Implements IReadOnlyList(Of Integer) Default Public ReadOnly Property ItemExplicit(index As Integer) As Integer Implements IReadOnlyList(Of Integer).Item Get Throw New NotImplementedException() End Get End Property Public ReadOnly Property CountExplicit As Integer Implements IReadOnlyCollection(Of Integer).Count Get Throw New NotImplementedException() End Get End Property Public Function GetEnumeratorExplicit() As IEnumerator(Of Integer) Implements IEnumerable(Of Integer).GetEnumerator Throw New NotImplementedException() End Function Private Function IEnumerable_GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator Throw New NotImplementedException() End Function End Class " Await TestInRegularAndScriptAsync(initial, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)> Public Async Function MultipleNext() As Task Dim initial = " Class Test Sub Method() For Each a [||] In New Integer() {} For Each b In New Integer() {} Console.WriteLine(a) Next b, a End Sub End Class" Await TestMissingInRegularAndScriptAsync(initial) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)> Public Async Function MultipleNext2() As Task Dim initial = " Class Test Sub Method() For Each a In New Integer() {} For Each [||] b In New Integer() {} Console.WriteLine(a) Next b, a End Sub End Class" Await TestMissingInRegularAndScriptAsync(initial) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)> Public Async Function WrongNext() As Task Dim initial = " Class Test Sub Method() For Each [||] a In New Integer() {} Console.WriteLine(a) Next b End Sub End Class" Await TestMissingInRegularAndScriptAsync(initial) End Function <WorkItem(31621, "https://github.com/dotnet/roslyn/issues/31621")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)> Public Async Function KeepNext() As Task Dim initial = " Class Test Sub Method() For Each [||] a In New Integer() {1, 2, 3} Next a End Sub End Class " Dim expected = " Class Test Sub Method() Dim {|Rename:array|} = New Integer() {1, 2, 3} For {|Rename:i|} = 0 To array.Length - 1 Dim a = array(i) Next i End Sub End Class " Await TestInRegularAndScriptAsync(initial, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)> Public Async Function IndexConflict2() As Task Dim initial = " Class Test Sub Method() For Each [||] i In New Integer() {1, 2, 3} Console.WriteLine(a) Next End Sub End Class " Dim expected = " Class Test Sub Method() Dim {|Rename:array|} = New Integer() {1, 2, 3} For {|Rename:i1|} = 0 To array.Length - 1 Dim i = array(i1) Console.WriteLine(a) Next End Sub End Class " Await TestInRegularAndScriptAsync(initial, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)> Public Async Function UseTypeAsUsedInForeach() As Task Dim initial = " Class Test Sub Method() For Each [||] a As Integer In New Integer() {1, 2, 3} Console.WriteLine(a) Next End Sub End Class " Dim expected = " Class Test Sub Method() Dim {|Rename:array|} = New Integer() {1, 2, 3} For {|Rename:i|} = 0 To array.Length - 1 Dim a As Integer = array(i) Console.WriteLine(a) Next End Sub End Class " Await TestInRegularAndScriptAsync(initial, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)> Public Async Function UniqueLocalName() As Task Dim initial = " Imports System Imports System.Collections.Generic Class Test Sub Method() For Each [||] a In New List(Of Integer)() Console.WriteLine(a) Next End Sub End Class " Dim expected = " Imports System Imports System.Collections.Generic Class Test Sub Method() Dim {|Rename:list|} = New List(Of Integer)() For {|Rename:i|} = 0 To list.Count - 1 Dim a = list(i) Console.WriteLine(a) Next End Sub End Class " Await TestInRegularAndScriptAsync(initial, expected) 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.CodeRefactorings Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeRefactorings Imports Microsoft.CodeAnalysis.VisualBasic.ConvertForEachToFor Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.ConvertForEachToFor Partial Public Class ConvertForEachToForTests Inherits AbstractVisualBasicCodeActionTest Protected Overrides Function CreateCodeRefactoringProvider( workspace As Workspace, parameters As TestParameters) As CodeRefactoringProvider Return New VisualBasicConvertForEachToForCodeRefactoringProvider() End Function <WorkItem(31621, "https://github.com/dotnet/roslyn/issues/31621")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)> Public Async Function EmptyBlockBody() As Task Dim initial = " Class Test Sub Method() Dim array = New Integer() {1, 2, 3} For Each [||] a In array Next End Sub End Class " Dim expected = " Class Test Sub Method() Dim array = New Integer() {1, 2, 3} For {|Rename:i|} = 0 To array.Length - 1 Dim a = array(i) Next End Sub End Class " Await TestInRegularAndScriptAsync(initial, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)> Public Async Function EmptyBody() As Task Dim initial = " Class Test Sub Method() Dim array = New Integer() {1, 2, 3} For Each [||] a In array : Next End Sub End Class " Await TestMissingInRegularAndScriptAsync(initial) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)> Public Async Function Body() As Task Dim initial = " Class Test Sub Method() Dim array = New Integer() {1, 2, 3} For Each [||] a In array : Console.WriteLine(a) : Next End Sub End Class " Await TestMissingInRegularAndScriptAsync(initial) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)> Public Async Function BlockBody() As Task Dim initial = " Class Test Sub Method() Dim array = New Integer() {1, 2, 3} For Each [||] a In array Console.WriteLine(a) Next End Sub End Class " Dim expected = " Class Test Sub Method() Dim array = New Integer() {1, 2, 3} For {|Rename:i|} = 0 To array.Length - 1 Dim a = array(i) Console.WriteLine(a) Next End Sub End Class " Await TestInRegularAndScriptAsync(initial, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)> Public Async Function Comment() As Task Dim initial = " Class Test Sub Method() Dim array = New Integer() {1, 2, 3} ' comment For Each [||] a In array ' comment Console.WriteLine(a) Next End Sub End Class " Dim expected = " Class Test Sub Method() Dim array = New Integer() {1, 2, 3} ' comment For {|Rename:i|} = 0 To array.Length - 1 ' comment Dim a = array(i) Console.WriteLine(a) Next End Sub End Class " Await TestInRegularAndScriptAsync(initial, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)> Public Async Function Comment2() As Task Dim initial = " Class Test Sub Method() Dim array = New Integer() {1, 2, 3} For Each [||] a In array ' comment Console.WriteLine(a) Next ' comment End Sub End Class " Dim expected = " Class Test Sub Method() Dim array = New Integer() {1, 2, 3} For {|Rename:i|} = 0 To array.Length - 1 Dim a = array(i) ' comment Console.WriteLine(a) Next ' comment End Sub End Class " Await TestInRegularAndScriptAsync(initial, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)> Public Async Function Comment3() As Task Dim initial = " Class Test Sub Method() Dim array = New Integer() {1, 2, 3} For Each [||] a In array Console.WriteLine(a) Next a ' comment End Sub End Class " Dim expected = " Class Test Sub Method() Dim array = New Integer() {1, 2, 3} For {|Rename:i|} = 0 To array.Length - 1 Dim a = array(i) Console.WriteLine(a) Next i ' comment End Sub End Class " Await TestInRegularAndScriptAsync(initial, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)> Public Async Function Comment4() As Task Dim initial = " Class Test Sub Method() For Each [||] a In New Integer() {1, 2, 3} ' test Console.WriteLine(a) Next End Sub End Class " Dim expected = " Class Test Sub Method() Dim {|Rename:array|} = New Integer() {1, 2, 3} For {|Rename:i|} = 0 To array.Length - 1 ' test Dim a = array(i) Console.WriteLine(a) Next End Sub End Class " Await TestInRegularAndScriptAsync(initial, expected) End Function <WorkItem(31621, "https://github.com/dotnet/roslyn/issues/31621")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)> Public Async Function Comment7() As Task Dim initial = " Class Test Sub Method() ' test For Each [||] a In New Integer() {1, 2, 3} Next End Sub End Class " Dim expected = " Class Test Sub Method() ' test Dim {|Rename:array|} = New Integer() {1, 2, 3} For {|Rename:i|} = 0 To array.Length - 1 Dim a = array(i) Next End Sub End Class " Await TestInRegularAndScriptAsync(initial, expected) End Function <WorkItem(31621, "https://github.com/dotnet/roslyn/issues/31621")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)> Public Async Function TestCommentsLiveBetweenForEachAndArrayDeclaration() As Task Dim initial = " Class Test Sub Method() For Each [||] a ' test In ' test New Integer() {1, 2, 3} Next End Sub End Class " Dim Expected = " Class Test Sub Method() Dim {|Rename:array|} = New Integer() {1, 2, 3} For {|Rename:i|} = 0 To array.Length - 1 Dim a = array(i) Next End Sub End Class " Await TestInRegularAndScriptAsync(initial, Expected) End Function <WorkItem(31621, "https://github.com/dotnet/roslyn/issues/31621")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)> Public Async Function CommentNotSupportedCommentsAfterLineContinuation() As Task Dim initial = " Class Test Sub Method() For Each [||] a _ ' test In ' test New Integer() {1, 2, 3} Next End Sub End Class " Dim expected = " Class Test Sub Method() Dim {|Rename:array|} = New Integer() {1, 2, 3} For {|Rename:i|} = 0 To array.Length - 1 Dim a = array(i) Next End Sub End Class " Await TestInRegularAndScriptAsync(initial, expected) End Function <WorkItem(31621, "https://github.com/dotnet/roslyn/issues/31621")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)> Public Async Function LineContinuation() As Task Dim initial = " Class Test Sub Method() For Each [||] a _ In New Integer() {1, 2, 3} Next End Sub End Class " Dim expected = " Class Test Sub Method() Dim {|Rename:array|} = New Integer() {1, 2, 3} For {|Rename:i|} = 0 To array.Length - 1 Dim a = array(i) Next End Sub End Class " Await TestInRegularAndScriptAsync(initial, expected) End Function <WorkItem(31621, "https://github.com/dotnet/roslyn/issues/31621")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)> Public Async Function CollectionStatement() As Task Dim initial = " Class Test Sub Method() For Each [||] a In New Integer() {1, 2, 3} Next End Sub End Class " Dim expected = " Class Test Sub Method() Dim {|Rename:array|} = New Integer() {1, 2, 3} For {|Rename:i|} = 0 To array.Length - 1 Dim a = array(i) Next End Sub End Class " Await TestInRegularAndScriptAsync(initial, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)> Public Async Function CollectionConflict() As Task Dim initial = " Class Test Sub Method() Dim array = 1 For Each [||] a In New Integer() {1, 2, 3} Console.WriteLine(a) Next End Sub End Class " Dim expected = " Class Test Sub Method() Dim array = 1 Dim {|Rename:array1|} = New Integer() {1, 2, 3} For {|Rename:i|} = 0 To array1.Length - 1 Dim a = array1(i) Console.WriteLine(a) Next End Sub End Class " Await TestInRegularAndScriptAsync(initial, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)> Public Async Function IndexConflict() As Task Dim initial = " Class Test Sub Method() For Each [||] a In New Integer() {1, 2, 3} Dim i = 1 Console.WriteLine(a) Next End Sub End Class " Dim expected = " Class Test Sub Method() Dim {|Rename:array|} = New Integer() {1, 2, 3} For {|Rename:i1|} = 0 To array.Length - 1 Dim a = array(i1) Dim i = 1 Console.WriteLine(a) Next End Sub End Class " Await TestInRegularAndScriptAsync(initial, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)> Public Async Function VariableWritten() As Task Dim initial = " Class Test Sub Method() For Each [||] a In New Integer() {1, 2, 3} a = 1 Next End Sub End Class " Dim expected = " Class Test Sub Method() Dim {|Rename:array|} = New Integer() {1, 2, 3} For {|Rename:i|} = 0 To array.Length - 1 {|Warning:Dim a = array(i)|} a = 1 Next End Sub End Class " Await TestInRegularAndScriptAsync(initial, expected) End Function Public Async Function StructPropertyReadFromAndAssignedToLocal() As Task Dim initial = " Class Test Sub Method() For Each [||] a In New Integer?() {1, 2, 3} Dim b = a.Value Next End Sub End Class " Dim expected = " Class Test Sub Method() Dim {|Rename:array|} = New Integer?() {1, 2, 3} For {|Rename:i|} = 0 To array.Length - 1 Dim a = array(i) Dim b = a.Value Next End Sub End Class " Await TestInRegularAndScriptAsync(initial, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)> Public Async Function StructPropertyRead() As Task Dim initial = " Class Test Sub Method() For Each [||] a In New Integer?() {1, 2, 3} a.Value Next End Sub End Class " Dim expected = " Class Test Sub Method() Dim {|Rename:array|} = New Integer?() {1, 2, 3} For {|Rename:i|} = 0 To array.Length - 1 Dim a = array(i) a.Value Next End Sub End Class " Await TestInRegularAndScriptAsync(initial, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)> Public Async Function WrongCaretPosition() As Task Dim initial = " Class Test Sub Method() For Each a In New Integer() {1, 2, 3} [||] Next End Sub End Class " Await TestMissingInRegularAndScriptAsync(initial) End Function <WorkItem(31621, "https://github.com/dotnet/roslyn/issues/31621")> <WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)> Public Async Function TestBefore() As Task Dim initial = " Class Test Sub Method() Dim array = New Integer() {1, 2, 3} [||] For Each a In array Next End Sub End Class " Dim expected = " Class Test Sub Method() Dim array = New Integer() {1, 2, 3} For {|Rename:i|} = 0 To array.Length - 1 Dim a = array(i) Next End Sub End Class " Await TestInRegularAndScriptAsync(initial, expected) End Function <WorkItem(31621, "https://github.com/dotnet/roslyn/issues/31621")> <WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)> Public Async Function TestAfter() As Task Dim initial = " Class Test Sub Method() Dim array = New Integer() {1, 2, 3} For Each a In array [||] Next End Sub End Class " Dim expected = " Class Test Sub Method() Dim array = New Integer() {1, 2, 3} For {|Rename:i|} = 0 To array.Length - 1 Dim a = array(i) Next End Sub End Class " Await TestInRegularAndScriptAsync(initial, expected) End Function <WorkItem(31621, "https://github.com/dotnet/roslyn/issues/31621")> <WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)> Public Async Function TestSelection() As Task Dim initial = " Class Test Sub Method() Dim array = New Integer() {1, 2, 3} [|For Each a In array Next|] End Sub End Class " Dim expected = " Class Test Sub Method() Dim array = New Integer() {1, 2, 3} For {|Rename:i|} = 0 To array.Length - 1 Dim a = array(i) Next End Sub End Class " Await TestInRegularAndScriptAsync(initial, expected) End Function <WorkItem(31621, "https://github.com/dotnet/roslyn/issues/31621")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)> Public Async Function Field() As Task Dim initial = " Class Test Dim list As Integer() = New Integer() {1, 2, 3} Sub Method() For Each [||] a In list Next End Sub End Class " Dim expected = " Class Test Dim list As Integer() = New Integer() {1, 2, 3} Sub Method() For {|Rename:i|} = 0 To list.Length - 1 Dim a = list(i) Next End Sub End Class " Await TestInRegularAndScriptAsync(initial, expected) End Function <WorkItem(31621, "https://github.com/dotnet/roslyn/issues/31621")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)> Public Async Function [Interface]() As Task Dim initial = " Imports System.Collections.Generic Class Test Sub Method() Dim list = DirectCast(New Integer() {1, 2, 3}, IList(Of Integer)) For [||] Each a In list Next End Sub End Class " Dim expected = " Imports System.Collections.Generic Class Test Sub Method() Dim list = DirectCast(New Integer() {1, 2, 3}, IList(Of Integer)) For {|Rename:i|} = 0 To list.Count - 1 Dim a = list(i) Next End Sub End Class " Await TestInRegularAndScriptAsync(initial, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)> Public Async Function ExplicitInterface() As Task Dim initial = " Imports System Imports System.Collections Imports System.Collections.Generic Class Test Sub Method() Dim list = New Explicit() For [||] Each a In list Console.WriteLine(a) Next End Sub End Class Class Explicit Implements IReadOnlyList(Of Integer) Default Public ReadOnly Property ItemExplicit(index As Integer) As Integer Implements IReadOnlyList(Of Integer).Item Get Throw New NotImplementedException() End Get End Property Public ReadOnly Property CountExplicit As Integer Implements IReadOnlyCollection(Of Integer).Count Get Throw New NotImplementedException() End Get End Property Public Function GetEnumeratorExplicit() As IEnumerator(Of Integer) Implements IEnumerable(Of Integer).GetEnumerator Throw New NotImplementedException() End Function Private Function IEnumerable_GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator Throw New NotImplementedException() End Function End Class " Dim expected = " Imports System Imports System.Collections Imports System.Collections.Generic Class Test Sub Method() Dim list = New Explicit() Dim {|Rename:list1|} = DirectCast(list, IReadOnlyList(Of Integer)) For {|Rename:i|} = 0 To list1.Count - 1 Dim a = list1(i) Console.WriteLine(a) Next End Sub End Class Class Explicit Implements IReadOnlyList(Of Integer) Default Public ReadOnly Property ItemExplicit(index As Integer) As Integer Implements IReadOnlyList(Of Integer).Item Get Throw New NotImplementedException() End Get End Property Public ReadOnly Property CountExplicit As Integer Implements IReadOnlyCollection(Of Integer).Count Get Throw New NotImplementedException() End Get End Property Public Function GetEnumeratorExplicit() As IEnumerator(Of Integer) Implements IEnumerable(Of Integer).GetEnumerator Throw New NotImplementedException() End Function Private Function IEnumerable_GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator Throw New NotImplementedException() End Function End Class " Await TestInRegularAndScriptAsync(initial, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)> Public Async Function MultipleNext() As Task Dim initial = " Class Test Sub Method() For Each a [||] In New Integer() {} For Each b In New Integer() {} Console.WriteLine(a) Next b, a End Sub End Class" Await TestMissingInRegularAndScriptAsync(initial) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)> Public Async Function MultipleNext2() As Task Dim initial = " Class Test Sub Method() For Each a In New Integer() {} For Each [||] b In New Integer() {} Console.WriteLine(a) Next b, a End Sub End Class" Await TestMissingInRegularAndScriptAsync(initial) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)> Public Async Function WrongNext() As Task Dim initial = " Class Test Sub Method() For Each [||] a In New Integer() {} Console.WriteLine(a) Next b End Sub End Class" Await TestMissingInRegularAndScriptAsync(initial) End Function <WorkItem(31621, "https://github.com/dotnet/roslyn/issues/31621")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)> Public Async Function KeepNext() As Task Dim initial = " Class Test Sub Method() For Each [||] a In New Integer() {1, 2, 3} Next a End Sub End Class " Dim expected = " Class Test Sub Method() Dim {|Rename:array|} = New Integer() {1, 2, 3} For {|Rename:i|} = 0 To array.Length - 1 Dim a = array(i) Next i End Sub End Class " Await TestInRegularAndScriptAsync(initial, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)> Public Async Function IndexConflict2() As Task Dim initial = " Class Test Sub Method() For Each [||] i In New Integer() {1, 2, 3} Console.WriteLine(a) Next End Sub End Class " Dim expected = " Class Test Sub Method() Dim {|Rename:array|} = New Integer() {1, 2, 3} For {|Rename:i1|} = 0 To array.Length - 1 Dim i = array(i1) Console.WriteLine(a) Next End Sub End Class " Await TestInRegularAndScriptAsync(initial, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)> Public Async Function UseTypeAsUsedInForeach() As Task Dim initial = " Class Test Sub Method() For Each [||] a As Integer In New Integer() {1, 2, 3} Console.WriteLine(a) Next End Sub End Class " Dim expected = " Class Test Sub Method() Dim {|Rename:array|} = New Integer() {1, 2, 3} For {|Rename:i|} = 0 To array.Length - 1 Dim a As Integer = array(i) Console.WriteLine(a) Next End Sub End Class " Await TestInRegularAndScriptAsync(initial, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)> Public Async Function UniqueLocalName() As Task Dim initial = " Imports System Imports System.Collections.Generic Class Test Sub Method() For Each [||] a In New List(Of Integer)() Console.WriteLine(a) Next End Sub End Class " Dim expected = " Imports System Imports System.Collections.Generic Class Test Sub Method() Dim {|Rename:list|} = New List(Of Integer)() For {|Rename:i|} = 0 To list.Count - 1 Dim a = list(i) Console.WriteLine(a) Next End Sub End Class " Await TestInRegularAndScriptAsync(initial, expected) End Function End Class End Namespace
-1
dotnet/roslyn
56,450
Implement INamespaceTypeReference.GetUnit for RootModuleType
Fixes #56412.
AlekseyTs
"2021-09-16T16:44:04Z"
"2021-09-17T18:21:59Z"
4b06ee428bafa0141c9eb3250003a19109dcfc86
d695369176aa109f0e0fb8b0019294aaa0823a54
Implement INamespaceTypeReference.GetUnit for RootModuleType. Fixes #56412.
./src/Compilers/CSharp/Test/Symbol/Symbols/ModuleInitializers/ModuleInitializersTests.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.Reflection; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Symbols.ModuleInitializers { [CompilerTrait(CompilerFeature.ModuleInitializers)] public sealed class ModuleInitializersTests : CSharpTestBase { private static readonly CSharpParseOptions s_parseOptions = TestOptions.Regular9; [Fact] public static void LastLanguageVersionNotSupportingModuleInitializersIs8() { var source = @"using System.Runtime.CompilerServices; class C { [ModuleInitializer] internal static void M() { } } namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } } "; var compilation = CreateCompilation(source, parseOptions: TestOptions.Regular8); compilation.VerifyDiagnostics( // (5,6): error CS8400: Feature 'module initializers' is not available in C# 8.0. Please use language version 9.0 or greater. // [ModuleInitializer] Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "ModuleInitializer").WithArguments("module initializers", "9.0").WithLocation(5, 6) ); } [Fact] public static void FirstLanguageVersionSupportingModuleInitializersIs9() { var source = @"using System.Runtime.CompilerServices; class C { [ModuleInitializer] internal static void M() { } } namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } } "; var compilation = CreateCompilation(source, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics(); } [Fact] public void ModuleTypeStaticConstructorIsNotEmittedWhenNoMethodIsMarkedWithModuleInitializerAttribute() { string source = @" using System; using System.Runtime.CompilerServices; class C { internal static void M() => Console.WriteLine(""C.M""); } class Program { static void Main() => Console.WriteLine(""Program.Main""); } namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } } "; CompileAndVerify( source, parseOptions: s_parseOptions, options: TestOptions.DebugExe.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module => { Assert.Equal(MetadataImportOptions.All, ((PEModuleSymbol)module).ImportOptions); var rootModuleType = (TypeSymbol)module.GlobalNamespace.GetMember("<Module>"); Assert.Null(rootModuleType.GetMember(".cctor")); }, expectedOutput: @" Program.Main"); } [Fact] public void ModuleTypeStaticConstructorCallsMethodMarkedWithModuleInitializerAttribute() { string source = @" using System; using System.Runtime.CompilerServices; class C { [ModuleInitializer] internal static void M() => Console.WriteLine(""C.M""); } class Program { static void Main() => Console.WriteLine(""Program.Main""); } namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } } "; CompileAndVerify( source, parseOptions: s_parseOptions, options: TestOptions.DebugExe.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module => { Assert.Equal(MetadataImportOptions.All, ((PEModuleSymbol)module).ImportOptions); var rootModuleType = (TypeSymbol)module.GlobalNamespace.GetMember("<Module>"); var staticConstructor = (PEMethodSymbol)rootModuleType.GetMember(".cctor"); Assert.NotNull(staticConstructor); Assert.Equal(MethodKind.StaticConstructor, staticConstructor.MethodKind); var expectedFlags = MethodAttributes.Private | MethodAttributes.Static | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName | MethodAttributes.HideBySig; Assert.Equal(expectedFlags, staticConstructor.Flags); }, expectedOutput: @" C.M Program.Main"); } [Fact] public void SingleCallIsGeneratedWhenMethodIsMarkedTwice() { string source = @" using System; using System.Runtime.CompilerServices; class C { [ModuleInitializer, ModuleInitializer] internal static void M() => Console.WriteLine(""C.M""); } class Program { static void Main() { } } namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.Method, AllowMultiple = true)] class ModuleInitializerAttribute : System.Attribute { } } "; CompileAndVerify(source, parseOptions: s_parseOptions, expectedOutput: "C.M"); } [Fact] public void AttributeCanBeAppliedWithinItsOwnDefinition() { string source = @" using System; class Program { static void Main() => Console.WriteLine(""Program.Main""); } namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { [ModuleInitializer] internal static void M() => Console.WriteLine(""ModuleInitializerAttribute.M""); } } "; CompileAndVerify(source, parseOptions: s_parseOptions, expectedOutput: @" ModuleInitializerAttribute.M Program.Main"); } [Fact] public void ExternMethodCanBeModuleInitializer() { string source = @" using System.Runtime.CompilerServices; using System.Runtime.InteropServices; class C { [ModuleInitializer, DllImport(""dllName"")] internal static extern void M(); } namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } } "; CompileAndVerify( source, parseOptions: s_parseOptions, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module => { Assert.Equal(MetadataImportOptions.All, ((PEModuleSymbol)module).ImportOptions); var rootModuleType = module.ContainingAssembly.GetTypeByMetadataName("<Module>"); Assert.NotNull(rootModuleType.GetMember(".cctor")); }); } [Fact] public void MayBeDeclaredByStruct() { string source = @" using System; using System.Runtime.CompilerServices; struct S { [ModuleInitializer] internal static void M() => Console.WriteLine(""S.M""); } class Program { static void Main() => Console.WriteLine(""Program.Main""); } namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } } "; CompileAndVerify(source, parseOptions: s_parseOptions, expectedOutput: @" S.M Program.Main"); } [Fact] public void MayBeDeclaredByInterface() { string source = @" using System; using System.Runtime.CompilerServices; interface I { [ModuleInitializer] internal static void M() => Console.WriteLine(""I.M""); } class Program { static void Main() => Console.WriteLine(""Program.Main""); } namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } } "; CompileAndVerify( source, parseOptions: s_parseOptions, targetFramework: TargetFramework.NetCoreApp, expectedOutput: ExecutionConditionUtil.IsMonoOrCoreClr ? @" I.M Program.Main" : null, verify: ExecutionConditionUtil.IsMonoOrCoreClr ? Verification.Passes : Verification.Skipped); } [Fact] public void MultipleInitializers_SingleFile() { string source = @" using System; using System.Runtime.CompilerServices; class C1 { [ModuleInitializer] internal static void M1() => Console.Write(1); internal class C2 { [ModuleInitializer] internal static void M2() => Console.Write(2); } [ModuleInitializer] internal static void M3() => Console.Write(3); } class Program { static void Main() => Console.Write(4); } namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } } "; CompileAndVerify( source, parseOptions: s_parseOptions, expectedOutput: "1234"); } [Fact] public void MultipleInitializers_DifferentContainingTypeKinds() { string source = @" using System; using System.Runtime.CompilerServices; class C1 { [ModuleInitializer] internal static void M1() => Console.Write(1); } struct S1 { [ModuleInitializer] internal static void M2() => Console.Write(2); } interface I1 { [ModuleInitializer] internal static void M3() => Console.Write(3); } class Program { static void Main() => Console.Write(4); } namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } } "; CompileAndVerify( source, parseOptions: s_parseOptions, targetFramework: TargetFramework.NetCoreApp, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : "1234", verify: !ExecutionConditionUtil.IsMonoOrCoreClr ? Verification.Skipped : Verification.Passes); } [Fact] public void MultipleInitializers_MultipleFiles() { string source1 = @" using System; using System.Runtime.CompilerServices; class C1 { [ModuleInitializer] internal static void M1() => Console.Write(1); [ModuleInitializer] internal static void M2() => Console.Write(2); } namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } } "; string source2 = @" using System; using System.Runtime.CompilerServices; class C2 { internal class C3 { [ModuleInitializer] internal static void M3() => Console.Write(3); } [ModuleInitializer] internal static void M4() => Console.Write(4); } class Program { static void Main() => Console.Write(6); } "; string source3 = @" using System; using System.Runtime.CompilerServices; class C4 { // shouldn't be called internal static void M() => Console.Write(0); [ModuleInitializer] internal static void M5() => Console.Write(5); } "; CompileAndVerify( new[] { source1, source2, source3 }, parseOptions: s_parseOptions, expectedOutput: "123456"); } [Fact] public void StaticConstructor_Ordering() { const string text = @" using System; using System.Runtime.CompilerServices; class C1 { [ModuleInitializer] internal static void Init() => Console.Write(1); } class C2 { static C2() => Console.Write(2); static void Main() { Console.Write(3); } } namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } } "; var verifier = CompileAndVerify(text, parseOptions: s_parseOptions, expectedOutput: "123"); verifier.VerifyDiagnostics(); } [Fact] public void StaticConstructor_Ordering_SameType() { const string text = @" using System; using System.Runtime.CompilerServices; class C { static C() => Console.Write(1); [ModuleInitializer] internal static void Init() => Console.Write(2); static void Main() { Console.Write(3); } } namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } } "; var verifier = CompileAndVerify(text, parseOptions: s_parseOptions, expectedOutput: "123"); verifier.VerifyDiagnostics(); } [Fact] public void StaticConstructor_DefaultInitializer_SameType() { const string text = @" using System; using System.Runtime.CompilerServices; class C { internal static string s1 = null; [ModuleInitializer] internal static void Init() { s1 = ""hello""; } static void Main() { Console.Write(s1); } } namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } } "; var verifier = CompileAndVerify( text, parseOptions: s_parseOptions, options: TestOptions.DebugExe.WithMetadataImportOptions(MetadataImportOptions.All), expectedOutput: "hello", symbolValidator: validator); verifier.VerifyDiagnostics(); void validator(ModuleSymbol module) { var cType = module.ContainingAssembly.GetTypeByMetadataName("C"); // static constructor should be optimized out Assert.Null(cType.GetMember<MethodSymbol>(".cctor")); var moduleType = module.ContainingAssembly.GetTypeByMetadataName("<Module>"); Assert.NotNull(moduleType.GetMember<MethodSymbol>(".cctor")); } } [Fact] public void StaticConstructor_EffectingInitializer_SameType() { const string text = @" using System; using System.Runtime.CompilerServices; class C { internal static int i = InitField(); internal static int InitField() { Console.Write(1); return -1; } [ModuleInitializer] internal static void Init() { i = 2; } static void Main() { Console.Write(i); } } namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } } "; var verifier = CompileAndVerify( text, parseOptions: s_parseOptions, options: TestOptions.DebugExe.WithMetadataImportOptions(MetadataImportOptions.All), expectedOutput: "12", symbolValidator: validator); verifier.VerifyDiagnostics(); void validator(ModuleSymbol module) { var cType = module.ContainingAssembly.GetTypeByMetadataName("C"); Assert.NotNull(cType.GetMember<MethodSymbol>(".cctor")); var moduleType = module.ContainingAssembly.GetTypeByMetadataName("<Module>"); Assert.NotNull(moduleType.GetMember<MethodSymbol>(".cctor")); } } [Fact] public void StaticConstructor_DefaultInitializer_OtherType() { const string text = @" using System; using System.Runtime.CompilerServices; class C1 { [ModuleInitializer] internal static void Init() { C2.s1 = ""hello""; } } class C2 { internal static string s1 = null; static void Main() { Console.Write(s1); } } namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } } "; var verifier = CompileAndVerify( text, parseOptions: s_parseOptions, options: TestOptions.DebugExe.WithMetadataImportOptions(MetadataImportOptions.All), expectedOutput: "hello", symbolValidator: validator); verifier.VerifyDiagnostics(); void validator(ModuleSymbol module) { var c2Type = module.ContainingAssembly.GetTypeByMetadataName("C2"); // static constructor should be optimized out Assert.Null(c2Type.GetMember<MethodSymbol>(".cctor")); var moduleType = module.ContainingAssembly.GetTypeByMetadataName("<Module>"); Assert.NotNull(moduleType.GetMember<MethodSymbol>(".cctor")); } } [Fact] public void StaticConstructor_EffectingInitializer_OtherType() { const string text = @" using System; using System.Runtime.CompilerServices; class C1 { [ModuleInitializer] internal static void Init() { C2.i = 2; } } class C2 { internal static int i = InitField(); static int InitField() { Console.Write(1); return -1; } static void Main() { Console.Write(i); } } namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } } "; var verifier = CompileAndVerify( text, parseOptions: s_parseOptions, options: TestOptions.DebugExe.WithMetadataImportOptions(MetadataImportOptions.All), expectedOutput: "12", symbolValidator: validator); verifier.VerifyDiagnostics(); void validator(ModuleSymbol module) { var c2Type = module.ContainingAssembly.GetTypeByMetadataName("C2"); Assert.NotNull(c2Type.GetMember<MethodSymbol>(".cctor")); var moduleType = module.ContainingAssembly.GetTypeByMetadataName("<Module>"); Assert.NotNull(moduleType.GetMember<MethodSymbol>(".cctor")); } } [Fact] public void ModuleInitializerAttributeIncludedByConditionalAttribute() { string source = @" #define INCLUDE using System; using System.Runtime.CompilerServices; class C { [ModuleInitializer] internal static void M() => Console.WriteLine(""C.M""); } class Program { static void Main() => Console.WriteLine(""Program.Main""); } namespace System.Runtime.CompilerServices { [System.Diagnostics.Conditional(""INCLUDE"")] class ModuleInitializerAttribute : System.Attribute { } } "; CompileAndVerify(source, parseOptions: s_parseOptions, expectedOutput: @" C.M Program.Main"); } [Fact] public void ModuleInitializerAttributeExcludedByConditionalAttribute() { string source = @" using System; using System.Runtime.CompilerServices; class C { [ModuleInitializer] internal static void M() => Console.WriteLine(""C.M""); } class Program { static void Main() => Console.WriteLine(""Program.Main""); } namespace System.Runtime.CompilerServices { [System.Diagnostics.Conditional(""EXCLUDE"")] class ModuleInitializerAttribute : System.Attribute { } } "; CompileAndVerify(source, parseOptions: s_parseOptions, expectedOutput: @" C.M Program.Main"); } [Fact] public void ModuleInitializerMethodIncludedByConditionalAttribute() { string source = @" #define INCLUDE using System; using System.Runtime.CompilerServices; class C { [System.Diagnostics.Conditional(""INCLUDE""), ModuleInitializer] internal static void Preceding() => Console.WriteLine(""C.Preceding""); [ModuleInitializer, System.Diagnostics.Conditional(""INCLUDE"")] internal static void Following() => Console.WriteLine(""C.Following""); } class Program { static void Main() => Console.WriteLine(""Program.Main""); } namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } } "; CompileAndVerify(source, parseOptions: s_parseOptions, expectedOutput: @" C.Preceding C.Following Program.Main"); } [Fact] public void ModuleInitializerMethodExcludedByConditionalAttribute() { string source = @" using System; using System.Runtime.CompilerServices; class C { [System.Diagnostics.Conditional(""EXCLUDE""), ModuleInitializer] internal static void Preceding() { } [ModuleInitializer, System.Diagnostics.Conditional(""EXCLUDE"")] internal static void Following() { } } namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } } "; CompileAndVerify( source, parseOptions: s_parseOptions, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module => { Assert.Equal(MetadataImportOptions.All, ((PEModuleSymbol)module).ImportOptions); var rootModuleType = module.ContainingAssembly.GetTypeByMetadataName("<Module>"); Assert.Null(rootModuleType.GetMember(".cctor")); }); } [Fact] public void ModuleInitializerMethodIsObsolete() { string source = @" using System; using System.Runtime.CompilerServices; class C { [Obsolete, ModuleInitializer] internal static void Init() => Console.WriteLine(""C.Init""); } class Program { static void Main() => Console.WriteLine(""Program.Main""); } namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } } "; CompileAndVerify(source, parseOptions: s_parseOptions, expectedOutput: @" C.Init Program.Main"); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.NetModulesNeedDesktop)] public void MultipleNetmodules() { var moduleOptions = TestOptions.ReleaseModule.WithMetadataImportOptions(MetadataImportOptions.All); var s1 = @" using System; using System.Runtime.CompilerServices; public class A { [ModuleInitializer] public static void M1() { Console.Write(1); } } namespace System.Runtime.CompilerServices { public class ModuleInitializerAttribute : System.Attribute { } }"; var comp1 = CreateCompilation(s1, options: moduleOptions.WithModuleName("A"), parseOptions: s_parseOptions); comp1.VerifyDiagnostics(); var ref1 = comp1.EmitToImageReference(); CompileAndVerify(comp1, symbolValidator: validateModuleInitializer, verify: Verification.Skipped); var s2 = @" using System; using System.Runtime.CompilerServices; public class B { [ModuleInitializer] public static void M2() { Console.Write(2); } }"; var comp2 = CreateCompilation(s2, options: moduleOptions.WithModuleName("B"), parseOptions: s_parseOptions, references: new[] { ref1 }); comp2.VerifyDiagnostics(); var ref2 = comp2.EmitToImageReference(); CompileAndVerify(comp2, symbolValidator: validateModuleInitializer, verify: Verification.Skipped); var exeOptions = TestOptions.ReleaseExe .WithMetadataImportOptions(MetadataImportOptions.All) .WithModuleName("C"); var s3 = @" using System; public class Program { public static void Main(string[] args) { Console.Write(3); } }"; var comp3 = CreateCompilation(s3, options: exeOptions, parseOptions: s_parseOptions, references: new[] { ref1, ref2 }); comp3.VerifyDiagnostics(); CompileAndVerify(comp3, symbolValidator: validateNoModuleInitializer, expectedOutput: "3"); var s4 = @" using System; public class Program { public static void Main(string[] args) { new A(); new B(); Console.Write(3); } }"; var comp4 = CreateCompilation(s4, options: exeOptions, parseOptions: s_parseOptions, references: new[] { ref1, ref2 }); comp4.VerifyDiagnostics(); CompileAndVerify(comp4, symbolValidator: validateNoModuleInitializer, expectedOutput: "123"); var s5 = @" using System; public class Program { public static void Main(string[] args) { new B(); Console.Write(3); new A(); } }"; var comp5 = CreateCompilation(s5, options: exeOptions, parseOptions: s_parseOptions, references: new[] { ref1, ref2 }); comp5.VerifyDiagnostics(); // This order seems surprising, but is likely related to the order in which types are loaded when a method is called. CompileAndVerify(comp5, symbolValidator: validateNoModuleInitializer, expectedOutput: "213"); var s6 = @" using System; public class Program { public static void Main(string[] args) { new A(); Console.Write(3); } }"; var comp6 = CreateCompilation(s6, options: exeOptions, parseOptions: s_parseOptions, references: new[] { ref1, ref2 }); comp6.VerifyDiagnostics(); CompileAndVerify(comp6, symbolValidator: validateNoModuleInitializer, expectedOutput: "13"); var s7 = @" using System; using System.Runtime.CompilerServices; public class Program { [ModuleInitializer] public static void Init() { Console.Write(0); } public static void Main(string[] args) { new B(); Console.Write(3); } }"; var comp7 = CreateCompilation(s7, options: exeOptions, parseOptions: s_parseOptions, references: new[] { ref1, ref2 }); comp7.VerifyDiagnostics(); CompileAndVerify(comp7, symbolValidator: validateModuleInitializer, expectedOutput: "023"); var s8 = @" using System; using System.Runtime.CompilerServices; public class Program { [ModuleInitializer] public static void Init() { Console.Write(0); new A(); } public static void Main(string[] args) { new A(); new B(); Console.Write(3); } }"; var comp8 = CreateCompilation(s8, options: exeOptions, parseOptions: s_parseOptions, references: new[] { ref1, ref2 }); comp8.VerifyDiagnostics(); CompileAndVerify(comp8, symbolValidator: validateModuleInitializer, expectedOutput: "1023"); void validateModuleInitializer(ModuleSymbol module) { Assert.Equal(MetadataImportOptions.All, ((PEModuleSymbol)module).ImportOptions); var moduleType = module.ContainingAssembly.GetTypeByMetadataName("<Module>"); Assert.NotNull(moduleType.GetMember<MethodSymbol>(".cctor")); } void validateNoModuleInitializer(ModuleSymbol module) { Assert.Equal(MetadataImportOptions.All, ((PEModuleSymbol)module).ImportOptions); var moduleType = module.ContainingAssembly.GetTypeByMetadataName("<Module>"); Assert.Null(moduleType.GetMember<MethodSymbol>(".cctor")); } } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.NetModulesNeedDesktop)] public void NetmoduleFromIL_InitializerNotCalled() { var il = @" .class public auto ansi beforefieldinit A extends [mscorlib]System.Object { .method public hidebysig static void M1() cil managed { .custom instance void System.Runtime.CompilerServices.ModuleInitializerAttribute::.ctor() = ( 01 00 00 00 ) // Code size 9 (0x9) .maxstack 8 IL_0000: nop IL_0001: ldc.i4.0 IL_0002: call void [mscorlib]System.Console::Write(int32) IL_0007: nop IL_0008: ret } // end of method A::M1 .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: nop IL_0007: ret } // end of method A::.ctor } // end of class A .class public auto ansi beforefieldinit System.Runtime.CompilerServices.ModuleInitializerAttribute extends [mscorlib]System.Attribute { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Attribute::.ctor() IL_0006: nop IL_0007: ret } // end of method ModuleInitializerAttribute::.ctor } // end of class System.Runtime.CompilerServices.ModuleInitializerAttribute"; var source1 = @" using System; using System.Runtime.CompilerServices; public class A { [ModuleInitializer] public static void M1() { Console.Write(1); } public static void Main() { Console.Write(2); } } namespace System.Runtime.CompilerServices { public class ModuleInitializerAttribute : System.Attribute { } } "; var source2 = @" using System; using System.Runtime.CompilerServices; public class A { public static void M1() { Console.Write(0); } public static void Main() { Console.Write(1); } } namespace System.Runtime.CompilerServices { public class ModuleInitializerAttribute : System.Attribute { } } "; var exeOptions = TestOptions.ReleaseExe .WithMetadataImportOptions(MetadataImportOptions.All) .WithModuleName("C"); var comp = CreateCompilationWithIL(source1, il, parseOptions: s_parseOptions, options: exeOptions); CompileAndVerify(comp, symbolValidator: validateModuleInitializer, verify: Verification.Skipped, expectedOutput: "12"); comp = CreateCompilationWithIL(source2, il, parseOptions: s_parseOptions, options: exeOptions); CompileAndVerify(comp, symbolValidator: validateNoModuleInitializer, verify: Verification.Skipped, expectedOutput: "1"); void validateModuleInitializer(ModuleSymbol module) { Assert.Equal(MetadataImportOptions.All, ((PEModuleSymbol)module).ImportOptions); var moduleType = module.ContainingAssembly.GetTypeByMetadataName("<Module>"); Assert.NotNull(moduleType.GetMember<MethodSymbol>(".cctor")); } void validateNoModuleInitializer(ModuleSymbol module) { Assert.Equal(MetadataImportOptions.All, ((PEModuleSymbol)module).ImportOptions); var moduleType = module.ContainingAssembly.GetTypeByMetadataName("<Module>"); Assert.Null(moduleType.GetMember<MethodSymbol>(".cctor")); } } [Fact] public void MultipleAttributesViaExternAlias() { var source1 = @" namespace System.Runtime.CompilerServices { public class ModuleInitializerAttribute : System.Attribute { } } "; var ref1 = CreateCompilation(source1).ToMetadataReference(aliases: ImmutableArray.Create("Alias1")); var ref2 = CreateCompilation(source1).ToMetadataReference(aliases: ImmutableArray.Create("Alias2")); var source = @" extern alias Alias1; extern alias Alias2; using System; class Program { [Alias1::System.Runtime.CompilerServices.ModuleInitializer] internal static void Init1() { Console.Write(1); } [Alias2::System.Runtime.CompilerServices.ModuleInitializer] internal static void Init2() { Console.Write(2); } static void Main() { Console.Write(3); } } "; CompileAndVerify(source, parseOptions: s_parseOptions, references: new[] { ref1, ref2 }, expectedOutput: "123"); } } }
// Licensed to the .NET Foundation under one or more 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.Reflection; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Symbols.ModuleInitializers { [CompilerTrait(CompilerFeature.ModuleInitializers)] public sealed class ModuleInitializersTests : CSharpTestBase { private static readonly CSharpParseOptions s_parseOptions = TestOptions.Regular9; [Fact] public static void LastLanguageVersionNotSupportingModuleInitializersIs8() { var source = @"using System.Runtime.CompilerServices; class C { [ModuleInitializer] internal static void M() { } } namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } } "; var compilation = CreateCompilation(source, parseOptions: TestOptions.Regular8); compilation.VerifyDiagnostics( // (5,6): error CS8400: Feature 'module initializers' is not available in C# 8.0. Please use language version 9.0 or greater. // [ModuleInitializer] Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "ModuleInitializer").WithArguments("module initializers", "9.0").WithLocation(5, 6) ); } [Fact] public static void FirstLanguageVersionSupportingModuleInitializersIs9() { var source = @"using System.Runtime.CompilerServices; class C { [ModuleInitializer] internal static void M() { } } namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } } "; var compilation = CreateCompilation(source, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics(); } [Fact] public void ModuleTypeStaticConstructorIsNotEmittedWhenNoMethodIsMarkedWithModuleInitializerAttribute() { string source = @" using System; using System.Runtime.CompilerServices; class C { internal static void M() => Console.WriteLine(""C.M""); } class Program { static void Main() => Console.WriteLine(""Program.Main""); } namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } } "; CompileAndVerify( source, parseOptions: s_parseOptions, options: TestOptions.DebugExe.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module => { Assert.Equal(MetadataImportOptions.All, ((PEModuleSymbol)module).ImportOptions); var rootModuleType = (TypeSymbol)module.GlobalNamespace.GetMember("<Module>"); Assert.Null(rootModuleType.GetMember(".cctor")); }, expectedOutput: @" Program.Main"); } [Fact] public void ModuleTypeStaticConstructorCallsMethodMarkedWithModuleInitializerAttribute() { string source = @" using System; using System.Runtime.CompilerServices; class C { [ModuleInitializer] internal static void M() => Console.WriteLine(""C.M""); } class Program { static void Main() => Console.WriteLine(""Program.Main""); } namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } } "; CompileAndVerify( source, parseOptions: s_parseOptions, options: TestOptions.DebugExe.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module => { Assert.Equal(MetadataImportOptions.All, ((PEModuleSymbol)module).ImportOptions); var rootModuleType = (TypeSymbol)module.GlobalNamespace.GetMember("<Module>"); var staticConstructor = (PEMethodSymbol)rootModuleType.GetMember(".cctor"); Assert.NotNull(staticConstructor); Assert.Equal(MethodKind.StaticConstructor, staticConstructor.MethodKind); var expectedFlags = MethodAttributes.Private | MethodAttributes.Static | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName | MethodAttributes.HideBySig; Assert.Equal(expectedFlags, staticConstructor.Flags); }, expectedOutput: @" C.M Program.Main"); } [Fact] public void SingleCallIsGeneratedWhenMethodIsMarkedTwice() { string source = @" using System; using System.Runtime.CompilerServices; class C { [ModuleInitializer, ModuleInitializer] internal static void M() => Console.WriteLine(""C.M""); } class Program { static void Main() { } } namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.Method, AllowMultiple = true)] class ModuleInitializerAttribute : System.Attribute { } } "; CompileAndVerify(source, parseOptions: s_parseOptions, expectedOutput: "C.M"); } [Fact] public void AttributeCanBeAppliedWithinItsOwnDefinition() { string source = @" using System; class Program { static void Main() => Console.WriteLine(""Program.Main""); } namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { [ModuleInitializer] internal static void M() => Console.WriteLine(""ModuleInitializerAttribute.M""); } } "; CompileAndVerify(source, parseOptions: s_parseOptions, expectedOutput: @" ModuleInitializerAttribute.M Program.Main"); } [Fact] public void ExternMethodCanBeModuleInitializer() { string source = @" using System.Runtime.CompilerServices; using System.Runtime.InteropServices; class C { [ModuleInitializer, DllImport(""dllName"")] internal static extern void M(); } namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } } "; CompileAndVerify( source, parseOptions: s_parseOptions, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module => { Assert.Equal(MetadataImportOptions.All, ((PEModuleSymbol)module).ImportOptions); var rootModuleType = module.ContainingAssembly.GetTypeByMetadataName("<Module>"); Assert.NotNull(rootModuleType.GetMember(".cctor")); }); } [Fact] public void MayBeDeclaredByStruct() { string source = @" using System; using System.Runtime.CompilerServices; struct S { [ModuleInitializer] internal static void M() => Console.WriteLine(""S.M""); } class Program { static void Main() => Console.WriteLine(""Program.Main""); } namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } } "; CompileAndVerify(source, parseOptions: s_parseOptions, expectedOutput: @" S.M Program.Main"); } [Fact] public void MayBeDeclaredByInterface() { string source = @" using System; using System.Runtime.CompilerServices; interface I { [ModuleInitializer] internal static void M() => Console.WriteLine(""I.M""); } class Program { static void Main() => Console.WriteLine(""Program.Main""); } namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } } "; CompileAndVerify( source, parseOptions: s_parseOptions, targetFramework: TargetFramework.NetCoreApp, expectedOutput: ExecutionConditionUtil.IsMonoOrCoreClr ? @" I.M Program.Main" : null, verify: ExecutionConditionUtil.IsMonoOrCoreClr ? Verification.Passes : Verification.Skipped); } [Fact] public void MultipleInitializers_SingleFile() { string source = @" using System; using System.Runtime.CompilerServices; class C1 { [ModuleInitializer] internal static void M1() => Console.Write(1); internal class C2 { [ModuleInitializer] internal static void M2() => Console.Write(2); } [ModuleInitializer] internal static void M3() => Console.Write(3); } class Program { static void Main() => Console.Write(4); } namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } } "; CompileAndVerify( source, parseOptions: s_parseOptions, expectedOutput: "1234"); } [Fact] public void MultipleInitializers_DifferentContainingTypeKinds() { string source = @" using System; using System.Runtime.CompilerServices; class C1 { [ModuleInitializer] internal static void M1() => Console.Write(1); } struct S1 { [ModuleInitializer] internal static void M2() => Console.Write(2); } interface I1 { [ModuleInitializer] internal static void M3() => Console.Write(3); } class Program { static void Main() => Console.Write(4); } namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } } "; CompileAndVerify( source, parseOptions: s_parseOptions, targetFramework: TargetFramework.NetCoreApp, expectedOutput: !ExecutionConditionUtil.IsMonoOrCoreClr ? null : "1234", verify: !ExecutionConditionUtil.IsMonoOrCoreClr ? Verification.Skipped : Verification.Passes); } [Fact] public void MultipleInitializers_MultipleFiles() { string source1 = @" using System; using System.Runtime.CompilerServices; class C1 { [ModuleInitializer] internal static void M1() => Console.Write(1); [ModuleInitializer] internal static void M2() => Console.Write(2); } namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } } "; string source2 = @" using System; using System.Runtime.CompilerServices; class C2 { internal class C3 { [ModuleInitializer] internal static void M3() => Console.Write(3); } [ModuleInitializer] internal static void M4() => Console.Write(4); } class Program { static void Main() => Console.Write(6); } "; string source3 = @" using System; using System.Runtime.CompilerServices; class C4 { // shouldn't be called internal static void M() => Console.Write(0); [ModuleInitializer] internal static void M5() => Console.Write(5); } "; CompileAndVerify( new[] { source1, source2, source3 }, parseOptions: s_parseOptions, expectedOutput: "123456"); } [Fact] public void StaticConstructor_Ordering() { const string text = @" using System; using System.Runtime.CompilerServices; class C1 { [ModuleInitializer] internal static void Init() => Console.Write(1); } class C2 { static C2() => Console.Write(2); static void Main() { Console.Write(3); } } namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } } "; var verifier = CompileAndVerify(text, parseOptions: s_parseOptions, expectedOutput: "123"); verifier.VerifyDiagnostics(); } [Fact] public void StaticConstructor_Ordering_SameType() { const string text = @" using System; using System.Runtime.CompilerServices; class C { static C() => Console.Write(1); [ModuleInitializer] internal static void Init() => Console.Write(2); static void Main() { Console.Write(3); } } namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } } "; var verifier = CompileAndVerify(text, parseOptions: s_parseOptions, expectedOutput: "123"); verifier.VerifyDiagnostics(); } [Fact] public void StaticConstructor_DefaultInitializer_SameType() { const string text = @" using System; using System.Runtime.CompilerServices; class C { internal static string s1 = null; [ModuleInitializer] internal static void Init() { s1 = ""hello""; } static void Main() { Console.Write(s1); } } namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } } "; var verifier = CompileAndVerify( text, parseOptions: s_parseOptions, options: TestOptions.DebugExe.WithMetadataImportOptions(MetadataImportOptions.All), expectedOutput: "hello", symbolValidator: validator); verifier.VerifyDiagnostics(); void validator(ModuleSymbol module) { var cType = module.ContainingAssembly.GetTypeByMetadataName("C"); // static constructor should be optimized out Assert.Null(cType.GetMember<MethodSymbol>(".cctor")); var moduleType = module.ContainingAssembly.GetTypeByMetadataName("<Module>"); Assert.NotNull(moduleType.GetMember<MethodSymbol>(".cctor")); } } [Fact] public void StaticConstructor_EffectingInitializer_SameType() { const string text = @" using System; using System.Runtime.CompilerServices; class C { internal static int i = InitField(); internal static int InitField() { Console.Write(1); return -1; } [ModuleInitializer] internal static void Init() { i = 2; } static void Main() { Console.Write(i); } } namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } } "; var verifier = CompileAndVerify( text, parseOptions: s_parseOptions, options: TestOptions.DebugExe.WithMetadataImportOptions(MetadataImportOptions.All), expectedOutput: "12", symbolValidator: validator); verifier.VerifyDiagnostics(); void validator(ModuleSymbol module) { var cType = module.ContainingAssembly.GetTypeByMetadataName("C"); Assert.NotNull(cType.GetMember<MethodSymbol>(".cctor")); var moduleType = module.ContainingAssembly.GetTypeByMetadataName("<Module>"); Assert.NotNull(moduleType.GetMember<MethodSymbol>(".cctor")); } } [Fact] public void StaticConstructor_DefaultInitializer_OtherType() { const string text = @" using System; using System.Runtime.CompilerServices; class C1 { [ModuleInitializer] internal static void Init() { C2.s1 = ""hello""; } } class C2 { internal static string s1 = null; static void Main() { Console.Write(s1); } } namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } } "; var verifier = CompileAndVerify( text, parseOptions: s_parseOptions, options: TestOptions.DebugExe.WithMetadataImportOptions(MetadataImportOptions.All), expectedOutput: "hello", symbolValidator: validator); verifier.VerifyDiagnostics(); void validator(ModuleSymbol module) { var c2Type = module.ContainingAssembly.GetTypeByMetadataName("C2"); // static constructor should be optimized out Assert.Null(c2Type.GetMember<MethodSymbol>(".cctor")); var moduleType = module.ContainingAssembly.GetTypeByMetadataName("<Module>"); Assert.NotNull(moduleType.GetMember<MethodSymbol>(".cctor")); } } [Fact] public void StaticConstructor_EffectingInitializer_OtherType() { const string text = @" using System; using System.Runtime.CompilerServices; class C1 { [ModuleInitializer] internal static void Init() { C2.i = 2; } } class C2 { internal static int i = InitField(); static int InitField() { Console.Write(1); return -1; } static void Main() { Console.Write(i); } } namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } } "; var verifier = CompileAndVerify( text, parseOptions: s_parseOptions, options: TestOptions.DebugExe.WithMetadataImportOptions(MetadataImportOptions.All), expectedOutput: "12", symbolValidator: validator); verifier.VerifyDiagnostics(); void validator(ModuleSymbol module) { var c2Type = module.ContainingAssembly.GetTypeByMetadataName("C2"); Assert.NotNull(c2Type.GetMember<MethodSymbol>(".cctor")); var moduleType = module.ContainingAssembly.GetTypeByMetadataName("<Module>"); Assert.NotNull(moduleType.GetMember<MethodSymbol>(".cctor")); } } [Fact] public void ModuleInitializerAttributeIncludedByConditionalAttribute() { string source = @" #define INCLUDE using System; using System.Runtime.CompilerServices; class C { [ModuleInitializer] internal static void M() => Console.WriteLine(""C.M""); } class Program { static void Main() => Console.WriteLine(""Program.Main""); } namespace System.Runtime.CompilerServices { [System.Diagnostics.Conditional(""INCLUDE"")] class ModuleInitializerAttribute : System.Attribute { } } "; CompileAndVerify(source, parseOptions: s_parseOptions, expectedOutput: @" C.M Program.Main"); } [Fact] public void ModuleInitializerAttributeExcludedByConditionalAttribute() { string source = @" using System; using System.Runtime.CompilerServices; class C { [ModuleInitializer] internal static void M() => Console.WriteLine(""C.M""); } class Program { static void Main() => Console.WriteLine(""Program.Main""); } namespace System.Runtime.CompilerServices { [System.Diagnostics.Conditional(""EXCLUDE"")] class ModuleInitializerAttribute : System.Attribute { } } "; CompileAndVerify(source, parseOptions: s_parseOptions, expectedOutput: @" C.M Program.Main"); } [Fact] public void ModuleInitializerMethodIncludedByConditionalAttribute() { string source = @" #define INCLUDE using System; using System.Runtime.CompilerServices; class C { [System.Diagnostics.Conditional(""INCLUDE""), ModuleInitializer] internal static void Preceding() => Console.WriteLine(""C.Preceding""); [ModuleInitializer, System.Diagnostics.Conditional(""INCLUDE"")] internal static void Following() => Console.WriteLine(""C.Following""); } class Program { static void Main() => Console.WriteLine(""Program.Main""); } namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } } "; CompileAndVerify(source, parseOptions: s_parseOptions, expectedOutput: @" C.Preceding C.Following Program.Main"); } [Fact] public void ModuleInitializerMethodExcludedByConditionalAttribute() { string source = @" using System; using System.Runtime.CompilerServices; class C { [System.Diagnostics.Conditional(""EXCLUDE""), ModuleInitializer] internal static void Preceding() { } [ModuleInitializer, System.Diagnostics.Conditional(""EXCLUDE"")] internal static void Following() { } } namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } } "; CompileAndVerify( source, parseOptions: s_parseOptions, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module => { Assert.Equal(MetadataImportOptions.All, ((PEModuleSymbol)module).ImportOptions); var rootModuleType = module.ContainingAssembly.GetTypeByMetadataName("<Module>"); Assert.Null(rootModuleType.GetMember(".cctor")); }); } [Fact] public void ModuleInitializerMethodIsObsolete() { string source = @" using System; using System.Runtime.CompilerServices; class C { [Obsolete, ModuleInitializer] internal static void Init() => Console.WriteLine(""C.Init""); } class Program { static void Main() => Console.WriteLine(""Program.Main""); } namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } } "; CompileAndVerify(source, parseOptions: s_parseOptions, expectedOutput: @" C.Init Program.Main"); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.NetModulesNeedDesktop)] public void MultipleNetmodules() { var moduleOptions = TestOptions.ReleaseModule.WithMetadataImportOptions(MetadataImportOptions.All); var s1 = @" using System; using System.Runtime.CompilerServices; public class A { [ModuleInitializer] public static void M1() { Console.Write(1); } } namespace System.Runtime.CompilerServices { public class ModuleInitializerAttribute : System.Attribute { } }"; var comp1 = CreateCompilation(s1, options: moduleOptions.WithModuleName("A"), parseOptions: s_parseOptions); comp1.VerifyDiagnostics(); var ref1 = comp1.EmitToImageReference(); CompileAndVerify(comp1, symbolValidator: validateModuleInitializer, verify: Verification.Skipped); var s2 = @" using System; using System.Runtime.CompilerServices; public class B { [ModuleInitializer] public static void M2() { Console.Write(2); } }"; var comp2 = CreateCompilation(s2, options: moduleOptions.WithModuleName("B"), parseOptions: s_parseOptions, references: new[] { ref1 }); comp2.VerifyDiagnostics(); var ref2 = comp2.EmitToImageReference(); CompileAndVerify(comp2, symbolValidator: validateModuleInitializer, verify: Verification.Skipped); var exeOptions = TestOptions.ReleaseExe .WithMetadataImportOptions(MetadataImportOptions.All) .WithModuleName("C"); var s3 = @" using System; public class Program { public static void Main(string[] args) { Console.Write(3); } }"; var comp3 = CreateCompilation(s3, options: exeOptions, parseOptions: s_parseOptions, references: new[] { ref1, ref2 }); comp3.VerifyDiagnostics(); CompileAndVerify(comp3, symbolValidator: validateNoModuleInitializer, expectedOutput: "3"); var s4 = @" using System; public class Program { public static void Main(string[] args) { new A(); new B(); Console.Write(3); } }"; var comp4 = CreateCompilation(s4, options: exeOptions, parseOptions: s_parseOptions, references: new[] { ref1, ref2 }); comp4.VerifyDiagnostics(); CompileAndVerify(comp4, symbolValidator: validateNoModuleInitializer, expectedOutput: "123"); var s5 = @" using System; public class Program { public static void Main(string[] args) { new B(); Console.Write(3); new A(); } }"; var comp5 = CreateCompilation(s5, options: exeOptions, parseOptions: s_parseOptions, references: new[] { ref1, ref2 }); comp5.VerifyDiagnostics(); // This order seems surprising, but is likely related to the order in which types are loaded when a method is called. CompileAndVerify(comp5, symbolValidator: validateNoModuleInitializer, expectedOutput: "213"); var s6 = @" using System; public class Program { public static void Main(string[] args) { new A(); Console.Write(3); } }"; var comp6 = CreateCompilation(s6, options: exeOptions, parseOptions: s_parseOptions, references: new[] { ref1, ref2 }); comp6.VerifyDiagnostics(); CompileAndVerify(comp6, symbolValidator: validateNoModuleInitializer, expectedOutput: "13"); var s7 = @" using System; using System.Runtime.CompilerServices; public class Program { [ModuleInitializer] public static void Init() { Console.Write(0); } public static void Main(string[] args) { new B(); Console.Write(3); } }"; var comp7 = CreateCompilation(s7, options: exeOptions, parseOptions: s_parseOptions, references: new[] { ref1, ref2 }); comp7.VerifyDiagnostics(); CompileAndVerify(comp7, symbolValidator: validateModuleInitializer, expectedOutput: "023"); var s8 = @" using System; using System.Runtime.CompilerServices; public class Program { [ModuleInitializer] public static void Init() { Console.Write(0); new A(); } public static void Main(string[] args) { new A(); new B(); Console.Write(3); } }"; var comp8 = CreateCompilation(s8, options: exeOptions, parseOptions: s_parseOptions, references: new[] { ref1, ref2 }); comp8.VerifyDiagnostics(); CompileAndVerify(comp8, symbolValidator: validateModuleInitializer, expectedOutput: "1023"); void validateModuleInitializer(ModuleSymbol module) { Assert.Equal(MetadataImportOptions.All, ((PEModuleSymbol)module).ImportOptions); var moduleType = module.ContainingAssembly.GetTypeByMetadataName("<Module>"); Assert.NotNull(moduleType.GetMember<MethodSymbol>(".cctor")); } void validateNoModuleInitializer(ModuleSymbol module) { Assert.Equal(MetadataImportOptions.All, ((PEModuleSymbol)module).ImportOptions); var moduleType = module.ContainingAssembly.GetTypeByMetadataName("<Module>"); Assert.Null(moduleType.GetMember<MethodSymbol>(".cctor")); } } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.NetModulesNeedDesktop)] public void NetmoduleFromIL_InitializerNotCalled() { var il = @" .class public auto ansi beforefieldinit A extends [mscorlib]System.Object { .method public hidebysig static void M1() cil managed { .custom instance void System.Runtime.CompilerServices.ModuleInitializerAttribute::.ctor() = ( 01 00 00 00 ) // Code size 9 (0x9) .maxstack 8 IL_0000: nop IL_0001: ldc.i4.0 IL_0002: call void [mscorlib]System.Console::Write(int32) IL_0007: nop IL_0008: ret } // end of method A::M1 .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: nop IL_0007: ret } // end of method A::.ctor } // end of class A .class public auto ansi beforefieldinit System.Runtime.CompilerServices.ModuleInitializerAttribute extends [mscorlib]System.Attribute { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Attribute::.ctor() IL_0006: nop IL_0007: ret } // end of method ModuleInitializerAttribute::.ctor } // end of class System.Runtime.CompilerServices.ModuleInitializerAttribute"; var source1 = @" using System; using System.Runtime.CompilerServices; public class A { [ModuleInitializer] public static void M1() { Console.Write(1); } public static void Main() { Console.Write(2); } } namespace System.Runtime.CompilerServices { public class ModuleInitializerAttribute : System.Attribute { } } "; var source2 = @" using System; using System.Runtime.CompilerServices; public class A { public static void M1() { Console.Write(0); } public static void Main() { Console.Write(1); } } namespace System.Runtime.CompilerServices { public class ModuleInitializerAttribute : System.Attribute { } } "; var exeOptions = TestOptions.ReleaseExe .WithMetadataImportOptions(MetadataImportOptions.All) .WithModuleName("C"); var comp = CreateCompilationWithIL(source1, il, parseOptions: s_parseOptions, options: exeOptions); CompileAndVerify(comp, symbolValidator: validateModuleInitializer, verify: Verification.Skipped, expectedOutput: "12"); comp = CreateCompilationWithIL(source2, il, parseOptions: s_parseOptions, options: exeOptions); CompileAndVerify(comp, symbolValidator: validateNoModuleInitializer, verify: Verification.Skipped, expectedOutput: "1"); void validateModuleInitializer(ModuleSymbol module) { Assert.Equal(MetadataImportOptions.All, ((PEModuleSymbol)module).ImportOptions); var moduleType = module.ContainingAssembly.GetTypeByMetadataName("<Module>"); Assert.NotNull(moduleType.GetMember<MethodSymbol>(".cctor")); } void validateNoModuleInitializer(ModuleSymbol module) { Assert.Equal(MetadataImportOptions.All, ((PEModuleSymbol)module).ImportOptions); var moduleType = module.ContainingAssembly.GetTypeByMetadataName("<Module>"); Assert.Null(moduleType.GetMember<MethodSymbol>(".cctor")); } } [Fact] public void MultipleAttributesViaExternAlias() { var source1 = @" namespace System.Runtime.CompilerServices { public class ModuleInitializerAttribute : System.Attribute { } } "; var ref1 = CreateCompilation(source1).ToMetadataReference(aliases: ImmutableArray.Create("Alias1")); var ref2 = CreateCompilation(source1).ToMetadataReference(aliases: ImmutableArray.Create("Alias2")); var source = @" extern alias Alias1; extern alias Alias2; using System; class Program { [Alias1::System.Runtime.CompilerServices.ModuleInitializer] internal static void Init1() { Console.Write(1); } [Alias2::System.Runtime.CompilerServices.ModuleInitializer] internal static void Init2() { Console.Write(2); } static void Main() { Console.Write(3); } } "; CompileAndVerify(source, parseOptions: s_parseOptions, references: new[] { ref1, ref2 }, expectedOutput: "123"); } [Fact] [WorkItem(56412, "https://github.com/dotnet/roslyn/issues/56412")] public void Issue56412() { string source = @" using System; using System.Runtime.CompilerServices; class C { [ModuleInitializer] internal static void M() => Console.WriteLine(""C.M""); } class Program { static void Main() => Console.WriteLine(""Program.Main""); } namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } } "; CompileAndVerify( source, options: TestOptions.ReleaseExe, emitOptions: EmitOptions.Default.WithDebugInformationFormat(PathUtilities.IsUnixLikePlatform ? DebugInformationFormat.PortablePdb : DebugInformationFormat.Pdb), expectedOutput: @" C.M Program.Main"); } } }
1
dotnet/roslyn
56,450
Implement INamespaceTypeReference.GetUnit for RootModuleType
Fixes #56412.
AlekseyTs
"2021-09-16T16:44:04Z"
"2021-09-17T18:21:59Z"
4b06ee428bafa0141c9eb3250003a19109dcfc86
d695369176aa109f0e0fb8b0019294aaa0823a54
Implement INamespaceTypeReference.GetUnit for RootModuleType. Fixes #56412.
./src/Compilers/Core/Portable/Emit/CommonPEModuleBuilder.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.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.IO; using System.Linq; using System.Security.Cryptography; using System.Threading; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.Emit.NoPia; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Symbols; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Emit { internal abstract class CommonPEModuleBuilder : Cci.IUnit, Cci.IModuleReference { internal readonly DebugDocumentsBuilder DebugDocumentsBuilder; internal readonly IEnumerable<ResourceDescription> ManifestResources; internal readonly Cci.ModulePropertiesForSerialization SerializationProperties; internal readonly OutputKind OutputKind; internal Stream RawWin32Resources; internal IEnumerable<Cci.IWin32Resource> Win32Resources; internal Cci.ResourceSection Win32ResourceSection; internal Stream SourceLinkStreamOpt; internal Cci.IMethodReference PEEntryPoint; internal Cci.IMethodReference DebugEntryPoint; private readonly ConcurrentDictionary<IMethodSymbolInternal, Cci.IMethodBody> _methodBodyMap; private readonly TokenMap _referencesInILMap = new(); private readonly ItemTokenMap<string> _stringsInILMap = new(); private readonly ItemTokenMap<Cci.DebugSourceDocument> _sourceDocumentsInILMap = new(); private ImmutableArray<Cci.AssemblyReferenceAlias> _lazyAssemblyReferenceAliases; private ImmutableArray<Cci.ManagedResource> _lazyManagedResources; private IEnumerable<EmbeddedText> _embeddedTexts = SpecializedCollections.EmptyEnumerable<EmbeddedText>(); // Only set when running tests to allow realized IL for a given method to be looked up by method. internal ConcurrentDictionary<IMethodSymbolInternal, CompilationTestData.MethodData> TestData { get; private set; } internal EmitOptions EmitOptions { get; } internal DebugInformationFormat DebugInformationFormat => EmitOptions.DebugInformationFormat; internal HashAlgorithmName PdbChecksumAlgorithm => EmitOptions.PdbChecksumAlgorithm; public CommonPEModuleBuilder( IEnumerable<ResourceDescription> manifestResources, EmitOptions emitOptions, OutputKind outputKind, Cci.ModulePropertiesForSerialization serializationProperties, Compilation compilation) { Debug.Assert(manifestResources != null); Debug.Assert(serializationProperties != null); Debug.Assert(compilation != null); ManifestResources = manifestResources; DebugDocumentsBuilder = new DebugDocumentsBuilder(compilation.Options.SourceReferenceResolver, compilation.IsCaseSensitive); OutputKind = outputKind; SerializationProperties = serializationProperties; _methodBodyMap = new ConcurrentDictionary<IMethodSymbolInternal, Cci.IMethodBody>(ReferenceEqualityComparer.Instance); EmitOptions = emitOptions; } #nullable enable /// <summary> /// Symbol changes when emitting EnC delta. /// </summary> public abstract SymbolChanges? EncSymbolChanges { get; } /// <summary> /// Previous EnC generation baseline, or null if this is not EnC delta. /// </summary> public abstract EmitBaseline? PreviousGeneration { get; } /// <summary> /// True if this module is an EnC update. /// </summary> public bool IsEncDelta => PreviousGeneration != null; /// <summary> /// EnC generation. 0 if the module is not an EnC delta, 1 if it is the first EnC delta, etc. /// </summary> public int CurrentGenerationOrdinal => (PreviousGeneration?.Ordinal + 1) ?? 0; #nullable disable /// <summary> /// If this module represents an assembly, name of the assembly used in AssemblyDef table. Otherwise name of the module same as <see cref="ModuleName"/>. /// </summary> public abstract string Name { get; } /// <summary> /// Name of the module. Used in ModuleDef table. /// </summary> internal abstract string ModuleName { get; } internal abstract Cci.IAssemblyReference Translate(IAssemblySymbolInternal symbol, DiagnosticBag diagnostics); internal abstract Cci.ITypeReference Translate(ITypeSymbolInternal symbol, SyntaxNode syntaxOpt, DiagnosticBag diagnostics); internal abstract Cci.IMethodReference Translate(IMethodSymbolInternal symbol, DiagnosticBag diagnostics, bool needDeclaration); internal abstract bool SupportsPrivateImplClass { get; } internal abstract Compilation CommonCompilation { get; } internal abstract IModuleSymbolInternal CommonSourceModule { get; } internal abstract IAssemblySymbolInternal CommonCorLibrary { get; } internal abstract CommonModuleCompilationState CommonModuleCompilationState { get; } internal abstract void CompilationFinished(); internal abstract ImmutableDictionary<ISymbolInternal, ImmutableArray<ISymbolInternal>> GetAllSynthesizedMembers(); internal abstract CommonEmbeddedTypesManager CommonEmbeddedTypesManagerOpt { get; } internal abstract Cci.ITypeReference EncTranslateType(ITypeSymbolInternal type, DiagnosticBag diagnostics); public abstract IEnumerable<Cci.ICustomAttribute> GetSourceAssemblyAttributes(bool isRefAssembly); public abstract IEnumerable<Cci.SecurityAttribute> GetSourceAssemblySecurityAttributes(); public abstract IEnumerable<Cci.ICustomAttribute> GetSourceModuleAttributes(); internal abstract Cci.ICustomAttribute SynthesizeAttribute(WellKnownMember attributeConstructor); /// <summary> /// Public types defined in other modules making up this assembly and to which other assemblies may refer to via this assembly /// followed by types forwarded to another assembly. /// </summary> public abstract ImmutableArray<Cci.ExportedType> GetExportedTypes(DiagnosticBag diagnostics); /// <summary> /// Used to distinguish which style to pick while writing native PDB information. /// </summary> /// <remarks> /// The PDB content for custom debug information is different between Visual Basic and CSharp. /// E.g. C# always includes a CustomMetadata Header (MD2) that contains the namespace scope counts, where /// as VB only outputs namespace imports into the namespace scopes. /// C# defines forwards in that header, VB includes them into the scopes list. /// /// Currently the compiler doesn't allow mixing C# and VB method bodies. Thus this flag can be per module. /// It is possible to move this flag to per-method basis but native PDB CDI forwarding would need to be adjusted accordingly. /// </remarks> public abstract bool GenerateVisualBasicStylePdb { get; } /// <summary> /// Linked assembly names to be stored to native PDB (VB only). /// </summary> public abstract IEnumerable<string> LinkedAssembliesDebugInfo { get; } /// <summary> /// Project level imports (VB only, TODO: C# scripts). /// </summary> public abstract ImmutableArray<Cci.UsedNamespaceOrType> GetImports(); /// <summary> /// Default namespace (VB only). /// </summary> public abstract string DefaultNamespace { get; } protected abstract Cci.IAssemblyReference GetCorLibraryReferenceToEmit(EmitContext context); protected abstract IEnumerable<Cci.IAssemblyReference> GetAssemblyReferencesFromAddedModules(DiagnosticBag diagnostics); protected abstract void AddEmbeddedResourcesFromAddedModules(ArrayBuilder<Cci.ManagedResource> builder, DiagnosticBag diagnostics); public abstract Cci.ITypeReference GetPlatformType(Cci.PlatformType platformType, EmitContext context); public abstract bool IsPlatformType(Cci.ITypeReference typeRef, Cci.PlatformType platformType); public abstract IEnumerable<Cci.INamespaceTypeDefinition> GetTopLevelTypeDefinitions(EmitContext context); public IEnumerable<Cci.INamespaceTypeDefinition> GetTopLevelTypeDefinitionsCore(EmitContext context) { foreach (var typeDef in GetAdditionalTopLevelTypeDefinitions(context)) { yield return typeDef; } foreach (var typeDef in GetEmbeddedTypeDefinitions(context)) { yield return typeDef; } foreach (var typeDef in GetTopLevelSourceTypeDefinitions(context)) { yield return typeDef; } } /// <summary> /// Additional top-level types injected by the Expression Evaluators. /// </summary> public abstract IEnumerable<Cci.INamespaceTypeDefinition> GetAdditionalTopLevelTypeDefinitions(EmitContext context); /// <summary> /// Anonymous types defined in the compilation. /// </summary> public abstract IEnumerable<Cci.INamespaceTypeDefinition> GetAnonymousTypeDefinitions(EmitContext context); /// <summary> /// Top-level embedded types (e.g. attribute types that are not present in referenced assemblies). /// </summary> public abstract IEnumerable<Cci.INamespaceTypeDefinition> GetEmbeddedTypeDefinitions(EmitContext context); /// <summary> /// Top-level named types defined in source. /// </summary> public abstract IEnumerable<Cci.INamespaceTypeDefinition> GetTopLevelSourceTypeDefinitions(EmitContext context); /// <summary> /// A list of the files that constitute the assembly. Empty for netmodule. These are not the source language files that may have been /// used to compile the assembly, but the files that contain constituent modules of a multi-module assembly as well /// as any external resources. It corresponds to the File table of the .NET assembly file format. /// </summary> public abstract IEnumerable<Cci.IFileReference> GetFiles(EmitContext context); /// <summary> /// Builds symbol definition to location map used for emitting token -> location info /// into PDB to be consumed by WinMdExp.exe tool (only applicable for /t:winmdobj) /// </summary> public abstract MultiDictionary<Cci.DebugSourceDocument, Cci.DefinitionWithLocation> GetSymbolToLocationMap(); /// <summary> /// Number of debug documents in the module. /// Used to determine capacities of lists and indices when emitting debug info. /// </summary> public int DebugDocumentCount => DebugDocumentsBuilder.DebugDocumentCount; public void Dispatch(Cci.MetadataVisitor visitor) => visitor.Visit(this); IEnumerable<Cci.ICustomAttribute> Cci.IReference.GetAttributes(EmitContext context) => SpecializedCollections.EmptyEnumerable<Cci.ICustomAttribute>(); Cci.IDefinition Cci.IReference.AsDefinition(EmitContext context) { Debug.Assert(ReferenceEquals(context.Module, this)); return this; } Symbols.ISymbolInternal Cci.IReference.GetInternalSymbol() => null; public abstract ISourceAssemblySymbolInternal SourceAssemblyOpt { get; } /// <summary> /// An approximate number of method definitions that can /// provide a basis for approximating the capacities of /// various databases used during Emit. /// </summary> public int HintNumberOfMethodDefinitions // Try to guess at the size of tables to prevent re-allocation. The method body // map is pretty close, but unfortunately it tends to undercount. x1.5 seems like // a healthy amount of room based on compiling Roslyn. => (int)(_methodBodyMap.Count * 1.5); internal Cci.IMethodBody GetMethodBody(IMethodSymbolInternal methodSymbol) { Debug.Assert(methodSymbol.ContainingModule == CommonSourceModule); Debug.Assert(methodSymbol.IsDefinition); Debug.Assert(((IMethodSymbol)methodSymbol.GetISymbol()).PartialDefinitionPart == null); // Must be definition. Cci.IMethodBody body; if (_methodBodyMap.TryGetValue(methodSymbol, out body)) { return body; } return null; } public void SetMethodBody(IMethodSymbolInternal methodSymbol, Cci.IMethodBody body) { Debug.Assert(methodSymbol.ContainingModule == CommonSourceModule); Debug.Assert(methodSymbol.IsDefinition); Debug.Assert(((IMethodSymbol)methodSymbol.GetISymbol()).PartialDefinitionPart == null); // Must be definition. Debug.Assert(body == null || (object)methodSymbol == body.MethodDefinition.GetInternalSymbol()); _methodBodyMap.Add(methodSymbol, body); } internal void SetPEEntryPoint(IMethodSymbolInternal method, DiagnosticBag diagnostics) { Debug.Assert(method == null || IsSourceDefinition(method)); Debug.Assert(OutputKind.IsApplication()); PEEntryPoint = Translate(method, diagnostics, needDeclaration: true); } internal void SetDebugEntryPoint(IMethodSymbolInternal method, DiagnosticBag diagnostics) { Debug.Assert(method == null || IsSourceDefinition(method)); DebugEntryPoint = Translate(method, diagnostics, needDeclaration: true); } private bool IsSourceDefinition(IMethodSymbolInternal method) { return method.ContainingModule == CommonSourceModule && method.IsDefinition; } /// <summary> /// CorLibrary assembly referenced by this module. /// </summary> public Cci.IAssemblyReference GetCorLibrary(EmitContext context) { return Translate(CommonCorLibrary, context.Diagnostics); } public Cci.IAssemblyReference GetContainingAssembly(EmitContext context) { return OutputKind == OutputKind.NetModule ? null : (Cci.IAssemblyReference)this; } /// <summary> /// Returns User Strings referenced from the IL in the module. /// </summary> public IEnumerable<string> GetStrings() { return _stringsInILMap.GetAllItems(); } public uint GetFakeSymbolTokenForIL(Cci.IReference symbol, SyntaxNode syntaxNode, DiagnosticBag diagnostics) { uint token = _referencesInILMap.GetOrAddTokenFor(symbol, out bool added); if (added) { ReferenceDependencyWalker.VisitReference(symbol, new EmitContext(this, syntaxNode, diagnostics, metadataOnly: false, includePrivateMembers: true)); } return token; } public uint GetFakeSymbolTokenForIL(Cci.ISignature symbol, SyntaxNode syntaxNode, DiagnosticBag diagnostics) { uint token = _referencesInILMap.GetOrAddTokenFor(symbol, out bool added); if (added) { ReferenceDependencyWalker.VisitSignature(symbol, new EmitContext(this, syntaxNode, diagnostics, metadataOnly: false, includePrivateMembers: true)); } return token; } public uint GetSourceDocumentIndexForIL(Cci.DebugSourceDocument document) { return _sourceDocumentsInILMap.GetOrAddTokenFor(document); } internal Cci.DebugSourceDocument GetSourceDocumentFromIndex(uint token) { return _sourceDocumentsInILMap.GetItem(token); } public object GetReferenceFromToken(uint token) { return _referencesInILMap.GetItem(token); } public uint GetFakeStringTokenForIL(string str) { return _stringsInILMap.GetOrAddTokenFor(str); } public string GetStringFromToken(uint token) { return _stringsInILMap.GetItem(token); } public ReadOnlySpan<object> ReferencesInIL() { return _referencesInILMap.GetAllItems(); } /// <summary> /// Assembly reference aliases (C# only). /// </summary> public ImmutableArray<Cci.AssemblyReferenceAlias> GetAssemblyReferenceAliases(EmitContext context) { if (_lazyAssemblyReferenceAliases.IsDefault) { ImmutableInterlocked.InterlockedCompareExchange(ref _lazyAssemblyReferenceAliases, CalculateAssemblyReferenceAliases(context), default(ImmutableArray<Cci.AssemblyReferenceAlias>)); } return _lazyAssemblyReferenceAliases; } private ImmutableArray<Cci.AssemblyReferenceAlias> CalculateAssemblyReferenceAliases(EmitContext context) { var result = ArrayBuilder<Cci.AssemblyReferenceAlias>.GetInstance(); foreach (var assemblyAndAliases in CommonCompilation.GetBoundReferenceManager().GetReferencedAssemblyAliases()) { var assembly = assemblyAndAliases.Item1; var aliases = assemblyAndAliases.Item2; for (int i = 0; i < aliases.Length; i++) { string alias = aliases[i]; // filter out duplicates and global aliases: if (alias != MetadataReferenceProperties.GlobalAlias && aliases.IndexOf(alias, 0, i) < 0) { result.Add(new Cci.AssemblyReferenceAlias(alias, Translate(assembly, context.Diagnostics))); } } } return result.ToImmutableAndFree(); } public IEnumerable<Cci.IAssemblyReference> GetAssemblyReferences(EmitContext context) { Cci.IAssemblyReference corLibrary = GetCorLibraryReferenceToEmit(context); // Only add Cor Library reference explicitly, PeWriter will add // other references implicitly on as needed basis. if (corLibrary != null) { yield return corLibrary; } if (OutputKind != OutputKind.NetModule) { // Explicitly add references from added modules foreach (var aRef in GetAssemblyReferencesFromAddedModules(context.Diagnostics)) { yield return aRef; } } } public ImmutableArray<Cci.ManagedResource> GetResources(EmitContext context) { if (context.IsRefAssembly) { // Manifest resources are not included in ref assemblies // Ref assemblies don't support added modules return ImmutableArray<Cci.ManagedResource>.Empty; } if (_lazyManagedResources.IsDefault) { var builder = ArrayBuilder<Cci.ManagedResource>.GetInstance(); foreach (ResourceDescription r in ManifestResources) { builder.Add(r.ToManagedResource(this)); } if (OutputKind != OutputKind.NetModule) { // Explicitly add resources from added modules AddEmbeddedResourcesFromAddedModules(builder, context.Diagnostics); } _lazyManagedResources = builder.ToImmutableAndFree(); } return _lazyManagedResources; } public IEnumerable<EmbeddedText> EmbeddedTexts { get { return _embeddedTexts; } set { Debug.Assert(value != null); _embeddedTexts = value; } } internal bool SaveTestData => TestData != null; internal void SetMethodTestData(IMethodSymbolInternal method, ILBuilder builder) { TestData.Add(method, new CompilationTestData.MethodData(builder, method)); } internal void SetMethodTestData(ConcurrentDictionary<IMethodSymbolInternal, CompilationTestData.MethodData> methods) { Debug.Assert(TestData == null); TestData = methods; } public int GetTypeDefinitionGeneration(Cci.INamedTypeDefinition typeDef) { if (PreviousGeneration != null) { var symbolChanges = EncSymbolChanges!; if (symbolChanges.IsReplaced(typeDef)) { // Type emitted with Replace semantics in this delta, it's name should have the current generation ordinal suffix. return CurrentGenerationOrdinal; } var previousTypeDef = symbolChanges.DefinitionMap.MapDefinition(typeDef); if (previousTypeDef != null && PreviousGeneration.GenerationOrdinals.TryGetValue(previousTypeDef, out int lastEmittedOrdinal)) { // Type previously emitted with Replace semantics is now updated in-place. Use the ordinal used to emit the last version of the type. return lastEmittedOrdinal; } } return 0; } } /// <summary> /// Common base class for C# and VB PE module builder. /// </summary> internal abstract class PEModuleBuilder<TCompilation, TSourceModuleSymbol, TAssemblySymbol, TTypeSymbol, TNamedTypeSymbol, TMethodSymbol, TSyntaxNode, TEmbeddedTypesManager, TModuleCompilationState> : CommonPEModuleBuilder, ITokenDeferral where TCompilation : Compilation where TSourceModuleSymbol : class, IModuleSymbolInternal where TAssemblySymbol : class, IAssemblySymbolInternal where TTypeSymbol : class, ITypeSymbolInternal where TNamedTypeSymbol : class, TTypeSymbol, INamedTypeSymbolInternal where TMethodSymbol : class, IMethodSymbolInternal where TSyntaxNode : SyntaxNode where TEmbeddedTypesManager : CommonEmbeddedTypesManager where TModuleCompilationState : ModuleCompilationState<TNamedTypeSymbol, TMethodSymbol> { internal readonly TSourceModuleSymbol SourceModule; internal readonly TCompilation Compilation; private PrivateImplementationDetails _privateImplementationDetails; private ArrayMethods _lazyArrayMethods; private HashSet<string> _namesOfTopLevelTypes; internal readonly TModuleCompilationState CompilationState; public Cci.RootModuleType RootModuleType { get; } = new Cci.RootModuleType(); public abstract TEmbeddedTypesManager EmbeddedTypesManagerOpt { get; } protected PEModuleBuilder( TCompilation compilation, TSourceModuleSymbol sourceModule, Cci.ModulePropertiesForSerialization serializationProperties, IEnumerable<ResourceDescription> manifestResources, OutputKind outputKind, EmitOptions emitOptions, TModuleCompilationState compilationState) : base(manifestResources, emitOptions, outputKind, serializationProperties, compilation) { Debug.Assert(sourceModule != null); Debug.Assert(serializationProperties != null); Compilation = compilation; SourceModule = sourceModule; this.CompilationState = compilationState; } internal sealed override void CompilationFinished() { this.CompilationState.Freeze(); } internal override IAssemblySymbolInternal CommonCorLibrary => CorLibrary; internal abstract TAssemblySymbol CorLibrary { get; } internal abstract Cci.INamedTypeReference GetSpecialType(SpecialType specialType, TSyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics); internal sealed override Cci.ITypeReference EncTranslateType(ITypeSymbolInternal type, DiagnosticBag diagnostics) { return EncTranslateLocalVariableType((TTypeSymbol)type, diagnostics); } internal virtual Cci.ITypeReference EncTranslateLocalVariableType(TTypeSymbol type, DiagnosticBag diagnostics) { return Translate(type, null, diagnostics); } protected bool HaveDeterminedTopLevelTypes { get { return _namesOfTopLevelTypes != null; } } protected bool ContainsTopLevelType(string fullEmittedName) { return _namesOfTopLevelTypes.Contains(fullEmittedName); } /// <summary> /// Returns all top-level (not nested) types defined in the module. /// </summary> public override IEnumerable<Cci.INamespaceTypeDefinition> GetTopLevelTypeDefinitions(EmitContext context) { Cci.TypeReferenceIndexer typeReferenceIndexer = null; HashSet<string> names; // First time through, we need to collect emitted names of all top level types. if (_namesOfTopLevelTypes == null) { names = new HashSet<string>(); } else { names = null; } // First time through, we need to push things through TypeReferenceIndexer // to make sure we collect all to be embedded NoPia types and members. if (EmbeddedTypesManagerOpt != null && !EmbeddedTypesManagerOpt.IsFrozen) { typeReferenceIndexer = new Cci.TypeReferenceIndexer(context); Debug.Assert(names != null); // Run this reference indexer on the assembly- and module-level attributes first. // We'll run it on all other types below. // The purpose is to trigger Translate on all types. Dispatch(typeReferenceIndexer); } AddTopLevelType(names, RootModuleType); VisitTopLevelType(typeReferenceIndexer, RootModuleType); yield return RootModuleType; foreach (var typeDef in GetAnonymousTypeDefinitions(context)) { AddTopLevelType(names, typeDef); VisitTopLevelType(typeReferenceIndexer, typeDef); yield return typeDef; } foreach (var typeDef in GetTopLevelTypeDefinitionsCore(context)) { AddTopLevelType(names, typeDef); VisitTopLevelType(typeReferenceIndexer, typeDef); yield return typeDef; } var privateImpl = PrivateImplClass; if (privateImpl != null) { AddTopLevelType(names, privateImpl); VisitTopLevelType(typeReferenceIndexer, privateImpl); yield return privateImpl; } if (EmbeddedTypesManagerOpt != null) { foreach (var embedded in EmbeddedTypesManagerOpt.GetTypes(context.Diagnostics, names)) { AddTopLevelType(names, embedded); yield return embedded; } } if (names != null) { Debug.Assert(_namesOfTopLevelTypes == null); _namesOfTopLevelTypes = names; } static void AddTopLevelType(HashSet<string> names, Cci.INamespaceTypeDefinition type) // _namesOfTopLevelTypes are only used to generated exported types, which are not emitted in EnC deltas (hence generation 0): => names?.Add(MetadataHelpers.BuildQualifiedName(type.NamespaceName, Cci.MetadataWriter.GetMangledName(type, generation: 0))); } public virtual ImmutableArray<TNamedTypeSymbol> GetAdditionalTopLevelTypes() => ImmutableArray<TNamedTypeSymbol>.Empty; public virtual ImmutableArray<TNamedTypeSymbol> GetEmbeddedTypes(DiagnosticBag diagnostics) => ImmutableArray<TNamedTypeSymbol>.Empty; internal abstract Cci.IAssemblyReference Translate(TAssemblySymbol symbol, DiagnosticBag diagnostics); internal abstract Cci.ITypeReference Translate(TTypeSymbol symbol, TSyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics); internal abstract Cci.IMethodReference Translate(TMethodSymbol symbol, DiagnosticBag diagnostics, bool needDeclaration); internal sealed override Cci.IAssemblyReference Translate(IAssemblySymbolInternal symbol, DiagnosticBag diagnostics) { return Translate((TAssemblySymbol)symbol, diagnostics); } internal sealed override Cci.ITypeReference Translate(ITypeSymbolInternal symbol, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics) { return Translate((TTypeSymbol)symbol, (TSyntaxNode)syntaxNodeOpt, diagnostics); } internal sealed override Cci.IMethodReference Translate(IMethodSymbolInternal symbol, DiagnosticBag diagnostics, bool needDeclaration) { return Translate((TMethodSymbol)symbol, diagnostics, needDeclaration); } internal sealed override IModuleSymbolInternal CommonSourceModule => SourceModule; internal sealed override Compilation CommonCompilation => Compilation; internal sealed override CommonModuleCompilationState CommonModuleCompilationState => CompilationState; internal sealed override CommonEmbeddedTypesManager CommonEmbeddedTypesManagerOpt => EmbeddedTypesManagerOpt; internal MetadataConstant CreateConstant( TTypeSymbol type, object value, TSyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics) { return new MetadataConstant(Translate(type, syntaxNodeOpt, diagnostics), value); } private static void VisitTopLevelType(Cci.TypeReferenceIndexer noPiaIndexer, Cci.INamespaceTypeDefinition type) { noPiaIndexer?.Visit((Cci.ITypeDefinition)type); } internal Cci.IFieldReference GetModuleVersionId(Cci.ITypeReference mvidType, TSyntaxNode syntaxOpt, DiagnosticBag diagnostics) { PrivateImplementationDetails details = GetPrivateImplClass(syntaxOpt, diagnostics); EnsurePrivateImplementationDetailsStaticConstructor(details, syntaxOpt, diagnostics); return details.GetModuleVersionId(mvidType); } internal Cci.IFieldReference GetInstrumentationPayloadRoot(int analysisKind, Cci.ITypeReference payloadType, TSyntaxNode syntaxOpt, DiagnosticBag diagnostics) { PrivateImplementationDetails details = GetPrivateImplClass(syntaxOpt, diagnostics); EnsurePrivateImplementationDetailsStaticConstructor(details, syntaxOpt, diagnostics); return details.GetOrAddInstrumentationPayloadRoot(analysisKind, payloadType); } private void EnsurePrivateImplementationDetailsStaticConstructor(PrivateImplementationDetails details, TSyntaxNode syntaxOpt, DiagnosticBag diagnostics) { if (details.GetMethod(WellKnownMemberNames.StaticConstructorName) == null) { details.TryAddSynthesizedMethod(CreatePrivateImplementationDetailsStaticConstructor(details, syntaxOpt, diagnostics)); } } protected abstract Cci.IMethodDefinition CreatePrivateImplementationDetailsStaticConstructor(PrivateImplementationDetails details, TSyntaxNode syntaxOpt, DiagnosticBag diagnostics); #region Synthesized Members /// <summary> /// Captures the set of synthesized definitions that should be added to a type /// during emit process. /// </summary> private sealed class SynthesizedDefinitions { public ConcurrentQueue<Cci.INestedTypeDefinition> NestedTypes; public ConcurrentQueue<Cci.IMethodDefinition> Methods; public ConcurrentQueue<Cci.IPropertyDefinition> Properties; public ConcurrentQueue<Cci.IFieldDefinition> Fields; public ImmutableArray<ISymbolInternal> GetAllMembers() { var builder = ArrayBuilder<ISymbolInternal>.GetInstance(); if (Fields != null) { foreach (var field in Fields) { builder.Add(field.GetInternalSymbol()); } } if (Methods != null) { foreach (var method in Methods) { builder.Add(method.GetInternalSymbol()); } } if (Properties != null) { foreach (var property in Properties) { builder.Add(property.GetInternalSymbol()); } } if (NestedTypes != null) { foreach (var type in NestedTypes) { builder.Add(type.GetInternalSymbol()); } } return builder.ToImmutableAndFree(); } } private readonly ConcurrentDictionary<TNamedTypeSymbol, SynthesizedDefinitions> _synthesizedTypeMembers = new ConcurrentDictionary<TNamedTypeSymbol, SynthesizedDefinitions>(ReferenceEqualityComparer.Instance); private ConcurrentDictionary<INamespaceSymbolInternal, ConcurrentQueue<INamespaceOrTypeSymbolInternal>> _lazySynthesizedNamespaceMembers; internal abstract IEnumerable<Cci.INestedTypeDefinition> GetSynthesizedNestedTypes(TNamedTypeSymbol container); /// <summary> /// Returns null if there are no compiler generated types. /// </summary> public IEnumerable<Cci.INestedTypeDefinition> GetSynthesizedTypes(TNamedTypeSymbol container) { IEnumerable<Cci.INestedTypeDefinition> declareTypes = GetSynthesizedNestedTypes(container); IEnumerable<Cci.INestedTypeDefinition> compileEmitTypes = null; if (_synthesizedTypeMembers.TryGetValue(container, out var defs)) { compileEmitTypes = defs.NestedTypes; } if (declareTypes == null) { return compileEmitTypes; } if (compileEmitTypes == null) { return declareTypes; } return declareTypes.Concat(compileEmitTypes); } private SynthesizedDefinitions GetOrAddSynthesizedDefinitions(TNamedTypeSymbol container) { Debug.Assert(container.IsDefinition); return _synthesizedTypeMembers.GetOrAdd(container, _ => new SynthesizedDefinitions()); } public void AddSynthesizedDefinition(TNamedTypeSymbol container, Cci.IMethodDefinition method) { Debug.Assert(method != null); SynthesizedDefinitions defs = GetOrAddSynthesizedDefinitions(container); if (defs.Methods == null) { Interlocked.CompareExchange(ref defs.Methods, new ConcurrentQueue<Cci.IMethodDefinition>(), null); } defs.Methods.Enqueue(method); } public void AddSynthesizedDefinition(TNamedTypeSymbol container, Cci.IPropertyDefinition property) { Debug.Assert(property != null); SynthesizedDefinitions defs = GetOrAddSynthesizedDefinitions(container); if (defs.Properties == null) { Interlocked.CompareExchange(ref defs.Properties, new ConcurrentQueue<Cci.IPropertyDefinition>(), null); } defs.Properties.Enqueue(property); } public void AddSynthesizedDefinition(TNamedTypeSymbol container, Cci.IFieldDefinition field) { Debug.Assert(field != null); SynthesizedDefinitions defs = GetOrAddSynthesizedDefinitions(container); if (defs.Fields == null) { Interlocked.CompareExchange(ref defs.Fields, new ConcurrentQueue<Cci.IFieldDefinition>(), null); } defs.Fields.Enqueue(field); } public void AddSynthesizedDefinition(TNamedTypeSymbol container, Cci.INestedTypeDefinition nestedType) { Debug.Assert(nestedType != null); SynthesizedDefinitions defs = GetOrAddSynthesizedDefinitions(container); if (defs.NestedTypes == null) { Interlocked.CompareExchange(ref defs.NestedTypes, new ConcurrentQueue<Cci.INestedTypeDefinition>(), null); } defs.NestedTypes.Enqueue(nestedType); } public void AddSynthesizedDefinition(INamespaceSymbolInternal container, INamespaceOrTypeSymbolInternal typeOrNamespace) { Debug.Assert(typeOrNamespace != null); if (_lazySynthesizedNamespaceMembers == null) { Interlocked.CompareExchange(ref _lazySynthesizedNamespaceMembers, new ConcurrentDictionary<INamespaceSymbolInternal, ConcurrentQueue<INamespaceOrTypeSymbolInternal>>(), null); } _lazySynthesizedNamespaceMembers.GetOrAdd(container, _ => new ConcurrentQueue<INamespaceOrTypeSymbolInternal>()).Enqueue(typeOrNamespace); } /// <summary> /// Returns null if there are no synthesized fields. /// </summary> public IEnumerable<Cci.IFieldDefinition> GetSynthesizedFields(TNamedTypeSymbol container) => _synthesizedTypeMembers.TryGetValue(container, out var defs) ? defs.Fields : null; /// <summary> /// Returns null if there are no synthesized properties. /// </summary> public IEnumerable<Cci.IPropertyDefinition> GetSynthesizedProperties(TNamedTypeSymbol container) => _synthesizedTypeMembers.TryGetValue(container, out var defs) ? defs.Properties : null; /// <summary> /// Returns null if there are no synthesized methods. /// </summary> public IEnumerable<Cci.IMethodDefinition> GetSynthesizedMethods(TNamedTypeSymbol container) => _synthesizedTypeMembers.TryGetValue(container, out var defs) ? defs.Methods : null; internal override ImmutableDictionary<ISymbolInternal, ImmutableArray<ISymbolInternal>> GetAllSynthesizedMembers() { var builder = ImmutableDictionary.CreateBuilder<ISymbolInternal, ImmutableArray<ISymbolInternal>>(); foreach (var entry in _synthesizedTypeMembers) { builder.Add(entry.Key, entry.Value.GetAllMembers()); } var namespaceMembers = _lazySynthesizedNamespaceMembers; if (namespaceMembers != null) { foreach (var entry in namespaceMembers) { builder.Add(entry.Key, entry.Value.ToImmutableArray<ISymbolInternal>()); } } return builder.ToImmutable(); } #endregion #region Token Mapping Cci.IFieldReference ITokenDeferral.GetFieldForData(ImmutableArray<byte> data, SyntaxNode syntaxNode, DiagnosticBag diagnostics) { Debug.Assert(this.SupportsPrivateImplClass); var privateImpl = this.GetPrivateImplClass((TSyntaxNode)syntaxNode, diagnostics); // map a field to the block (that makes it addressable via a token) return privateImpl.CreateDataField(data); } public abstract Cci.IMethodReference GetInitArrayHelper(); public ArrayMethods ArrayMethods { get { ArrayMethods result = _lazyArrayMethods; if (result == null) { result = new ArrayMethods(); if (Interlocked.CompareExchange(ref _lazyArrayMethods, result, null) != null) { result = _lazyArrayMethods; } } return result; } } #endregion #region Private Implementation Details Type internal PrivateImplementationDetails GetPrivateImplClass(TSyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics) { var result = _privateImplementationDetails; if ((result == null) && this.SupportsPrivateImplClass) { result = new PrivateImplementationDetails( this, this.SourceModule.Name, Compilation.GetSubmissionSlotIndex(), this.GetSpecialType(SpecialType.System_Object, syntaxNodeOpt, diagnostics), this.GetSpecialType(SpecialType.System_ValueType, syntaxNodeOpt, diagnostics), this.GetSpecialType(SpecialType.System_Byte, syntaxNodeOpt, diagnostics), this.GetSpecialType(SpecialType.System_Int16, syntaxNodeOpt, diagnostics), this.GetSpecialType(SpecialType.System_Int32, syntaxNodeOpt, diagnostics), this.GetSpecialType(SpecialType.System_Int64, syntaxNodeOpt, diagnostics), SynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_CompilerGeneratedAttribute__ctor)); if (Interlocked.CompareExchange(ref _privateImplementationDetails, result, null) != null) { result = _privateImplementationDetails; } } return result; } internal PrivateImplementationDetails PrivateImplClass { get { return _privateImplementationDetails; } } internal override bool SupportsPrivateImplClass { get { return true; } } #endregion public sealed override Cci.ITypeReference GetPlatformType(Cci.PlatformType platformType, EmitContext context) { Debug.Assert((object)this == context.Module); switch (platformType) { case Cci.PlatformType.SystemType: throw ExceptionUtilities.UnexpectedValue(platformType); default: return GetSpecialType((SpecialType)platformType, (TSyntaxNode)context.SyntaxNode, context.Diagnostics); } } } }
// Licensed to the .NET Foundation under one or more 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.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.IO; using System.Linq; using System.Security.Cryptography; using System.Threading; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.Emit.NoPia; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Symbols; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Emit { internal abstract class CommonPEModuleBuilder : Cci.IUnit, Cci.IModuleReference { internal readonly DebugDocumentsBuilder DebugDocumentsBuilder; internal readonly IEnumerable<ResourceDescription> ManifestResources; internal readonly Cci.ModulePropertiesForSerialization SerializationProperties; internal readonly OutputKind OutputKind; internal Stream RawWin32Resources; internal IEnumerable<Cci.IWin32Resource> Win32Resources; internal Cci.ResourceSection Win32ResourceSection; internal Stream SourceLinkStreamOpt; internal Cci.IMethodReference PEEntryPoint; internal Cci.IMethodReference DebugEntryPoint; private readonly ConcurrentDictionary<IMethodSymbolInternal, Cci.IMethodBody> _methodBodyMap; private readonly TokenMap _referencesInILMap = new(); private readonly ItemTokenMap<string> _stringsInILMap = new(); private readonly ItemTokenMap<Cci.DebugSourceDocument> _sourceDocumentsInILMap = new(); private ImmutableArray<Cci.AssemblyReferenceAlias> _lazyAssemblyReferenceAliases; private ImmutableArray<Cci.ManagedResource> _lazyManagedResources; private IEnumerable<EmbeddedText> _embeddedTexts = SpecializedCollections.EmptyEnumerable<EmbeddedText>(); // Only set when running tests to allow realized IL for a given method to be looked up by method. internal ConcurrentDictionary<IMethodSymbolInternal, CompilationTestData.MethodData> TestData { get; private set; } internal EmitOptions EmitOptions { get; } internal DebugInformationFormat DebugInformationFormat => EmitOptions.DebugInformationFormat; internal HashAlgorithmName PdbChecksumAlgorithm => EmitOptions.PdbChecksumAlgorithm; public CommonPEModuleBuilder( IEnumerable<ResourceDescription> manifestResources, EmitOptions emitOptions, OutputKind outputKind, Cci.ModulePropertiesForSerialization serializationProperties, Compilation compilation) { Debug.Assert(manifestResources != null); Debug.Assert(serializationProperties != null); Debug.Assert(compilation != null); ManifestResources = manifestResources; DebugDocumentsBuilder = new DebugDocumentsBuilder(compilation.Options.SourceReferenceResolver, compilation.IsCaseSensitive); OutputKind = outputKind; SerializationProperties = serializationProperties; _methodBodyMap = new ConcurrentDictionary<IMethodSymbolInternal, Cci.IMethodBody>(ReferenceEqualityComparer.Instance); EmitOptions = emitOptions; } #nullable enable /// <summary> /// Symbol changes when emitting EnC delta. /// </summary> public abstract SymbolChanges? EncSymbolChanges { get; } /// <summary> /// Previous EnC generation baseline, or null if this is not EnC delta. /// </summary> public abstract EmitBaseline? PreviousGeneration { get; } /// <summary> /// True if this module is an EnC update. /// </summary> public bool IsEncDelta => PreviousGeneration != null; /// <summary> /// EnC generation. 0 if the module is not an EnC delta, 1 if it is the first EnC delta, etc. /// </summary> public int CurrentGenerationOrdinal => (PreviousGeneration?.Ordinal + 1) ?? 0; #nullable disable /// <summary> /// If this module represents an assembly, name of the assembly used in AssemblyDef table. Otherwise name of the module same as <see cref="ModuleName"/>. /// </summary> public abstract string Name { get; } /// <summary> /// Name of the module. Used in ModuleDef table. /// </summary> internal abstract string ModuleName { get; } internal abstract Cci.IAssemblyReference Translate(IAssemblySymbolInternal symbol, DiagnosticBag diagnostics); internal abstract Cci.ITypeReference Translate(ITypeSymbolInternal symbol, SyntaxNode syntaxOpt, DiagnosticBag diagnostics); internal abstract Cci.IMethodReference Translate(IMethodSymbolInternal symbol, DiagnosticBag diagnostics, bool needDeclaration); internal abstract bool SupportsPrivateImplClass { get; } internal abstract Compilation CommonCompilation { get; } internal abstract IModuleSymbolInternal CommonSourceModule { get; } internal abstract IAssemblySymbolInternal CommonCorLibrary { get; } internal abstract CommonModuleCompilationState CommonModuleCompilationState { get; } internal abstract void CompilationFinished(); internal abstract ImmutableDictionary<ISymbolInternal, ImmutableArray<ISymbolInternal>> GetAllSynthesizedMembers(); internal abstract CommonEmbeddedTypesManager CommonEmbeddedTypesManagerOpt { get; } internal abstract Cci.ITypeReference EncTranslateType(ITypeSymbolInternal type, DiagnosticBag diagnostics); public abstract IEnumerable<Cci.ICustomAttribute> GetSourceAssemblyAttributes(bool isRefAssembly); public abstract IEnumerable<Cci.SecurityAttribute> GetSourceAssemblySecurityAttributes(); public abstract IEnumerable<Cci.ICustomAttribute> GetSourceModuleAttributes(); internal abstract Cci.ICustomAttribute SynthesizeAttribute(WellKnownMember attributeConstructor); /// <summary> /// Public types defined in other modules making up this assembly and to which other assemblies may refer to via this assembly /// followed by types forwarded to another assembly. /// </summary> public abstract ImmutableArray<Cci.ExportedType> GetExportedTypes(DiagnosticBag diagnostics); /// <summary> /// Used to distinguish which style to pick while writing native PDB information. /// </summary> /// <remarks> /// The PDB content for custom debug information is different between Visual Basic and CSharp. /// E.g. C# always includes a CustomMetadata Header (MD2) that contains the namespace scope counts, where /// as VB only outputs namespace imports into the namespace scopes. /// C# defines forwards in that header, VB includes them into the scopes list. /// /// Currently the compiler doesn't allow mixing C# and VB method bodies. Thus this flag can be per module. /// It is possible to move this flag to per-method basis but native PDB CDI forwarding would need to be adjusted accordingly. /// </remarks> public abstract bool GenerateVisualBasicStylePdb { get; } /// <summary> /// Linked assembly names to be stored to native PDB (VB only). /// </summary> public abstract IEnumerable<string> LinkedAssembliesDebugInfo { get; } /// <summary> /// Project level imports (VB only, TODO: C# scripts). /// </summary> public abstract ImmutableArray<Cci.UsedNamespaceOrType> GetImports(); /// <summary> /// Default namespace (VB only). /// </summary> public abstract string DefaultNamespace { get; } protected abstract Cci.IAssemblyReference GetCorLibraryReferenceToEmit(EmitContext context); protected abstract IEnumerable<Cci.IAssemblyReference> GetAssemblyReferencesFromAddedModules(DiagnosticBag diagnostics); protected abstract void AddEmbeddedResourcesFromAddedModules(ArrayBuilder<Cci.ManagedResource> builder, DiagnosticBag diagnostics); public abstract Cci.ITypeReference GetPlatformType(Cci.PlatformType platformType, EmitContext context); public abstract bool IsPlatformType(Cci.ITypeReference typeRef, Cci.PlatformType platformType); public abstract IEnumerable<Cci.INamespaceTypeDefinition> GetTopLevelTypeDefinitions(EmitContext context); public IEnumerable<Cci.INamespaceTypeDefinition> GetTopLevelTypeDefinitionsCore(EmitContext context) { foreach (var typeDef in GetAdditionalTopLevelTypeDefinitions(context)) { yield return typeDef; } foreach (var typeDef in GetEmbeddedTypeDefinitions(context)) { yield return typeDef; } foreach (var typeDef in GetTopLevelSourceTypeDefinitions(context)) { yield return typeDef; } } /// <summary> /// Additional top-level types injected by the Expression Evaluators. /// </summary> public abstract IEnumerable<Cci.INamespaceTypeDefinition> GetAdditionalTopLevelTypeDefinitions(EmitContext context); /// <summary> /// Anonymous types defined in the compilation. /// </summary> public abstract IEnumerable<Cci.INamespaceTypeDefinition> GetAnonymousTypeDefinitions(EmitContext context); /// <summary> /// Top-level embedded types (e.g. attribute types that are not present in referenced assemblies). /// </summary> public abstract IEnumerable<Cci.INamespaceTypeDefinition> GetEmbeddedTypeDefinitions(EmitContext context); /// <summary> /// Top-level named types defined in source. /// </summary> public abstract IEnumerable<Cci.INamespaceTypeDefinition> GetTopLevelSourceTypeDefinitions(EmitContext context); /// <summary> /// A list of the files that constitute the assembly. Empty for netmodule. These are not the source language files that may have been /// used to compile the assembly, but the files that contain constituent modules of a multi-module assembly as well /// as any external resources. It corresponds to the File table of the .NET assembly file format. /// </summary> public abstract IEnumerable<Cci.IFileReference> GetFiles(EmitContext context); /// <summary> /// Builds symbol definition to location map used for emitting token -> location info /// into PDB to be consumed by WinMdExp.exe tool (only applicable for /t:winmdobj) /// </summary> public abstract MultiDictionary<Cci.DebugSourceDocument, Cci.DefinitionWithLocation> GetSymbolToLocationMap(); /// <summary> /// Number of debug documents in the module. /// Used to determine capacities of lists and indices when emitting debug info. /// </summary> public int DebugDocumentCount => DebugDocumentsBuilder.DebugDocumentCount; public void Dispatch(Cci.MetadataVisitor visitor) => visitor.Visit(this); IEnumerable<Cci.ICustomAttribute> Cci.IReference.GetAttributes(EmitContext context) => SpecializedCollections.EmptyEnumerable<Cci.ICustomAttribute>(); Cci.IDefinition Cci.IReference.AsDefinition(EmitContext context) { Debug.Assert(ReferenceEquals(context.Module, this)); return this; } Symbols.ISymbolInternal Cci.IReference.GetInternalSymbol() => null; public abstract ISourceAssemblySymbolInternal SourceAssemblyOpt { get; } /// <summary> /// An approximate number of method definitions that can /// provide a basis for approximating the capacities of /// various databases used during Emit. /// </summary> public int HintNumberOfMethodDefinitions // Try to guess at the size of tables to prevent re-allocation. The method body // map is pretty close, but unfortunately it tends to undercount. x1.5 seems like // a healthy amount of room based on compiling Roslyn. => (int)(_methodBodyMap.Count * 1.5); internal Cci.IMethodBody GetMethodBody(IMethodSymbolInternal methodSymbol) { Debug.Assert(methodSymbol.ContainingModule == CommonSourceModule); Debug.Assert(methodSymbol.IsDefinition); Debug.Assert(((IMethodSymbol)methodSymbol.GetISymbol()).PartialDefinitionPart == null); // Must be definition. Cci.IMethodBody body; if (_methodBodyMap.TryGetValue(methodSymbol, out body)) { return body; } return null; } public void SetMethodBody(IMethodSymbolInternal methodSymbol, Cci.IMethodBody body) { Debug.Assert(methodSymbol.ContainingModule == CommonSourceModule); Debug.Assert(methodSymbol.IsDefinition); Debug.Assert(((IMethodSymbol)methodSymbol.GetISymbol()).PartialDefinitionPart == null); // Must be definition. Debug.Assert(body == null || (object)methodSymbol == body.MethodDefinition.GetInternalSymbol()); _methodBodyMap.Add(methodSymbol, body); } internal void SetPEEntryPoint(IMethodSymbolInternal method, DiagnosticBag diagnostics) { Debug.Assert(method == null || IsSourceDefinition(method)); Debug.Assert(OutputKind.IsApplication()); PEEntryPoint = Translate(method, diagnostics, needDeclaration: true); } internal void SetDebugEntryPoint(IMethodSymbolInternal method, DiagnosticBag diagnostics) { Debug.Assert(method == null || IsSourceDefinition(method)); DebugEntryPoint = Translate(method, diagnostics, needDeclaration: true); } private bool IsSourceDefinition(IMethodSymbolInternal method) { return method.ContainingModule == CommonSourceModule && method.IsDefinition; } /// <summary> /// CorLibrary assembly referenced by this module. /// </summary> public Cci.IAssemblyReference GetCorLibrary(EmitContext context) { return Translate(CommonCorLibrary, context.Diagnostics); } public Cci.IAssemblyReference GetContainingAssembly(EmitContext context) { return OutputKind == OutputKind.NetModule ? null : (Cci.IAssemblyReference)this; } /// <summary> /// Returns User Strings referenced from the IL in the module. /// </summary> public IEnumerable<string> GetStrings() { return _stringsInILMap.GetAllItems(); } public uint GetFakeSymbolTokenForIL(Cci.IReference symbol, SyntaxNode syntaxNode, DiagnosticBag diagnostics) { uint token = _referencesInILMap.GetOrAddTokenFor(symbol, out bool added); if (added) { ReferenceDependencyWalker.VisitReference(symbol, new EmitContext(this, syntaxNode, diagnostics, metadataOnly: false, includePrivateMembers: true)); } return token; } public uint GetFakeSymbolTokenForIL(Cci.ISignature symbol, SyntaxNode syntaxNode, DiagnosticBag diagnostics) { uint token = _referencesInILMap.GetOrAddTokenFor(symbol, out bool added); if (added) { ReferenceDependencyWalker.VisitSignature(symbol, new EmitContext(this, syntaxNode, diagnostics, metadataOnly: false, includePrivateMembers: true)); } return token; } public uint GetSourceDocumentIndexForIL(Cci.DebugSourceDocument document) { return _sourceDocumentsInILMap.GetOrAddTokenFor(document); } internal Cci.DebugSourceDocument GetSourceDocumentFromIndex(uint token) { return _sourceDocumentsInILMap.GetItem(token); } public object GetReferenceFromToken(uint token) { return _referencesInILMap.GetItem(token); } public uint GetFakeStringTokenForIL(string str) { return _stringsInILMap.GetOrAddTokenFor(str); } public string GetStringFromToken(uint token) { return _stringsInILMap.GetItem(token); } public ReadOnlySpan<object> ReferencesInIL() { return _referencesInILMap.GetAllItems(); } /// <summary> /// Assembly reference aliases (C# only). /// </summary> public ImmutableArray<Cci.AssemblyReferenceAlias> GetAssemblyReferenceAliases(EmitContext context) { if (_lazyAssemblyReferenceAliases.IsDefault) { ImmutableInterlocked.InterlockedCompareExchange(ref _lazyAssemblyReferenceAliases, CalculateAssemblyReferenceAliases(context), default(ImmutableArray<Cci.AssemblyReferenceAlias>)); } return _lazyAssemblyReferenceAliases; } private ImmutableArray<Cci.AssemblyReferenceAlias> CalculateAssemblyReferenceAliases(EmitContext context) { var result = ArrayBuilder<Cci.AssemblyReferenceAlias>.GetInstance(); foreach (var assemblyAndAliases in CommonCompilation.GetBoundReferenceManager().GetReferencedAssemblyAliases()) { var assembly = assemblyAndAliases.Item1; var aliases = assemblyAndAliases.Item2; for (int i = 0; i < aliases.Length; i++) { string alias = aliases[i]; // filter out duplicates and global aliases: if (alias != MetadataReferenceProperties.GlobalAlias && aliases.IndexOf(alias, 0, i) < 0) { result.Add(new Cci.AssemblyReferenceAlias(alias, Translate(assembly, context.Diagnostics))); } } } return result.ToImmutableAndFree(); } public IEnumerable<Cci.IAssemblyReference> GetAssemblyReferences(EmitContext context) { Cci.IAssemblyReference corLibrary = GetCorLibraryReferenceToEmit(context); // Only add Cor Library reference explicitly, PeWriter will add // other references implicitly on as needed basis. if (corLibrary != null) { yield return corLibrary; } if (OutputKind != OutputKind.NetModule) { // Explicitly add references from added modules foreach (var aRef in GetAssemblyReferencesFromAddedModules(context.Diagnostics)) { yield return aRef; } } } public ImmutableArray<Cci.ManagedResource> GetResources(EmitContext context) { if (context.IsRefAssembly) { // Manifest resources are not included in ref assemblies // Ref assemblies don't support added modules return ImmutableArray<Cci.ManagedResource>.Empty; } if (_lazyManagedResources.IsDefault) { var builder = ArrayBuilder<Cci.ManagedResource>.GetInstance(); foreach (ResourceDescription r in ManifestResources) { builder.Add(r.ToManagedResource(this)); } if (OutputKind != OutputKind.NetModule) { // Explicitly add resources from added modules AddEmbeddedResourcesFromAddedModules(builder, context.Diagnostics); } _lazyManagedResources = builder.ToImmutableAndFree(); } return _lazyManagedResources; } public IEnumerable<EmbeddedText> EmbeddedTexts { get { return _embeddedTexts; } set { Debug.Assert(value != null); _embeddedTexts = value; } } internal bool SaveTestData => TestData != null; internal void SetMethodTestData(IMethodSymbolInternal method, ILBuilder builder) { TestData.Add(method, new CompilationTestData.MethodData(builder, method)); } internal void SetMethodTestData(ConcurrentDictionary<IMethodSymbolInternal, CompilationTestData.MethodData> methods) { Debug.Assert(TestData == null); TestData = methods; } public int GetTypeDefinitionGeneration(Cci.INamedTypeDefinition typeDef) { if (PreviousGeneration != null) { var symbolChanges = EncSymbolChanges!; if (symbolChanges.IsReplaced(typeDef)) { // Type emitted with Replace semantics in this delta, it's name should have the current generation ordinal suffix. return CurrentGenerationOrdinal; } var previousTypeDef = symbolChanges.DefinitionMap.MapDefinition(typeDef); if (previousTypeDef != null && PreviousGeneration.GenerationOrdinals.TryGetValue(previousTypeDef, out int lastEmittedOrdinal)) { // Type previously emitted with Replace semantics is now updated in-place. Use the ordinal used to emit the last version of the type. return lastEmittedOrdinal; } } return 0; } } /// <summary> /// Common base class for C# and VB PE module builder. /// </summary> internal abstract class PEModuleBuilder<TCompilation, TSourceModuleSymbol, TAssemblySymbol, TTypeSymbol, TNamedTypeSymbol, TMethodSymbol, TSyntaxNode, TEmbeddedTypesManager, TModuleCompilationState> : CommonPEModuleBuilder, ITokenDeferral where TCompilation : Compilation where TSourceModuleSymbol : class, IModuleSymbolInternal where TAssemblySymbol : class, IAssemblySymbolInternal where TTypeSymbol : class, ITypeSymbolInternal where TNamedTypeSymbol : class, TTypeSymbol, INamedTypeSymbolInternal where TMethodSymbol : class, IMethodSymbolInternal where TSyntaxNode : SyntaxNode where TEmbeddedTypesManager : CommonEmbeddedTypesManager where TModuleCompilationState : ModuleCompilationState<TNamedTypeSymbol, TMethodSymbol> { internal readonly TSourceModuleSymbol SourceModule; internal readonly TCompilation Compilation; private PrivateImplementationDetails _privateImplementationDetails; private ArrayMethods _lazyArrayMethods; private HashSet<string> _namesOfTopLevelTypes; internal readonly TModuleCompilationState CompilationState; private readonly Cci.RootModuleType _rootModuleType; public abstract TEmbeddedTypesManager EmbeddedTypesManagerOpt { get; } protected PEModuleBuilder( TCompilation compilation, TSourceModuleSymbol sourceModule, Cci.ModulePropertiesForSerialization serializationProperties, IEnumerable<ResourceDescription> manifestResources, OutputKind outputKind, EmitOptions emitOptions, TModuleCompilationState compilationState) : base(manifestResources, emitOptions, outputKind, serializationProperties, compilation) { Debug.Assert(sourceModule != null); Debug.Assert(serializationProperties != null); Compilation = compilation; SourceModule = sourceModule; this.CompilationState = compilationState; _rootModuleType = new Cci.RootModuleType(this); } public Cci.RootModuleType RootModuleType => _rootModuleType; internal sealed override void CompilationFinished() { this.CompilationState.Freeze(); } internal override IAssemblySymbolInternal CommonCorLibrary => CorLibrary; internal abstract TAssemblySymbol CorLibrary { get; } internal abstract Cci.INamedTypeReference GetSpecialType(SpecialType specialType, TSyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics); internal sealed override Cci.ITypeReference EncTranslateType(ITypeSymbolInternal type, DiagnosticBag diagnostics) { return EncTranslateLocalVariableType((TTypeSymbol)type, diagnostics); } internal virtual Cci.ITypeReference EncTranslateLocalVariableType(TTypeSymbol type, DiagnosticBag diagnostics) { return Translate(type, null, diagnostics); } protected bool HaveDeterminedTopLevelTypes { get { return _namesOfTopLevelTypes != null; } } protected bool ContainsTopLevelType(string fullEmittedName) { return _namesOfTopLevelTypes.Contains(fullEmittedName); } /// <summary> /// Returns all top-level (not nested) types defined in the module. /// </summary> public override IEnumerable<Cci.INamespaceTypeDefinition> GetTopLevelTypeDefinitions(EmitContext context) { Cci.TypeReferenceIndexer typeReferenceIndexer = null; HashSet<string> names; // First time through, we need to collect emitted names of all top level types. if (_namesOfTopLevelTypes == null) { names = new HashSet<string>(); } else { names = null; } // First time through, we need to push things through TypeReferenceIndexer // to make sure we collect all to be embedded NoPia types and members. if (EmbeddedTypesManagerOpt != null && !EmbeddedTypesManagerOpt.IsFrozen) { typeReferenceIndexer = new Cci.TypeReferenceIndexer(context); Debug.Assert(names != null); // Run this reference indexer on the assembly- and module-level attributes first. // We'll run it on all other types below. // The purpose is to trigger Translate on all types. Dispatch(typeReferenceIndexer); } AddTopLevelType(names, RootModuleType); VisitTopLevelType(typeReferenceIndexer, RootModuleType); yield return RootModuleType; foreach (var typeDef in GetAnonymousTypeDefinitions(context)) { AddTopLevelType(names, typeDef); VisitTopLevelType(typeReferenceIndexer, typeDef); yield return typeDef; } foreach (var typeDef in GetTopLevelTypeDefinitionsCore(context)) { AddTopLevelType(names, typeDef); VisitTopLevelType(typeReferenceIndexer, typeDef); yield return typeDef; } var privateImpl = PrivateImplClass; if (privateImpl != null) { AddTopLevelType(names, privateImpl); VisitTopLevelType(typeReferenceIndexer, privateImpl); yield return privateImpl; } if (EmbeddedTypesManagerOpt != null) { foreach (var embedded in EmbeddedTypesManagerOpt.GetTypes(context.Diagnostics, names)) { AddTopLevelType(names, embedded); yield return embedded; } } if (names != null) { Debug.Assert(_namesOfTopLevelTypes == null); _namesOfTopLevelTypes = names; } static void AddTopLevelType(HashSet<string> names, Cci.INamespaceTypeDefinition type) // _namesOfTopLevelTypes are only used to generated exported types, which are not emitted in EnC deltas (hence generation 0): => names?.Add(MetadataHelpers.BuildQualifiedName(type.NamespaceName, Cci.MetadataWriter.GetMangledName(type, generation: 0))); } public virtual ImmutableArray<TNamedTypeSymbol> GetAdditionalTopLevelTypes() => ImmutableArray<TNamedTypeSymbol>.Empty; public virtual ImmutableArray<TNamedTypeSymbol> GetEmbeddedTypes(DiagnosticBag diagnostics) => ImmutableArray<TNamedTypeSymbol>.Empty; internal abstract Cci.IAssemblyReference Translate(TAssemblySymbol symbol, DiagnosticBag diagnostics); internal abstract Cci.ITypeReference Translate(TTypeSymbol symbol, TSyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics); internal abstract Cci.IMethodReference Translate(TMethodSymbol symbol, DiagnosticBag diagnostics, bool needDeclaration); internal sealed override Cci.IAssemblyReference Translate(IAssemblySymbolInternal symbol, DiagnosticBag diagnostics) { return Translate((TAssemblySymbol)symbol, diagnostics); } internal sealed override Cci.ITypeReference Translate(ITypeSymbolInternal symbol, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics) { return Translate((TTypeSymbol)symbol, (TSyntaxNode)syntaxNodeOpt, diagnostics); } internal sealed override Cci.IMethodReference Translate(IMethodSymbolInternal symbol, DiagnosticBag diagnostics, bool needDeclaration) { return Translate((TMethodSymbol)symbol, diagnostics, needDeclaration); } internal sealed override IModuleSymbolInternal CommonSourceModule => SourceModule; internal sealed override Compilation CommonCompilation => Compilation; internal sealed override CommonModuleCompilationState CommonModuleCompilationState => CompilationState; internal sealed override CommonEmbeddedTypesManager CommonEmbeddedTypesManagerOpt => EmbeddedTypesManagerOpt; internal MetadataConstant CreateConstant( TTypeSymbol type, object value, TSyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics) { return new MetadataConstant(Translate(type, syntaxNodeOpt, diagnostics), value); } private static void VisitTopLevelType(Cci.TypeReferenceIndexer noPiaIndexer, Cci.INamespaceTypeDefinition type) { noPiaIndexer?.Visit((Cci.ITypeDefinition)type); } internal Cci.IFieldReference GetModuleVersionId(Cci.ITypeReference mvidType, TSyntaxNode syntaxOpt, DiagnosticBag diagnostics) { PrivateImplementationDetails details = GetPrivateImplClass(syntaxOpt, diagnostics); EnsurePrivateImplementationDetailsStaticConstructor(details, syntaxOpt, diagnostics); return details.GetModuleVersionId(mvidType); } internal Cci.IFieldReference GetInstrumentationPayloadRoot(int analysisKind, Cci.ITypeReference payloadType, TSyntaxNode syntaxOpt, DiagnosticBag diagnostics) { PrivateImplementationDetails details = GetPrivateImplClass(syntaxOpt, diagnostics); EnsurePrivateImplementationDetailsStaticConstructor(details, syntaxOpt, diagnostics); return details.GetOrAddInstrumentationPayloadRoot(analysisKind, payloadType); } private void EnsurePrivateImplementationDetailsStaticConstructor(PrivateImplementationDetails details, TSyntaxNode syntaxOpt, DiagnosticBag diagnostics) { if (details.GetMethod(WellKnownMemberNames.StaticConstructorName) == null) { details.TryAddSynthesizedMethod(CreatePrivateImplementationDetailsStaticConstructor(details, syntaxOpt, diagnostics)); } } protected abstract Cci.IMethodDefinition CreatePrivateImplementationDetailsStaticConstructor(PrivateImplementationDetails details, TSyntaxNode syntaxOpt, DiagnosticBag diagnostics); #region Synthesized Members /// <summary> /// Captures the set of synthesized definitions that should be added to a type /// during emit process. /// </summary> private sealed class SynthesizedDefinitions { public ConcurrentQueue<Cci.INestedTypeDefinition> NestedTypes; public ConcurrentQueue<Cci.IMethodDefinition> Methods; public ConcurrentQueue<Cci.IPropertyDefinition> Properties; public ConcurrentQueue<Cci.IFieldDefinition> Fields; public ImmutableArray<ISymbolInternal> GetAllMembers() { var builder = ArrayBuilder<ISymbolInternal>.GetInstance(); if (Fields != null) { foreach (var field in Fields) { builder.Add(field.GetInternalSymbol()); } } if (Methods != null) { foreach (var method in Methods) { builder.Add(method.GetInternalSymbol()); } } if (Properties != null) { foreach (var property in Properties) { builder.Add(property.GetInternalSymbol()); } } if (NestedTypes != null) { foreach (var type in NestedTypes) { builder.Add(type.GetInternalSymbol()); } } return builder.ToImmutableAndFree(); } } private readonly ConcurrentDictionary<TNamedTypeSymbol, SynthesizedDefinitions> _synthesizedTypeMembers = new ConcurrentDictionary<TNamedTypeSymbol, SynthesizedDefinitions>(ReferenceEqualityComparer.Instance); private ConcurrentDictionary<INamespaceSymbolInternal, ConcurrentQueue<INamespaceOrTypeSymbolInternal>> _lazySynthesizedNamespaceMembers; internal abstract IEnumerable<Cci.INestedTypeDefinition> GetSynthesizedNestedTypes(TNamedTypeSymbol container); /// <summary> /// Returns null if there are no compiler generated types. /// </summary> public IEnumerable<Cci.INestedTypeDefinition> GetSynthesizedTypes(TNamedTypeSymbol container) { IEnumerable<Cci.INestedTypeDefinition> declareTypes = GetSynthesizedNestedTypes(container); IEnumerable<Cci.INestedTypeDefinition> compileEmitTypes = null; if (_synthesizedTypeMembers.TryGetValue(container, out var defs)) { compileEmitTypes = defs.NestedTypes; } if (declareTypes == null) { return compileEmitTypes; } if (compileEmitTypes == null) { return declareTypes; } return declareTypes.Concat(compileEmitTypes); } private SynthesizedDefinitions GetOrAddSynthesizedDefinitions(TNamedTypeSymbol container) { Debug.Assert(container.IsDefinition); return _synthesizedTypeMembers.GetOrAdd(container, _ => new SynthesizedDefinitions()); } public void AddSynthesizedDefinition(TNamedTypeSymbol container, Cci.IMethodDefinition method) { Debug.Assert(method != null); SynthesizedDefinitions defs = GetOrAddSynthesizedDefinitions(container); if (defs.Methods == null) { Interlocked.CompareExchange(ref defs.Methods, new ConcurrentQueue<Cci.IMethodDefinition>(), null); } defs.Methods.Enqueue(method); } public void AddSynthesizedDefinition(TNamedTypeSymbol container, Cci.IPropertyDefinition property) { Debug.Assert(property != null); SynthesizedDefinitions defs = GetOrAddSynthesizedDefinitions(container); if (defs.Properties == null) { Interlocked.CompareExchange(ref defs.Properties, new ConcurrentQueue<Cci.IPropertyDefinition>(), null); } defs.Properties.Enqueue(property); } public void AddSynthesizedDefinition(TNamedTypeSymbol container, Cci.IFieldDefinition field) { Debug.Assert(field != null); SynthesizedDefinitions defs = GetOrAddSynthesizedDefinitions(container); if (defs.Fields == null) { Interlocked.CompareExchange(ref defs.Fields, new ConcurrentQueue<Cci.IFieldDefinition>(), null); } defs.Fields.Enqueue(field); } public void AddSynthesizedDefinition(TNamedTypeSymbol container, Cci.INestedTypeDefinition nestedType) { Debug.Assert(nestedType != null); SynthesizedDefinitions defs = GetOrAddSynthesizedDefinitions(container); if (defs.NestedTypes == null) { Interlocked.CompareExchange(ref defs.NestedTypes, new ConcurrentQueue<Cci.INestedTypeDefinition>(), null); } defs.NestedTypes.Enqueue(nestedType); } public void AddSynthesizedDefinition(INamespaceSymbolInternal container, INamespaceOrTypeSymbolInternal typeOrNamespace) { Debug.Assert(typeOrNamespace != null); if (_lazySynthesizedNamespaceMembers == null) { Interlocked.CompareExchange(ref _lazySynthesizedNamespaceMembers, new ConcurrentDictionary<INamespaceSymbolInternal, ConcurrentQueue<INamespaceOrTypeSymbolInternal>>(), null); } _lazySynthesizedNamespaceMembers.GetOrAdd(container, _ => new ConcurrentQueue<INamespaceOrTypeSymbolInternal>()).Enqueue(typeOrNamespace); } /// <summary> /// Returns null if there are no synthesized fields. /// </summary> public IEnumerable<Cci.IFieldDefinition> GetSynthesizedFields(TNamedTypeSymbol container) => _synthesizedTypeMembers.TryGetValue(container, out var defs) ? defs.Fields : null; /// <summary> /// Returns null if there are no synthesized properties. /// </summary> public IEnumerable<Cci.IPropertyDefinition> GetSynthesizedProperties(TNamedTypeSymbol container) => _synthesizedTypeMembers.TryGetValue(container, out var defs) ? defs.Properties : null; /// <summary> /// Returns null if there are no synthesized methods. /// </summary> public IEnumerable<Cci.IMethodDefinition> GetSynthesizedMethods(TNamedTypeSymbol container) => _synthesizedTypeMembers.TryGetValue(container, out var defs) ? defs.Methods : null; internal override ImmutableDictionary<ISymbolInternal, ImmutableArray<ISymbolInternal>> GetAllSynthesizedMembers() { var builder = ImmutableDictionary.CreateBuilder<ISymbolInternal, ImmutableArray<ISymbolInternal>>(); foreach (var entry in _synthesizedTypeMembers) { builder.Add(entry.Key, entry.Value.GetAllMembers()); } var namespaceMembers = _lazySynthesizedNamespaceMembers; if (namespaceMembers != null) { foreach (var entry in namespaceMembers) { builder.Add(entry.Key, entry.Value.ToImmutableArray<ISymbolInternal>()); } } return builder.ToImmutable(); } #endregion #region Token Mapping Cci.IFieldReference ITokenDeferral.GetFieldForData(ImmutableArray<byte> data, SyntaxNode syntaxNode, DiagnosticBag diagnostics) { Debug.Assert(this.SupportsPrivateImplClass); var privateImpl = this.GetPrivateImplClass((TSyntaxNode)syntaxNode, diagnostics); // map a field to the block (that makes it addressable via a token) return privateImpl.CreateDataField(data); } public abstract Cci.IMethodReference GetInitArrayHelper(); public ArrayMethods ArrayMethods { get { ArrayMethods result = _lazyArrayMethods; if (result == null) { result = new ArrayMethods(); if (Interlocked.CompareExchange(ref _lazyArrayMethods, result, null) != null) { result = _lazyArrayMethods; } } return result; } } #endregion #region Private Implementation Details Type internal PrivateImplementationDetails GetPrivateImplClass(TSyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics) { var result = _privateImplementationDetails; if ((result == null) && this.SupportsPrivateImplClass) { result = new PrivateImplementationDetails( this, this.SourceModule.Name, Compilation.GetSubmissionSlotIndex(), this.GetSpecialType(SpecialType.System_Object, syntaxNodeOpt, diagnostics), this.GetSpecialType(SpecialType.System_ValueType, syntaxNodeOpt, diagnostics), this.GetSpecialType(SpecialType.System_Byte, syntaxNodeOpt, diagnostics), this.GetSpecialType(SpecialType.System_Int16, syntaxNodeOpt, diagnostics), this.GetSpecialType(SpecialType.System_Int32, syntaxNodeOpt, diagnostics), this.GetSpecialType(SpecialType.System_Int64, syntaxNodeOpt, diagnostics), SynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_CompilerGeneratedAttribute__ctor)); if (Interlocked.CompareExchange(ref _privateImplementationDetails, result, null) != null) { result = _privateImplementationDetails; } } return result; } internal PrivateImplementationDetails PrivateImplClass { get { return _privateImplementationDetails; } } internal override bool SupportsPrivateImplClass { get { return true; } } #endregion public sealed override Cci.ITypeReference GetPlatformType(Cci.PlatformType platformType, EmitContext context) { Debug.Assert((object)this == context.Module); switch (platformType) { case Cci.PlatformType.SystemType: throw ExceptionUtilities.UnexpectedValue(platformType); default: return GetSpecialType((SpecialType)platformType, (TSyntaxNode)context.SyntaxNode, context.Diagnostics); } } } }
1
dotnet/roslyn
56,450
Implement INamespaceTypeReference.GetUnit for RootModuleType
Fixes #56412.
AlekseyTs
"2021-09-16T16:44:04Z"
"2021-09-17T18:21:59Z"
4b06ee428bafa0141c9eb3250003a19109dcfc86
d695369176aa109f0e0fb8b0019294aaa0823a54
Implement INamespaceTypeReference.GetUnit for RootModuleType. Fixes #56412.
./src/Compilers/Core/Portable/PEWriter/RootModuleType.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.Diagnostics; using System.Reflection.Metadata; using System.Runtime.InteropServices; using Roslyn.Utilities; using EmitContext = Microsoft.CodeAnalysis.Emit.EmitContext; namespace Microsoft.Cci { /// <summary> /// Special type &lt;Module&gt; /// </summary> internal class RootModuleType : INamespaceTypeDefinition { private IReadOnlyList<IMethodDefinition>? _methods; public void SetStaticConstructorBody(ImmutableArray<byte> il) { Debug.Assert(_methods is null); _methods = SpecializedCollections.SingletonReadOnlyList( new RootModuleStaticConstructor(containingTypeDefinition: this, il)); } public IEnumerable<IMethodDefinition> GetMethods(EmitContext context) { return _methods ??= SpecializedCollections.EmptyReadOnlyList<IMethodDefinition>(); } public TypeDefinitionHandle TypeDef { get { return default(TypeDefinitionHandle); } } public ITypeDefinition ResolvedType { get { return this; } } public IEnumerable<ICustomAttribute> GetAttributes(EmitContext context) { return SpecializedCollections.EmptyEnumerable<ICustomAttribute>(); } public bool MangleName { get { return false; } } public string Name { get { return "<Module>"; } } public ushort Alignment { get { return 0; } } public ITypeReference? GetBaseClass(EmitContext context) { return null; } public IEnumerable<IEventDefinition> GetEvents(EmitContext context) { return SpecializedCollections.EmptyEnumerable<IEventDefinition>(); } public IEnumerable<MethodImplementation> GetExplicitImplementationOverrides(EmitContext context) { return SpecializedCollections.EmptyEnumerable<MethodImplementation>(); } public IEnumerable<IFieldDefinition> GetFields(EmitContext context) { return SpecializedCollections.EmptyEnumerable<IFieldDefinition>(); } public bool HasDeclarativeSecurity { get { return false; } } public IEnumerable<Cci.TypeReferenceWithAttributes> Interfaces(EmitContext context) { return SpecializedCollections.EmptyEnumerable<Cci.TypeReferenceWithAttributes>(); } public bool IsAbstract { get { return false; } } public bool IsBeforeFieldInit { get { return false; } } public bool IsComObject { get { return false; } } public bool IsGeneric { get { return false; } } public bool IsInterface { get { return false; } } public bool IsDelegate { get { return false; } } public bool IsRuntimeSpecial { get { return false; } } public bool IsSerializable { get { return false; } } public bool IsSpecialName { get { return false; } } public bool IsWindowsRuntimeImport { get { return false; } } public bool IsSealed { get { return false; } } public LayoutKind Layout { get { return LayoutKind.Auto; } } public IEnumerable<INestedTypeDefinition> GetNestedTypes(EmitContext context) { return SpecializedCollections.EmptyEnumerable<INestedTypeDefinition>(); } public IEnumerable<IPropertyDefinition> GetProperties(EmitContext context) { return SpecializedCollections.EmptyEnumerable<IPropertyDefinition>(); } public uint SizeOf { get { return 0; } } public CharSet StringFormat { get { return CharSet.Ansi; } } public bool IsPublic { get { return false; } } public bool IsNested { get { return false; } } IEnumerable<IGenericTypeParameter> ITypeDefinition.GenericParameters { get { throw ExceptionUtilities.Unreachable; } } ushort ITypeDefinition.GenericParameterCount { get { return 0; } } IEnumerable<SecurityAttribute> ITypeDefinition.SecurityAttributes { get { throw ExceptionUtilities.Unreachable; } } void IReference.Dispatch(MetadataVisitor visitor) { throw ExceptionUtilities.Unreachable; } bool ITypeReference.IsEnum { get { throw ExceptionUtilities.Unreachable; } } bool ITypeReference.IsValueType { get { throw ExceptionUtilities.Unreachable; } } ITypeDefinition ITypeReference.GetResolvedType(EmitContext context) { return this; } PrimitiveTypeCode ITypeReference.TypeCode { get { throw ExceptionUtilities.Unreachable; } } ushort INamedTypeReference.GenericParameterCount { get { throw ExceptionUtilities.Unreachable; } } IUnitReference INamespaceTypeReference.GetUnit(EmitContext context) { throw ExceptionUtilities.Unreachable; } string INamespaceTypeReference.NamespaceName { get { return string.Empty; } } IGenericMethodParameterReference? ITypeReference.AsGenericMethodParameterReference { get { return null; } } IGenericTypeInstanceReference? ITypeReference.AsGenericTypeInstanceReference { get { return null; } } IGenericTypeParameterReference? ITypeReference.AsGenericTypeParameterReference { get { return null; } } INamespaceTypeDefinition ITypeReference.AsNamespaceTypeDefinition(EmitContext context) { return this; } INamespaceTypeReference ITypeReference.AsNamespaceTypeReference { get { return this; } } INestedTypeDefinition? ITypeReference.AsNestedTypeDefinition(EmitContext context) { return null; } INestedTypeReference? ITypeReference.AsNestedTypeReference { get { return null; } } ISpecializedNestedTypeReference? ITypeReference.AsSpecializedNestedTypeReference { get { return null; } } ITypeDefinition ITypeReference.AsTypeDefinition(EmitContext context) { return this; } IDefinition IReference.AsDefinition(EmitContext context) { return this; } CodeAnalysis.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. using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Reflection.Metadata; using System.Runtime.InteropServices; using Roslyn.Utilities; using EmitContext = Microsoft.CodeAnalysis.Emit.EmitContext; namespace Microsoft.Cci { /// <summary> /// Special type &lt;Module&gt; /// </summary> internal class RootModuleType : INamespaceTypeDefinition { private readonly IUnit _unit; private IReadOnlyList<IMethodDefinition>? _methods; public RootModuleType(IUnit unit) { _unit = unit; } public void SetStaticConstructorBody(ImmutableArray<byte> il) { Debug.Assert(_methods is null); _methods = SpecializedCollections.SingletonReadOnlyList( new RootModuleStaticConstructor(containingTypeDefinition: this, il)); } public IEnumerable<IMethodDefinition> GetMethods(EmitContext context) { return _methods ??= SpecializedCollections.EmptyReadOnlyList<IMethodDefinition>(); } public TypeDefinitionHandle TypeDef { get { return default(TypeDefinitionHandle); } } public ITypeDefinition ResolvedType { get { return this; } } public IEnumerable<ICustomAttribute> GetAttributes(EmitContext context) { return SpecializedCollections.EmptyEnumerable<ICustomAttribute>(); } public bool MangleName { get { return false; } } public string Name { get { return "<Module>"; } } public ushort Alignment { get { return 0; } } public ITypeReference? GetBaseClass(EmitContext context) { return null; } public IEnumerable<IEventDefinition> GetEvents(EmitContext context) { return SpecializedCollections.EmptyEnumerable<IEventDefinition>(); } public IEnumerable<MethodImplementation> GetExplicitImplementationOverrides(EmitContext context) { return SpecializedCollections.EmptyEnumerable<MethodImplementation>(); } public IEnumerable<IFieldDefinition> GetFields(EmitContext context) { return SpecializedCollections.EmptyEnumerable<IFieldDefinition>(); } public bool HasDeclarativeSecurity { get { return false; } } public IEnumerable<Cci.TypeReferenceWithAttributes> Interfaces(EmitContext context) { return SpecializedCollections.EmptyEnumerable<Cci.TypeReferenceWithAttributes>(); } public bool IsAbstract { get { return false; } } public bool IsBeforeFieldInit { get { return false; } } public bool IsComObject { get { return false; } } public bool IsGeneric { get { return false; } } public bool IsInterface { get { return false; } } public bool IsDelegate { get { return false; } } public bool IsRuntimeSpecial { get { return false; } } public bool IsSerializable { get { return false; } } public bool IsSpecialName { get { return false; } } public bool IsWindowsRuntimeImport { get { return false; } } public bool IsSealed { get { return false; } } public LayoutKind Layout { get { return LayoutKind.Auto; } } public IEnumerable<INestedTypeDefinition> GetNestedTypes(EmitContext context) { return SpecializedCollections.EmptyEnumerable<INestedTypeDefinition>(); } public IEnumerable<IPropertyDefinition> GetProperties(EmitContext context) { return SpecializedCollections.EmptyEnumerable<IPropertyDefinition>(); } public uint SizeOf { get { return 0; } } public CharSet StringFormat { get { return CharSet.Ansi; } } public bool IsPublic { get { return false; } } public bool IsNested { get { return false; } } IEnumerable<IGenericTypeParameter> ITypeDefinition.GenericParameters { get { throw ExceptionUtilities.Unreachable; } } ushort ITypeDefinition.GenericParameterCount { get { return 0; } } IEnumerable<SecurityAttribute> ITypeDefinition.SecurityAttributes { get { throw ExceptionUtilities.Unreachable; } } void IReference.Dispatch(MetadataVisitor visitor) { throw ExceptionUtilities.Unreachable; } bool ITypeReference.IsEnum { get { throw ExceptionUtilities.Unreachable; } } bool ITypeReference.IsValueType { get { throw ExceptionUtilities.Unreachable; } } ITypeDefinition ITypeReference.GetResolvedType(EmitContext context) { return this; } PrimitiveTypeCode ITypeReference.TypeCode { get { throw ExceptionUtilities.Unreachable; } } ushort INamedTypeReference.GenericParameterCount { get { throw ExceptionUtilities.Unreachable; } } IUnitReference INamespaceTypeReference.GetUnit(EmitContext context) { return _unit; } string INamespaceTypeReference.NamespaceName { get { return string.Empty; } } IGenericMethodParameterReference? ITypeReference.AsGenericMethodParameterReference { get { return null; } } IGenericTypeInstanceReference? ITypeReference.AsGenericTypeInstanceReference { get { return null; } } IGenericTypeParameterReference? ITypeReference.AsGenericTypeParameterReference { get { return null; } } INamespaceTypeDefinition ITypeReference.AsNamespaceTypeDefinition(EmitContext context) { return this; } INamespaceTypeReference ITypeReference.AsNamespaceTypeReference { get { return this; } } INestedTypeDefinition? ITypeReference.AsNestedTypeDefinition(EmitContext context) { return null; } INestedTypeReference? ITypeReference.AsNestedTypeReference { get { return null; } } ISpecializedNestedTypeReference? ITypeReference.AsSpecializedNestedTypeReference { get { return null; } } ITypeDefinition ITypeReference.AsTypeDefinition(EmitContext context) { return this; } IDefinition IReference.AsDefinition(EmitContext context) { return this; } CodeAnalysis.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
56,450
Implement INamespaceTypeReference.GetUnit for RootModuleType
Fixes #56412.
AlekseyTs
"2021-09-16T16:44:04Z"
"2021-09-17T18:21:59Z"
4b06ee428bafa0141c9eb3250003a19109dcfc86
d695369176aa109f0e0fb8b0019294aaa0823a54
Implement INamespaceTypeReference.GetUnit for RootModuleType. Fixes #56412.
./src/Workspaces/CSharp/Portable/CodeGeneration/NamedTypeGenerator.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 System.Threading; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; using static Microsoft.CodeAnalysis.CodeGeneration.CodeGenerationHelpers; using static Microsoft.CodeAnalysis.CSharp.CodeGeneration.CSharpCodeGenerationHelpers; namespace Microsoft.CodeAnalysis.CSharp.CodeGeneration { internal static class NamedTypeGenerator { public static TypeDeclarationSyntax AddNamedTypeTo( ICodeGenerationService service, TypeDeclarationSyntax destination, INamedTypeSymbol namedType, CodeGenerationOptions options, IList<bool> availableIndices, CancellationToken cancellationToken) { var declaration = GenerateNamedTypeDeclaration(service, namedType, GetDestination(destination), options, cancellationToken); var members = Insert(destination.Members, declaration, options, availableIndices); return AddMembersTo(destination, members); } public static BaseNamespaceDeclarationSyntax AddNamedTypeTo( ICodeGenerationService service, BaseNamespaceDeclarationSyntax destination, INamedTypeSymbol namedType, CodeGenerationOptions options, IList<bool> availableIndices, CancellationToken cancellationToken) { var declaration = GenerateNamedTypeDeclaration(service, namedType, CodeGenerationDestination.Namespace, options, cancellationToken); var members = Insert(destination.Members, declaration, options, availableIndices); return ConditionallyAddFormattingAnnotationTo( destination.WithMembers(members), members); } public static CompilationUnitSyntax AddNamedTypeTo( ICodeGenerationService service, CompilationUnitSyntax destination, INamedTypeSymbol namedType, CodeGenerationOptions options, IList<bool> availableIndices, CancellationToken cancellationToken) { var declaration = GenerateNamedTypeDeclaration(service, namedType, CodeGenerationDestination.CompilationUnit, options, cancellationToken); var members = Insert(destination.Members, declaration, options, availableIndices); return destination.WithMembers(members); } public static MemberDeclarationSyntax GenerateNamedTypeDeclaration( ICodeGenerationService service, INamedTypeSymbol namedType, CodeGenerationDestination destination, CodeGenerationOptions options, CancellationToken cancellationToken) { options ??= CodeGenerationOptions.Default; var declaration = GetDeclarationSyntaxWithoutMembers(namedType, destination, options); // If we are generating members then make sure to exclude properties that cannot be generated. // Reason: Calling AddProperty on a propertysymbol that can't be generated (like one with params) causes // the getter and setter to get generated instead. Since the list of members is going to include // the method symbols for the getter and setter, we don't want to generate them twice. var members = GetMembers(namedType).Where(s => s.Kind != SymbolKind.Property || PropertyGenerator.CanBeGenerated((IPropertySymbol)s)) .ToImmutableArray(); if (namedType.IsRecord) { declaration = GenerateRecordMembers(service, options, (RecordDeclarationSyntax)declaration, members, cancellationToken); } else { // If we're generating a ComImport type, then do not attempt to do any // reordering of members. if (namedType.IsComImport) options = options.With(autoInsertionLocation: false, sortMembers: false); if (options.GenerateMembers && namedType.TypeKind != TypeKind.Delegate) declaration = service.AddMembers(declaration, members, options, cancellationToken); } return AddFormatterAndCodeGeneratorAnnotationsTo(ConditionallyAddDocumentationCommentTo(declaration, namedType, options, cancellationToken)); } private static RecordDeclarationSyntax GenerateRecordMembers( ICodeGenerationService service, CodeGenerationOptions options, RecordDeclarationSyntax recordDeclaration, ImmutableArray<ISymbol> members, CancellationToken cancellationToken) { if (!options.GenerateMembers) members = ImmutableArray<ISymbol>.Empty; // For a record, add record parameters if we have a primary constructor. var primaryConstructor = members.OfType<IMethodSymbol>().FirstOrDefault(m => CodeGenerationConstructorInfo.GetIsPrimaryConstructor(m)); if (primaryConstructor != null) { var parameterList = ParameterGenerator.GenerateParameterList(primaryConstructor.Parameters, isExplicit: false, options); recordDeclaration = recordDeclaration.WithParameterList(parameterList); // remove the primary constructor from the list of members to generate. members = members.Remove(primaryConstructor); // remove any fields/properties that were created by the primary constructor members = members.WhereAsArray(m => m is not IPropertySymbol and not IFieldSymbol || !primaryConstructor.Parameters.Any(p => p.Name == m.Name)); } // remove any implicit overrides to generate. members = members.WhereAsArray(m => !m.IsImplicitlyDeclared); // If there are no members, just make a simple record with no body if (members.Length == 0) return recordDeclaration.WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)); // Otherwise, give the record a body and add the members to it. recordDeclaration = recordDeclaration.WithOpenBraceToken(SyntaxFactory.Token(SyntaxKind.OpenBraceToken)) .WithCloseBraceToken(SyntaxFactory.Token(SyntaxKind.CloseBraceToken)) .WithSemicolonToken(default); return service.AddMembers(recordDeclaration, members, options, cancellationToken); } public static MemberDeclarationSyntax UpdateNamedTypeDeclaration( ICodeGenerationService service, MemberDeclarationSyntax declaration, IList<ISymbol> newMembers, CodeGenerationOptions options, CancellationToken cancellationToken) { declaration = RemoveAllMembers(declaration); declaration = service.AddMembers(declaration, newMembers, options, cancellationToken); return AddFormatterAndCodeGeneratorAnnotationsTo(declaration); } private static MemberDeclarationSyntax GetDeclarationSyntaxWithoutMembers( INamedTypeSymbol namedType, CodeGenerationDestination destination, CodeGenerationOptions options) { var reusableDeclarationSyntax = GetReuseableSyntaxNodeForSymbol<MemberDeclarationSyntax>(namedType, options); return reusableDeclarationSyntax == null ? GetDeclarationSyntaxWithoutMembersWorker(namedType, destination, options) : RemoveAllMembers(reusableDeclarationSyntax); } private static MemberDeclarationSyntax RemoveAllMembers(MemberDeclarationSyntax declaration) { switch (declaration.Kind()) { case SyntaxKind.EnumDeclaration: return ((EnumDeclarationSyntax)declaration).WithMembers(default); case SyntaxKind.StructDeclaration: case SyntaxKind.RecordStructDeclaration: case SyntaxKind.InterfaceDeclaration: case SyntaxKind.ClassDeclaration: case SyntaxKind.RecordDeclaration: return ((TypeDeclarationSyntax)declaration).WithMembers(default); default: return declaration; } } private static MemberDeclarationSyntax GetDeclarationSyntaxWithoutMembersWorker( INamedTypeSymbol namedType, CodeGenerationDestination destination, CodeGenerationOptions options) { if (namedType.TypeKind == TypeKind.Enum) { return GenerateEnumDeclaration(namedType, destination, options); } else if (namedType.TypeKind == TypeKind.Delegate) { return GenerateDelegateDeclaration(namedType, destination, options); } TypeDeclarationSyntax typeDeclaration; if (namedType.IsRecord) { var isRecordClass = namedType.TypeKind is TypeKind.Class; var declarationKind = isRecordClass ? SyntaxKind.RecordDeclaration : SyntaxKind.RecordStructDeclaration; var classOrStructKeyword = SyntaxFactory.Token(isRecordClass ? default : SyntaxKind.StructKeyword); typeDeclaration = SyntaxFactory.RecordDeclaration(kind: declarationKind, attributeLists: default, modifiers: default, SyntaxFactory.Token(SyntaxKind.RecordKeyword), classOrStructKeyword, namedType.Name.ToIdentifierToken(), typeParameterList: null, parameterList: null, baseList: null, constraintClauses: default, openBraceToken: default, members: default, closeBraceToken: default, SyntaxFactory.Token(SyntaxKind.SemicolonToken)); } else { var kind = namedType.TypeKind == TypeKind.Struct ? SyntaxKind.StructDeclaration : namedType.TypeKind == TypeKind.Interface ? SyntaxKind.InterfaceDeclaration : SyntaxKind.ClassDeclaration; typeDeclaration = SyntaxFactory.TypeDeclaration(kind, namedType.Name.ToIdentifierToken()); } var result = typeDeclaration .WithAttributeLists(GenerateAttributeDeclarations(namedType, options)) .WithModifiers(GenerateModifiers(namedType, destination, options)) .WithTypeParameterList(GenerateTypeParameterList(namedType, options)) .WithBaseList(GenerateBaseList(namedType)) .WithConstraintClauses(GenerateConstraintClauses(namedType)); return result; } private static DelegateDeclarationSyntax GenerateDelegateDeclaration( INamedTypeSymbol namedType, CodeGenerationDestination destination, CodeGenerationOptions options) { var invokeMethod = namedType.DelegateInvokeMethod; Contract.ThrowIfNull(invokeMethod); return SyntaxFactory.DelegateDeclaration( GenerateAttributeDeclarations(namedType, options), GenerateModifiers(namedType, destination, options), invokeMethod.ReturnType.GenerateTypeSyntax(), namedType.Name.ToIdentifierToken(), TypeParameterGenerator.GenerateTypeParameterList(namedType.TypeParameters, options), ParameterGenerator.GenerateParameterList(invokeMethod.Parameters, isExplicit: false, options: options), namedType.TypeParameters.GenerateConstraintClauses()); } private static EnumDeclarationSyntax GenerateEnumDeclaration( INamedTypeSymbol namedType, CodeGenerationDestination destination, CodeGenerationOptions options) { var baseList = namedType.EnumUnderlyingType != null && namedType.EnumUnderlyingType.SpecialType != SpecialType.System_Int32 ? SyntaxFactory.BaseList(SyntaxFactory.SingletonSeparatedList<BaseTypeSyntax>(SyntaxFactory.SimpleBaseType(namedType.EnumUnderlyingType.GenerateTypeSyntax()))) : null; return SyntaxFactory.EnumDeclaration( GenerateAttributeDeclarations(namedType, options), GenerateModifiers(namedType, destination, options), namedType.Name.ToIdentifierToken(), baseList: baseList, members: default); } private static SyntaxList<AttributeListSyntax> GenerateAttributeDeclarations( INamedTypeSymbol namedType, CodeGenerationOptions options) { return AttributeGenerator.GenerateAttributeLists(namedType.GetAttributes(), options); } private static SyntaxTokenList GenerateModifiers( INamedTypeSymbol namedType, CodeGenerationDestination destination, CodeGenerationOptions options) { var tokens = ArrayBuilder<SyntaxToken>.GetInstance(); var defaultAccessibility = destination == CodeGenerationDestination.CompilationUnit || destination == CodeGenerationDestination.Namespace ? Accessibility.Internal : Accessibility.Private; AddAccessibilityModifiers(namedType.DeclaredAccessibility, tokens, options, defaultAccessibility); if (namedType.IsStatic) { tokens.Add(SyntaxFactory.Token(SyntaxKind.StaticKeyword)); } else { if (namedType.TypeKind == TypeKind.Class) { if (namedType.IsAbstract) { tokens.Add(SyntaxFactory.Token(SyntaxKind.AbstractKeyword)); } if (namedType.IsSealed) { tokens.Add(SyntaxFactory.Token(SyntaxKind.SealedKeyword)); } } } if (namedType.IsReadOnly) { tokens.Add(SyntaxFactory.Token(SyntaxKind.ReadOnlyKeyword)); } if (namedType.IsRefLikeType) { tokens.Add(SyntaxFactory.Token(SyntaxKind.RefKeyword)); } return tokens.ToSyntaxTokenListAndFree(); } private static TypeParameterListSyntax GenerateTypeParameterList( INamedTypeSymbol namedType, CodeGenerationOptions options) { return TypeParameterGenerator.GenerateTypeParameterList(namedType.TypeParameters, options); } private static BaseListSyntax? GenerateBaseList(INamedTypeSymbol namedType) { var types = new List<BaseTypeSyntax>(); if (namedType.TypeKind == TypeKind.Class && namedType.BaseType != null && namedType.BaseType.SpecialType != Microsoft.CodeAnalysis.SpecialType.System_Object) types.Add(SyntaxFactory.SimpleBaseType(namedType.BaseType.GenerateTypeSyntax())); foreach (var type in namedType.Interfaces) types.Add(SyntaxFactory.SimpleBaseType(type.GenerateTypeSyntax())); if (types.Count == 0) return null; return SyntaxFactory.BaseList(SyntaxFactory.SeparatedList(types)); } private static SyntaxList<TypeParameterConstraintClauseSyntax> GenerateConstraintClauses(INamedTypeSymbol namedType) => namedType.TypeParameters.GenerateConstraintClauses(); } }
// Licensed to the .NET Foundation under one or more 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 System.Threading; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; using static Microsoft.CodeAnalysis.CodeGeneration.CodeGenerationHelpers; using static Microsoft.CodeAnalysis.CSharp.CodeGeneration.CSharpCodeGenerationHelpers; namespace Microsoft.CodeAnalysis.CSharp.CodeGeneration { internal static class NamedTypeGenerator { public static TypeDeclarationSyntax AddNamedTypeTo( ICodeGenerationService service, TypeDeclarationSyntax destination, INamedTypeSymbol namedType, CodeGenerationOptions options, IList<bool> availableIndices, CancellationToken cancellationToken) { var declaration = GenerateNamedTypeDeclaration(service, namedType, GetDestination(destination), options, cancellationToken); var members = Insert(destination.Members, declaration, options, availableIndices); return AddMembersTo(destination, members); } public static BaseNamespaceDeclarationSyntax AddNamedTypeTo( ICodeGenerationService service, BaseNamespaceDeclarationSyntax destination, INamedTypeSymbol namedType, CodeGenerationOptions options, IList<bool> availableIndices, CancellationToken cancellationToken) { var declaration = GenerateNamedTypeDeclaration(service, namedType, CodeGenerationDestination.Namespace, options, cancellationToken); var members = Insert(destination.Members, declaration, options, availableIndices); return ConditionallyAddFormattingAnnotationTo( destination.WithMembers(members), members); } public static CompilationUnitSyntax AddNamedTypeTo( ICodeGenerationService service, CompilationUnitSyntax destination, INamedTypeSymbol namedType, CodeGenerationOptions options, IList<bool> availableIndices, CancellationToken cancellationToken) { var declaration = GenerateNamedTypeDeclaration(service, namedType, CodeGenerationDestination.CompilationUnit, options, cancellationToken); var members = Insert(destination.Members, declaration, options, availableIndices); return destination.WithMembers(members); } public static MemberDeclarationSyntax GenerateNamedTypeDeclaration( ICodeGenerationService service, INamedTypeSymbol namedType, CodeGenerationDestination destination, CodeGenerationOptions options, CancellationToken cancellationToken) { options ??= CodeGenerationOptions.Default; var declaration = GetDeclarationSyntaxWithoutMembers(namedType, destination, options); // If we are generating members then make sure to exclude properties that cannot be generated. // Reason: Calling AddProperty on a propertysymbol that can't be generated (like one with params) causes // the getter and setter to get generated instead. Since the list of members is going to include // the method symbols for the getter and setter, we don't want to generate them twice. var members = GetMembers(namedType).Where(s => s.Kind != SymbolKind.Property || PropertyGenerator.CanBeGenerated((IPropertySymbol)s)) .ToImmutableArray(); if (namedType.IsRecord) { declaration = GenerateRecordMembers(service, options, (RecordDeclarationSyntax)declaration, members, cancellationToken); } else { // If we're generating a ComImport type, then do not attempt to do any // reordering of members. if (namedType.IsComImport) options = options.With(autoInsertionLocation: false, sortMembers: false); if (options.GenerateMembers && namedType.TypeKind != TypeKind.Delegate) declaration = service.AddMembers(declaration, members, options, cancellationToken); } return AddFormatterAndCodeGeneratorAnnotationsTo(ConditionallyAddDocumentationCommentTo(declaration, namedType, options, cancellationToken)); } private static RecordDeclarationSyntax GenerateRecordMembers( ICodeGenerationService service, CodeGenerationOptions options, RecordDeclarationSyntax recordDeclaration, ImmutableArray<ISymbol> members, CancellationToken cancellationToken) { if (!options.GenerateMembers) members = ImmutableArray<ISymbol>.Empty; // For a record, add record parameters if we have a primary constructor. var primaryConstructor = members.OfType<IMethodSymbol>().FirstOrDefault(m => CodeGenerationConstructorInfo.GetIsPrimaryConstructor(m)); if (primaryConstructor != null) { var parameterList = ParameterGenerator.GenerateParameterList(primaryConstructor.Parameters, isExplicit: false, options); recordDeclaration = recordDeclaration.WithParameterList(parameterList); // remove the primary constructor from the list of members to generate. members = members.Remove(primaryConstructor); // remove any fields/properties that were created by the primary constructor members = members.WhereAsArray(m => m is not IPropertySymbol and not IFieldSymbol || !primaryConstructor.Parameters.Any(p => p.Name == m.Name)); } // remove any implicit overrides to generate. members = members.WhereAsArray(m => !m.IsImplicitlyDeclared); // If there are no members, just make a simple record with no body if (members.Length == 0) return recordDeclaration.WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)); // Otherwise, give the record a body and add the members to it. recordDeclaration = recordDeclaration.WithOpenBraceToken(SyntaxFactory.Token(SyntaxKind.OpenBraceToken)) .WithCloseBraceToken(SyntaxFactory.Token(SyntaxKind.CloseBraceToken)) .WithSemicolonToken(default); return service.AddMembers(recordDeclaration, members, options, cancellationToken); } public static MemberDeclarationSyntax UpdateNamedTypeDeclaration( ICodeGenerationService service, MemberDeclarationSyntax declaration, IList<ISymbol> newMembers, CodeGenerationOptions options, CancellationToken cancellationToken) { declaration = RemoveAllMembers(declaration); declaration = service.AddMembers(declaration, newMembers, options, cancellationToken); return AddFormatterAndCodeGeneratorAnnotationsTo(declaration); } private static MemberDeclarationSyntax GetDeclarationSyntaxWithoutMembers( INamedTypeSymbol namedType, CodeGenerationDestination destination, CodeGenerationOptions options) { var reusableDeclarationSyntax = GetReuseableSyntaxNodeForSymbol<MemberDeclarationSyntax>(namedType, options); return reusableDeclarationSyntax == null ? GetDeclarationSyntaxWithoutMembersWorker(namedType, destination, options) : RemoveAllMembers(reusableDeclarationSyntax); } private static MemberDeclarationSyntax RemoveAllMembers(MemberDeclarationSyntax declaration) { switch (declaration.Kind()) { case SyntaxKind.EnumDeclaration: return ((EnumDeclarationSyntax)declaration).WithMembers(default); case SyntaxKind.StructDeclaration: case SyntaxKind.RecordStructDeclaration: case SyntaxKind.InterfaceDeclaration: case SyntaxKind.ClassDeclaration: case SyntaxKind.RecordDeclaration: return ((TypeDeclarationSyntax)declaration).WithMembers(default); default: return declaration; } } private static MemberDeclarationSyntax GetDeclarationSyntaxWithoutMembersWorker( INamedTypeSymbol namedType, CodeGenerationDestination destination, CodeGenerationOptions options) { if (namedType.TypeKind == TypeKind.Enum) { return GenerateEnumDeclaration(namedType, destination, options); } else if (namedType.TypeKind == TypeKind.Delegate) { return GenerateDelegateDeclaration(namedType, destination, options); } TypeDeclarationSyntax typeDeclaration; if (namedType.IsRecord) { var isRecordClass = namedType.TypeKind is TypeKind.Class; var declarationKind = isRecordClass ? SyntaxKind.RecordDeclaration : SyntaxKind.RecordStructDeclaration; var classOrStructKeyword = SyntaxFactory.Token(isRecordClass ? default : SyntaxKind.StructKeyword); typeDeclaration = SyntaxFactory.RecordDeclaration(kind: declarationKind, attributeLists: default, modifiers: default, SyntaxFactory.Token(SyntaxKind.RecordKeyword), classOrStructKeyword, namedType.Name.ToIdentifierToken(), typeParameterList: null, parameterList: null, baseList: null, constraintClauses: default, openBraceToken: default, members: default, closeBraceToken: default, SyntaxFactory.Token(SyntaxKind.SemicolonToken)); } else { var kind = namedType.TypeKind == TypeKind.Struct ? SyntaxKind.StructDeclaration : namedType.TypeKind == TypeKind.Interface ? SyntaxKind.InterfaceDeclaration : SyntaxKind.ClassDeclaration; typeDeclaration = SyntaxFactory.TypeDeclaration(kind, namedType.Name.ToIdentifierToken()); } var result = typeDeclaration .WithAttributeLists(GenerateAttributeDeclarations(namedType, options)) .WithModifiers(GenerateModifiers(namedType, destination, options)) .WithTypeParameterList(GenerateTypeParameterList(namedType, options)) .WithBaseList(GenerateBaseList(namedType)) .WithConstraintClauses(GenerateConstraintClauses(namedType)); return result; } private static DelegateDeclarationSyntax GenerateDelegateDeclaration( INamedTypeSymbol namedType, CodeGenerationDestination destination, CodeGenerationOptions options) { var invokeMethod = namedType.DelegateInvokeMethod; Contract.ThrowIfNull(invokeMethod); return SyntaxFactory.DelegateDeclaration( GenerateAttributeDeclarations(namedType, options), GenerateModifiers(namedType, destination, options), invokeMethod.ReturnType.GenerateTypeSyntax(), namedType.Name.ToIdentifierToken(), TypeParameterGenerator.GenerateTypeParameterList(namedType.TypeParameters, options), ParameterGenerator.GenerateParameterList(invokeMethod.Parameters, isExplicit: false, options: options), namedType.TypeParameters.GenerateConstraintClauses()); } private static EnumDeclarationSyntax GenerateEnumDeclaration( INamedTypeSymbol namedType, CodeGenerationDestination destination, CodeGenerationOptions options) { var baseList = namedType.EnumUnderlyingType != null && namedType.EnumUnderlyingType.SpecialType != SpecialType.System_Int32 ? SyntaxFactory.BaseList(SyntaxFactory.SingletonSeparatedList<BaseTypeSyntax>(SyntaxFactory.SimpleBaseType(namedType.EnumUnderlyingType.GenerateTypeSyntax()))) : null; return SyntaxFactory.EnumDeclaration( GenerateAttributeDeclarations(namedType, options), GenerateModifiers(namedType, destination, options), namedType.Name.ToIdentifierToken(), baseList: baseList, members: default); } private static SyntaxList<AttributeListSyntax> GenerateAttributeDeclarations( INamedTypeSymbol namedType, CodeGenerationOptions options) { return AttributeGenerator.GenerateAttributeLists(namedType.GetAttributes(), options); } private static SyntaxTokenList GenerateModifiers( INamedTypeSymbol namedType, CodeGenerationDestination destination, CodeGenerationOptions options) { var tokens = ArrayBuilder<SyntaxToken>.GetInstance(); var defaultAccessibility = destination == CodeGenerationDestination.CompilationUnit || destination == CodeGenerationDestination.Namespace ? Accessibility.Internal : Accessibility.Private; AddAccessibilityModifiers(namedType.DeclaredAccessibility, tokens, options, defaultAccessibility); if (namedType.IsStatic) { tokens.Add(SyntaxFactory.Token(SyntaxKind.StaticKeyword)); } else { if (namedType.TypeKind == TypeKind.Class) { if (namedType.IsAbstract) { tokens.Add(SyntaxFactory.Token(SyntaxKind.AbstractKeyword)); } if (namedType.IsSealed) { tokens.Add(SyntaxFactory.Token(SyntaxKind.SealedKeyword)); } } } if (namedType.IsReadOnly) { tokens.Add(SyntaxFactory.Token(SyntaxKind.ReadOnlyKeyword)); } if (namedType.IsRefLikeType) { tokens.Add(SyntaxFactory.Token(SyntaxKind.RefKeyword)); } return tokens.ToSyntaxTokenListAndFree(); } private static TypeParameterListSyntax GenerateTypeParameterList( INamedTypeSymbol namedType, CodeGenerationOptions options) { return TypeParameterGenerator.GenerateTypeParameterList(namedType.TypeParameters, options); } private static BaseListSyntax? GenerateBaseList(INamedTypeSymbol namedType) { var types = new List<BaseTypeSyntax>(); if (namedType.TypeKind == TypeKind.Class && namedType.BaseType != null && namedType.BaseType.SpecialType != Microsoft.CodeAnalysis.SpecialType.System_Object) types.Add(SyntaxFactory.SimpleBaseType(namedType.BaseType.GenerateTypeSyntax())); foreach (var type in namedType.Interfaces) types.Add(SyntaxFactory.SimpleBaseType(type.GenerateTypeSyntax())); if (types.Count == 0) return null; return SyntaxFactory.BaseList(SyntaxFactory.SeparatedList(types)); } private static SyntaxList<TypeParameterConstraintClauseSyntax> GenerateConstraintClauses(INamedTypeSymbol namedType) => namedType.TypeParameters.GenerateConstraintClauses(); } }
-1
dotnet/roslyn
56,450
Implement INamespaceTypeReference.GetUnit for RootModuleType
Fixes #56412.
AlekseyTs
"2021-09-16T16:44:04Z"
"2021-09-17T18:21:59Z"
4b06ee428bafa0141c9eb3250003a19109dcfc86
d695369176aa109f0e0fb8b0019294aaa0823a54
Implement INamespaceTypeReference.GetUnit for RootModuleType. Fixes #56412.
./src/Workspaces/Remote/ServiceHub/Host/RemoteWorkspaceManager.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.Reflection; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.ServiceHub.Framework; using Microsoft.VisualStudio.Composition; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Remote { /// <summary> /// Manages remote workspaces. Currently supports only a single, primary workspace of kind <see cref="WorkspaceKind.RemoteWorkspace"/>. /// In future it should support workspaces of all kinds. /// </summary> internal class RemoteWorkspaceManager { /// <summary> /// Default workspace manager used by the product. Tests may specify a custom <see cref="RemoteWorkspaceManager"/> /// in order to override workspace services. /// </summary> internal static readonly RemoteWorkspaceManager Default = new RemoteWorkspaceManager( new SolutionAssetCache(cleanupInterval: TimeSpan.FromMinutes(1), purgeAfter: TimeSpan.FromMinutes(3), gcAfter: TimeSpan.FromMinutes(5))); internal static readonly ImmutableArray<Assembly> RemoteHostAssemblies = MefHostServices.DefaultAssemblies .Add(typeof(BrokeredServiceBase).Assembly) .Add(typeof(RemoteWorkspacesResources).Assembly); private readonly Lazy<RemoteWorkspace> _lazyPrimaryWorkspace; internal readonly SolutionAssetCache SolutionAssetCache; public RemoteWorkspaceManager(SolutionAssetCache assetCache) { _lazyPrimaryWorkspace = new Lazy<RemoteWorkspace>(CreatePrimaryWorkspace); SolutionAssetCache = assetCache; } private static ComposableCatalog CreateCatalog(ImmutableArray<Assembly> assemblies) { var resolver = new Resolver(SimpleAssemblyLoader.Instance); var discovery = new AttributedPartDiscovery(resolver, isNonPublicSupported: true); var parts = Task.Run(async () => await discovery.CreatePartsAsync(assemblies).ConfigureAwait(false)).GetAwaiter().GetResult(); return ComposableCatalog.Create(resolver).AddParts(parts); } private static IExportProviderFactory CreateExportProviderFactory(ComposableCatalog catalog) { var configuration = CompositionConfiguration.Create(catalog); var runtimeComposition = RuntimeComposition.CreateRuntimeComposition(configuration); return runtimeComposition.CreateExportProviderFactory(); } private static RemoteWorkspace CreatePrimaryWorkspace() { var catalog = CreateCatalog(RemoteHostAssemblies); var exportProviderFactory = CreateExportProviderFactory(catalog); var exportProvider = exportProviderFactory.CreateExportProvider(); return new RemoteWorkspace(VisualStudioMefHostServices.Create(exportProvider), WorkspaceKind.RemoteWorkspace); } public virtual RemoteWorkspace GetWorkspace() => _lazyPrimaryWorkspace.Value; public ValueTask<Solution> GetSolutionAsync(ServiceBrokerClient client, PinnedSolutionInfo solutionInfo, CancellationToken cancellationToken) { var assetSource = new SolutionAssetSource(client); var workspace = GetWorkspace(); var assetProvider = workspace.CreateAssetProvider(solutionInfo, SolutionAssetCache, assetSource); return workspace.GetSolutionAsync(assetProvider, solutionInfo.SolutionChecksum, solutionInfo.FromPrimaryBranch, solutionInfo.WorkspaceVersion, solutionInfo.ProjectId, cancellationToken); } private sealed class SimpleAssemblyLoader : IAssemblyLoader { public static readonly IAssemblyLoader Instance = new SimpleAssemblyLoader(); public Assembly LoadAssembly(AssemblyName assemblyName) => Assembly.Load(assemblyName); public Assembly LoadAssembly(string assemblyFullName, string codeBasePath) { var assemblyName = new AssemblyName(assemblyFullName); if (!string.IsNullOrEmpty(codeBasePath)) { assemblyName.CodeBase = codeBasePath; } return LoadAssembly(assemblyName); } } } }
// Licensed to the .NET Foundation under one or more 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.Reflection; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.ServiceHub.Framework; using Microsoft.VisualStudio.Composition; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Remote { /// <summary> /// Manages remote workspaces. Currently supports only a single, primary workspace of kind <see cref="WorkspaceKind.RemoteWorkspace"/>. /// In future it should support workspaces of all kinds. /// </summary> internal class RemoteWorkspaceManager { /// <summary> /// Default workspace manager used by the product. Tests may specify a custom <see cref="RemoteWorkspaceManager"/> /// in order to override workspace services. /// </summary> internal static readonly RemoteWorkspaceManager Default = new RemoteWorkspaceManager( new SolutionAssetCache(cleanupInterval: TimeSpan.FromMinutes(1), purgeAfter: TimeSpan.FromMinutes(3), gcAfter: TimeSpan.FromMinutes(5))); internal static readonly ImmutableArray<Assembly> RemoteHostAssemblies = MefHostServices.DefaultAssemblies .Add(typeof(BrokeredServiceBase).Assembly) .Add(typeof(RemoteWorkspacesResources).Assembly); private readonly Lazy<RemoteWorkspace> _lazyPrimaryWorkspace; internal readonly SolutionAssetCache SolutionAssetCache; public RemoteWorkspaceManager(SolutionAssetCache assetCache) { _lazyPrimaryWorkspace = new Lazy<RemoteWorkspace>(CreatePrimaryWorkspace); SolutionAssetCache = assetCache; } private static ComposableCatalog CreateCatalog(ImmutableArray<Assembly> assemblies) { var resolver = new Resolver(SimpleAssemblyLoader.Instance); var discovery = new AttributedPartDiscovery(resolver, isNonPublicSupported: true); var parts = Task.Run(async () => await discovery.CreatePartsAsync(assemblies).ConfigureAwait(false)).GetAwaiter().GetResult(); return ComposableCatalog.Create(resolver).AddParts(parts); } private static IExportProviderFactory CreateExportProviderFactory(ComposableCatalog catalog) { var configuration = CompositionConfiguration.Create(catalog); var runtimeComposition = RuntimeComposition.CreateRuntimeComposition(configuration); return runtimeComposition.CreateExportProviderFactory(); } private static RemoteWorkspace CreatePrimaryWorkspace() { var catalog = CreateCatalog(RemoteHostAssemblies); var exportProviderFactory = CreateExportProviderFactory(catalog); var exportProvider = exportProviderFactory.CreateExportProvider(); return new RemoteWorkspace(VisualStudioMefHostServices.Create(exportProvider), WorkspaceKind.RemoteWorkspace); } public virtual RemoteWorkspace GetWorkspace() => _lazyPrimaryWorkspace.Value; public ValueTask<Solution> GetSolutionAsync(ServiceBrokerClient client, PinnedSolutionInfo solutionInfo, CancellationToken cancellationToken) { var assetSource = new SolutionAssetSource(client); var workspace = GetWorkspace(); var assetProvider = workspace.CreateAssetProvider(solutionInfo, SolutionAssetCache, assetSource); return workspace.GetSolutionAsync(assetProvider, solutionInfo.SolutionChecksum, solutionInfo.FromPrimaryBranch, solutionInfo.WorkspaceVersion, solutionInfo.ProjectId, cancellationToken); } private sealed class SimpleAssemblyLoader : IAssemblyLoader { public static readonly IAssemblyLoader Instance = new SimpleAssemblyLoader(); public Assembly LoadAssembly(AssemblyName assemblyName) => Assembly.Load(assemblyName); public Assembly LoadAssembly(string assemblyFullName, string codeBasePath) { var assemblyName = new AssemblyName(assemblyFullName); if (!string.IsNullOrEmpty(codeBasePath)) { assemblyName.CodeBase = codeBasePath; } return LoadAssembly(assemblyName); } } } }
-1
dotnet/roslyn
56,450
Implement INamespaceTypeReference.GetUnit for RootModuleType
Fixes #56412.
AlekseyTs
"2021-09-16T16:44:04Z"
"2021-09-17T18:21:59Z"
4b06ee428bafa0141c9eb3250003a19109dcfc86
d695369176aa109f0e0fb8b0019294aaa0823a54
Implement INamespaceTypeReference.GetUnit for RootModuleType. Fixes #56412.
./src/Workspaces/Core/Portable/ExternalAccess/VSTypeScript/Api/VSTypeScriptDocumentationCommentWrapper.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.Shared.Utilities; namespace Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript.Api { internal readonly struct VSTypeScriptDocumentationCommentWrapper { private readonly DocumentationComment _underlyingObject; public VSTypeScriptDocumentationCommentWrapper(DocumentationComment underlyingObject) => _underlyingObject = underlyingObject; public static VSTypeScriptDocumentationCommentWrapper FromXmlFragment(string xml) => new(DocumentationComment.FromXmlFragment(xml)); public bool IsDefault => _underlyingObject == null; public string? SummaryTextOpt => _underlyingObject?.SummaryText; public string? GetParameterTextOpt(string parameterName) => _underlyingObject?.GetParameterText(parameterName); } }
// Licensed to the .NET Foundation under one or more 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.Shared.Utilities; namespace Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript.Api { internal readonly struct VSTypeScriptDocumentationCommentWrapper { private readonly DocumentationComment _underlyingObject; public VSTypeScriptDocumentationCommentWrapper(DocumentationComment underlyingObject) => _underlyingObject = underlyingObject; public static VSTypeScriptDocumentationCommentWrapper FromXmlFragment(string xml) => new(DocumentationComment.FromXmlFragment(xml)); public bool IsDefault => _underlyingObject == null; public string? SummaryTextOpt => _underlyingObject?.SummaryText; public string? GetParameterTextOpt(string parameterName) => _underlyingObject?.GetParameterText(parameterName); } }
-1
dotnet/roslyn
56,450
Implement INamespaceTypeReference.GetUnit for RootModuleType
Fixes #56412.
AlekseyTs
"2021-09-16T16:44:04Z"
"2021-09-17T18:21:59Z"
4b06ee428bafa0141c9eb3250003a19109dcfc86
d695369176aa109f0e0fb8b0019294aaa0823a54
Implement INamespaceTypeReference.GetUnit for RootModuleType. Fixes #56412.
./src/Compilers/CSharp/Portable/Utilities/ValueSetFactory.SByteTC.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.Diagnostics; namespace Microsoft.CodeAnalysis.CSharp { using static BinaryOperatorKind; internal static partial class ValueSetFactory { private struct SByteTC : INumericTC<sbyte> { sbyte INumericTC<sbyte>.MinValue => sbyte.MinValue; sbyte INumericTC<sbyte>.MaxValue => sbyte.MaxValue; sbyte INumericTC<sbyte>.Zero => 0; bool INumericTC<sbyte>.Related(BinaryOperatorKind relation, sbyte left, sbyte right) { switch (relation) { case Equal: return left == right; case GreaterThanOrEqual: return left >= right; case GreaterThan: return left > right; case LessThanOrEqual: return left <= right; case LessThan: return left < right; default: throw new ArgumentException("relation"); } } sbyte INumericTC<sbyte>.Next(sbyte value) { Debug.Assert(value != sbyte.MaxValue); return (sbyte)(value + 1); } sbyte INumericTC<sbyte>.Prev(sbyte value) { Debug.Assert(value != sbyte.MinValue); return (sbyte)(value - 1); } sbyte INumericTC<sbyte>.FromConstantValue(ConstantValue constantValue) => constantValue.IsBad ? (sbyte)0 : constantValue.SByteValue; public ConstantValue ToConstantValue(sbyte value) => ConstantValue.Create(value); string INumericTC<sbyte>.ToString(sbyte value) => value.ToString(); sbyte INumericTC<sbyte>.Random(Random random) { return (sbyte)random.Next(); } } } }
// Licensed to the .NET Foundation under one or more 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.Diagnostics; namespace Microsoft.CodeAnalysis.CSharp { using static BinaryOperatorKind; internal static partial class ValueSetFactory { private struct SByteTC : INumericTC<sbyte> { sbyte INumericTC<sbyte>.MinValue => sbyte.MinValue; sbyte INumericTC<sbyte>.MaxValue => sbyte.MaxValue; sbyte INumericTC<sbyte>.Zero => 0; bool INumericTC<sbyte>.Related(BinaryOperatorKind relation, sbyte left, sbyte right) { switch (relation) { case Equal: return left == right; case GreaterThanOrEqual: return left >= right; case GreaterThan: return left > right; case LessThanOrEqual: return left <= right; case LessThan: return left < right; default: throw new ArgumentException("relation"); } } sbyte INumericTC<sbyte>.Next(sbyte value) { Debug.Assert(value != sbyte.MaxValue); return (sbyte)(value + 1); } sbyte INumericTC<sbyte>.Prev(sbyte value) { Debug.Assert(value != sbyte.MinValue); return (sbyte)(value - 1); } sbyte INumericTC<sbyte>.FromConstantValue(ConstantValue constantValue) => constantValue.IsBad ? (sbyte)0 : constantValue.SByteValue; public ConstantValue ToConstantValue(sbyte value) => ConstantValue.Create(value); string INumericTC<sbyte>.ToString(sbyte value) => value.ToString(); sbyte INumericTC<sbyte>.Random(Random random) { return (sbyte)random.Next(); } } } }
-1
dotnet/roslyn
56,450
Implement INamespaceTypeReference.GetUnit for RootModuleType
Fixes #56412.
AlekseyTs
"2021-09-16T16:44:04Z"
"2021-09-17T18:21:59Z"
4b06ee428bafa0141c9eb3250003a19109dcfc86
d695369176aa109f0e0fb8b0019294aaa0823a54
Implement INamespaceTypeReference.GetUnit for RootModuleType. Fixes #56412.
./src/Compilers/Core/MSBuildTaskTests/TestUtilities/DotNetSdkVersionAttribute.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.BuildTasks.UnitTests { /// <summary> /// Attribute added to the test assembly during build. /// Captures the version of dotnet SDK the build is targeting. /// </summary> [AttributeUsage(AttributeTargets.Assembly)] public sealed class DotNetSdkVersionAttribute : Attribute { public string Version { get; } public DotNetSdkVersionAttribute(string version) { Version = version; } } }
// Licensed to the .NET Foundation under one or more 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.BuildTasks.UnitTests { /// <summary> /// Attribute added to the test assembly during build. /// Captures the version of dotnet SDK the build is targeting. /// </summary> [AttributeUsage(AttributeTargets.Assembly)] public sealed class DotNetSdkVersionAttribute : Attribute { public string Version { get; } public DotNetSdkVersionAttribute(string version) { Version = version; } } }
-1
dotnet/roslyn
56,450
Implement INamespaceTypeReference.GetUnit for RootModuleType
Fixes #56412.
AlekseyTs
"2021-09-16T16:44:04Z"
"2021-09-17T18:21:59Z"
4b06ee428bafa0141c9eb3250003a19109dcfc86
d695369176aa109f0e0fb8b0019294aaa0823a54
Implement INamespaceTypeReference.GetUnit for RootModuleType. Fixes #56412.
./src/Workspaces/Core/Portable/Workspace/Solution/SolutionState.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.Diagnostics.CodeAnalysis; using System.Linq; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Logging; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Remote; using Microsoft.CodeAnalysis.Serialization; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// Represents a set of projects and their source code documents. /// /// this is a green node of Solution like ProjectState/DocumentState are for /// Project and Document. /// </summary> internal partial class SolutionState { // branch id for this solution private readonly BranchId _branchId; // the version of the workspace this solution is from private readonly int _workspaceVersion; private readonly SolutionInfo.SolutionAttributes _solutionAttributes; private readonly SolutionServices _solutionServices; private readonly ImmutableDictionary<ProjectId, ProjectState> _projectIdToProjectStateMap; private readonly ImmutableHashSet<string> _remoteSupportedLanguages; private readonly ImmutableDictionary<string, ImmutableArray<DocumentId>> _filePathToDocumentIdsMap; private readonly ProjectDependencyGraph _dependencyGraph; public readonly IReadOnlyList<AnalyzerReference> AnalyzerReferences; // Values for all these are created on demand. private ImmutableDictionary<ProjectId, ICompilationTracker> _projectIdToTrackerMap; // Checksums for this solution state private readonly ValueSource<SolutionStateChecksums> _lazyChecksums; /// <summary> /// Mapping from project-id to the options and checksums needed to synchronize it (and the projects it depends on) over /// to an OOP host. Options are stored as well so that when we are attempting to match a request for a particular project-subset /// we can return the options specific to that project-subset (which may be different from the <see cref="Options"/> defined /// for the entire solution). Lock this specific field before reading/writing to it. /// </summary> private readonly Dictionary<ProjectId, (SerializableOptionSet options, ValueSource<SolutionStateChecksums> checksums)> _lazyProjectChecksums = new(); // holds on data calculated based on the AnalyzerReferences list private readonly Lazy<HostDiagnosticAnalyzers> _lazyAnalyzers; /// <summary> /// Cache we use to map between unrooted symbols (i.e. assembly, module and dynamic symbols) and the project /// they came from. That way if we are asked about many symbols from the same assembly/module we can answer the /// question quickly after computing for the first one. Created on demand. /// </summary> private ConditionalWeakTable<ISymbol, ProjectId?>? _unrootedSymbolToProjectId; private static readonly Func<ConditionalWeakTable<ISymbol, ProjectId?>> s_createTable = () => new ConditionalWeakTable<ISymbol, ProjectId?>(); private readonly SourceGeneratedDocumentState? _frozenSourceGeneratedDocumentState; private SolutionState( BranchId branchId, int workspaceVersion, SolutionServices solutionServices, SolutionInfo.SolutionAttributes solutionAttributes, IReadOnlyList<ProjectId> projectIds, SerializableOptionSet options, IReadOnlyList<AnalyzerReference> analyzerReferences, ImmutableDictionary<ProjectId, ProjectState> idToProjectStateMap, ImmutableHashSet<string> remoteSupportedLanguages, ImmutableDictionary<ProjectId, ICompilationTracker> projectIdToTrackerMap, ImmutableDictionary<string, ImmutableArray<DocumentId>> filePathToDocumentIdsMap, ProjectDependencyGraph dependencyGraph, Lazy<HostDiagnosticAnalyzers>? lazyAnalyzers, SourceGeneratedDocumentState? frozenSourceGeneratedDocument) { _branchId = branchId; _workspaceVersion = workspaceVersion; _solutionAttributes = solutionAttributes; _solutionServices = solutionServices; ProjectIds = projectIds; Options = options; AnalyzerReferences = analyzerReferences; _projectIdToProjectStateMap = idToProjectStateMap; _remoteSupportedLanguages = remoteSupportedLanguages; _projectIdToTrackerMap = projectIdToTrackerMap; _filePathToDocumentIdsMap = filePathToDocumentIdsMap; _dependencyGraph = dependencyGraph; _lazyAnalyzers = lazyAnalyzers ?? CreateLazyHostDiagnosticAnalyzers(analyzerReferences); _frozenSourceGeneratedDocumentState = frozenSourceGeneratedDocument; // when solution state is changed, we recalculate its checksum _lazyChecksums = new AsyncLazy<SolutionStateChecksums>( c => ComputeChecksumsAsync(projectsToInclude: null, Options, c), cacheResult: true); CheckInvariants(); // make sure we don't accidentally capture any state but the list of references: static Lazy<HostDiagnosticAnalyzers> CreateLazyHostDiagnosticAnalyzers(IReadOnlyList<AnalyzerReference> analyzerReferences) => new(() => new HostDiagnosticAnalyzers(analyzerReferences)); } public SolutionState( BranchId primaryBranchId, SolutionServices solutionServices, SolutionInfo.SolutionAttributes solutionAttributes, SerializableOptionSet options, IReadOnlyList<AnalyzerReference> analyzerReferences) : this( primaryBranchId, workspaceVersion: 0, solutionServices, solutionAttributes, projectIds: SpecializedCollections.EmptyBoxedImmutableArray<ProjectId>(), options, analyzerReferences, idToProjectStateMap: ImmutableDictionary<ProjectId, ProjectState>.Empty, remoteSupportedLanguages: ImmutableHashSet<string>.Empty, projectIdToTrackerMap: ImmutableDictionary<ProjectId, ICompilationTracker>.Empty, filePathToDocumentIdsMap: ImmutableDictionary.Create<string, ImmutableArray<DocumentId>>(StringComparer.OrdinalIgnoreCase), dependencyGraph: ProjectDependencyGraph.Empty, lazyAnalyzers: null, frozenSourceGeneratedDocument: null) { } public SolutionState WithNewWorkspace(Workspace workspace, int workspaceVersion) { var services = workspace != _solutionServices.Workspace ? new SolutionServices(workspace) : _solutionServices; // Note: this will potentially have problems if the workspace services are different, as some services // get locked-in by document states and project states when first constructed. return CreatePrimarySolution(branchId: workspace.PrimaryBranchId, workspaceVersion: workspaceVersion, services: services); } public HostDiagnosticAnalyzers Analyzers => _lazyAnalyzers.Value; public SolutionInfo.SolutionAttributes SolutionAttributes => _solutionAttributes; public SourceGeneratedDocumentState? FrozenSourceGeneratedDocumentState => _frozenSourceGeneratedDocumentState; public ImmutableDictionary<ProjectId, ProjectState> ProjectStates => _projectIdToProjectStateMap; public int WorkspaceVersion => _workspaceVersion; public SolutionServices Services => _solutionServices; public SerializableOptionSet Options { get; } /// <summary> /// branch id of this solution /// /// currently, it only supports one level of branching. there is a primary branch of a workspace and all other /// branches that are branched from the primary branch. /// /// one still can create multiple forked solutions from an already branched solution, but versions among those /// can't be reliably used and compared. /// /// version only has a meaning between primary solution and branched one or between solutions from same branch. /// </summary> public BranchId BranchId => _branchId; /// <summary> /// The Workspace this solution is associated with. /// </summary> public Workspace Workspace => _solutionServices.Workspace; /// <summary> /// The Id of the solution. Multiple solution instances may share the same Id. /// </summary> public SolutionId Id => _solutionAttributes.Id; /// <summary> /// The path to the solution file or null if there is no solution file. /// </summary> public string? FilePath => _solutionAttributes.FilePath; /// <summary> /// The solution version. This equates to the solution file's version. /// </summary> public VersionStamp Version => _solutionAttributes.Version; /// <summary> /// A list of all the ids for all the projects contained by the solution. /// </summary> public IReadOnlyList<ProjectId> ProjectIds { get; } // Only run this in debug builds; even the .Any() call across all projects can be expensive when there's a lot of them. [Conditional("DEBUG")] private void CheckInvariants() { Contract.ThrowIfFalse(_projectIdToProjectStateMap.Count == ProjectIds.Count); Contract.ThrowIfFalse(_projectIdToProjectStateMap.Count == _dependencyGraph.ProjectIds.Count); // An id shouldn't point at a tracker for a different project. Contract.ThrowIfTrue(_projectIdToTrackerMap.Any(kvp => kvp.Key != kvp.Value.ProjectState.Id)); // project ids must be the same: Debug.Assert(_projectIdToProjectStateMap.Keys.SetEquals(ProjectIds)); Debug.Assert(_projectIdToProjectStateMap.Keys.SetEquals(_dependencyGraph.ProjectIds)); Debug.Assert(_remoteSupportedLanguages.SetEquals(GetRemoteSupportedProjectLanguages(_projectIdToProjectStateMap))); } private SolutionState Branch( SolutionInfo.SolutionAttributes? solutionAttributes = null, IReadOnlyList<ProjectId>? projectIds = null, SerializableOptionSet? options = null, IReadOnlyList<AnalyzerReference>? analyzerReferences = null, ImmutableDictionary<ProjectId, ProjectState>? idToProjectStateMap = null, ImmutableHashSet<string>? remoteSupportedProjectLanguages = null, ImmutableDictionary<ProjectId, ICompilationTracker>? projectIdToTrackerMap = null, ImmutableDictionary<string, ImmutableArray<DocumentId>>? filePathToDocumentIdsMap = null, ProjectDependencyGraph? dependencyGraph = null, Optional<SourceGeneratedDocumentState?> frozenSourceGeneratedDocument = default) { var branchId = GetBranchId(); if (idToProjectStateMap is not null) { Contract.ThrowIfNull(remoteSupportedProjectLanguages); } solutionAttributes ??= _solutionAttributes; projectIds ??= ProjectIds; idToProjectStateMap ??= _projectIdToProjectStateMap; remoteSupportedProjectLanguages ??= _remoteSupportedLanguages; Debug.Assert(remoteSupportedProjectLanguages.SetEquals(GetRemoteSupportedProjectLanguages(idToProjectStateMap))); options ??= Options.WithLanguages(remoteSupportedProjectLanguages); analyzerReferences ??= AnalyzerReferences; projectIdToTrackerMap ??= _projectIdToTrackerMap; filePathToDocumentIdsMap ??= _filePathToDocumentIdsMap; dependencyGraph ??= _dependencyGraph; var newFrozenSourceGeneratedDocumentState = frozenSourceGeneratedDocument.HasValue ? frozenSourceGeneratedDocument.Value : _frozenSourceGeneratedDocumentState; var analyzerReferencesEqual = AnalyzerReferences.SequenceEqual(analyzerReferences); if (branchId == _branchId && solutionAttributes == _solutionAttributes && projectIds == ProjectIds && options == Options && analyzerReferencesEqual && idToProjectStateMap == _projectIdToProjectStateMap && projectIdToTrackerMap == _projectIdToTrackerMap && filePathToDocumentIdsMap == _filePathToDocumentIdsMap && dependencyGraph == _dependencyGraph && newFrozenSourceGeneratedDocumentState == _frozenSourceGeneratedDocumentState) { return this; } return new SolutionState( branchId, _workspaceVersion, _solutionServices, solutionAttributes, projectIds, options, analyzerReferences, idToProjectStateMap, remoteSupportedProjectLanguages, projectIdToTrackerMap, filePathToDocumentIdsMap, dependencyGraph, analyzerReferencesEqual ? _lazyAnalyzers : null, newFrozenSourceGeneratedDocumentState); } private SolutionState CreatePrimarySolution( BranchId branchId, int workspaceVersion, SolutionServices services) { if (branchId == _branchId && workspaceVersion == _workspaceVersion && services == _solutionServices) { return this; } return new SolutionState( branchId, workspaceVersion, services, _solutionAttributes, ProjectIds, Options, AnalyzerReferences, _projectIdToProjectStateMap, _remoteSupportedLanguages, _projectIdToTrackerMap, _filePathToDocumentIdsMap, _dependencyGraph, _lazyAnalyzers, frozenSourceGeneratedDocument: null); } private BranchId GetBranchId() { // currently we only support one level branching. // my reasonings are // 1. it seems there is no-one who needs sub branches. // 2. this lets us to branch without explicit branch API return _branchId == Workspace.PrimaryBranchId ? BranchId.GetNextId() : _branchId; } /// <summary> /// The version of the most recently modified project. /// </summary> public VersionStamp GetLatestProjectVersion() { // this may produce a version that is out of sync with the actual Document versions. var latestVersion = VersionStamp.Default; foreach (var project in this.ProjectStates.Values) { latestVersion = project.Version.GetNewerVersion(latestVersion); } return latestVersion; } /// <summary> /// True if the solution contains a project with the specified project ID. /// </summary> public bool ContainsProject([NotNullWhen(returnValue: true)] ProjectId? projectId) => projectId != null && _projectIdToProjectStateMap.ContainsKey(projectId); /// <summary> /// True if the solution contains the document in one of its projects /// </summary> public bool ContainsDocument([NotNullWhen(returnValue: true)] DocumentId? documentId) { return documentId != null && this.ContainsProject(documentId.ProjectId) && this.GetProjectState(documentId.ProjectId)!.DocumentStates.Contains(documentId); } /// <summary> /// True if the solution contains the additional document in one of its projects /// </summary> public bool ContainsAdditionalDocument([NotNullWhen(returnValue: true)] DocumentId? documentId) { return documentId != null && this.ContainsProject(documentId.ProjectId) && this.GetProjectState(documentId.ProjectId)!.AdditionalDocumentStates.Contains(documentId); } /// <summary> /// True if the solution contains the analyzer config document in one of its projects /// </summary> public bool ContainsAnalyzerConfigDocument([NotNullWhen(returnValue: true)] DocumentId? documentId) { return documentId != null && this.ContainsProject(documentId.ProjectId) && this.GetProjectState(documentId.ProjectId)!.AnalyzerConfigDocumentStates.Contains(documentId); } private DocumentState GetRequiredDocumentState(DocumentId documentId) => GetRequiredProjectState(documentId.ProjectId).DocumentStates.GetRequiredState(documentId); private AdditionalDocumentState GetRequiredAdditionalDocumentState(DocumentId documentId) => GetRequiredProjectState(documentId.ProjectId).AdditionalDocumentStates.GetRequiredState(documentId); private AnalyzerConfigDocumentState GetRequiredAnalyzerConfigDocumentState(DocumentId documentId) => GetRequiredProjectState(documentId.ProjectId).AnalyzerConfigDocumentStates.GetRequiredState(documentId); internal DocumentState? GetDocumentState(SyntaxTree? syntaxTree, ProjectId? projectId) { if (syntaxTree != null) { // is this tree known to be associated with a document? var documentId = DocumentState.GetDocumentIdForTree(syntaxTree); if (documentId != null && (projectId == null || documentId.ProjectId == projectId)) { // does this solution even have the document? var projectState = GetProjectState(documentId.ProjectId); if (projectState != null) { var document = projectState.DocumentStates.GetState(documentId); if (document != null) { // does this document really have the syntax tree? if (document.TryGetSyntaxTree(out var documentTree) && documentTree == syntaxTree) { return document; } } else { var generatedDocument = TryGetSourceGeneratedDocumentStateForAlreadyGeneratedId(documentId); if (generatedDocument != null) { // does this document really have the syntax tree? if (generatedDocument.TryGetSyntaxTree(out var documentTree) && documentTree == syntaxTree) { return generatedDocument; } } } } } } return null; } public Task<VersionStamp> GetDependentVersionAsync(ProjectId projectId, CancellationToken cancellationToken) => this.GetCompilationTracker(projectId).GetDependentVersionAsync(this, cancellationToken); public Task<VersionStamp> GetDependentSemanticVersionAsync(ProjectId projectId, CancellationToken cancellationToken) => this.GetCompilationTracker(projectId).GetDependentSemanticVersionAsync(this, cancellationToken); public ProjectState? GetProjectState(ProjectId projectId) { _projectIdToProjectStateMap.TryGetValue(projectId, out var state); return state; } public ProjectState GetRequiredProjectState(ProjectId projectId) { var result = GetProjectState(projectId); Contract.ThrowIfNull(result); return result; } /// <summary> /// Gets the <see cref="Project"/> associated with an assembly symbol. /// </summary> public ProjectState? GetProjectState(IAssemblySymbol? assemblySymbol) { if (assemblySymbol == null) return null; s_assemblyOrModuleSymbolToProjectMap.TryGetValue(assemblySymbol, out var id); return id == null ? null : this.GetProjectState(id); } private bool TryGetCompilationTracker(ProjectId projectId, [NotNullWhen(returnValue: true)] out ICompilationTracker? tracker) => _projectIdToTrackerMap.TryGetValue(projectId, out tracker); private static readonly Func<ProjectId, SolutionState, CompilationTracker> s_createCompilationTrackerFunction = CreateCompilationTracker; private static CompilationTracker CreateCompilationTracker(ProjectId projectId, SolutionState solution) { var projectState = solution.GetProjectState(projectId); Contract.ThrowIfNull(projectState); return new CompilationTracker(projectState); } private ICompilationTracker GetCompilationTracker(ProjectId projectId) { if (!_projectIdToTrackerMap.TryGetValue(projectId, out var tracker)) { tracker = ImmutableInterlocked.GetOrAdd(ref _projectIdToTrackerMap, projectId, s_createCompilationTrackerFunction, this); } return tracker; } private SolutionState AddProject(ProjectId projectId, ProjectState projectState) { // changed project list so, increment version. var newSolutionAttributes = _solutionAttributes.With(version: Version.GetNewerVersion()); var newProjectIds = ProjectIds.ToImmutableArray().Add(projectId); var newStateMap = _projectIdToProjectStateMap.Add(projectId, projectState); var newLanguages = RemoteSupportedLanguages.IsSupported(projectState.Language) ? _remoteSupportedLanguages.Add(projectState.Language) : _remoteSupportedLanguages; var newDependencyGraph = _dependencyGraph .WithAdditionalProject(projectId) .WithAdditionalProjectReferences(projectId, projectState.ProjectReferences); // It's possible that another project already in newStateMap has a reference to this project that we're adding, since we allow // dangling references like that. If so, we'll need to link those in too. foreach (var newState in newStateMap) { foreach (var projectReference in newState.Value.ProjectReferences) { if (projectReference.ProjectId == projectId) { newDependencyGraph = newDependencyGraph.WithAdditionalProjectReferences( newState.Key, SpecializedCollections.SingletonReadOnlyList(projectReference)); break; } } } var newTrackerMap = CreateCompilationTrackerMap(projectId, newDependencyGraph); var newFilePathToDocumentIdsMap = CreateFilePathToDocumentIdsMapWithAddedDocuments(GetDocumentStates(newStateMap[projectId])); return Branch( solutionAttributes: newSolutionAttributes, projectIds: newProjectIds, idToProjectStateMap: newStateMap, remoteSupportedProjectLanguages: newLanguages, projectIdToTrackerMap: newTrackerMap, filePathToDocumentIdsMap: newFilePathToDocumentIdsMap, dependencyGraph: newDependencyGraph); } /// <summary> /// Create a new solution instance that includes a project with the specified project information. /// </summary> public SolutionState AddProject(ProjectInfo projectInfo) { if (projectInfo == null) { throw new ArgumentNullException(nameof(projectInfo)); } var projectId = projectInfo.Id; var language = projectInfo.Language; if (language == null) { throw new ArgumentNullException(nameof(language)); } var displayName = projectInfo.Name; if (displayName == null) { throw new ArgumentNullException(nameof(displayName)); } CheckNotContainsProject(projectId); var languageServices = this.Workspace.Services.GetLanguageServices(language); if (languageServices == null) { throw new ArgumentException(string.Format(WorkspacesResources.The_language_0_is_not_supported, language)); } var newProject = new ProjectState(projectInfo, languageServices, _solutionServices); return this.AddProject(newProject.Id, newProject); } private ImmutableDictionary<string, ImmutableArray<DocumentId>> CreateFilePathToDocumentIdsMapWithAddedDocuments(IEnumerable<TextDocumentState> documentStates) { var builder = _filePathToDocumentIdsMap.ToBuilder(); foreach (var documentState in documentStates) { var filePath = documentState.FilePath; if (RoslynString.IsNullOrEmpty(filePath)) { continue; } builder.MultiAdd(filePath, documentState.Id); } return builder.ToImmutable(); } private static IEnumerable<TextDocumentState> GetDocumentStates(ProjectState projectState) => projectState.DocumentStates.States.Values .Concat<TextDocumentState>(projectState.AdditionalDocumentStates.States.Values) .Concat(projectState.AnalyzerConfigDocumentStates.States.Values); /// <summary> /// Create a new solution instance without the project specified. /// </summary> public SolutionState RemoveProject(ProjectId projectId) { if (projectId == null) { throw new ArgumentNullException(nameof(projectId)); } CheckContainsProject(projectId); // changed project list so, increment version. var newSolutionAttributes = _solutionAttributes.With(version: this.Version.GetNewerVersion()); var newProjectIds = ProjectIds.ToImmutableArray().Remove(projectId); var newStateMap = _projectIdToProjectStateMap.Remove(projectId); // Remote supported languages only changes if the removed project is the last project of a supported language. var newLanguages = _remoteSupportedLanguages; if (_projectIdToProjectStateMap.TryGetValue(projectId, out var projectState) && RemoteSupportedLanguages.IsSupported(projectState.Language)) { var stillSupportsLanguage = false; foreach (var (id, state) in _projectIdToProjectStateMap) { if (id == projectId) continue; if (state.Language == projectState.Language) { stillSupportsLanguage = true; break; } } if (!stillSupportsLanguage) { newLanguages = newLanguages.Remove(projectState.Language); } } var newDependencyGraph = _dependencyGraph.WithProjectRemoved(projectId); var newTrackerMap = CreateCompilationTrackerMap(projectId, newDependencyGraph); var newFilePathToDocumentIdsMap = CreateFilePathToDocumentIdsMapWithRemovedDocuments(GetDocumentStates(_projectIdToProjectStateMap[projectId])); return this.Branch( solutionAttributes: newSolutionAttributes, projectIds: newProjectIds, idToProjectStateMap: newStateMap, remoteSupportedProjectLanguages: newLanguages, projectIdToTrackerMap: newTrackerMap.Remove(projectId), filePathToDocumentIdsMap: newFilePathToDocumentIdsMap, dependencyGraph: newDependencyGraph); } private ImmutableDictionary<string, ImmutableArray<DocumentId>> CreateFilePathToDocumentIdsMapWithRemovedDocuments(IEnumerable<TextDocumentState> documentStates) { var builder = _filePathToDocumentIdsMap.ToBuilder(); foreach (var documentState in documentStates) { var filePath = documentState.FilePath; if (RoslynString.IsNullOrEmpty(filePath)) { continue; } if (!builder.TryGetValue(filePath, out var documentIdsWithPath) || !documentIdsWithPath.Contains(documentState.Id)) { throw new ArgumentException($"The given documentId was not found in '{nameof(_filePathToDocumentIdsMap)}'."); } builder.MultiRemove(filePath, documentState.Id); } return builder.ToImmutable(); } private ImmutableDictionary<string, ImmutableArray<DocumentId>> CreateFilePathToDocumentIdsMapWithFilePath(DocumentId documentId, string? oldFilePath, string? newFilePath) { if (oldFilePath == newFilePath) { return _filePathToDocumentIdsMap; } var builder = _filePathToDocumentIdsMap.ToBuilder(); if (!RoslynString.IsNullOrEmpty(oldFilePath)) { builder.MultiRemove(oldFilePath, documentId); } if (!RoslynString.IsNullOrEmpty(newFilePath)) { builder.MultiAdd(newFilePath, documentId); } return builder.ToImmutable(); } /// <summary> /// Creates a new solution instance with the project specified updated to have the new /// assembly name. /// </summary> public SolutionState WithProjectAssemblyName(ProjectId projectId, string assemblyName) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithAssemblyName(assemblyName); if (oldProject == newProject) { return this; } return ForkProject(newProject, new CompilationAndGeneratorDriverTranslationAction.ProjectAssemblyNameAction(assemblyName)); } /// <summary> /// Creates a new solution instance with the project specified updated to have the output file path. /// </summary> public SolutionState WithProjectOutputFilePath(ProjectId projectId, string? outputFilePath) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithOutputFilePath(outputFilePath); if (oldProject == newProject) { return this; } return ForkProject(newProject); } /// <summary> /// Creates a new solution instance with the project specified updated to have the output file path. /// </summary> public SolutionState WithProjectOutputRefFilePath(ProjectId projectId, string? outputRefFilePath) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithOutputRefFilePath(outputRefFilePath); if (oldProject == newProject) { return this; } return ForkProject(newProject); } /// <summary> /// Creates a new solution instance with the project specified updated to have the compiler output file path. /// </summary> public SolutionState WithProjectCompilationOutputInfo(ProjectId projectId, in CompilationOutputInfo info) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithCompilationOutputInfo(info); if (oldProject == newProject) { return this; } return ForkProject(newProject); } /// <summary> /// Creates a new solution instance with the project specified updated to have the default namespace. /// </summary> public SolutionState WithProjectDefaultNamespace(ProjectId projectId, string? defaultNamespace) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithDefaultNamespace(defaultNamespace); if (oldProject == newProject) { return this; } return ForkProject(newProject); } /// <summary> /// Creates a new solution instance with the project specified updated to have the name. /// </summary> public SolutionState WithProjectName(ProjectId projectId, string name) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithName(name); if (oldProject == newProject) { return this; } return ForkProject(newProject); } /// <summary> /// Creates a new solution instance with the project specified updated to have the project file path. /// </summary> public SolutionState WithProjectFilePath(ProjectId projectId, string? filePath) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithFilePath(filePath); if (oldProject == newProject) { return this; } return ForkProject(newProject); } /// <summary> /// Create a new solution instance with the project specified updated to have /// the specified compilation options. /// </summary> public SolutionState WithProjectCompilationOptions(ProjectId projectId, CompilationOptions options) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithCompilationOptions(options); if (oldProject == newProject) { return this; } return ForkProject(newProject, new CompilationAndGeneratorDriverTranslationAction.ProjectCompilationOptionsAction(newProject, isAnalyzerConfigChange: false)); } /// <summary> /// Create a new solution instance with the project specified updated to have /// the specified parse options. /// </summary> public SolutionState WithProjectParseOptions(ProjectId projectId, ParseOptions options) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithParseOptions(options); if (oldProject == newProject) { return this; } if (Workspace.PartialSemanticsEnabled) { // don't fork tracker with queued action since access via partial semantics can become inconsistent (throw). // Since changing options is rare event, it is okay to start compilation building from scratch. return ForkProject(newProject, forkTracker: false); } else { return ForkProject(newProject, new CompilationAndGeneratorDriverTranslationAction.ReplaceAllSyntaxTreesAction(newProject, isParseOptionChange: true)); } } /// <summary> /// Create a new solution instance with the project specified updated to have /// the specified hasAllInformation. /// </summary> public SolutionState WithHasAllInformation(ProjectId projectId, bool hasAllInformation) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithHasAllInformation(hasAllInformation); if (oldProject == newProject) { return this; } // fork without any change on compilation. return ForkProject(newProject); } /// <summary> /// Create a new solution instance with the project specified updated to have /// the specified runAnalyzers. /// </summary> public SolutionState WithRunAnalyzers(ProjectId projectId, bool runAnalyzers) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithRunAnalyzers(runAnalyzers); if (oldProject == newProject) { return this; } // fork without any change on compilation. return ForkProject(newProject); } /// <summary> /// Create a new solution instance with the project specified updated to include /// the specified project references. /// </summary> public SolutionState AddProjectReferences(ProjectId projectId, IReadOnlyCollection<ProjectReference> projectReferences) { if (projectReferences.Count == 0) { return this; } var oldProject = GetRequiredProjectState(projectId); var oldReferences = oldProject.ProjectReferences.ToImmutableArray(); var newReferences = oldReferences.AddRange(projectReferences); var newProject = oldProject.WithProjectReferences(newReferences); var newDependencyGraph = _dependencyGraph.WithAdditionalProjectReferences(projectId, projectReferences); return ForkProject(newProject, newDependencyGraph: newDependencyGraph); } /// <summary> /// Create a new solution instance with the project specified updated to no longer /// include the specified project reference. /// </summary> public SolutionState RemoveProjectReference(ProjectId projectId, ProjectReference projectReference) { var oldProject = GetRequiredProjectState(projectId); var oldReferences = oldProject.ProjectReferences.ToImmutableArray(); // Note: uses ProjectReference equality to compare references. var newReferences = oldReferences.Remove(projectReference); if (oldReferences == newReferences) { return this; } var newProject = oldProject.WithProjectReferences(newReferences); ProjectDependencyGraph newDependencyGraph; if (newProject.ContainsReferenceToProject(projectReference.ProjectId) || !_projectIdToProjectStateMap.ContainsKey(projectReference.ProjectId)) { // Two cases: // 1) The project contained multiple non-equivalent references to the project, // and not all of them were removed. The dependency graph doesn't change. // Note that there might be two references to the same project, one with // extern alias and the other without. These are not considered duplicates. // 2) The referenced project is not part of the solution and hence not included // in the dependency graph. newDependencyGraph = _dependencyGraph; } else { newDependencyGraph = _dependencyGraph.WithProjectReferenceRemoved(projectId, projectReference.ProjectId); } return ForkProject(newProject, newDependencyGraph: newDependencyGraph); } /// <summary> /// Create a new solution instance with the project specified updated to contain /// the specified list of project references. /// </summary> public SolutionState WithProjectReferences(ProjectId projectId, IReadOnlyList<ProjectReference> projectReferences) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithProjectReferences(projectReferences); if (oldProject == newProject) { return this; } var newDependencyGraph = _dependencyGraph.WithProjectReferences(projectId, projectReferences); return ForkProject(newProject, newDependencyGraph: newDependencyGraph); } /// <summary> /// Creates a new solution instance with the project documents in the order by the specified document ids. /// The specified document ids must be the same as what is already in the project; no adding or removing is allowed. /// </summary> public SolutionState WithProjectDocumentsOrder(ProjectId projectId, ImmutableList<DocumentId> documentIds) { var oldProject = GetRequiredProjectState(projectId); if (documentIds.Count != oldProject.DocumentStates.Count) { throw new ArgumentException($"The specified documents do not equal the project document count.", nameof(documentIds)); } foreach (var id in documentIds) { if (!oldProject.DocumentStates.Contains(id)) { throw new InvalidOperationException($"The document '{id}' does not exist in the project."); } } var newProject = oldProject.UpdateDocumentsOrder(documentIds); if (oldProject == newProject) { return this; } return ForkProject(newProject, new CompilationAndGeneratorDriverTranslationAction.ReplaceAllSyntaxTreesAction(newProject, isParseOptionChange: false)); } /// <summary> /// Create a new solution instance with the project specified updated to include the /// specified metadata references. /// </summary> public SolutionState AddMetadataReferences(ProjectId projectId, IReadOnlyCollection<MetadataReference> metadataReferences) { if (metadataReferences.Count == 0) { return this; } var oldProject = GetRequiredProjectState(projectId); var oldReferences = oldProject.MetadataReferences.ToImmutableArray(); var newReferences = oldReferences.AddRange(metadataReferences); return ForkProject(oldProject.WithMetadataReferences(newReferences)); } /// <summary> /// Create a new solution instance with the project specified updated to no longer include /// the specified metadata reference. /// </summary> public SolutionState RemoveMetadataReference(ProjectId projectId, MetadataReference metadataReference) { var oldProject = GetRequiredProjectState(projectId); var oldReferences = oldProject.MetadataReferences.ToImmutableArray(); var newReferences = oldReferences.Remove(metadataReference); if (oldReferences == newReferences) { return this; } return ForkProject(oldProject.WithMetadataReferences(newReferences)); } /// <summary> /// Create a new solution instance with the project specified updated to include only the /// specified metadata references. /// </summary> public SolutionState WithProjectMetadataReferences(ProjectId projectId, IReadOnlyList<MetadataReference> metadataReferences) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithMetadataReferences(metadataReferences); if (oldProject == newProject) { return this; } return ForkProject(newProject); } /// <summary> /// Create a new solution instance with the project specified updated to include the /// specified analyzer references. /// </summary> public SolutionState AddAnalyzerReferences(ProjectId projectId, ImmutableArray<AnalyzerReference> analyzerReferences) { if (analyzerReferences.Length == 0) { return this; } var oldProject = GetRequiredProjectState(projectId); var oldReferences = oldProject.AnalyzerReferences.ToImmutableArray(); var newReferences = oldReferences.AddRange(analyzerReferences); return ForkProject( oldProject.WithAnalyzerReferences(newReferences), new CompilationAndGeneratorDriverTranslationAction.AddAnalyzerReferencesAction(analyzerReferences, oldProject.Language)); } /// <summary> /// Create a new solution instance with the project specified updated to no longer include /// the specified analyzer reference. /// </summary> public SolutionState RemoveAnalyzerReference(ProjectId projectId, AnalyzerReference analyzerReference) { var oldProject = GetRequiredProjectState(projectId); var oldReferences = oldProject.AnalyzerReferences.ToImmutableArray(); var newReferences = oldReferences.Remove(analyzerReference); if (oldReferences == newReferences) { return this; } return ForkProject( oldProject.WithAnalyzerReferences(newReferences), new CompilationAndGeneratorDriverTranslationAction.RemoveAnalyzerReferencesAction(ImmutableArray.Create(analyzerReference), oldProject.Language)); } /// <summary> /// Create a new solution instance with the project specified updated to include only the /// specified analyzer references. /// </summary> public SolutionState WithProjectAnalyzerReferences(ProjectId projectId, IEnumerable<AnalyzerReference> analyzerReferences) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithAnalyzerReferences(analyzerReferences); if (oldProject == newProject) { return this; } return ForkProject(newProject); } /// <summary> /// Create a new solution instance with the corresponding projects updated to include new /// documents defined by the document info. /// </summary> public SolutionState AddDocuments(ImmutableArray<DocumentInfo> documentInfos) { return AddDocumentsToMultipleProjects(documentInfos, (documentInfo, project) => project.CreateDocument(documentInfo, project.ParseOptions), (oldProject, documents) => (oldProject.AddDocuments(documents), new CompilationAndGeneratorDriverTranslationAction.AddDocumentsAction(documents))); } /// <summary> /// Core helper that takes a set of <see cref="DocumentInfo" />s and does the application of the appropriate documents to each project. /// </summary> /// <param name="documentInfos">The set of documents to add.</param> /// <param name="addDocumentsToProjectState">Returns the new <see cref="ProjectState"/> with the documents added, and the <see cref="CompilationAndGeneratorDriverTranslationAction"/> needed as well.</param> /// <returns></returns> private SolutionState AddDocumentsToMultipleProjects<T>( ImmutableArray<DocumentInfo> documentInfos, Func<DocumentInfo, ProjectState, T> createDocumentState, Func<ProjectState, ImmutableArray<T>, (ProjectState newState, CompilationAndGeneratorDriverTranslationAction translationAction)> addDocumentsToProjectState) where T : TextDocumentState { if (documentInfos.IsDefault) { throw new ArgumentNullException(nameof(documentInfos)); } if (documentInfos.IsEmpty) { return this; } // The documents might be contributing to multiple different projects; split them by project and then we'll process // project-at-a-time. var documentInfosByProjectId = documentInfos.ToLookup(d => d.Id.ProjectId); var newSolutionState = this; foreach (var documentInfosInProject in documentInfosByProjectId) { CheckContainsProject(documentInfosInProject.Key); var oldProjectState = this.GetProjectState(documentInfosInProject.Key)!; var newDocumentStatesForProjectBuilder = ArrayBuilder<T>.GetInstance(); foreach (var documentInfo in documentInfosInProject) { newDocumentStatesForProjectBuilder.Add(createDocumentState(documentInfo, oldProjectState)); } var newDocumentStatesForProject = newDocumentStatesForProjectBuilder.ToImmutableAndFree(); var (newProjectState, compilationTranslationAction) = addDocumentsToProjectState(oldProjectState, newDocumentStatesForProject); newSolutionState = newSolutionState.ForkProject(newProjectState, compilationTranslationAction, newFilePathToDocumentIdsMap: CreateFilePathToDocumentIdsMapWithAddedDocuments(newDocumentStatesForProject)); } return newSolutionState; } public SolutionState AddAdditionalDocuments(ImmutableArray<DocumentInfo> documentInfos) { return AddDocumentsToMultipleProjects(documentInfos, (documentInfo, project) => new AdditionalDocumentState(documentInfo, _solutionServices), (projectState, documents) => (projectState.AddAdditionalDocuments(documents), new CompilationAndGeneratorDriverTranslationAction.AddAdditionalDocumentsAction(documents))); } public SolutionState AddAnalyzerConfigDocuments(ImmutableArray<DocumentInfo> documentInfos) { // Adding a new analyzer config potentially modifies the compilation options return AddDocumentsToMultipleProjects(documentInfos, (documentInfo, project) => new AnalyzerConfigDocumentState(documentInfo, _solutionServices), (oldProject, documents) => { var newProject = oldProject.AddAnalyzerConfigDocuments(documents); return (newProject, new CompilationAndGeneratorDriverTranslationAction.ProjectCompilationOptionsAction(newProject, isAnalyzerConfigChange: true)); }); } public SolutionState RemoveAnalyzerConfigDocuments(ImmutableArray<DocumentId> documentIds) { return RemoveDocumentsFromMultipleProjects(documentIds, (projectState, documentId) => projectState.AnalyzerConfigDocumentStates.GetRequiredState(documentId), (oldProject, documentIds, _) => { var newProject = oldProject.RemoveAnalyzerConfigDocuments(documentIds); return (newProject, new CompilationAndGeneratorDriverTranslationAction.ProjectCompilationOptionsAction(newProject, isAnalyzerConfigChange: true)); }); } /// <summary> /// Creates a new solution instance that no longer includes the specified document. /// </summary> public SolutionState RemoveDocuments(ImmutableArray<DocumentId> documentIds) { return RemoveDocumentsFromMultipleProjects(documentIds, (projectState, documentId) => projectState.DocumentStates.GetRequiredState(documentId), (projectState, documentIds, documentStates) => (projectState.RemoveDocuments(documentIds), new CompilationAndGeneratorDriverTranslationAction.RemoveDocumentsAction(documentStates))); } private SolutionState RemoveDocumentsFromMultipleProjects<T>( ImmutableArray<DocumentId> documentIds, Func<ProjectState, DocumentId, T> getExistingTextDocumentState, Func<ProjectState, ImmutableArray<DocumentId>, ImmutableArray<T>, (ProjectState newState, CompilationAndGeneratorDriverTranslationAction translationAction)> removeDocumentsFromProjectState) where T : TextDocumentState { if (documentIds.IsEmpty) { return this; } // The documents might be contributing to multiple different projects; split them by project and then we'll process // project-at-a-time. var documentIdsByProjectId = documentIds.ToLookup(id => id.ProjectId); var newSolutionState = this; foreach (var documentIdsInProject in documentIdsByProjectId) { var oldProjectState = this.GetProjectState(documentIdsInProject.Key); if (oldProjectState == null) { throw new InvalidOperationException(string.Format(WorkspacesResources._0_is_not_part_of_the_workspace, documentIdsInProject.Key)); } var removedDocumentStatesBuilder = ArrayBuilder<T>.GetInstance(); foreach (var documentId in documentIdsInProject) { removedDocumentStatesBuilder.Add(getExistingTextDocumentState(oldProjectState, documentId)); } var removedDocumentStatesForProject = removedDocumentStatesBuilder.ToImmutableAndFree(); var (newProjectState, compilationTranslationAction) = removeDocumentsFromProjectState(oldProjectState, documentIdsInProject.ToImmutableArray(), removedDocumentStatesForProject); newSolutionState = newSolutionState.ForkProject(newProjectState, compilationTranslationAction, newFilePathToDocumentIdsMap: CreateFilePathToDocumentIdsMapWithRemovedDocuments(removedDocumentStatesForProject)); } return newSolutionState; } /// <summary> /// Creates a new solution instance that no longer includes the specified additional documents. /// </summary> public SolutionState RemoveAdditionalDocuments(ImmutableArray<DocumentId> documentIds) { return RemoveDocumentsFromMultipleProjects(documentIds, (projectState, documentId) => projectState.AdditionalDocumentStates.GetRequiredState(documentId), (projectState, documentIds, documentStates) => (projectState.RemoveAdditionalDocuments(documentIds), new CompilationAndGeneratorDriverTranslationAction.RemoveAdditionalDocumentsAction(documentStates))); } /// <summary> /// Creates a new solution instance with the document specified updated to have the specified name. /// </summary> public SolutionState WithDocumentName(DocumentId documentId, string name) { var oldDocument = GetRequiredDocumentState(documentId); if (oldDocument.Attributes.Name == name) { return this; } return UpdateDocumentState(oldDocument.UpdateName(name)); } /// <summary> /// Creates a new solution instance with the document specified updated to be contained in /// the sequence of logical folders. /// </summary> public SolutionState WithDocumentFolders(DocumentId documentId, IReadOnlyList<string> folders) { var oldDocument = GetRequiredDocumentState(documentId); if (oldDocument.Folders.SequenceEqual(folders)) { return this; } return UpdateDocumentState(oldDocument.UpdateFolders(folders)); } /// <summary> /// Creates a new solution instance with the document specified updated to have the specified file path. /// </summary> public SolutionState WithDocumentFilePath(DocumentId documentId, string? filePath) { var oldDocument = GetRequiredDocumentState(documentId); if (oldDocument.FilePath == filePath) { return this; } return UpdateDocumentState(oldDocument.UpdateFilePath(filePath)); } /// <summary> /// Creates a new solution instance with the document specified updated to have the text /// specified. /// </summary> public SolutionState WithDocumentText(DocumentId documentId, SourceText text, PreservationMode mode = PreservationMode.PreserveValue) { var oldDocument = GetRequiredDocumentState(documentId); if (oldDocument.TryGetText(out var oldText) && text == oldText) { return this; } return UpdateDocumentState(oldDocument.UpdateText(text, mode), textChanged: true); } /// <summary> /// Creates a new solution instance with the additional document specified updated to have the text /// specified. /// </summary> public SolutionState WithAdditionalDocumentText(DocumentId documentId, SourceText text, PreservationMode mode = PreservationMode.PreserveValue) { var oldDocument = GetRequiredAdditionalDocumentState(documentId); if (oldDocument.TryGetText(out var oldText) && text == oldText) { return this; } return UpdateAdditionalDocumentState(oldDocument.UpdateText(text, mode), textChanged: true); } /// <summary> /// Creates a new solution instance with the document specified updated to have the text /// specified. /// </summary> public SolutionState WithAnalyzerConfigDocumentText(DocumentId documentId, SourceText text, PreservationMode mode = PreservationMode.PreserveValue) { var oldDocument = GetRequiredAnalyzerConfigDocumentState(documentId); if (oldDocument.TryGetText(out var oldText) && text == oldText) { return this; } return UpdateAnalyzerConfigDocumentState(oldDocument.UpdateText(text, mode)); } /// <summary> /// Creates a new solution instance with the document specified updated to have the text /// and version specified. /// </summary> public SolutionState WithDocumentText(DocumentId documentId, TextAndVersion textAndVersion, PreservationMode mode = PreservationMode.PreserveValue) { var oldDocument = GetRequiredDocumentState(documentId); if (oldDocument.TryGetTextAndVersion(out var oldTextAndVersion) && textAndVersion == oldTextAndVersion) { return this; } return UpdateDocumentState(oldDocument.UpdateText(textAndVersion, mode), textChanged: true); } /// <summary> /// Creates a new solution instance with the additional document specified updated to have the text /// and version specified. /// </summary> public SolutionState WithAdditionalDocumentText(DocumentId documentId, TextAndVersion textAndVersion, PreservationMode mode = PreservationMode.PreserveValue) { var oldDocument = GetRequiredAdditionalDocumentState(documentId); if (oldDocument.TryGetTextAndVersion(out var oldTextAndVersion) && textAndVersion == oldTextAndVersion) { return this; } return UpdateAdditionalDocumentState(oldDocument.UpdateText(textAndVersion, mode), textChanged: true); } /// <summary> /// Creates a new solution instance with the analyzer config document specified updated to have the text /// and version specified. /// </summary> public SolutionState WithAnalyzerConfigDocumentText(DocumentId documentId, TextAndVersion textAndVersion, PreservationMode mode = PreservationMode.PreserveValue) { var oldDocument = GetRequiredAnalyzerConfigDocumentState(documentId); if (oldDocument.TryGetTextAndVersion(out var oldTextAndVersion) && textAndVersion == oldTextAndVersion) { return this; } return UpdateAnalyzerConfigDocumentState(oldDocument.UpdateText(textAndVersion, mode)); } /// <summary> /// Creates a new solution instance with the document specified updated to have a syntax tree /// rooted by the specified syntax node. /// </summary> public SolutionState WithDocumentSyntaxRoot(DocumentId documentId, SyntaxNode root, PreservationMode mode = PreservationMode.PreserveValue) { var oldDocument = GetRequiredDocumentState(documentId); if (oldDocument.TryGetSyntaxTree(out var oldTree) && oldTree.TryGetRoot(out var oldRoot) && oldRoot == root) { return this; } return UpdateDocumentState(oldDocument.UpdateTree(root, mode), textChanged: true); } private static async Task<Compilation> UpdateDocumentInCompilationAsync( Compilation compilation, DocumentState oldDocument, DocumentState newDocument, CancellationToken cancellationToken) { return compilation.ReplaceSyntaxTree( await oldDocument.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false), await newDocument.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false)); } /// <summary> /// Creates a new solution instance with the document specified updated to have the source /// code kind specified. /// </summary> public SolutionState WithDocumentSourceCodeKind(DocumentId documentId, SourceCodeKind sourceCodeKind) { var oldDocument = GetRequiredDocumentState(documentId); if (oldDocument.SourceCodeKind == sourceCodeKind) { return this; } return UpdateDocumentState(oldDocument.UpdateSourceCodeKind(sourceCodeKind), textChanged: true); } public SolutionState UpdateDocumentTextLoader(DocumentId documentId, TextLoader loader, SourceText? text, PreservationMode mode) { var oldDocument = GetRequiredDocumentState(documentId); // Assumes that text has changed. User could have closed a doc without saving and we are loading text from closed file with // old content. Also this should make sure we don't re-use latest doc version with data associated with opened document. return UpdateDocumentState(oldDocument.UpdateText(loader, text, mode), textChanged: true, recalculateDependentVersions: true); } /// <summary> /// Creates a new solution instance with the additional document specified updated to have the text /// supplied by the text loader. /// </summary> public SolutionState UpdateAdditionalDocumentTextLoader(DocumentId documentId, TextLoader loader, PreservationMode mode) { var oldDocument = GetRequiredAdditionalDocumentState(documentId); // Assumes that text has changed. User could have closed a doc without saving and we are loading text from closed file with // old content. Also this should make sure we don't re-use latest doc version with data associated with opened document. return UpdateAdditionalDocumentState(oldDocument.UpdateText(loader, mode), textChanged: true, recalculateDependentVersions: true); } /// <summary> /// Creates a new solution instance with the analyzer config document specified updated to have the text /// supplied by the text loader. /// </summary> public SolutionState UpdateAnalyzerConfigDocumentTextLoader(DocumentId documentId, TextLoader loader, PreservationMode mode) { var oldDocument = GetRequiredAnalyzerConfigDocumentState(documentId); // Assumes that text has changed. User could have closed a doc without saving and we are loading text from closed file with // old content. Also this should make sure we don't re-use latest doc version with data associated with opened document. return UpdateAnalyzerConfigDocumentState(oldDocument.UpdateText(loader, mode)); } private SolutionState UpdateDocumentState(DocumentState newDocument, bool textChanged = false, bool recalculateDependentVersions = false) { var oldProject = GetProjectState(newDocument.Id.ProjectId)!; var newProject = oldProject.UpdateDocument(newDocument, textChanged, recalculateDependentVersions); // This method shouldn't have been called if the document has not changed. Debug.Assert(oldProject != newProject); var oldDocument = oldProject.DocumentStates.GetRequiredState(newDocument.Id); var newFilePathToDocumentIdsMap = CreateFilePathToDocumentIdsMapWithFilePath(newDocument.Id, oldDocument.FilePath, newDocument.FilePath); return ForkProject( newProject, new CompilationAndGeneratorDriverTranslationAction.TouchDocumentAction(oldDocument, newDocument), newFilePathToDocumentIdsMap: newFilePathToDocumentIdsMap); } private SolutionState UpdateAdditionalDocumentState(AdditionalDocumentState newDocument, bool textChanged = false, bool recalculateDependentVersions = false) { var oldProject = GetProjectState(newDocument.Id.ProjectId)!; var newProject = oldProject.UpdateAdditionalDocument(newDocument, textChanged, recalculateDependentVersions); // This method shouldn't have been called if the document has not changed. Debug.Assert(oldProject != newProject); var oldDocument = oldProject.AdditionalDocumentStates.GetRequiredState(newDocument.Id); return ForkProject( newProject, translate: new CompilationAndGeneratorDriverTranslationAction.TouchAdditionalDocumentAction(oldDocument, newDocument)); } private SolutionState UpdateAnalyzerConfigDocumentState(AnalyzerConfigDocumentState newDocument) { var oldProject = GetProjectState(newDocument.Id.ProjectId)!; var newProject = oldProject.UpdateAnalyzerConfigDocument(newDocument); // This method shouldn't have been called if the document has not changed. Debug.Assert(oldProject != newProject); return ForkProject(newProject, newProject.CompilationOptions != null ? new CompilationAndGeneratorDriverTranslationAction.ProjectCompilationOptionsAction(newProject, isAnalyzerConfigChange: true) : null); } /// <summary> /// Creates a new snapshot with an updated project and an action that will produce a new /// compilation matching the new project out of an old compilation. All dependent projects /// are fixed-up if the change to the new project affects its public metadata, and old /// dependent compilations are forgotten. /// </summary> private SolutionState ForkProject( ProjectState newProjectState, CompilationAndGeneratorDriverTranslationAction? translate = null, ProjectDependencyGraph? newDependencyGraph = null, ImmutableDictionary<string, ImmutableArray<DocumentId>>? newFilePathToDocumentIdsMap = null, bool forkTracker = true) { var projectId = newProjectState.Id; var newStateMap = _projectIdToProjectStateMap.SetItem(projectId, newProjectState); // Remote supported languages can only change if the project changes language. This is an unexpected edge // case, so it's not optimized for incremental updates. var newLanguages = !_projectIdToProjectStateMap.TryGetValue(projectId, out var projectState) || projectState.Language != newProjectState.Language ? GetRemoteSupportedProjectLanguages(newStateMap) : _remoteSupportedLanguages; newDependencyGraph ??= _dependencyGraph; var newTrackerMap = CreateCompilationTrackerMap(projectId, newDependencyGraph); // If we have a tracker for this project, then fork it as well (along with the // translation action and store it in the tracker map. if (newTrackerMap.TryGetValue(projectId, out var tracker)) { newTrackerMap = newTrackerMap.Remove(projectId); if (forkTracker) { newTrackerMap = newTrackerMap.Add(projectId, tracker.Fork(newProjectState, translate)); } } return this.Branch( idToProjectStateMap: newStateMap, remoteSupportedProjectLanguages: newLanguages, projectIdToTrackerMap: newTrackerMap, dependencyGraph: newDependencyGraph, filePathToDocumentIdsMap: newFilePathToDocumentIdsMap ?? _filePathToDocumentIdsMap); } /// <summary> /// Gets the set of <see cref="DocumentId"/>s in this <see cref="Solution"/> with a /// <see cref="TextDocument.FilePath"/> that matches the given file path. /// </summary> public ImmutableArray<DocumentId> GetDocumentIdsWithFilePath(string? filePath) { if (string.IsNullOrEmpty(filePath)) { return ImmutableArray<DocumentId>.Empty; } return _filePathToDocumentIdsMap.TryGetValue(filePath!, out var documentIds) ? documentIds : ImmutableArray<DocumentId>.Empty; } private static ProjectDependencyGraph CreateDependencyGraph( IReadOnlyList<ProjectId> projectIds, ImmutableDictionary<ProjectId, ProjectState> projectStates) { var map = projectStates.Values.Select(state => new KeyValuePair<ProjectId, ImmutableHashSet<ProjectId>>( state.Id, state.ProjectReferences.Where(pr => projectStates.ContainsKey(pr.ProjectId)).Select(pr => pr.ProjectId).ToImmutableHashSet())) .ToImmutableDictionary(); return new ProjectDependencyGraph(projectIds.ToImmutableHashSet(), map); } private ImmutableDictionary<ProjectId, ICompilationTracker> CreateCompilationTrackerMap(ProjectId changedProjectId, ProjectDependencyGraph dependencyGraph) { var builder = ImmutableDictionary.CreateBuilder<ProjectId, ICompilationTracker>(); IEnumerable<ProjectId>? dependencies = null; foreach (var (id, tracker) in _projectIdToTrackerMap) builder.Add(id, CanReuse(id) ? tracker : tracker.Fork(tracker.ProjectState)); return builder.ToImmutable(); // Returns true if 'tracker' can be reused for project 'id' bool CanReuse(ProjectId id) { if (id == changedProjectId) { return true; } // Check the dependency graph to see if project 'id' directly or transitively depends on 'projectId'. // If the information is not available, do not compute it. var forwardDependencies = dependencyGraph.TryGetProjectsThatThisProjectTransitivelyDependsOn(id); if (forwardDependencies is object && !forwardDependencies.Contains(changedProjectId)) { return true; } // Compute the set of all projects that depend on 'projectId'. This information answers the same // question as the previous check, but involves at most one transitive computation within the // dependency graph. dependencies ??= dependencyGraph.GetProjectsThatTransitivelyDependOnThisProject(changedProjectId); return !dependencies.Contains(id); } } public SolutionState WithOptions(SerializableOptionSet options) => Branch(options: options); public SolutionState AddAnalyzerReferences(IReadOnlyCollection<AnalyzerReference> analyzerReferences) { if (analyzerReferences.Count == 0) { return this; } var oldReferences = AnalyzerReferences.ToImmutableArray(); var newReferences = oldReferences.AddRange(analyzerReferences); return Branch(analyzerReferences: newReferences); } public SolutionState RemoveAnalyzerReference(AnalyzerReference analyzerReference) { var oldReferences = AnalyzerReferences.ToImmutableArray(); var newReferences = oldReferences.Remove(analyzerReference); if (oldReferences == newReferences) { return this; } return Branch(analyzerReferences: newReferences); } public SolutionState WithAnalyzerReferences(IReadOnlyList<AnalyzerReference> analyzerReferences) { if (analyzerReferences == AnalyzerReferences) { return this; } return Branch(analyzerReferences: analyzerReferences); } // this lock guards all the mutable fields (do not share lock with derived classes) private NonReentrantLock? _stateLockBackingField; private NonReentrantLock StateLock { get { // TODO: why did I need to do a nullable suppression here? return LazyInitializer.EnsureInitialized(ref _stateLockBackingField, NonReentrantLock.Factory)!; } } private WeakReference<SolutionState>? _latestSolutionWithPartialCompilation; private DateTime _timeOfLatestSolutionWithPartialCompilation; private DocumentId? _documentIdOfLatestSolutionWithPartialCompilation; /// <summary> /// Creates a branch of the solution that has its compilations frozen in whatever state they are in at the time, assuming a background compiler is /// busy building this compilations. /// /// A compilation for the project containing the specified document id will be guaranteed to exist with at least the syntax tree for the document. /// /// This not intended to be the public API, use Document.WithFrozenPartialSemantics() instead. /// </summary> public SolutionState WithFrozenPartialCompilationIncludingSpecificDocument(DocumentId documentId, CancellationToken cancellationToken) { try { var doc = this.GetRequiredDocumentState(documentId); var tree = doc.GetSyntaxTree(cancellationToken); using (this.StateLock.DisposableWait(cancellationToken)) { // in progress solutions are disabled for some testing if (this.Workspace is Workspace ws && ws.TestHookPartialSolutionsDisabled) { return this; } SolutionState? currentPartialSolution = null; if (_latestSolutionWithPartialCompilation != null) { _latestSolutionWithPartialCompilation.TryGetTarget(out currentPartialSolution); } var reuseExistingPartialSolution = currentPartialSolution != null && (DateTime.UtcNow - _timeOfLatestSolutionWithPartialCompilation).TotalSeconds < 0.1 && _documentIdOfLatestSolutionWithPartialCompilation == documentId; if (reuseExistingPartialSolution) { SolutionLogger.UseExistingPartialSolution(); return currentPartialSolution!; } // if we don't have one or it is stale, create a new partial solution var tracker = this.GetCompilationTracker(documentId.ProjectId); var newTracker = tracker.FreezePartialStateWithTree(this, doc, tree, cancellationToken); var newIdToProjectStateMap = _projectIdToProjectStateMap.SetItem(documentId.ProjectId, newTracker.ProjectState); var newLanguages = _remoteSupportedLanguages; var newIdToTrackerMap = _projectIdToTrackerMap.SetItem(documentId.ProjectId, newTracker); currentPartialSolution = this.Branch( idToProjectStateMap: newIdToProjectStateMap, remoteSupportedProjectLanguages: newLanguages, projectIdToTrackerMap: newIdToTrackerMap, dependencyGraph: CreateDependencyGraph(ProjectIds, newIdToProjectStateMap)); _latestSolutionWithPartialCompilation = new WeakReference<SolutionState>(currentPartialSolution); _timeOfLatestSolutionWithPartialCompilation = DateTime.UtcNow; _documentIdOfLatestSolutionWithPartialCompilation = documentId; SolutionLogger.CreatePartialSolution(); return currentPartialSolution; } } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } /// <summary> /// Creates a new solution instance with all the documents specified updated to have the same specified text. /// </summary> public SolutionState WithDocumentText(IEnumerable<DocumentId?> documentIds, SourceText text, PreservationMode mode) { var solution = this; foreach (var documentId in documentIds) { if (documentId == null) { continue; } var doc = GetProjectState(documentId.ProjectId)?.DocumentStates.GetState(documentId); if (doc != null) { if (!doc.TryGetText(out var existingText) || existingText != text) { solution = solution.WithDocumentText(documentId, text, mode); } } } return solution; } public bool TryGetCompilation(ProjectId projectId, [NotNullWhen(returnValue: true)] out Compilation? compilation) { CheckContainsProject(projectId); compilation = null; return this.TryGetCompilationTracker(projectId, out var tracker) && tracker.TryGetCompilation(out compilation); } /// <summary> /// Returns the compilation for the specified <see cref="ProjectId"/>. Can return <see langword="null"/> when the project /// does not support compilations. /// </summary> /// <remarks> /// The compilation is guaranteed to have a syntax tree for each document of the project. /// </remarks> private Task<Compilation?> GetCompilationAsync(ProjectId projectId, CancellationToken cancellationToken) { // TODO: figure out where this is called and why the nullable suppression is required return GetCompilationAsync(GetProjectState(projectId)!, cancellationToken); } /// <summary> /// Returns the compilation for the specified <see cref="ProjectState"/>. Can return <see langword="null"/> when the project /// does not support compilations. /// </summary> /// <remarks> /// The compilation is guaranteed to have a syntax tree for each document of the project. /// </remarks> public Task<Compilation?> GetCompilationAsync(ProjectState project, CancellationToken cancellationToken) { return project.SupportsCompilation ? GetCompilationTracker(project.Id).GetCompilationAsync(this, cancellationToken).AsNullable() : SpecializedTasks.Null<Compilation>(); } /// <summary> /// Return reference completeness for the given project and all projects this references. /// </summary> public Task<bool> HasSuccessfullyLoadedAsync(ProjectState project, CancellationToken cancellationToken) { // return HasAllInformation when compilation is not supported. // regardless whether project support compilation or not, if projectInfo is not complete, we can't guarantee its reference completeness return project.SupportsCompilation ? this.GetCompilationTracker(project.Id).HasSuccessfullyLoadedAsync(this, cancellationToken) : project.HasAllInformation ? SpecializedTasks.True : SpecializedTasks.False; } /// <summary> /// Returns the generated document states for source generated documents. /// </summary> public ValueTask<TextDocumentStates<SourceGeneratedDocumentState>> GetSourceGeneratedDocumentStatesAsync(ProjectState project, CancellationToken cancellationToken) { return project.SupportsCompilation ? GetCompilationTracker(project.Id).GetSourceGeneratedDocumentStatesAsync(this, cancellationToken) : new(TextDocumentStates<SourceGeneratedDocumentState>.Empty); } /// <summary> /// Returns the <see cref="SourceGeneratedDocumentState"/> for a source generated document that has already been generated and observed. /// </summary> /// <remarks> /// This is only safe to call if you already have seen the SyntaxTree or equivalent that indicates the document state has already been /// generated. This method exists to implement <see cref="Solution.GetDocument(SyntaxTree?)"/> and is best avoided unless you're doing something /// similarly tricky like that. /// </remarks> public SourceGeneratedDocumentState? TryGetSourceGeneratedDocumentStateForAlreadyGeneratedId(DocumentId documentId) { return GetCompilationTracker(documentId.ProjectId).TryGetSourceGeneratedDocumentStateForAlreadyGeneratedId(documentId); } /// <summary> /// Returns a new SolutionState that will always produce a specific output for a generated file. This is used only in the /// implementation of <see cref="TextExtensions.GetOpenDocumentInCurrentContextWithChanges"/> where if a user has a source /// generated file open, we need to make sure everything lines up. /// </summary> public SolutionState WithFrozenSourceGeneratedDocument(SourceGeneratedDocumentIdentity documentIdentity, SourceText sourceText) { // We won't support freezing multiple source generated documents at once. Although nothing in the implementation // of this method would have problems, this simplifies the handling of serializing this solution to out-of-proc. // Since we only produce these snapshots from an open document, there should be no way to observe this, so this assertion // also serves as a good check on the system. If down the road we need to support this, we can remove this check and // update the out-of-process serialization logic accordingly. Contract.ThrowIfTrue(_frozenSourceGeneratedDocumentState != null, "We shouldn't be calling WithFrozenSourceGeneratedDocument on a solution with a frozen source generated document."); var existingGeneratedState = TryGetSourceGeneratedDocumentStateForAlreadyGeneratedId(documentIdentity.DocumentId); SourceGeneratedDocumentState newGeneratedState; if (existingGeneratedState != null) { newGeneratedState = existingGeneratedState.WithUpdatedGeneratedContent(sourceText, existingGeneratedState.ParseOptions); // If the content already matched, we can just reuse the existing state if (newGeneratedState == existingGeneratedState) { return this; } } else { var projectState = GetRequiredProjectState(documentIdentity.DocumentId.ProjectId); newGeneratedState = SourceGeneratedDocumentState.Create( documentIdentity, sourceText, projectState.ParseOptions!, projectState.LanguageServices, _solutionServices); } var projectId = documentIdentity.DocumentId.ProjectId; var newTrackerMap = CreateCompilationTrackerMap(projectId, _dependencyGraph); // We want to create a new snapshot with a new compilation tracker that will do this replacement. // If we already have an existing tracker we'll just wrap that (so we also are reusing any underlying // computations). If we don't have one, we'll create one and then wrap it. if (!newTrackerMap.TryGetValue(projectId, out var existingTracker)) { existingTracker = CreateCompilationTracker(projectId, this); } newTrackerMap = newTrackerMap.SetItem( projectId, new GeneratedFileReplacingCompilationTracker(existingTracker, newGeneratedState)); return this.Branch( projectIdToTrackerMap: newTrackerMap, frozenSourceGeneratedDocument: newGeneratedState); } /// <summary> /// Symbols need to be either <see cref="IAssemblySymbol"/> or <see cref="IModuleSymbol"/>. /// </summary> private static readonly ConditionalWeakTable<ISymbol, ProjectId> s_assemblyOrModuleSymbolToProjectMap = new(); /// <summary> /// Get a metadata reference for the project's compilation /// </summary> public Task<MetadataReference> GetMetadataReferenceAsync(ProjectReference projectReference, ProjectState fromProject, CancellationToken cancellationToken) { try { // Get the compilation state for this project. If it's not already created, then this // will create it. Then force that state to completion and get a metadata reference to it. var tracker = this.GetCompilationTracker(projectReference.ProjectId); return tracker.GetMetadataReferenceAsync(this, fromProject, projectReference, cancellationToken); } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } /// <summary> /// Attempt to get the best readily available compilation for the project. It may be a /// partially built compilation. /// </summary> private MetadataReference? GetPartialMetadataReference( ProjectReference projectReference, ProjectState fromProject) { // Try to get the compilation state for this project. If it doesn't exist, don't do any // more work. if (!_projectIdToTrackerMap.TryGetValue(projectReference.ProjectId, out var state)) { return null; } return state.GetPartialMetadataReference(fromProject, projectReference); } /// <summary> /// Gets a <see cref="ProjectDependencyGraph"/> that details the dependencies between projects for this solution. /// </summary> public ProjectDependencyGraph GetProjectDependencyGraph() => _dependencyGraph; private void CheckNotContainsProject(ProjectId projectId) { if (this.ContainsProject(projectId)) { throw new InvalidOperationException(WorkspacesResources.The_solution_already_contains_the_specified_project); } } private void CheckContainsProject(ProjectId projectId) { if (!this.ContainsProject(projectId)) { throw new InvalidOperationException(WorkspacesResources.The_solution_does_not_contain_the_specified_project); } } internal bool ContainsProjectReference(ProjectId projectId, ProjectReference projectReference) => GetRequiredProjectState(projectId).ProjectReferences.Contains(projectReference); internal bool ContainsMetadataReference(ProjectId projectId, MetadataReference metadataReference) => GetRequiredProjectState(projectId).MetadataReferences.Contains(metadataReference); internal bool ContainsAnalyzerReference(ProjectId projectId, AnalyzerReference analyzerReference) => GetRequiredProjectState(projectId).AnalyzerReferences.Contains(analyzerReference); internal bool ContainsTransitiveReference(ProjectId fromProjectId, ProjectId toProjectId) => _dependencyGraph.GetProjectsThatThisProjectTransitivelyDependsOn(fromProjectId).Contains(toProjectId); internal ImmutableHashSet<string> GetRemoteSupportedProjectLanguages() => _remoteSupportedLanguages; private static ImmutableHashSet<string> GetRemoteSupportedProjectLanguages(ImmutableDictionary<ProjectId, ProjectState> projectStates) { var builder = ImmutableHashSet.CreateBuilder<string>(); foreach (var projectState in projectStates) { if (RemoteSupportedLanguages.IsSupported(projectState.Value.Language)) { builder.Add(projectState.Value.Language); } } return builder.ToImmutable(); } } }
// Licensed to the .NET Foundation under one or more 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.Diagnostics.CodeAnalysis; using System.Linq; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Logging; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Remote; using Microsoft.CodeAnalysis.Serialization; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// Represents a set of projects and their source code documents. /// /// this is a green node of Solution like ProjectState/DocumentState are for /// Project and Document. /// </summary> internal partial class SolutionState { // branch id for this solution private readonly BranchId _branchId; // the version of the workspace this solution is from private readonly int _workspaceVersion; private readonly SolutionInfo.SolutionAttributes _solutionAttributes; private readonly SolutionServices _solutionServices; private readonly ImmutableDictionary<ProjectId, ProjectState> _projectIdToProjectStateMap; private readonly ImmutableHashSet<string> _remoteSupportedLanguages; private readonly ImmutableDictionary<string, ImmutableArray<DocumentId>> _filePathToDocumentIdsMap; private readonly ProjectDependencyGraph _dependencyGraph; public readonly IReadOnlyList<AnalyzerReference> AnalyzerReferences; // Values for all these are created on demand. private ImmutableDictionary<ProjectId, ICompilationTracker> _projectIdToTrackerMap; // Checksums for this solution state private readonly ValueSource<SolutionStateChecksums> _lazyChecksums; /// <summary> /// Mapping from project-id to the options and checksums needed to synchronize it (and the projects it depends on) over /// to an OOP host. Options are stored as well so that when we are attempting to match a request for a particular project-subset /// we can return the options specific to that project-subset (which may be different from the <see cref="Options"/> defined /// for the entire solution). Lock this specific field before reading/writing to it. /// </summary> private readonly Dictionary<ProjectId, (SerializableOptionSet options, ValueSource<SolutionStateChecksums> checksums)> _lazyProjectChecksums = new(); // holds on data calculated based on the AnalyzerReferences list private readonly Lazy<HostDiagnosticAnalyzers> _lazyAnalyzers; /// <summary> /// Cache we use to map between unrooted symbols (i.e. assembly, module and dynamic symbols) and the project /// they came from. That way if we are asked about many symbols from the same assembly/module we can answer the /// question quickly after computing for the first one. Created on demand. /// </summary> private ConditionalWeakTable<ISymbol, ProjectId?>? _unrootedSymbolToProjectId; private static readonly Func<ConditionalWeakTable<ISymbol, ProjectId?>> s_createTable = () => new ConditionalWeakTable<ISymbol, ProjectId?>(); private readonly SourceGeneratedDocumentState? _frozenSourceGeneratedDocumentState; private SolutionState( BranchId branchId, int workspaceVersion, SolutionServices solutionServices, SolutionInfo.SolutionAttributes solutionAttributes, IReadOnlyList<ProjectId> projectIds, SerializableOptionSet options, IReadOnlyList<AnalyzerReference> analyzerReferences, ImmutableDictionary<ProjectId, ProjectState> idToProjectStateMap, ImmutableHashSet<string> remoteSupportedLanguages, ImmutableDictionary<ProjectId, ICompilationTracker> projectIdToTrackerMap, ImmutableDictionary<string, ImmutableArray<DocumentId>> filePathToDocumentIdsMap, ProjectDependencyGraph dependencyGraph, Lazy<HostDiagnosticAnalyzers>? lazyAnalyzers, SourceGeneratedDocumentState? frozenSourceGeneratedDocument) { _branchId = branchId; _workspaceVersion = workspaceVersion; _solutionAttributes = solutionAttributes; _solutionServices = solutionServices; ProjectIds = projectIds; Options = options; AnalyzerReferences = analyzerReferences; _projectIdToProjectStateMap = idToProjectStateMap; _remoteSupportedLanguages = remoteSupportedLanguages; _projectIdToTrackerMap = projectIdToTrackerMap; _filePathToDocumentIdsMap = filePathToDocumentIdsMap; _dependencyGraph = dependencyGraph; _lazyAnalyzers = lazyAnalyzers ?? CreateLazyHostDiagnosticAnalyzers(analyzerReferences); _frozenSourceGeneratedDocumentState = frozenSourceGeneratedDocument; // when solution state is changed, we recalculate its checksum _lazyChecksums = new AsyncLazy<SolutionStateChecksums>( c => ComputeChecksumsAsync(projectsToInclude: null, Options, c), cacheResult: true); CheckInvariants(); // make sure we don't accidentally capture any state but the list of references: static Lazy<HostDiagnosticAnalyzers> CreateLazyHostDiagnosticAnalyzers(IReadOnlyList<AnalyzerReference> analyzerReferences) => new(() => new HostDiagnosticAnalyzers(analyzerReferences)); } public SolutionState( BranchId primaryBranchId, SolutionServices solutionServices, SolutionInfo.SolutionAttributes solutionAttributes, SerializableOptionSet options, IReadOnlyList<AnalyzerReference> analyzerReferences) : this( primaryBranchId, workspaceVersion: 0, solutionServices, solutionAttributes, projectIds: SpecializedCollections.EmptyBoxedImmutableArray<ProjectId>(), options, analyzerReferences, idToProjectStateMap: ImmutableDictionary<ProjectId, ProjectState>.Empty, remoteSupportedLanguages: ImmutableHashSet<string>.Empty, projectIdToTrackerMap: ImmutableDictionary<ProjectId, ICompilationTracker>.Empty, filePathToDocumentIdsMap: ImmutableDictionary.Create<string, ImmutableArray<DocumentId>>(StringComparer.OrdinalIgnoreCase), dependencyGraph: ProjectDependencyGraph.Empty, lazyAnalyzers: null, frozenSourceGeneratedDocument: null) { } public SolutionState WithNewWorkspace(Workspace workspace, int workspaceVersion) { var services = workspace != _solutionServices.Workspace ? new SolutionServices(workspace) : _solutionServices; // Note: this will potentially have problems if the workspace services are different, as some services // get locked-in by document states and project states when first constructed. return CreatePrimarySolution(branchId: workspace.PrimaryBranchId, workspaceVersion: workspaceVersion, services: services); } public HostDiagnosticAnalyzers Analyzers => _lazyAnalyzers.Value; public SolutionInfo.SolutionAttributes SolutionAttributes => _solutionAttributes; public SourceGeneratedDocumentState? FrozenSourceGeneratedDocumentState => _frozenSourceGeneratedDocumentState; public ImmutableDictionary<ProjectId, ProjectState> ProjectStates => _projectIdToProjectStateMap; public int WorkspaceVersion => _workspaceVersion; public SolutionServices Services => _solutionServices; public SerializableOptionSet Options { get; } /// <summary> /// branch id of this solution /// /// currently, it only supports one level of branching. there is a primary branch of a workspace and all other /// branches that are branched from the primary branch. /// /// one still can create multiple forked solutions from an already branched solution, but versions among those /// can't be reliably used and compared. /// /// version only has a meaning between primary solution and branched one or between solutions from same branch. /// </summary> public BranchId BranchId => _branchId; /// <summary> /// The Workspace this solution is associated with. /// </summary> public Workspace Workspace => _solutionServices.Workspace; /// <summary> /// The Id of the solution. Multiple solution instances may share the same Id. /// </summary> public SolutionId Id => _solutionAttributes.Id; /// <summary> /// The path to the solution file or null if there is no solution file. /// </summary> public string? FilePath => _solutionAttributes.FilePath; /// <summary> /// The solution version. This equates to the solution file's version. /// </summary> public VersionStamp Version => _solutionAttributes.Version; /// <summary> /// A list of all the ids for all the projects contained by the solution. /// </summary> public IReadOnlyList<ProjectId> ProjectIds { get; } // Only run this in debug builds; even the .Any() call across all projects can be expensive when there's a lot of them. [Conditional("DEBUG")] private void CheckInvariants() { Contract.ThrowIfFalse(_projectIdToProjectStateMap.Count == ProjectIds.Count); Contract.ThrowIfFalse(_projectIdToProjectStateMap.Count == _dependencyGraph.ProjectIds.Count); // An id shouldn't point at a tracker for a different project. Contract.ThrowIfTrue(_projectIdToTrackerMap.Any(kvp => kvp.Key != kvp.Value.ProjectState.Id)); // project ids must be the same: Debug.Assert(_projectIdToProjectStateMap.Keys.SetEquals(ProjectIds)); Debug.Assert(_projectIdToProjectStateMap.Keys.SetEquals(_dependencyGraph.ProjectIds)); Debug.Assert(_remoteSupportedLanguages.SetEquals(GetRemoteSupportedProjectLanguages(_projectIdToProjectStateMap))); } private SolutionState Branch( SolutionInfo.SolutionAttributes? solutionAttributes = null, IReadOnlyList<ProjectId>? projectIds = null, SerializableOptionSet? options = null, IReadOnlyList<AnalyzerReference>? analyzerReferences = null, ImmutableDictionary<ProjectId, ProjectState>? idToProjectStateMap = null, ImmutableHashSet<string>? remoteSupportedProjectLanguages = null, ImmutableDictionary<ProjectId, ICompilationTracker>? projectIdToTrackerMap = null, ImmutableDictionary<string, ImmutableArray<DocumentId>>? filePathToDocumentIdsMap = null, ProjectDependencyGraph? dependencyGraph = null, Optional<SourceGeneratedDocumentState?> frozenSourceGeneratedDocument = default) { var branchId = GetBranchId(); if (idToProjectStateMap is not null) { Contract.ThrowIfNull(remoteSupportedProjectLanguages); } solutionAttributes ??= _solutionAttributes; projectIds ??= ProjectIds; idToProjectStateMap ??= _projectIdToProjectStateMap; remoteSupportedProjectLanguages ??= _remoteSupportedLanguages; Debug.Assert(remoteSupportedProjectLanguages.SetEquals(GetRemoteSupportedProjectLanguages(idToProjectStateMap))); options ??= Options.WithLanguages(remoteSupportedProjectLanguages); analyzerReferences ??= AnalyzerReferences; projectIdToTrackerMap ??= _projectIdToTrackerMap; filePathToDocumentIdsMap ??= _filePathToDocumentIdsMap; dependencyGraph ??= _dependencyGraph; var newFrozenSourceGeneratedDocumentState = frozenSourceGeneratedDocument.HasValue ? frozenSourceGeneratedDocument.Value : _frozenSourceGeneratedDocumentState; var analyzerReferencesEqual = AnalyzerReferences.SequenceEqual(analyzerReferences); if (branchId == _branchId && solutionAttributes == _solutionAttributes && projectIds == ProjectIds && options == Options && analyzerReferencesEqual && idToProjectStateMap == _projectIdToProjectStateMap && projectIdToTrackerMap == _projectIdToTrackerMap && filePathToDocumentIdsMap == _filePathToDocumentIdsMap && dependencyGraph == _dependencyGraph && newFrozenSourceGeneratedDocumentState == _frozenSourceGeneratedDocumentState) { return this; } return new SolutionState( branchId, _workspaceVersion, _solutionServices, solutionAttributes, projectIds, options, analyzerReferences, idToProjectStateMap, remoteSupportedProjectLanguages, projectIdToTrackerMap, filePathToDocumentIdsMap, dependencyGraph, analyzerReferencesEqual ? _lazyAnalyzers : null, newFrozenSourceGeneratedDocumentState); } private SolutionState CreatePrimarySolution( BranchId branchId, int workspaceVersion, SolutionServices services) { if (branchId == _branchId && workspaceVersion == _workspaceVersion && services == _solutionServices) { return this; } return new SolutionState( branchId, workspaceVersion, services, _solutionAttributes, ProjectIds, Options, AnalyzerReferences, _projectIdToProjectStateMap, _remoteSupportedLanguages, _projectIdToTrackerMap, _filePathToDocumentIdsMap, _dependencyGraph, _lazyAnalyzers, frozenSourceGeneratedDocument: null); } private BranchId GetBranchId() { // currently we only support one level branching. // my reasonings are // 1. it seems there is no-one who needs sub branches. // 2. this lets us to branch without explicit branch API return _branchId == Workspace.PrimaryBranchId ? BranchId.GetNextId() : _branchId; } /// <summary> /// The version of the most recently modified project. /// </summary> public VersionStamp GetLatestProjectVersion() { // this may produce a version that is out of sync with the actual Document versions. var latestVersion = VersionStamp.Default; foreach (var project in this.ProjectStates.Values) { latestVersion = project.Version.GetNewerVersion(latestVersion); } return latestVersion; } /// <summary> /// True if the solution contains a project with the specified project ID. /// </summary> public bool ContainsProject([NotNullWhen(returnValue: true)] ProjectId? projectId) => projectId != null && _projectIdToProjectStateMap.ContainsKey(projectId); /// <summary> /// True if the solution contains the document in one of its projects /// </summary> public bool ContainsDocument([NotNullWhen(returnValue: true)] DocumentId? documentId) { return documentId != null && this.ContainsProject(documentId.ProjectId) && this.GetProjectState(documentId.ProjectId)!.DocumentStates.Contains(documentId); } /// <summary> /// True if the solution contains the additional document in one of its projects /// </summary> public bool ContainsAdditionalDocument([NotNullWhen(returnValue: true)] DocumentId? documentId) { return documentId != null && this.ContainsProject(documentId.ProjectId) && this.GetProjectState(documentId.ProjectId)!.AdditionalDocumentStates.Contains(documentId); } /// <summary> /// True if the solution contains the analyzer config document in one of its projects /// </summary> public bool ContainsAnalyzerConfigDocument([NotNullWhen(returnValue: true)] DocumentId? documentId) { return documentId != null && this.ContainsProject(documentId.ProjectId) && this.GetProjectState(documentId.ProjectId)!.AnalyzerConfigDocumentStates.Contains(documentId); } private DocumentState GetRequiredDocumentState(DocumentId documentId) => GetRequiredProjectState(documentId.ProjectId).DocumentStates.GetRequiredState(documentId); private AdditionalDocumentState GetRequiredAdditionalDocumentState(DocumentId documentId) => GetRequiredProjectState(documentId.ProjectId).AdditionalDocumentStates.GetRequiredState(documentId); private AnalyzerConfigDocumentState GetRequiredAnalyzerConfigDocumentState(DocumentId documentId) => GetRequiredProjectState(documentId.ProjectId).AnalyzerConfigDocumentStates.GetRequiredState(documentId); internal DocumentState? GetDocumentState(SyntaxTree? syntaxTree, ProjectId? projectId) { if (syntaxTree != null) { // is this tree known to be associated with a document? var documentId = DocumentState.GetDocumentIdForTree(syntaxTree); if (documentId != null && (projectId == null || documentId.ProjectId == projectId)) { // does this solution even have the document? var projectState = GetProjectState(documentId.ProjectId); if (projectState != null) { var document = projectState.DocumentStates.GetState(documentId); if (document != null) { // does this document really have the syntax tree? if (document.TryGetSyntaxTree(out var documentTree) && documentTree == syntaxTree) { return document; } } else { var generatedDocument = TryGetSourceGeneratedDocumentStateForAlreadyGeneratedId(documentId); if (generatedDocument != null) { // does this document really have the syntax tree? if (generatedDocument.TryGetSyntaxTree(out var documentTree) && documentTree == syntaxTree) { return generatedDocument; } } } } } } return null; } public Task<VersionStamp> GetDependentVersionAsync(ProjectId projectId, CancellationToken cancellationToken) => this.GetCompilationTracker(projectId).GetDependentVersionAsync(this, cancellationToken); public Task<VersionStamp> GetDependentSemanticVersionAsync(ProjectId projectId, CancellationToken cancellationToken) => this.GetCompilationTracker(projectId).GetDependentSemanticVersionAsync(this, cancellationToken); public ProjectState? GetProjectState(ProjectId projectId) { _projectIdToProjectStateMap.TryGetValue(projectId, out var state); return state; } public ProjectState GetRequiredProjectState(ProjectId projectId) { var result = GetProjectState(projectId); Contract.ThrowIfNull(result); return result; } /// <summary> /// Gets the <see cref="Project"/> associated with an assembly symbol. /// </summary> public ProjectState? GetProjectState(IAssemblySymbol? assemblySymbol) { if (assemblySymbol == null) return null; s_assemblyOrModuleSymbolToProjectMap.TryGetValue(assemblySymbol, out var id); return id == null ? null : this.GetProjectState(id); } private bool TryGetCompilationTracker(ProjectId projectId, [NotNullWhen(returnValue: true)] out ICompilationTracker? tracker) => _projectIdToTrackerMap.TryGetValue(projectId, out tracker); private static readonly Func<ProjectId, SolutionState, CompilationTracker> s_createCompilationTrackerFunction = CreateCompilationTracker; private static CompilationTracker CreateCompilationTracker(ProjectId projectId, SolutionState solution) { var projectState = solution.GetProjectState(projectId); Contract.ThrowIfNull(projectState); return new CompilationTracker(projectState); } private ICompilationTracker GetCompilationTracker(ProjectId projectId) { if (!_projectIdToTrackerMap.TryGetValue(projectId, out var tracker)) { tracker = ImmutableInterlocked.GetOrAdd(ref _projectIdToTrackerMap, projectId, s_createCompilationTrackerFunction, this); } return tracker; } private SolutionState AddProject(ProjectId projectId, ProjectState projectState) { // changed project list so, increment version. var newSolutionAttributes = _solutionAttributes.With(version: Version.GetNewerVersion()); var newProjectIds = ProjectIds.ToImmutableArray().Add(projectId); var newStateMap = _projectIdToProjectStateMap.Add(projectId, projectState); var newLanguages = RemoteSupportedLanguages.IsSupported(projectState.Language) ? _remoteSupportedLanguages.Add(projectState.Language) : _remoteSupportedLanguages; var newDependencyGraph = _dependencyGraph .WithAdditionalProject(projectId) .WithAdditionalProjectReferences(projectId, projectState.ProjectReferences); // It's possible that another project already in newStateMap has a reference to this project that we're adding, since we allow // dangling references like that. If so, we'll need to link those in too. foreach (var newState in newStateMap) { foreach (var projectReference in newState.Value.ProjectReferences) { if (projectReference.ProjectId == projectId) { newDependencyGraph = newDependencyGraph.WithAdditionalProjectReferences( newState.Key, SpecializedCollections.SingletonReadOnlyList(projectReference)); break; } } } var newTrackerMap = CreateCompilationTrackerMap(projectId, newDependencyGraph); var newFilePathToDocumentIdsMap = CreateFilePathToDocumentIdsMapWithAddedDocuments(GetDocumentStates(newStateMap[projectId])); return Branch( solutionAttributes: newSolutionAttributes, projectIds: newProjectIds, idToProjectStateMap: newStateMap, remoteSupportedProjectLanguages: newLanguages, projectIdToTrackerMap: newTrackerMap, filePathToDocumentIdsMap: newFilePathToDocumentIdsMap, dependencyGraph: newDependencyGraph); } /// <summary> /// Create a new solution instance that includes a project with the specified project information. /// </summary> public SolutionState AddProject(ProjectInfo projectInfo) { if (projectInfo == null) { throw new ArgumentNullException(nameof(projectInfo)); } var projectId = projectInfo.Id; var language = projectInfo.Language; if (language == null) { throw new ArgumentNullException(nameof(language)); } var displayName = projectInfo.Name; if (displayName == null) { throw new ArgumentNullException(nameof(displayName)); } CheckNotContainsProject(projectId); var languageServices = this.Workspace.Services.GetLanguageServices(language); if (languageServices == null) { throw new ArgumentException(string.Format(WorkspacesResources.The_language_0_is_not_supported, language)); } var newProject = new ProjectState(projectInfo, languageServices, _solutionServices); return this.AddProject(newProject.Id, newProject); } private ImmutableDictionary<string, ImmutableArray<DocumentId>> CreateFilePathToDocumentIdsMapWithAddedDocuments(IEnumerable<TextDocumentState> documentStates) { var builder = _filePathToDocumentIdsMap.ToBuilder(); foreach (var documentState in documentStates) { var filePath = documentState.FilePath; if (RoslynString.IsNullOrEmpty(filePath)) { continue; } builder.MultiAdd(filePath, documentState.Id); } return builder.ToImmutable(); } private static IEnumerable<TextDocumentState> GetDocumentStates(ProjectState projectState) => projectState.DocumentStates.States.Values .Concat<TextDocumentState>(projectState.AdditionalDocumentStates.States.Values) .Concat(projectState.AnalyzerConfigDocumentStates.States.Values); /// <summary> /// Create a new solution instance without the project specified. /// </summary> public SolutionState RemoveProject(ProjectId projectId) { if (projectId == null) { throw new ArgumentNullException(nameof(projectId)); } CheckContainsProject(projectId); // changed project list so, increment version. var newSolutionAttributes = _solutionAttributes.With(version: this.Version.GetNewerVersion()); var newProjectIds = ProjectIds.ToImmutableArray().Remove(projectId); var newStateMap = _projectIdToProjectStateMap.Remove(projectId); // Remote supported languages only changes if the removed project is the last project of a supported language. var newLanguages = _remoteSupportedLanguages; if (_projectIdToProjectStateMap.TryGetValue(projectId, out var projectState) && RemoteSupportedLanguages.IsSupported(projectState.Language)) { var stillSupportsLanguage = false; foreach (var (id, state) in _projectIdToProjectStateMap) { if (id == projectId) continue; if (state.Language == projectState.Language) { stillSupportsLanguage = true; break; } } if (!stillSupportsLanguage) { newLanguages = newLanguages.Remove(projectState.Language); } } var newDependencyGraph = _dependencyGraph.WithProjectRemoved(projectId); var newTrackerMap = CreateCompilationTrackerMap(projectId, newDependencyGraph); var newFilePathToDocumentIdsMap = CreateFilePathToDocumentIdsMapWithRemovedDocuments(GetDocumentStates(_projectIdToProjectStateMap[projectId])); return this.Branch( solutionAttributes: newSolutionAttributes, projectIds: newProjectIds, idToProjectStateMap: newStateMap, remoteSupportedProjectLanguages: newLanguages, projectIdToTrackerMap: newTrackerMap.Remove(projectId), filePathToDocumentIdsMap: newFilePathToDocumentIdsMap, dependencyGraph: newDependencyGraph); } private ImmutableDictionary<string, ImmutableArray<DocumentId>> CreateFilePathToDocumentIdsMapWithRemovedDocuments(IEnumerable<TextDocumentState> documentStates) { var builder = _filePathToDocumentIdsMap.ToBuilder(); foreach (var documentState in documentStates) { var filePath = documentState.FilePath; if (RoslynString.IsNullOrEmpty(filePath)) { continue; } if (!builder.TryGetValue(filePath, out var documentIdsWithPath) || !documentIdsWithPath.Contains(documentState.Id)) { throw new ArgumentException($"The given documentId was not found in '{nameof(_filePathToDocumentIdsMap)}'."); } builder.MultiRemove(filePath, documentState.Id); } return builder.ToImmutable(); } private ImmutableDictionary<string, ImmutableArray<DocumentId>> CreateFilePathToDocumentIdsMapWithFilePath(DocumentId documentId, string? oldFilePath, string? newFilePath) { if (oldFilePath == newFilePath) { return _filePathToDocumentIdsMap; } var builder = _filePathToDocumentIdsMap.ToBuilder(); if (!RoslynString.IsNullOrEmpty(oldFilePath)) { builder.MultiRemove(oldFilePath, documentId); } if (!RoslynString.IsNullOrEmpty(newFilePath)) { builder.MultiAdd(newFilePath, documentId); } return builder.ToImmutable(); } /// <summary> /// Creates a new solution instance with the project specified updated to have the new /// assembly name. /// </summary> public SolutionState WithProjectAssemblyName(ProjectId projectId, string assemblyName) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithAssemblyName(assemblyName); if (oldProject == newProject) { return this; } return ForkProject(newProject, new CompilationAndGeneratorDriverTranslationAction.ProjectAssemblyNameAction(assemblyName)); } /// <summary> /// Creates a new solution instance with the project specified updated to have the output file path. /// </summary> public SolutionState WithProjectOutputFilePath(ProjectId projectId, string? outputFilePath) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithOutputFilePath(outputFilePath); if (oldProject == newProject) { return this; } return ForkProject(newProject); } /// <summary> /// Creates a new solution instance with the project specified updated to have the output file path. /// </summary> public SolutionState WithProjectOutputRefFilePath(ProjectId projectId, string? outputRefFilePath) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithOutputRefFilePath(outputRefFilePath); if (oldProject == newProject) { return this; } return ForkProject(newProject); } /// <summary> /// Creates a new solution instance with the project specified updated to have the compiler output file path. /// </summary> public SolutionState WithProjectCompilationOutputInfo(ProjectId projectId, in CompilationOutputInfo info) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithCompilationOutputInfo(info); if (oldProject == newProject) { return this; } return ForkProject(newProject); } /// <summary> /// Creates a new solution instance with the project specified updated to have the default namespace. /// </summary> public SolutionState WithProjectDefaultNamespace(ProjectId projectId, string? defaultNamespace) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithDefaultNamespace(defaultNamespace); if (oldProject == newProject) { return this; } return ForkProject(newProject); } /// <summary> /// Creates a new solution instance with the project specified updated to have the name. /// </summary> public SolutionState WithProjectName(ProjectId projectId, string name) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithName(name); if (oldProject == newProject) { return this; } return ForkProject(newProject); } /// <summary> /// Creates a new solution instance with the project specified updated to have the project file path. /// </summary> public SolutionState WithProjectFilePath(ProjectId projectId, string? filePath) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithFilePath(filePath); if (oldProject == newProject) { return this; } return ForkProject(newProject); } /// <summary> /// Create a new solution instance with the project specified updated to have /// the specified compilation options. /// </summary> public SolutionState WithProjectCompilationOptions(ProjectId projectId, CompilationOptions options) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithCompilationOptions(options); if (oldProject == newProject) { return this; } return ForkProject(newProject, new CompilationAndGeneratorDriverTranslationAction.ProjectCompilationOptionsAction(newProject, isAnalyzerConfigChange: false)); } /// <summary> /// Create a new solution instance with the project specified updated to have /// the specified parse options. /// </summary> public SolutionState WithProjectParseOptions(ProjectId projectId, ParseOptions options) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithParseOptions(options); if (oldProject == newProject) { return this; } if (Workspace.PartialSemanticsEnabled) { // don't fork tracker with queued action since access via partial semantics can become inconsistent (throw). // Since changing options is rare event, it is okay to start compilation building from scratch. return ForkProject(newProject, forkTracker: false); } else { return ForkProject(newProject, new CompilationAndGeneratorDriverTranslationAction.ReplaceAllSyntaxTreesAction(newProject, isParseOptionChange: true)); } } /// <summary> /// Create a new solution instance with the project specified updated to have /// the specified hasAllInformation. /// </summary> public SolutionState WithHasAllInformation(ProjectId projectId, bool hasAllInformation) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithHasAllInformation(hasAllInformation); if (oldProject == newProject) { return this; } // fork without any change on compilation. return ForkProject(newProject); } /// <summary> /// Create a new solution instance with the project specified updated to have /// the specified runAnalyzers. /// </summary> public SolutionState WithRunAnalyzers(ProjectId projectId, bool runAnalyzers) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithRunAnalyzers(runAnalyzers); if (oldProject == newProject) { return this; } // fork without any change on compilation. return ForkProject(newProject); } /// <summary> /// Create a new solution instance with the project specified updated to include /// the specified project references. /// </summary> public SolutionState AddProjectReferences(ProjectId projectId, IReadOnlyCollection<ProjectReference> projectReferences) { if (projectReferences.Count == 0) { return this; } var oldProject = GetRequiredProjectState(projectId); var oldReferences = oldProject.ProjectReferences.ToImmutableArray(); var newReferences = oldReferences.AddRange(projectReferences); var newProject = oldProject.WithProjectReferences(newReferences); var newDependencyGraph = _dependencyGraph.WithAdditionalProjectReferences(projectId, projectReferences); return ForkProject(newProject, newDependencyGraph: newDependencyGraph); } /// <summary> /// Create a new solution instance with the project specified updated to no longer /// include the specified project reference. /// </summary> public SolutionState RemoveProjectReference(ProjectId projectId, ProjectReference projectReference) { var oldProject = GetRequiredProjectState(projectId); var oldReferences = oldProject.ProjectReferences.ToImmutableArray(); // Note: uses ProjectReference equality to compare references. var newReferences = oldReferences.Remove(projectReference); if (oldReferences == newReferences) { return this; } var newProject = oldProject.WithProjectReferences(newReferences); ProjectDependencyGraph newDependencyGraph; if (newProject.ContainsReferenceToProject(projectReference.ProjectId) || !_projectIdToProjectStateMap.ContainsKey(projectReference.ProjectId)) { // Two cases: // 1) The project contained multiple non-equivalent references to the project, // and not all of them were removed. The dependency graph doesn't change. // Note that there might be two references to the same project, one with // extern alias and the other without. These are not considered duplicates. // 2) The referenced project is not part of the solution and hence not included // in the dependency graph. newDependencyGraph = _dependencyGraph; } else { newDependencyGraph = _dependencyGraph.WithProjectReferenceRemoved(projectId, projectReference.ProjectId); } return ForkProject(newProject, newDependencyGraph: newDependencyGraph); } /// <summary> /// Create a new solution instance with the project specified updated to contain /// the specified list of project references. /// </summary> public SolutionState WithProjectReferences(ProjectId projectId, IReadOnlyList<ProjectReference> projectReferences) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithProjectReferences(projectReferences); if (oldProject == newProject) { return this; } var newDependencyGraph = _dependencyGraph.WithProjectReferences(projectId, projectReferences); return ForkProject(newProject, newDependencyGraph: newDependencyGraph); } /// <summary> /// Creates a new solution instance with the project documents in the order by the specified document ids. /// The specified document ids must be the same as what is already in the project; no adding or removing is allowed. /// </summary> public SolutionState WithProjectDocumentsOrder(ProjectId projectId, ImmutableList<DocumentId> documentIds) { var oldProject = GetRequiredProjectState(projectId); if (documentIds.Count != oldProject.DocumentStates.Count) { throw new ArgumentException($"The specified documents do not equal the project document count.", nameof(documentIds)); } foreach (var id in documentIds) { if (!oldProject.DocumentStates.Contains(id)) { throw new InvalidOperationException($"The document '{id}' does not exist in the project."); } } var newProject = oldProject.UpdateDocumentsOrder(documentIds); if (oldProject == newProject) { return this; } return ForkProject(newProject, new CompilationAndGeneratorDriverTranslationAction.ReplaceAllSyntaxTreesAction(newProject, isParseOptionChange: false)); } /// <summary> /// Create a new solution instance with the project specified updated to include the /// specified metadata references. /// </summary> public SolutionState AddMetadataReferences(ProjectId projectId, IReadOnlyCollection<MetadataReference> metadataReferences) { if (metadataReferences.Count == 0) { return this; } var oldProject = GetRequiredProjectState(projectId); var oldReferences = oldProject.MetadataReferences.ToImmutableArray(); var newReferences = oldReferences.AddRange(metadataReferences); return ForkProject(oldProject.WithMetadataReferences(newReferences)); } /// <summary> /// Create a new solution instance with the project specified updated to no longer include /// the specified metadata reference. /// </summary> public SolutionState RemoveMetadataReference(ProjectId projectId, MetadataReference metadataReference) { var oldProject = GetRequiredProjectState(projectId); var oldReferences = oldProject.MetadataReferences.ToImmutableArray(); var newReferences = oldReferences.Remove(metadataReference); if (oldReferences == newReferences) { return this; } return ForkProject(oldProject.WithMetadataReferences(newReferences)); } /// <summary> /// Create a new solution instance with the project specified updated to include only the /// specified metadata references. /// </summary> public SolutionState WithProjectMetadataReferences(ProjectId projectId, IReadOnlyList<MetadataReference> metadataReferences) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithMetadataReferences(metadataReferences); if (oldProject == newProject) { return this; } return ForkProject(newProject); } /// <summary> /// Create a new solution instance with the project specified updated to include the /// specified analyzer references. /// </summary> public SolutionState AddAnalyzerReferences(ProjectId projectId, ImmutableArray<AnalyzerReference> analyzerReferences) { if (analyzerReferences.Length == 0) { return this; } var oldProject = GetRequiredProjectState(projectId); var oldReferences = oldProject.AnalyzerReferences.ToImmutableArray(); var newReferences = oldReferences.AddRange(analyzerReferences); return ForkProject( oldProject.WithAnalyzerReferences(newReferences), new CompilationAndGeneratorDriverTranslationAction.AddAnalyzerReferencesAction(analyzerReferences, oldProject.Language)); } /// <summary> /// Create a new solution instance with the project specified updated to no longer include /// the specified analyzer reference. /// </summary> public SolutionState RemoveAnalyzerReference(ProjectId projectId, AnalyzerReference analyzerReference) { var oldProject = GetRequiredProjectState(projectId); var oldReferences = oldProject.AnalyzerReferences.ToImmutableArray(); var newReferences = oldReferences.Remove(analyzerReference); if (oldReferences == newReferences) { return this; } return ForkProject( oldProject.WithAnalyzerReferences(newReferences), new CompilationAndGeneratorDriverTranslationAction.RemoveAnalyzerReferencesAction(ImmutableArray.Create(analyzerReference), oldProject.Language)); } /// <summary> /// Create a new solution instance with the project specified updated to include only the /// specified analyzer references. /// </summary> public SolutionState WithProjectAnalyzerReferences(ProjectId projectId, IEnumerable<AnalyzerReference> analyzerReferences) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithAnalyzerReferences(analyzerReferences); if (oldProject == newProject) { return this; } return ForkProject(newProject); } /// <summary> /// Create a new solution instance with the corresponding projects updated to include new /// documents defined by the document info. /// </summary> public SolutionState AddDocuments(ImmutableArray<DocumentInfo> documentInfos) { return AddDocumentsToMultipleProjects(documentInfos, (documentInfo, project) => project.CreateDocument(documentInfo, project.ParseOptions), (oldProject, documents) => (oldProject.AddDocuments(documents), new CompilationAndGeneratorDriverTranslationAction.AddDocumentsAction(documents))); } /// <summary> /// Core helper that takes a set of <see cref="DocumentInfo" />s and does the application of the appropriate documents to each project. /// </summary> /// <param name="documentInfos">The set of documents to add.</param> /// <param name="addDocumentsToProjectState">Returns the new <see cref="ProjectState"/> with the documents added, and the <see cref="CompilationAndGeneratorDriverTranslationAction"/> needed as well.</param> /// <returns></returns> private SolutionState AddDocumentsToMultipleProjects<T>( ImmutableArray<DocumentInfo> documentInfos, Func<DocumentInfo, ProjectState, T> createDocumentState, Func<ProjectState, ImmutableArray<T>, (ProjectState newState, CompilationAndGeneratorDriverTranslationAction translationAction)> addDocumentsToProjectState) where T : TextDocumentState { if (documentInfos.IsDefault) { throw new ArgumentNullException(nameof(documentInfos)); } if (documentInfos.IsEmpty) { return this; } // The documents might be contributing to multiple different projects; split them by project and then we'll process // project-at-a-time. var documentInfosByProjectId = documentInfos.ToLookup(d => d.Id.ProjectId); var newSolutionState = this; foreach (var documentInfosInProject in documentInfosByProjectId) { CheckContainsProject(documentInfosInProject.Key); var oldProjectState = this.GetProjectState(documentInfosInProject.Key)!; var newDocumentStatesForProjectBuilder = ArrayBuilder<T>.GetInstance(); foreach (var documentInfo in documentInfosInProject) { newDocumentStatesForProjectBuilder.Add(createDocumentState(documentInfo, oldProjectState)); } var newDocumentStatesForProject = newDocumentStatesForProjectBuilder.ToImmutableAndFree(); var (newProjectState, compilationTranslationAction) = addDocumentsToProjectState(oldProjectState, newDocumentStatesForProject); newSolutionState = newSolutionState.ForkProject(newProjectState, compilationTranslationAction, newFilePathToDocumentIdsMap: CreateFilePathToDocumentIdsMapWithAddedDocuments(newDocumentStatesForProject)); } return newSolutionState; } public SolutionState AddAdditionalDocuments(ImmutableArray<DocumentInfo> documentInfos) { return AddDocumentsToMultipleProjects(documentInfos, (documentInfo, project) => new AdditionalDocumentState(documentInfo, _solutionServices), (projectState, documents) => (projectState.AddAdditionalDocuments(documents), new CompilationAndGeneratorDriverTranslationAction.AddAdditionalDocumentsAction(documents))); } public SolutionState AddAnalyzerConfigDocuments(ImmutableArray<DocumentInfo> documentInfos) { // Adding a new analyzer config potentially modifies the compilation options return AddDocumentsToMultipleProjects(documentInfos, (documentInfo, project) => new AnalyzerConfigDocumentState(documentInfo, _solutionServices), (oldProject, documents) => { var newProject = oldProject.AddAnalyzerConfigDocuments(documents); return (newProject, new CompilationAndGeneratorDriverTranslationAction.ProjectCompilationOptionsAction(newProject, isAnalyzerConfigChange: true)); }); } public SolutionState RemoveAnalyzerConfigDocuments(ImmutableArray<DocumentId> documentIds) { return RemoveDocumentsFromMultipleProjects(documentIds, (projectState, documentId) => projectState.AnalyzerConfigDocumentStates.GetRequiredState(documentId), (oldProject, documentIds, _) => { var newProject = oldProject.RemoveAnalyzerConfigDocuments(documentIds); return (newProject, new CompilationAndGeneratorDriverTranslationAction.ProjectCompilationOptionsAction(newProject, isAnalyzerConfigChange: true)); }); } /// <summary> /// Creates a new solution instance that no longer includes the specified document. /// </summary> public SolutionState RemoveDocuments(ImmutableArray<DocumentId> documentIds) { return RemoveDocumentsFromMultipleProjects(documentIds, (projectState, documentId) => projectState.DocumentStates.GetRequiredState(documentId), (projectState, documentIds, documentStates) => (projectState.RemoveDocuments(documentIds), new CompilationAndGeneratorDriverTranslationAction.RemoveDocumentsAction(documentStates))); } private SolutionState RemoveDocumentsFromMultipleProjects<T>( ImmutableArray<DocumentId> documentIds, Func<ProjectState, DocumentId, T> getExistingTextDocumentState, Func<ProjectState, ImmutableArray<DocumentId>, ImmutableArray<T>, (ProjectState newState, CompilationAndGeneratorDriverTranslationAction translationAction)> removeDocumentsFromProjectState) where T : TextDocumentState { if (documentIds.IsEmpty) { return this; } // The documents might be contributing to multiple different projects; split them by project and then we'll process // project-at-a-time. var documentIdsByProjectId = documentIds.ToLookup(id => id.ProjectId); var newSolutionState = this; foreach (var documentIdsInProject in documentIdsByProjectId) { var oldProjectState = this.GetProjectState(documentIdsInProject.Key); if (oldProjectState == null) { throw new InvalidOperationException(string.Format(WorkspacesResources._0_is_not_part_of_the_workspace, documentIdsInProject.Key)); } var removedDocumentStatesBuilder = ArrayBuilder<T>.GetInstance(); foreach (var documentId in documentIdsInProject) { removedDocumentStatesBuilder.Add(getExistingTextDocumentState(oldProjectState, documentId)); } var removedDocumentStatesForProject = removedDocumentStatesBuilder.ToImmutableAndFree(); var (newProjectState, compilationTranslationAction) = removeDocumentsFromProjectState(oldProjectState, documentIdsInProject.ToImmutableArray(), removedDocumentStatesForProject); newSolutionState = newSolutionState.ForkProject(newProjectState, compilationTranslationAction, newFilePathToDocumentIdsMap: CreateFilePathToDocumentIdsMapWithRemovedDocuments(removedDocumentStatesForProject)); } return newSolutionState; } /// <summary> /// Creates a new solution instance that no longer includes the specified additional documents. /// </summary> public SolutionState RemoveAdditionalDocuments(ImmutableArray<DocumentId> documentIds) { return RemoveDocumentsFromMultipleProjects(documentIds, (projectState, documentId) => projectState.AdditionalDocumentStates.GetRequiredState(documentId), (projectState, documentIds, documentStates) => (projectState.RemoveAdditionalDocuments(documentIds), new CompilationAndGeneratorDriverTranslationAction.RemoveAdditionalDocumentsAction(documentStates))); } /// <summary> /// Creates a new solution instance with the document specified updated to have the specified name. /// </summary> public SolutionState WithDocumentName(DocumentId documentId, string name) { var oldDocument = GetRequiredDocumentState(documentId); if (oldDocument.Attributes.Name == name) { return this; } return UpdateDocumentState(oldDocument.UpdateName(name)); } /// <summary> /// Creates a new solution instance with the document specified updated to be contained in /// the sequence of logical folders. /// </summary> public SolutionState WithDocumentFolders(DocumentId documentId, IReadOnlyList<string> folders) { var oldDocument = GetRequiredDocumentState(documentId); if (oldDocument.Folders.SequenceEqual(folders)) { return this; } return UpdateDocumentState(oldDocument.UpdateFolders(folders)); } /// <summary> /// Creates a new solution instance with the document specified updated to have the specified file path. /// </summary> public SolutionState WithDocumentFilePath(DocumentId documentId, string? filePath) { var oldDocument = GetRequiredDocumentState(documentId); if (oldDocument.FilePath == filePath) { return this; } return UpdateDocumentState(oldDocument.UpdateFilePath(filePath)); } /// <summary> /// Creates a new solution instance with the document specified updated to have the text /// specified. /// </summary> public SolutionState WithDocumentText(DocumentId documentId, SourceText text, PreservationMode mode = PreservationMode.PreserveValue) { var oldDocument = GetRequiredDocumentState(documentId); if (oldDocument.TryGetText(out var oldText) && text == oldText) { return this; } return UpdateDocumentState(oldDocument.UpdateText(text, mode), textChanged: true); } /// <summary> /// Creates a new solution instance with the additional document specified updated to have the text /// specified. /// </summary> public SolutionState WithAdditionalDocumentText(DocumentId documentId, SourceText text, PreservationMode mode = PreservationMode.PreserveValue) { var oldDocument = GetRequiredAdditionalDocumentState(documentId); if (oldDocument.TryGetText(out var oldText) && text == oldText) { return this; } return UpdateAdditionalDocumentState(oldDocument.UpdateText(text, mode), textChanged: true); } /// <summary> /// Creates a new solution instance with the document specified updated to have the text /// specified. /// </summary> public SolutionState WithAnalyzerConfigDocumentText(DocumentId documentId, SourceText text, PreservationMode mode = PreservationMode.PreserveValue) { var oldDocument = GetRequiredAnalyzerConfigDocumentState(documentId); if (oldDocument.TryGetText(out var oldText) && text == oldText) { return this; } return UpdateAnalyzerConfigDocumentState(oldDocument.UpdateText(text, mode)); } /// <summary> /// Creates a new solution instance with the document specified updated to have the text /// and version specified. /// </summary> public SolutionState WithDocumentText(DocumentId documentId, TextAndVersion textAndVersion, PreservationMode mode = PreservationMode.PreserveValue) { var oldDocument = GetRequiredDocumentState(documentId); if (oldDocument.TryGetTextAndVersion(out var oldTextAndVersion) && textAndVersion == oldTextAndVersion) { return this; } return UpdateDocumentState(oldDocument.UpdateText(textAndVersion, mode), textChanged: true); } /// <summary> /// Creates a new solution instance with the additional document specified updated to have the text /// and version specified. /// </summary> public SolutionState WithAdditionalDocumentText(DocumentId documentId, TextAndVersion textAndVersion, PreservationMode mode = PreservationMode.PreserveValue) { var oldDocument = GetRequiredAdditionalDocumentState(documentId); if (oldDocument.TryGetTextAndVersion(out var oldTextAndVersion) && textAndVersion == oldTextAndVersion) { return this; } return UpdateAdditionalDocumentState(oldDocument.UpdateText(textAndVersion, mode), textChanged: true); } /// <summary> /// Creates a new solution instance with the analyzer config document specified updated to have the text /// and version specified. /// </summary> public SolutionState WithAnalyzerConfigDocumentText(DocumentId documentId, TextAndVersion textAndVersion, PreservationMode mode = PreservationMode.PreserveValue) { var oldDocument = GetRequiredAnalyzerConfigDocumentState(documentId); if (oldDocument.TryGetTextAndVersion(out var oldTextAndVersion) && textAndVersion == oldTextAndVersion) { return this; } return UpdateAnalyzerConfigDocumentState(oldDocument.UpdateText(textAndVersion, mode)); } /// <summary> /// Creates a new solution instance with the document specified updated to have a syntax tree /// rooted by the specified syntax node. /// </summary> public SolutionState WithDocumentSyntaxRoot(DocumentId documentId, SyntaxNode root, PreservationMode mode = PreservationMode.PreserveValue) { var oldDocument = GetRequiredDocumentState(documentId); if (oldDocument.TryGetSyntaxTree(out var oldTree) && oldTree.TryGetRoot(out var oldRoot) && oldRoot == root) { return this; } return UpdateDocumentState(oldDocument.UpdateTree(root, mode), textChanged: true); } private static async Task<Compilation> UpdateDocumentInCompilationAsync( Compilation compilation, DocumentState oldDocument, DocumentState newDocument, CancellationToken cancellationToken) { return compilation.ReplaceSyntaxTree( await oldDocument.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false), await newDocument.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false)); } /// <summary> /// Creates a new solution instance with the document specified updated to have the source /// code kind specified. /// </summary> public SolutionState WithDocumentSourceCodeKind(DocumentId documentId, SourceCodeKind sourceCodeKind) { var oldDocument = GetRequiredDocumentState(documentId); if (oldDocument.SourceCodeKind == sourceCodeKind) { return this; } return UpdateDocumentState(oldDocument.UpdateSourceCodeKind(sourceCodeKind), textChanged: true); } public SolutionState UpdateDocumentTextLoader(DocumentId documentId, TextLoader loader, SourceText? text, PreservationMode mode) { var oldDocument = GetRequiredDocumentState(documentId); // Assumes that text has changed. User could have closed a doc without saving and we are loading text from closed file with // old content. Also this should make sure we don't re-use latest doc version with data associated with opened document. return UpdateDocumentState(oldDocument.UpdateText(loader, text, mode), textChanged: true, recalculateDependentVersions: true); } /// <summary> /// Creates a new solution instance with the additional document specified updated to have the text /// supplied by the text loader. /// </summary> public SolutionState UpdateAdditionalDocumentTextLoader(DocumentId documentId, TextLoader loader, PreservationMode mode) { var oldDocument = GetRequiredAdditionalDocumentState(documentId); // Assumes that text has changed. User could have closed a doc without saving and we are loading text from closed file with // old content. Also this should make sure we don't re-use latest doc version with data associated with opened document. return UpdateAdditionalDocumentState(oldDocument.UpdateText(loader, mode), textChanged: true, recalculateDependentVersions: true); } /// <summary> /// Creates a new solution instance with the analyzer config document specified updated to have the text /// supplied by the text loader. /// </summary> public SolutionState UpdateAnalyzerConfigDocumentTextLoader(DocumentId documentId, TextLoader loader, PreservationMode mode) { var oldDocument = GetRequiredAnalyzerConfigDocumentState(documentId); // Assumes that text has changed. User could have closed a doc without saving and we are loading text from closed file with // old content. Also this should make sure we don't re-use latest doc version with data associated with opened document. return UpdateAnalyzerConfigDocumentState(oldDocument.UpdateText(loader, mode)); } private SolutionState UpdateDocumentState(DocumentState newDocument, bool textChanged = false, bool recalculateDependentVersions = false) { var oldProject = GetProjectState(newDocument.Id.ProjectId)!; var newProject = oldProject.UpdateDocument(newDocument, textChanged, recalculateDependentVersions); // This method shouldn't have been called if the document has not changed. Debug.Assert(oldProject != newProject); var oldDocument = oldProject.DocumentStates.GetRequiredState(newDocument.Id); var newFilePathToDocumentIdsMap = CreateFilePathToDocumentIdsMapWithFilePath(newDocument.Id, oldDocument.FilePath, newDocument.FilePath); return ForkProject( newProject, new CompilationAndGeneratorDriverTranslationAction.TouchDocumentAction(oldDocument, newDocument), newFilePathToDocumentIdsMap: newFilePathToDocumentIdsMap); } private SolutionState UpdateAdditionalDocumentState(AdditionalDocumentState newDocument, bool textChanged = false, bool recalculateDependentVersions = false) { var oldProject = GetProjectState(newDocument.Id.ProjectId)!; var newProject = oldProject.UpdateAdditionalDocument(newDocument, textChanged, recalculateDependentVersions); // This method shouldn't have been called if the document has not changed. Debug.Assert(oldProject != newProject); var oldDocument = oldProject.AdditionalDocumentStates.GetRequiredState(newDocument.Id); return ForkProject( newProject, translate: new CompilationAndGeneratorDriverTranslationAction.TouchAdditionalDocumentAction(oldDocument, newDocument)); } private SolutionState UpdateAnalyzerConfigDocumentState(AnalyzerConfigDocumentState newDocument) { var oldProject = GetProjectState(newDocument.Id.ProjectId)!; var newProject = oldProject.UpdateAnalyzerConfigDocument(newDocument); // This method shouldn't have been called if the document has not changed. Debug.Assert(oldProject != newProject); return ForkProject(newProject, newProject.CompilationOptions != null ? new CompilationAndGeneratorDriverTranslationAction.ProjectCompilationOptionsAction(newProject, isAnalyzerConfigChange: true) : null); } /// <summary> /// Creates a new snapshot with an updated project and an action that will produce a new /// compilation matching the new project out of an old compilation. All dependent projects /// are fixed-up if the change to the new project affects its public metadata, and old /// dependent compilations are forgotten. /// </summary> private SolutionState ForkProject( ProjectState newProjectState, CompilationAndGeneratorDriverTranslationAction? translate = null, ProjectDependencyGraph? newDependencyGraph = null, ImmutableDictionary<string, ImmutableArray<DocumentId>>? newFilePathToDocumentIdsMap = null, bool forkTracker = true) { var projectId = newProjectState.Id; var newStateMap = _projectIdToProjectStateMap.SetItem(projectId, newProjectState); // Remote supported languages can only change if the project changes language. This is an unexpected edge // case, so it's not optimized for incremental updates. var newLanguages = !_projectIdToProjectStateMap.TryGetValue(projectId, out var projectState) || projectState.Language != newProjectState.Language ? GetRemoteSupportedProjectLanguages(newStateMap) : _remoteSupportedLanguages; newDependencyGraph ??= _dependencyGraph; var newTrackerMap = CreateCompilationTrackerMap(projectId, newDependencyGraph); // If we have a tracker for this project, then fork it as well (along with the // translation action and store it in the tracker map. if (newTrackerMap.TryGetValue(projectId, out var tracker)) { newTrackerMap = newTrackerMap.Remove(projectId); if (forkTracker) { newTrackerMap = newTrackerMap.Add(projectId, tracker.Fork(newProjectState, translate)); } } return this.Branch( idToProjectStateMap: newStateMap, remoteSupportedProjectLanguages: newLanguages, projectIdToTrackerMap: newTrackerMap, dependencyGraph: newDependencyGraph, filePathToDocumentIdsMap: newFilePathToDocumentIdsMap ?? _filePathToDocumentIdsMap); } /// <summary> /// Gets the set of <see cref="DocumentId"/>s in this <see cref="Solution"/> with a /// <see cref="TextDocument.FilePath"/> that matches the given file path. /// </summary> public ImmutableArray<DocumentId> GetDocumentIdsWithFilePath(string? filePath) { if (string.IsNullOrEmpty(filePath)) { return ImmutableArray<DocumentId>.Empty; } return _filePathToDocumentIdsMap.TryGetValue(filePath!, out var documentIds) ? documentIds : ImmutableArray<DocumentId>.Empty; } private static ProjectDependencyGraph CreateDependencyGraph( IReadOnlyList<ProjectId> projectIds, ImmutableDictionary<ProjectId, ProjectState> projectStates) { var map = projectStates.Values.Select(state => new KeyValuePair<ProjectId, ImmutableHashSet<ProjectId>>( state.Id, state.ProjectReferences.Where(pr => projectStates.ContainsKey(pr.ProjectId)).Select(pr => pr.ProjectId).ToImmutableHashSet())) .ToImmutableDictionary(); return new ProjectDependencyGraph(projectIds.ToImmutableHashSet(), map); } private ImmutableDictionary<ProjectId, ICompilationTracker> CreateCompilationTrackerMap(ProjectId changedProjectId, ProjectDependencyGraph dependencyGraph) { var builder = ImmutableDictionary.CreateBuilder<ProjectId, ICompilationTracker>(); IEnumerable<ProjectId>? dependencies = null; foreach (var (id, tracker) in _projectIdToTrackerMap) builder.Add(id, CanReuse(id) ? tracker : tracker.Fork(tracker.ProjectState)); return builder.ToImmutable(); // Returns true if 'tracker' can be reused for project 'id' bool CanReuse(ProjectId id) { if (id == changedProjectId) { return true; } // Check the dependency graph to see if project 'id' directly or transitively depends on 'projectId'. // If the information is not available, do not compute it. var forwardDependencies = dependencyGraph.TryGetProjectsThatThisProjectTransitivelyDependsOn(id); if (forwardDependencies is object && !forwardDependencies.Contains(changedProjectId)) { return true; } // Compute the set of all projects that depend on 'projectId'. This information answers the same // question as the previous check, but involves at most one transitive computation within the // dependency graph. dependencies ??= dependencyGraph.GetProjectsThatTransitivelyDependOnThisProject(changedProjectId); return !dependencies.Contains(id); } } public SolutionState WithOptions(SerializableOptionSet options) => Branch(options: options); public SolutionState AddAnalyzerReferences(IReadOnlyCollection<AnalyzerReference> analyzerReferences) { if (analyzerReferences.Count == 0) { return this; } var oldReferences = AnalyzerReferences.ToImmutableArray(); var newReferences = oldReferences.AddRange(analyzerReferences); return Branch(analyzerReferences: newReferences); } public SolutionState RemoveAnalyzerReference(AnalyzerReference analyzerReference) { var oldReferences = AnalyzerReferences.ToImmutableArray(); var newReferences = oldReferences.Remove(analyzerReference); if (oldReferences == newReferences) { return this; } return Branch(analyzerReferences: newReferences); } public SolutionState WithAnalyzerReferences(IReadOnlyList<AnalyzerReference> analyzerReferences) { if (analyzerReferences == AnalyzerReferences) { return this; } return Branch(analyzerReferences: analyzerReferences); } // this lock guards all the mutable fields (do not share lock with derived classes) private NonReentrantLock? _stateLockBackingField; private NonReentrantLock StateLock { get { // TODO: why did I need to do a nullable suppression here? return LazyInitializer.EnsureInitialized(ref _stateLockBackingField, NonReentrantLock.Factory)!; } } private WeakReference<SolutionState>? _latestSolutionWithPartialCompilation; private DateTime _timeOfLatestSolutionWithPartialCompilation; private DocumentId? _documentIdOfLatestSolutionWithPartialCompilation; /// <summary> /// Creates a branch of the solution that has its compilations frozen in whatever state they are in at the time, assuming a background compiler is /// busy building this compilations. /// /// A compilation for the project containing the specified document id will be guaranteed to exist with at least the syntax tree for the document. /// /// This not intended to be the public API, use Document.WithFrozenPartialSemantics() instead. /// </summary> public SolutionState WithFrozenPartialCompilationIncludingSpecificDocument(DocumentId documentId, CancellationToken cancellationToken) { try { var doc = this.GetRequiredDocumentState(documentId); var tree = doc.GetSyntaxTree(cancellationToken); using (this.StateLock.DisposableWait(cancellationToken)) { // in progress solutions are disabled for some testing if (this.Workspace is Workspace ws && ws.TestHookPartialSolutionsDisabled) { return this; } SolutionState? currentPartialSolution = null; if (_latestSolutionWithPartialCompilation != null) { _latestSolutionWithPartialCompilation.TryGetTarget(out currentPartialSolution); } var reuseExistingPartialSolution = currentPartialSolution != null && (DateTime.UtcNow - _timeOfLatestSolutionWithPartialCompilation).TotalSeconds < 0.1 && _documentIdOfLatestSolutionWithPartialCompilation == documentId; if (reuseExistingPartialSolution) { SolutionLogger.UseExistingPartialSolution(); return currentPartialSolution!; } // if we don't have one or it is stale, create a new partial solution var tracker = this.GetCompilationTracker(documentId.ProjectId); var newTracker = tracker.FreezePartialStateWithTree(this, doc, tree, cancellationToken); var newIdToProjectStateMap = _projectIdToProjectStateMap.SetItem(documentId.ProjectId, newTracker.ProjectState); var newLanguages = _remoteSupportedLanguages; var newIdToTrackerMap = _projectIdToTrackerMap.SetItem(documentId.ProjectId, newTracker); currentPartialSolution = this.Branch( idToProjectStateMap: newIdToProjectStateMap, remoteSupportedProjectLanguages: newLanguages, projectIdToTrackerMap: newIdToTrackerMap, dependencyGraph: CreateDependencyGraph(ProjectIds, newIdToProjectStateMap)); _latestSolutionWithPartialCompilation = new WeakReference<SolutionState>(currentPartialSolution); _timeOfLatestSolutionWithPartialCompilation = DateTime.UtcNow; _documentIdOfLatestSolutionWithPartialCompilation = documentId; SolutionLogger.CreatePartialSolution(); return currentPartialSolution; } } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } /// <summary> /// Creates a new solution instance with all the documents specified updated to have the same specified text. /// </summary> public SolutionState WithDocumentText(IEnumerable<DocumentId?> documentIds, SourceText text, PreservationMode mode) { var solution = this; foreach (var documentId in documentIds) { if (documentId == null) { continue; } var doc = GetProjectState(documentId.ProjectId)?.DocumentStates.GetState(documentId); if (doc != null) { if (!doc.TryGetText(out var existingText) || existingText != text) { solution = solution.WithDocumentText(documentId, text, mode); } } } return solution; } public bool TryGetCompilation(ProjectId projectId, [NotNullWhen(returnValue: true)] out Compilation? compilation) { CheckContainsProject(projectId); compilation = null; return this.TryGetCompilationTracker(projectId, out var tracker) && tracker.TryGetCompilation(out compilation); } /// <summary> /// Returns the compilation for the specified <see cref="ProjectId"/>. Can return <see langword="null"/> when the project /// does not support compilations. /// </summary> /// <remarks> /// The compilation is guaranteed to have a syntax tree for each document of the project. /// </remarks> private Task<Compilation?> GetCompilationAsync(ProjectId projectId, CancellationToken cancellationToken) { // TODO: figure out where this is called and why the nullable suppression is required return GetCompilationAsync(GetProjectState(projectId)!, cancellationToken); } /// <summary> /// Returns the compilation for the specified <see cref="ProjectState"/>. Can return <see langword="null"/> when the project /// does not support compilations. /// </summary> /// <remarks> /// The compilation is guaranteed to have a syntax tree for each document of the project. /// </remarks> public Task<Compilation?> GetCompilationAsync(ProjectState project, CancellationToken cancellationToken) { return project.SupportsCompilation ? GetCompilationTracker(project.Id).GetCompilationAsync(this, cancellationToken).AsNullable() : SpecializedTasks.Null<Compilation>(); } /// <summary> /// Return reference completeness for the given project and all projects this references. /// </summary> public Task<bool> HasSuccessfullyLoadedAsync(ProjectState project, CancellationToken cancellationToken) { // return HasAllInformation when compilation is not supported. // regardless whether project support compilation or not, if projectInfo is not complete, we can't guarantee its reference completeness return project.SupportsCompilation ? this.GetCompilationTracker(project.Id).HasSuccessfullyLoadedAsync(this, cancellationToken) : project.HasAllInformation ? SpecializedTasks.True : SpecializedTasks.False; } /// <summary> /// Returns the generated document states for source generated documents. /// </summary> public ValueTask<TextDocumentStates<SourceGeneratedDocumentState>> GetSourceGeneratedDocumentStatesAsync(ProjectState project, CancellationToken cancellationToken) { return project.SupportsCompilation ? GetCompilationTracker(project.Id).GetSourceGeneratedDocumentStatesAsync(this, cancellationToken) : new(TextDocumentStates<SourceGeneratedDocumentState>.Empty); } /// <summary> /// Returns the <see cref="SourceGeneratedDocumentState"/> for a source generated document that has already been generated and observed. /// </summary> /// <remarks> /// This is only safe to call if you already have seen the SyntaxTree or equivalent that indicates the document state has already been /// generated. This method exists to implement <see cref="Solution.GetDocument(SyntaxTree?)"/> and is best avoided unless you're doing something /// similarly tricky like that. /// </remarks> public SourceGeneratedDocumentState? TryGetSourceGeneratedDocumentStateForAlreadyGeneratedId(DocumentId documentId) { return GetCompilationTracker(documentId.ProjectId).TryGetSourceGeneratedDocumentStateForAlreadyGeneratedId(documentId); } /// <summary> /// Returns a new SolutionState that will always produce a specific output for a generated file. This is used only in the /// implementation of <see cref="TextExtensions.GetOpenDocumentInCurrentContextWithChanges"/> where if a user has a source /// generated file open, we need to make sure everything lines up. /// </summary> public SolutionState WithFrozenSourceGeneratedDocument(SourceGeneratedDocumentIdentity documentIdentity, SourceText sourceText) { // We won't support freezing multiple source generated documents at once. Although nothing in the implementation // of this method would have problems, this simplifies the handling of serializing this solution to out-of-proc. // Since we only produce these snapshots from an open document, there should be no way to observe this, so this assertion // also serves as a good check on the system. If down the road we need to support this, we can remove this check and // update the out-of-process serialization logic accordingly. Contract.ThrowIfTrue(_frozenSourceGeneratedDocumentState != null, "We shouldn't be calling WithFrozenSourceGeneratedDocument on a solution with a frozen source generated document."); var existingGeneratedState = TryGetSourceGeneratedDocumentStateForAlreadyGeneratedId(documentIdentity.DocumentId); SourceGeneratedDocumentState newGeneratedState; if (existingGeneratedState != null) { newGeneratedState = existingGeneratedState.WithUpdatedGeneratedContent(sourceText, existingGeneratedState.ParseOptions); // If the content already matched, we can just reuse the existing state if (newGeneratedState == existingGeneratedState) { return this; } } else { var projectState = GetRequiredProjectState(documentIdentity.DocumentId.ProjectId); newGeneratedState = SourceGeneratedDocumentState.Create( documentIdentity, sourceText, projectState.ParseOptions!, projectState.LanguageServices, _solutionServices); } var projectId = documentIdentity.DocumentId.ProjectId; var newTrackerMap = CreateCompilationTrackerMap(projectId, _dependencyGraph); // We want to create a new snapshot with a new compilation tracker that will do this replacement. // If we already have an existing tracker we'll just wrap that (so we also are reusing any underlying // computations). If we don't have one, we'll create one and then wrap it. if (!newTrackerMap.TryGetValue(projectId, out var existingTracker)) { existingTracker = CreateCompilationTracker(projectId, this); } newTrackerMap = newTrackerMap.SetItem( projectId, new GeneratedFileReplacingCompilationTracker(existingTracker, newGeneratedState)); return this.Branch( projectIdToTrackerMap: newTrackerMap, frozenSourceGeneratedDocument: newGeneratedState); } /// <summary> /// Symbols need to be either <see cref="IAssemblySymbol"/> or <see cref="IModuleSymbol"/>. /// </summary> private static readonly ConditionalWeakTable<ISymbol, ProjectId> s_assemblyOrModuleSymbolToProjectMap = new(); /// <summary> /// Get a metadata reference for the project's compilation /// </summary> public Task<MetadataReference> GetMetadataReferenceAsync(ProjectReference projectReference, ProjectState fromProject, CancellationToken cancellationToken) { try { // Get the compilation state for this project. If it's not already created, then this // will create it. Then force that state to completion and get a metadata reference to it. var tracker = this.GetCompilationTracker(projectReference.ProjectId); return tracker.GetMetadataReferenceAsync(this, fromProject, projectReference, cancellationToken); } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } /// <summary> /// Attempt to get the best readily available compilation for the project. It may be a /// partially built compilation. /// </summary> private MetadataReference? GetPartialMetadataReference( ProjectReference projectReference, ProjectState fromProject) { // Try to get the compilation state for this project. If it doesn't exist, don't do any // more work. if (!_projectIdToTrackerMap.TryGetValue(projectReference.ProjectId, out var state)) { return null; } return state.GetPartialMetadataReference(fromProject, projectReference); } /// <summary> /// Gets a <see cref="ProjectDependencyGraph"/> that details the dependencies between projects for this solution. /// </summary> public ProjectDependencyGraph GetProjectDependencyGraph() => _dependencyGraph; private void CheckNotContainsProject(ProjectId projectId) { if (this.ContainsProject(projectId)) { throw new InvalidOperationException(WorkspacesResources.The_solution_already_contains_the_specified_project); } } private void CheckContainsProject(ProjectId projectId) { if (!this.ContainsProject(projectId)) { throw new InvalidOperationException(WorkspacesResources.The_solution_does_not_contain_the_specified_project); } } internal bool ContainsProjectReference(ProjectId projectId, ProjectReference projectReference) => GetRequiredProjectState(projectId).ProjectReferences.Contains(projectReference); internal bool ContainsMetadataReference(ProjectId projectId, MetadataReference metadataReference) => GetRequiredProjectState(projectId).MetadataReferences.Contains(metadataReference); internal bool ContainsAnalyzerReference(ProjectId projectId, AnalyzerReference analyzerReference) => GetRequiredProjectState(projectId).AnalyzerReferences.Contains(analyzerReference); internal bool ContainsTransitiveReference(ProjectId fromProjectId, ProjectId toProjectId) => _dependencyGraph.GetProjectsThatThisProjectTransitivelyDependsOn(fromProjectId).Contains(toProjectId); internal ImmutableHashSet<string> GetRemoteSupportedProjectLanguages() => _remoteSupportedLanguages; private static ImmutableHashSet<string> GetRemoteSupportedProjectLanguages(ImmutableDictionary<ProjectId, ProjectState> projectStates) { var builder = ImmutableHashSet.CreateBuilder<string>(); foreach (var projectState in projectStates) { if (RemoteSupportedLanguages.IsSupported(projectState.Value.Language)) { builder.Add(projectState.Value.Language); } } return builder.ToImmutable(); } } }
-1
dotnet/roslyn
56,450
Implement INamespaceTypeReference.GetUnit for RootModuleType
Fixes #56412.
AlekseyTs
"2021-09-16T16:44:04Z"
"2021-09-17T18:21:59Z"
4b06ee428bafa0141c9eb3250003a19109dcfc86
d695369176aa109f0e0fb8b0019294aaa0823a54
Implement INamespaceTypeReference.GetUnit for RootModuleType. Fixes #56412.
./src/EditorFeatures/CSharpTest/PullMemberUp/CSharpPullMemberUpTests.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.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CSharp.CodeRefactorings.PullMemberUp; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; using System.Collections.Immutable; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeRefactorings.PullMemberUp.Dialog; using System.Collections.Generic; using Microsoft.CodeAnalysis.Test.Utilities.PullMemberUp; using Roslyn.Test.Utilities; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.Editing; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.PullMemberUp { public class CSharpPullMemberUpTests : AbstractCSharpCodeActionTest { protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters) => new CSharpPullMemberUpCodeRefactoringProvider((IPullMemberUpOptionsService)parameters.fixProviderData); protected override ImmutableArray<CodeAction> MassageActions(ImmutableArray<CodeAction> actions) => FlattenActions(actions); #region Quick Action private async Task TestQuickActionNotProvidedAsync( string initialMarkup, TestParameters parameters = default) { using var workspace = CreateWorkspaceFromOptions(initialMarkup, parameters); var (actions, _) = await GetCodeActionsAsync(workspace, parameters); if (actions.Length == 1) { // The dialog shows up, not quick action Assert.Equal(actions.First().Title, FeaturesResources.Pull_members_up_to_base_type); } else if (actions.Length > 1) { Assert.True(false, "Pull Members Up is provided via quick action"); } else { Assert.True(true); } } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestNoRefactoringProvidedWhenPullFieldInInterfaceViaQuickAction() { var testText = @" namespace PushUpTest { public interface ITestInterface { } public class TestClass : ITestInterface { public int yo[||]u = 10086; } }"; await TestQuickActionNotProvidedAsync(testText); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestNoRefactoringProvidedWhenMethodDeclarationAlreadyExistsInInterfaceViaQuickAction() { var methodTest = @" namespace PushUpTest { public interface ITestInterface { void TestMethod(); } public class TestClass : ITestInterface { public void TestM[||]ethod() { System.Console.WriteLine(""Hello World""); } } }"; await TestQuickActionNotProvidedAsync(methodTest); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestNoRefactoringProvidedWhenPropertyDeclarationAlreadyExistsInInterfaceViaQuickAction() { var propertyTest1 = @" using System; namespace PushUpTest { interface IInterface { int TestProperty { get; } } public class TestClass : IInterface { public int TestPr[||]operty { get; private set; } } }"; await TestQuickActionNotProvidedAsync(propertyTest1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestNoRefactoringProvidedWhenEventDeclarationAlreadyExistsToInterfaceViaQuickAction() { var eventTest = @" using System; namespace PushUpTest { interface IInterface { event EventHandler Event2; } public class TestClass : IInterface { public event EventHandler Event1, Eve[||]nt2, Event3; } }"; await TestQuickActionNotProvidedAsync(eventTest); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestNoRefactoringProvidedInNestedTypesViaQuickAction() { var input = @" namespace PushUpTest { public interface ITestInterface { void Foobar(); } public class TestClass : ITestInterface { public class N[||]estedClass { } } }"; await TestQuickActionNotProvidedAsync(input); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullMethodUpToInterfaceViaQuickAction() { var testText = @" using System; namespace PushUpTest { interface IInterface { } public class TestClass : IInterface { public void TestM[||]ethod() { System.Console.WriteLine(""Hello World""); } } }"; var expected = @" using System; namespace PushUpTest { interface IInterface { void TestMethod(); } public class TestClass : IInterface { public void TestMethod() { System.Console.WriteLine(""Hello World""); } } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullAbstractMethodToInterfaceViaQuickAction() { var testText = @" namespace PushUpTest { public interface IInterface { } public abstract class TestClass : IInterface { public abstract void TestMeth[||]od(); } }"; var expected = @" namespace PushUpTest { public interface IInterface { void TestMethod(); } public abstract class TestClass : IInterface { public abstract void TestMethod(); } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullGenericsUpToInterfaceViaQuickAction() { var testText = @" using System; namespace PushUpTest { public interface IInterface { } public class TestClass : IInterface { public void TestMeth[||]od<T>() where T : IDisposable { } } }"; var expected = @" using System; namespace PushUpTest { public interface IInterface { void TestMethod<T>() where T : IDisposable; } public class TestClass : IInterface { public void TestMeth[||]od<T>() where T : IDisposable { } } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullSingleEventToInterfaceViaQuickAction() { var testText = @" using System; namespace PushUpTest { interface IInterface { } public class TestClass : IInterface { public event EventHandler Eve[||]nt1 { add { System.Console.Writeline(""This is add""); } remove { System.Console.Writeline(""This is remove""); } } } }"; var expected = @" using System; namespace PushUpTest { interface IInterface { event EventHandler Event1; } public class TestClass : IInterface { public event EventHandler Event1 { add { System.Console.Writeline(""This is add""); } remove { System.Console.Writeline(""This is remove""); } } } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullOneEventFromMultipleEventsToInterfaceViaQuickAction() { var testText = @" using System; namespace PushUpTest { interface IInterface { } public class TestClass : IInterface { public event EventHandler Event1, Eve[||]nt2, Event3; } }"; var expected = @" using System; namespace PushUpTest { interface IInterface { event EventHandler Event2; } public class TestClass : IInterface { public event EventHandler Event1, Event2, Event3; } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullPublicEventWithAccessorsToInterfaceViaQuickAction() { var testText = @" using System; namespace PushUpTest { interface IInterface { } public class TestClass : IInterface { public event EventHandler Eve[||]nt2 { add { System.Console.Writeln(""This is add in event1""); } remove { System.Console.Writeln(""This is remove in event2""); } } } }"; var expected = @" using System; namespace PushUpTest { interface IInterface { event EventHandler Event2; } public class TestClass : IInterface { public event EventHandler Event2 { add { System.Console.Writeln(""This is add in event1""); } remove { System.Console.Writeln(""This is remove in event2""); } } } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullPropertyWithPrivateSetterToInterfaceViaQuickAction() { var testText = @" using System; namespace PushUpTest { interface IInterface { } public class TestClass : IInterface { public int TestPr[||]operty { get; private set; } } }"; var expected = @" using System; namespace PushUpTest { interface IInterface { int TestProperty { get; } } public class TestClass : IInterface { public int TestProperty { get; private set; } } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullPropertyWithPrivateGetterToInterfaceViaQuickAction() { var testText = @" using System; namespace PushUpTest { interface IInterface { } public class TestClass : IInterface { public int TestProperty[||]{ private get; set; } } }"; var expected = @" using System; namespace PushUpTest { interface IInterface { int TestProperty { set; } } public class TestClass : IInterface { public int TestProperty{ private get; set; } } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullMemberFromInterfaceToInterfaceViaQuickAction() { var testText = @" using System; namespace PushUpTest { interface IInterface { } interface FooInterface : IInterface { int TestPr[||]operty { set; } } }"; var expected = @" using System; namespace PushUpTest { interface IInterface { int TestProperty { set; } } interface FooInterface : IInterface { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullIndexerWithOnlySetterToInterfaceViaQuickAction() { var testText = @" using System; namespace PushUpTest { interface IInterface { } public class TestClass : IInterface { private int j; public int th[||]is[int i] { set => j = value; } } }"; var expected = @" using System; namespace PushUpTest { interface IInterface { int this[int i] { set; } } public class TestClass : IInterface { private int j; public int this[int i] { set => j = value; } } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullIndexerWithOnlyGetterToInterfaceViaQuickAction() { var testText = @" using System; namespace PushUpTest { interface IInterface { } public class TestClass : IInterface { private int j; public int th[||]is[int i] { get => j = value; } } }"; var expected = @" using System; namespace PushUpTest { interface IInterface { int this[int i] { get; } } public class TestClass : IInterface { private int j; public int this[int i] { get => j = value; } } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullPropertyToInterfaceWithAddUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public interface IBase { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : IBase { public Uri En[||]dpoint { get; set; } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; public interface IBase { Uri Endpoint { get; set; } } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : IBase { public Uri Endpoint { get; set; } } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToInterfaceWithoutAddUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public interface IBase { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : IBase { public bool Test[||]Method() { var endpoint1 = new Uri(""http://localhost""); var endpoint2 = new Uri(""http://localhost""); return endpoint1.Equals(endpoint2); } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public interface IBase { bool TestMethod(); } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : IBase { public bool Test[||]Method() { var endpoint1 = new Uri(""http://localhost""); var endpoint2 = new Uri(""http://localhost""); return endpoint1.Equals(endpoint2); } } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodWithNewReturnTypeToInterfaceWithAddUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public interface IBase { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : IBase { public Uri Test[||]Method() { return new Uri(""http://localhost""); } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; public interface IBase { Uri TestMethod(); } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : IBase { public Uri TestMethod() { return new Uri(""http://localhost""); } } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodWithNewParamTypeToInterfaceWithAddUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public interface IBase { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : IBase { public bool Test[||]Method(Uri endpoint) { var localHost = new Uri(""http://localhost""); return endpoint.Equals(localhost); } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; public interface IBase { bool TestMethod(Uri endpoint); } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : IBase { public bool TestMethod(Uri endpoint) { var localHost = new Uri(""http://localhost""); return endpoint.Equals(localhost); } } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullEventToInterfaceWithAddUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public interface IBase { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : IBase { public event EventHandler Test[||]Event { add { Console.WriteLine(""adding event...""); } remove { Console.WriteLine(""removing event...""); } } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; public interface IBase { event EventHandler TestEvent; } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : IBase { public event EventHandler TestEvent { add { Console.WriteLine(""adding event...""); } remove { Console.WriteLine(""removing event...""); } } } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullPropertyToClassWithAddUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public class Base { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { public Uri En[||]dpoint { get; set; } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using System; public class Base { public Uri Endpoint { get; set; } } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullPropertyToClassWithAddUsingsViaQuickAction2() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">public class Base { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { public Uri En[||]dpoint { get; set; } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using System; public class Base { public Uri Endpoint { get; set; } } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullPropertyToClassWithoutDuplicatingUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; public class Base { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { public Uri En[||]dpoint { get; set; } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; public class Base { public Uri Endpoint { get; set; } } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullPropertyWithNewBodyTypeToClassWithAddUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public class Base { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { public bool Test[||]Property { get { var endpoint1 = new Uri(""http://localhost""); var endpoint2 = new Uri(""http://localhost""); return endpoint1.Equals(endpoint2); } } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using System; public class Base { public bool TestProperty { get { var endpoint1 = new Uri(""http://localhost""); var endpoint2 = new Uri(""http://localhost""); return endpoint1.Equals(endpoint2); } } } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodWithNewNonDeclaredBodyTypeToClassWithAddUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public class Base { } </Document> <Document FilePath = ""File2.cs""> using System.Linq; public class Derived : Base { public int Test[||]Method() { return Enumerable.Range(0, 5).Sum(); } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using System.Linq; public class Base { public int Test[||]Method() { return Enumerable.Range(0, 5).Sum(); } } </Document> <Document FilePath = ""File2.cs""> using System.Linq; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithOverlappingUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; using System.Threading.Tasks; public class Base { public Uri Endpoint{ get; set; } public async Task&lt;int&gt; Get5Async() { return 5; } } </Document> <Document FilePath = ""File2.cs""> using System.Linq; using System.Threading.Tasks; public class Derived : Base { public async Task&lt;int&gt; Test[||]Method() { return Enumerable.Range(0, 5).Sum(); } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; using System.Linq; using System.Threading.Tasks; public class Base { public Uri Endpoint{ get; set; } public async Task&lt;int&gt; Get5Async() { return 5; } public async Task&lt;int&gt; Test[||]Method() { return Enumerable.Range(0, 5).Sum(); } } </Document> <Document FilePath = ""File2.cs""> using System.Linq; using System.Threading.Tasks; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithUnnecessaryFirstUsingViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System.Threading.Tasks; public class Base { public async Task&lt;int&gt; Get5Async() { return 5; } } </Document> <Document FilePath = ""File2.cs""> using System; using System.Linq; using System.Threading.Tasks; public class Derived : Base { public async Task&lt;int&gt; Test[||]Method() { return Enumerable.Range(0, 5).Sum(); } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using System.Linq; using System.Threading.Tasks; public class Base { public async Task&lt;int&gt; Get5Async() { return 5; } public async Task&lt;int&gt; Test[||]Method() { return Enumerable.Range(0, 5).Sum(); } } </Document> <Document FilePath = ""File2.cs""> using System; using System.Linq; using System.Threading.Tasks; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithUnusedBaseUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; using System.Threading.Tasks; public class Base { public Uri Endpoint{ get; set; } } </Document> <Document FilePath = ""File2.cs""> using System.Linq; public class Derived : Base { public int Test[||]Method() { return Enumerable.Range(0, 5).Sum(); } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; using System.Linq; using System.Threading.Tasks; public class Base { public Uri Endpoint{ get; set; } public int TestMethod() { return Enumerable.Range(0, 5).Sum(); } } </Document> <Document FilePath = ""File2.cs""> using System.Linq; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithRetainCommentsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> // blah blah public class Base { } </Document> <Document FilePath = ""File2.cs""> using System.Linq; public class Derived : Base { public int Test[||]Method() { return 5; } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> // blah blah public class Base { public int TestMethod() { return 5; } } </Document> <Document FilePath = ""File2.cs""> using System.Linq; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithRetainPreImportCommentsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> // blah blah using System.Linq; public class Base { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { public Uri End[||]point { get; set; } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> // blah blah using System; using System.Linq; public class Base { public Uri Endpoint { get; set; } } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithRetainPostImportCommentsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System.Linq; // blah blah public class Base { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { public Uri End[||]point { get; set; } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; using System.Linq; // blah blah public class Base { public Uri Endpoint { get; set; } } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithLambdaUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public class Base { } </Document> <Document FilePath = ""File2.cs""> using System; using System.Linq; public class Derived : Base { public int Test[||]Method() { return Enumerable.Range(0, 5). Select((n) => new Uri(""http://"" + n)). Count((uri) => uri != null); } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using System; using System.Linq; public class Base { public int TestMethod() { return Enumerable.Range(0, 5). Select((n) => new Uri(""http://"" + n)). Count((uri) => uri != null); } } </Document> <Document FilePath = ""File2.cs""> using System; using System.Linq; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithUnusedUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; public class Base { public Uri Endpoint{ get; set; } } </Document> <Document FilePath = ""File2.cs""> using System.Linq; using System.Threading.Tasks; public class Derived : Base { public int Test[||]Method() { return Enumerable.Range(0, 5).Sum(); } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; using System.Linq; public class Base { public Uri Endpoint{ get; set; } public int TestMethod() { return Enumerable.Range(0, 5).Sum(); } } </Document> <Document FilePath = ""File2.cs""> using System.Linq; using System.Threading.Tasks; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassKeepSystemFirstViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace TestNs1 { using System; public class Base { public Uri Endpoint{ get; set; } } } </Document> <Document FilePath = ""File2.cs""> namespace A_TestNs2 { using TestNs1; public class Derived : Base { public Foo Test[||]Method() { return null; } } public class Foo { } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace TestNs1 { using System; using A_TestNs2; public class Base { public Uri Endpoint{ get; set; } public Foo TestMethod() { return null; } } } </Document> <Document FilePath = ""File2.cs""> namespace A_TestNs2 { using TestNs1; public class Derived : Base { } public class Foo { } } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassKeepSystemFirstViaQuickAction2() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace TestNs1 { public class Base { } } </Document> <Document FilePath = ""File2.cs""> namespace A_TestNs2 { using System; using TestNs1; public class Derived : Base { public Foo Test[||]Method() { var uri = new Uri(""http://localhost""); return null; } } public class Foo { } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using System; using A_TestNs2; namespace TestNs1 { public class Base { public Foo TestMethod() { var uri = new Uri(""http://localhost""); return null; } } } </Document> <Document FilePath = ""File2.cs""> namespace A_TestNs2 { using System; using TestNs1; public class Derived : Base { } public class Foo { } } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithExtensionViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace TestNs1 { public class Base { } public class Foo { } } </Document> <Document FilePath = ""File2.cs""> namespace TestNs2 { using TestNs1; public class Derived : Base { public int Test[||]Method() { var foo = new Foo(); return foo.FooBar(); } } public static class FooExtensions { public static int FooBar(this Foo foo) { return 5; } } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using TestNs2; namespace TestNs1 { public class Base { public int TestMethod() { var foo = new Foo(); return foo.FooBar(); } } public class Foo { } } </Document> <Document FilePath = ""File2.cs""> namespace TestNs2 { using TestNs1; public class Derived : Base { } public static class FooExtensions { public static int FooBar(this Foo foo) { return 5; } } } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithExtensionViaQuickAction2() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace TestNs1 { public class Base { } } </Document> <Document FilePath = ""File2.cs""> using TestNs1; using TestNs3; using TestNs4; namespace TestNs2 { public class Derived : Base { public int Test[||]Method() { var foo = new Foo(); return foo.FooBar(); } } } </Document> <Document FilePath = ""File3.cs""> namespace TestNs3 { public class Foo { } } </Document> <Document FilePath = ""File4.cs""> using TestNs3; namespace TestNs4 { public static class FooExtensions { public static int FooBar(this Foo foo) { return 5; } } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using TestNs3; using TestNs4; namespace TestNs1 { public class Base { public int TestMethod() { var foo = new Foo(); return foo.FooBar(); } } } </Document> <Document FilePath = ""File2.cs""> using TestNs1; using TestNs3; using TestNs4; namespace TestNs2 { public class Derived : Base { } } </Document> <Document FilePath = ""File3.cs""> namespace TestNs3 { public class Foo { } } </Document> <Document FilePath = ""File4.cs""> using TestNs3; namespace TestNs4 { public static class FooExtensions { public static int FooBar(this Foo foo) { return 5; } } } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithAliasUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; public class Base { public Uri Endpoint{ get; set; } } </Document> <Document FilePath = ""File2.cs""> using Enumer = System.Linq.Enumerable; using Sys = System; public class Derived : Base { public void Test[||]Method() { Sys.Console.WriteLine(Enumer.Range(0, 5).Sum()); } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; using Enumer = System.Linq.Enumerable; using Sys = System; public class Base { public Uri Endpoint{ get; set; } public void TestMethod() { Sys.Console.WriteLine(Enumer.Range(0, 5).Sum()); } } </Document> <Document FilePath = ""File2.cs""> using Enumer = System.Linq.Enumerable; using Sys = System; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullPropertyToClassWithBaseAliasUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using Enumer = System.Linq.Enumerable; public class Base { public void TestMethod() { System.Console.WriteLine(Enumer.Range(0, 5).Sum()); } } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { public Uri End[||]point{ get; set; } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; using Enumer = System.Linq.Enumerable; public class Base { public Uri Endpoint{ get; set; } public void TestMethod() { System.Console.WriteLine(Enumer.Range(0, 5).Sum()); } } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithMultipleNamespacedUsingsViaQuickAction() { var testText = @" namespace TestNs1 { using System; public class Base { public Uri Endpoint{ get; set; } } } namespace TestNs2 { using System.Linq; using TestNs1; public class Derived : Base { public int Test[||]Method() { return Enumerable.Range(0, 5).Sum(); } } } "; var expected = @" namespace TestNs1 { using System; using System.Linq; public class Base { public Uri Endpoint{ get; set; } public int TestMethod() { return Enumerable.Range(0, 5).Sum(); } } } namespace TestNs2 { using System.Linq; using TestNs1; public class Derived : Base { } } "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithNestedNamespacedUsingsViaQuickAction() { var testText = @" namespace TestNs1 { namespace InnerNs1 { using System; public class Base { public Uri Endpoint { get; set; } } } } namespace TestNs2 { namespace InnerNs2 { using System.Linq; using TestNs1.InnerNs1; public class Derived : Base { public int Test[||]Method() { return Foo.Bar(Enumerable.Range(0, 5).Sum()); } } public class Foo { public static int Bar(int num) { return num + 1; } } } } "; var expected = @" namespace TestNs1 { namespace InnerNs1 { using System; using System.Linq; using TestNs2.InnerNs2; public class Base { public Uri Endpoint { get; set; } public int TestMethod() { return Foo.Bar(Enumerable.Range(0, 5).Sum()); } } } } namespace TestNs2 { namespace InnerNs2 { using System.Linq; using TestNs1.InnerNs1; public class Derived : Base { } public class Foo { public static int Bar(int num) { return num + 1; } } } } "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithNewNamespaceUsingViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace A.B { class Base { } } </Document> <Document FilePath = ""File2.cs""> namespace X.Y { class Derived : A.B.Base { public Other Get[||]Other() => null; } class Other { } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using X.Y; namespace A.B { class Base { public Other GetOther() => null; } } </Document> <Document FilePath = ""File2.cs""> namespace X.Y { class Derived : A.B.Base { } class Other { } } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithFileNamespaceUsingViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace A.B; class Base { } </Document> <Document FilePath = ""File2.cs""> namespace X.Y; class Derived : A.B.Base { public Other Get[||]Other() => null; } class Other { } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using X.Y; namespace A.B; class Base { public Other GetOther() => null; } </Document> <Document FilePath = ""File2.cs""> namespace X.Y; class Derived : A.B.Base { } class Other { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithUnusedNamespaceUsingViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace A.B { class Base { } } </Document> <Document FilePath = ""File2.cs""> namespace X.Y { class Derived : A.B.Base { public int Get[||]Five() => 5; } class Other { } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace A.B { class Base { public int GetFive() => 5; } } </Document> <Document FilePath = ""File2.cs""> namespace X.Y { class Derived : A.B.Base { } class Other { } } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithMultipleNamespacesAndCommentsViaQuickAction() { var testText = @" // comment 1 namespace TestNs1 { // comment 2 // comment 3 public class Base { } } namespace TestNs2 { // comment 4 using System.Linq; using TestNs1; public class Derived : Base { public int Test[||]Method() { return 5; } } } "; var expected = @" // comment 1 namespace TestNs1 { // comment 2 // comment 3 public class Base { public int TestMethod() { return 5; } } } namespace TestNs2 { // comment 4 using System.Linq; using TestNs1; public class Derived : Base { } } "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithMultipleNamespacedUsingsAndCommentsViaQuickAction() { var testText = @" // comment 1 namespace TestNs1 { // comment 2 using System; // comment 3 public class Base { } } namespace TestNs2 { // comment 4 using System.Linq; using TestNs1; public class Derived : Base { public int Test[||]Method() { return Enumerable.Range(0, 5).Sum(); } } } "; var expected = @" // comment 1 namespace TestNs1 { // comment 2 using System; using System.Linq; // comment 3 public class Base { public int TestMethod() { return Enumerable.Range(0, 5).Sum(); } } } namespace TestNs2 { // comment 4 using System.Linq; using TestNs1; public class Derived : Base { } } "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithNamespacedUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace ClassLibrary1 { using System; public class Base { public Uri Endpoint{ get; set; } } } </Document> <Document FilePath = ""File2.cs""> namespace ClassLibrary1 { using System.Linq; public class Derived : Base { public int Test[||]Method() { return Enumerable.Range(0, 5).Sum(); } } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace ClassLibrary1 { using System; using System.Linq; public class Base { public Uri Endpoint{ get; set; } public int Test[||]Method() { return Enumerable.Range(0, 5).Sum(); } } } </Document> <Document FilePath = ""File2.cs""> namespace ClassLibrary1 { using System.Linq; public class Derived : Base { } } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithDuplicateNamespacedUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace ClassLibrary1 { using System; public class Base { public Uri Endpoint{ get; set; } } } </Document> <Document FilePath = ""File2.cs""> using System.Linq; namespace ClassLibrary1 { using System.Linq; public class Derived : Base { public int Test[||]Method() { return Enumerable.Range(0, 5).Sum(); } } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace ClassLibrary1 { using System; using System.Linq; public class Base { public Uri Endpoint{ get; set; } public int Test[||]Method() { return Enumerable.Range(0, 5).Sum(); } } } </Document> <Document FilePath = ""File2.cs""> using System.Linq; namespace ClassLibrary1 { using System.Linq; public class Derived : Base { } } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodWithNewReturnTypeToClassWithAddUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public class Base { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { public Uri En[||]dpoint() { return new Uri(""http://localhost""); } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using System; public class Base { public Uri Endpoint() { return new Uri(""http://localhost""); } } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodWithNewParamTypeToClassWithAddUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public class Base { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { public bool Test[||]Method(Uri endpoint) { var localHost = new Uri(""http://localhost""); return endpoint.Equals(localhost); } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using System; public class Base { public bool TestMethod(Uri endpoint) { var localHost = new Uri(""http://localhost""); return endpoint.Equals(localhost); } } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodWithNewBodyTypeToClassWithAddUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public class Base { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { public bool Test[||]Method() { var endpoint1 = new Uri(""http://localhost""); var endpoint2 = new Uri(""http://localhost""); return endpoint1.Equals(endpoint2); } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using System; public class Base { public bool TestMethod() { var endpoint1 = new Uri(""http://localhost""); var endpoint2 = new Uri(""http://localhost""); return endpoint1.Equals(endpoint2); } } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullEventToClassWithAddUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public class Base { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { public event EventHandler Test[||]Event { add { Console.WriteLine(""adding event...""); } remove { Console.WriteLine(""removing event...""); } } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using System; public class Base { public event EventHandler Test[||]Event { add { Console.WriteLine(""adding event...""); } remove { Console.WriteLine(""removing event...""); } } } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullFieldToClassWithAddUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public class Base { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { public var en[||]dpoint = new Uri(""http://localhost""); } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using System; public class Base { public var endpoint = new Uri(""http://localhost""); } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullFieldToClassNoConstructorWithAddUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public class Base { } </Document> <Document FilePath = ""File2.cs""> using System.Linq; public class Derived : Base { public var ran[||]ge = Enumerable.Range(0, 5); } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using System.Linq; public class Base { public var range = Enumerable.Range(0, 5); } </Document> <Document FilePath = ""File2.cs""> using System.Linq; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestNoRefactoringProvidedWhenPullOverrideMethodUpToClassViaQuickAction() { var methodTest = @" namespace PushUpTest { public class Base { public virtual void TestMethod() => System.Console.WriteLine(""foo bar bar foo""); } public class TestClass : Base { public override void TestMeth[||]od() { System.Console.WriteLine(""Hello World""); } } }"; await TestQuickActionNotProvidedAsync(methodTest); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestNoRefactoringProvidedWhenPullOverridePropertyUpToClassViaQuickAction() { var propertyTest = @" using System; namespace PushUpTest { public class Base { public virtual int TestProperty { get => 111; private set; } } public class TestClass : Base { public override int TestPr[||]operty { get; private set; } } }"; await TestQuickActionNotProvidedAsync(propertyTest); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestNoRefactoringProvidedWhenPullOverrideEventUpToClassViaQuickAction() { var eventTest = @" using System; namespace PushUpTest { public class Base2 { protected virtual event EventHandler Event3 { add { System.Console.WriteLine(""Hello""); } remove { System.Console.WriteLine(""World""); } }; } public class TestClass2 : Base2 { protected override event EventHandler E[||]vent3 { add { System.Console.WriteLine(""foo""); } remove { System.Console.WriteLine(""bar""); } }; } }"; await TestQuickActionNotProvidedAsync(eventTest); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestNoRefactoringProvidedWhenPullSameNameFieldUpToClassViaQuickAction() { // Fields share the same name will be thought as 'override', since it will cause error // if two same name fields exist in one class var fieldTest = @" namespace PushUpTest { public class Base { public int you = -100000; } public class TestClass : Base { public int y[||]ou = 10086; } }"; await TestQuickActionNotProvidedAsync(fieldTest); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullMethodToOrdinaryClassViaQuickAction() { var testText = @" namespace PushUpTest { public class Base { } public class TestClass : Base { public void TestMeth[||]od() { System.Console.WriteLine(""Hello World""); } } }"; var expected = @" namespace PushUpTest { public class Base { public void TestMethod() { System.Console.WriteLine(""Hello World""); } } public class TestClass : Base { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullOneFieldsToClassViaQuickAction() { var testText = @" namespace PushUpTest { public class Base { } public class TestClass : Base { public int you[||]= 10086; } }"; var expected = @" namespace PushUpTest { public class Base { public int you = 10086; } public class TestClass : Base { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullGenericsUpToClassViaQuickAction() { var testText = @" using System; namespace PushUpTest { public class BaseClass { } public class TestClass : BaseClass { public void TestMeth[||]od<T>() where T : IDisposable { } } }"; var expected = @" using System; namespace PushUpTest { public class BaseClass { public void TestMethod<T>() where T : IDisposable { } } public class TestClass : BaseClass { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullOneFieldFromMultipleFieldsToClassViaQuickAction() { var testText = @" namespace PushUpTest { public class Base { } public class TestClass : Base { public int you, a[||]nd, someone = 10086; } }"; var expected = @" namespace PushUpTest { public class Base { public int and; } public class TestClass : Base { public int you, someone = 10086; } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullMiddleFieldWithValueToClassViaQuickAction() { var testText = @" namespace PushUpTest { public class Base { } public class TestClass : Base { public int you, a[||]nd = 4000, someone = 10086; } }"; var expected = @" namespace PushUpTest { public class Base { public int and = 4000; } public class TestClass : Base { public int you, someone = 10086; } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullOneEventFromMultipleToClassViaQuickAction() { var testText = @" using System; namespace PushUpTest { public class Base2 { } public class Testclass2 : Base2 { private static event EventHandler Event1, Eve[||]nt3, Event4; } }"; var expected = @" using System; namespace PushUpTest { public class Base2 { private static event EventHandler Event3; } public class Testclass2 : Base2 { private static event EventHandler Event1, Event4; } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullEventToClassViaQuickAction() { var testText = @" using System; namespace PushUpTest { public class Base2 { } public class TestClass2 : Base2 { private static event EventHandler Eve[||]nt3; } }"; var expected = @" using System; namespace PushUpTest { public class Base2 { private static event EventHandler Event3; } public class TestClass2 : Base2 { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullEventWithBodyToClassViaQuickAction() { var testText = @" using System; namespace PushUpTest { public class Base2 { } public class TestClass2 : Base2 { private static event EventHandler Eve[||]nt3 { add { System.Console.Writeln(""Hello""); } remove { System.Console.Writeln(""World""); } }; } }"; var expected = @" using System; namespace PushUpTest { public class Base2 { private static event EventHandler Event3 { add { System.Console.Writeln(""Hello""); } remove { System.Console.Writeln(""World""); } }; } public class TestClass2 : Base2 { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullPropertyToClassViaQuickAction() { var testText = @" using System; namespace PushUpTest { public class Base { } public class TestClass : Base { public int TestPr[||]operty { get; private set; } } }"; var expected = @" using System; namespace PushUpTest { public class Base { public int TestProperty { get; private set; } } public class TestClass : Base { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullIndexerToClassViaQuickAction() { var testText = @" namespace PushUpTest { public class Base { } public class TestClass : Base { private int j; public int th[||]is[int i] { get => j; set => j = value; } } }"; var expected = @" namespace PushUpTest { public class Base { public int this[int i] { get => j; set => j = value; } } public class TestClass : Base { private int j; } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullMethodUpAcrossProjectViaQuickAction() { var testText = @" <Workspace> <Project Language=""C#"" AssemblyName=""CSAssembly1"" CommonReferences=""true""> <ProjectReference>CSAssembly2</ProjectReference> <Document> using Destination; public class TestClass : IInterface { public int Bar[||]Bar() { return 12345; } } </Document> </Project> <Project Language=""C#"" AssemblyName=""CSAssembly2"" CommonReferences=""true""> <Document> namespace Destination { public interface IInterface { } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""CSAssembly1"" CommonReferences=""true""> <ProjectReference>CSAssembly2</ProjectReference> <Document> using Destination; public class TestClass : IInterface { public int Bar[||]Bar() { return 12345; } } </Document> </Project> <Project Language=""C#"" AssemblyName=""CSAssembly2"" CommonReferences=""true""> <Document> namespace Destination { public interface IInterface { int BarBar(); } } </Document> </Project> </Workspace>"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullPropertyUpAcrossProjectViaQuickAction() { var testText = @" <Workspace> <Project Language=""C#"" AssemblyName=""CSAssembly1"" CommonReferences=""true""> <ProjectReference>CSAssembly2</ProjectReference> <Document> using Destination; public class TestClass : IInterface { public int F[||]oo { get; set; } } </Document> </Project> <Project Language=""C#"" AssemblyName=""CSAssembly2"" CommonReferences=""true""> <Document> namespace Destination { public interface IInterface { } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""CSAssembly1"" CommonReferences=""true""> <ProjectReference>CSAssembly2</ProjectReference> <Document> using Destination; public class TestClass : IInterface { public int Foo { get; set; } } </Document> </Project> <Project Language=""C#"" AssemblyName=""CSAssembly2"" CommonReferences=""true""> <Document> namespace Destination { public interface IInterface { int Foo { get; set; } } } </Document> </Project> </Workspace>"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullFieldUpAcrossProjectViaQuickAction() { var testText = @" <Workspace> <Project Language=""C#"" AssemblyName=""CSAssembly1"" CommonReferences=""true""> <ProjectReference>CSAssembly2</ProjectReference> <Document> using Destination; public class TestClass : BaseClass { private int i, j, [||]k = 10; } </Document> </Project> <Project Language=""C#"" AssemblyName=""CSAssembly2"" CommonReferences=""true""> <Document> namespace Destination { public class BaseClass { } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""CSAssembly1"" CommonReferences=""true""> <ProjectReference>CSAssembly2</ProjectReference> <Document> using Destination; public class TestClass : BaseClass { private int i, j; } </Document> </Project> <Project Language=""C#"" AssemblyName=""CSAssembly2"" CommonReferences=""true""> <Document> namespace Destination { public class BaseClass { private int k = 10; } } </Document> </Project> </Workspace>"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullMethodUpToVBClassViaQuickAction() { // Moving member from C# to Visual Basic is not supported currently since the FindMostRelevantDeclarationAsync method in // AbstractCodeGenerationService will return null. var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""CSAssembly"" CommonReferences=""true""> <ProjectReference>VBAssembly</ProjectReference> <Document> using VBAssembly; public class TestClass : VBClass { public int Bar[||]bar() { return 12345; } } </Document> </Project> <Project Language=""Visual Basic"" AssemblyName=""VBAssembly"" CommonReferences=""true""> <Document> Public Class VBClass End Class </Document> </Project> </Workspace>"; await TestQuickActionNotProvidedAsync(input); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullMethodUpToVBInterfaceViaQuickAction() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""CSAssembly"" CommonReferences=""true""> <ProjectReference>VBAssembly</ProjectReference> <Document> public class TestClass : VBInterface { public int Bar[||]bar() { return 12345; } } </Document> </Project> <Project Language=""Visual Basic"" AssemblyName=""VBAssembly"" CommonReferences=""true""> <Document> Public Interface VBInterface End Interface </Document> </Project> </Workspace> "; await TestQuickActionNotProvidedAsync(input); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullFieldUpToVBClassViaQuickAction() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""CSAssembly"" CommonReferences=""true""> <ProjectReference>VBAssembly</ProjectReference> <Document> using VBAssembly; public class TestClass : VBClass { public int fo[||]obar = 0; } </Document> </Project> <Project Language=""Visual Basic"" AssemblyName=""VBAssembly"" CommonReferences=""true""> <Document> Public Class VBClass End Class </Document> </Project> </Workspace>"; await TestQuickActionNotProvidedAsync(input); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullPropertyUpToVBClassViaQuickAction() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""CSAssembly"" CommonReferences=""true""> <ProjectReference>VBAssembly</ProjectReference> <Document> using VBAssembly; public class TestClass : VBClass { public int foo[||]bar { get; set; } }</Document> </Project> <Project Language=""Visual Basic"" AssemblyName=""VBAssembly"" CommonReferences=""true""> <Document> Public Class VBClass End Class </Document> </Project> </Workspace> "; await TestQuickActionNotProvidedAsync(input); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullPropertyUpToVBInterfaceViaQuickAction() { var input = @"<Workspace> <Project Language=""C#"" AssemblyName=""CSAssembly"" CommonReferences=""true""> <ProjectReference>VBAssembly</ProjectReference> <Document> using VBAssembly; public class TestClass : VBInterface { public int foo[||]bar { get; set; } } </Document> </Project> <Project Language = ""Visual Basic"" AssemblyName=""VBAssembly"" CommonReferences=""true""> <Document> Public Interface VBInterface End Interface </Document> </Project> </Workspace>"; await TestQuickActionNotProvidedAsync(input); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullEventUpToVBClassViaQuickAction() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""CSAssembly"" CommonReferences=""true""> <ProjectReference>VBAssembly</ProjectReference> <Document> using VBAssembly; public class TestClass : VBClass { public event EventHandler BarEve[||]nt; } </Document> </Project> <Project Language=""Visual Basic"" AssemblyName=""VBAssembly"" CommonReferences=""true""> <Document> Public Class VBClass End Class </Document> </Project> </Workspace>"; await TestQuickActionNotProvidedAsync(input); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullEventUpToVBInterfaceViaQuickAction() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""CSAssembly"" CommonReferences=""true""> <ProjectReference>VBAssembly</ProjectReference> <Document> using VBAssembly; public class TestClass : VBInterface { public event EventHandler BarEve[||]nt; } </Document> </Project> <Project Language=""Visual Basic"" AssemblyName=""VBAssembly"" CommonReferences=""true""> <Document> Public Interface VBInterface End Interface </Document> </Project> </Workspace>"; await TestQuickActionNotProvidedAsync(input); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(55746, "https://github.com/dotnet/roslyn/issues/55746")] public async Task TestPullMethodWithToClassWithAddUsingsInsideNamespaceViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace N { public class Base { } } </Document> <Document FilePath = ""File2.cs""> using System; namespace N { public class Derived : Base { public Uri En[||]dpoint() { return new Uri(""http://localhost""); } } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace N { using System; public class Base { public Uri Endpoint() { return new Uri(""http://localhost""); } } } </Document> <Document FilePath = ""File2.cs""> using System; namespace N { public class Derived : Base { } } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync( testText, expected, options: Option(CSharpCodeStyleOptions.PreferredUsingDirectivePlacement, CodeAnalysis.AddImports.AddImportPlacement.InsideNamespace, CodeStyle.NotificationOption2.Silent)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(55746, "https://github.com/dotnet/roslyn/issues/55746")] public async Task TestPullMethodWithToClassWithAddUsingsSystemUsingsLastViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace N1 { public class Base { } } </Document> <Document FilePath = ""File2.cs""> using System; using N2; namespace N1 { public class Derived : Base { public Goo Ge[||]tGoo() { return new Goo(String.Empty); } } } namespace N2 { public class Goo { public Goo(String s) { } } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using N2; using System; namespace N1 { public class Base { public Goo GetGoo() { return new Goo(String.Empty); } } } </Document> <Document FilePath = ""File2.cs""> using System; using N2; namespace N1 { public class Derived : Base { } } namespace N2 { public class Goo { public Goo(String s) { } } } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync( testText, expected, options: new(GetLanguage()) { { GenerationOptions.PlaceSystemNamespaceFirst, false }, }); } #endregion Quick Action #region Dialog internal Task TestWithPullMemberDialogAsync( string initialMarkUp, string expectedResult, IEnumerable<(string name, bool makeAbstract)> selection = null, string destinationName = null, int index = 0, TestParameters parameters = default) { var service = new TestPullMemberUpService(selection, destinationName); return TestInRegularAndScript1Async( initialMarkUp, expectedResult, index, parameters.WithFixProviderData(service)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullPartialMethodUpToInterfaceViaDialog() { var testText = @" using System; namespace PushUpTest { partial interface IInterface { } public partial class TestClass : IInterface { partial void Bar[||]Bar() } public partial class TestClass { partial void BarBar() {} } partial interface IInterface { } }"; var expected = @" using System; namespace PushUpTest { partial interface IInterface { void BarBar(); } public partial class TestClass : IInterface { void BarBar() } public partial class TestClass { partial void BarBar() {} } partial interface IInterface { } }"; await TestWithPullMemberDialogAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullExtendedPartialMethodUpToInterfaceViaDialog() { var testText = @" using System; namespace PushUpTest { partial interface IInterface { } public partial class TestClass : IInterface { public partial void Bar[||]Bar() } public partial class TestClass { public partial void BarBar() {} } partial interface IInterface { } }"; var expected = @" using System; namespace PushUpTest { partial interface IInterface { void BarBar(); } public partial class TestClass : IInterface { public partial void BarBar() } public partial class TestClass { public partial void BarBar() {} } partial interface IInterface { } }"; await TestWithPullMemberDialogAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullMultipleNonPublicMethodsToInterfaceViaDialog() { var testText = @" using System; namespace PushUpTest { interface IInterface { } public class TestClass : IInterface { public void TestMethod() { System.Console.WriteLine(""Hello World""); } protected void F[||]oo(int i) { // do awesome things } private static string Bar(string x) {} } }"; var expected = @" using System; namespace PushUpTest { interface IInterface { string Bar(string x); void Foo(int i); void TestMethod(); } public class TestClass : IInterface { public void TestMethod() { System.Console.WriteLine(""Hello World""); } public void Foo(int i) { // do awesome things } public string Bar(string x) {} } }"; await TestWithPullMemberDialogAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullMultipleNonPublicEventsToInterface() { var testText = @" using System; namespace PushUpTest { interface IInterface { } public class TestClass : IInterface { private event EventHandler Event1, Eve[||]nt2, Event3; } }"; var expected = @" using System; namespace PushUpTest { interface IInterface { event EventHandler Event1; event EventHandler Event2; event EventHandler Event3; } public class TestClass : IInterface { public event EventHandler Event1; public event EventHandler Event2; public event EventHandler Event3; } }"; await TestWithPullMemberDialogAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullMethodToInnerInterfaceViaDialog() { var testText = @" using System; namespace PushUpTest { public class TestClass : TestClass.IInterface { private void Bar[||]Bar() { } interface IInterface { } } }"; var expected = @" using System; namespace PushUpTest { public class TestClass : TestClass.IInterface { public void BarBar() { } interface IInterface { void BarBar(); } } }"; await TestWithPullMemberDialogAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullDifferentMembersFromClassToPartialInterfaceViaDialog() { var testText = @" using System; namespace PushUpTest { partial interface IInterface { } public class TestClass : IInterface { public int th[||]is[int i] { get => j = value; } private static void BarBar() {} protected static event EventHandler event1, event2; internal static int Foo { get; set; } } partial interface IInterface { } }"; var expected = @" using System; namespace PushUpTest { partial interface IInterface { int this[int i] { get; } int Foo { get; set; } event EventHandler event1; event EventHandler event2; void BarBar(); } public class TestClass : IInterface { public int this[int i] { get => j = value; } public void BarBar() {} public event EventHandler event1; public event EventHandler event2; public int Foo { get; set; } } partial interface IInterface { } }"; await TestWithPullMemberDialogAsync(testText, expected, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullAsyncMethod() { var testText = @" using System.Threading.Tasks; internal interface IPullUp { } internal class PullUp : IPullUp { internal async Task PullU[||]pAsync() { await Task.Delay(1000); } }"; var expectedText = @" using System.Threading.Tasks; internal interface IPullUp { Task PullUpAsync(); } internal class PullUp : IPullUp { public async Task PullUpAsync() { await Task.Delay(1000); } }"; await TestWithPullMemberDialogAsync(testText, expectedText); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullMethodWithAbstractOptionToClassViaDialog() { var testText = @" namespace PushUpTest { public class Base { } public class TestClass : Base { public void TestMeth[||]od() { System.Console.WriteLine(""Hello World""); } } }"; var expected = @" namespace PushUpTest { public abstract class Base { public abstract void TestMethod(); } public class TestClass : Base { public override void TestMeth[||]od() { System.Console.WriteLine(""Hello World""); } } }"; await TestWithPullMemberDialogAsync(testText, expected, new (string, bool)[] { ("TestMethod", true) }, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullAbstractMethodToClassViaDialog() { var testText = @" namespace PushUpTest { public class Base { } public abstract class TestClass : Base { public abstract void TestMeth[||]od(); } }"; var expected = @" namespace PushUpTest { public abstract class Base { public abstract void TestMethod(); } public abstract class TestClass : Base { } }"; await TestWithPullMemberDialogAsync(testText, expected, new (string, bool)[] { ("TestMethod", true) }, index: 0); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullMultipleEventsToClassViaDialog() { var testText = @" using System; namespace PushUpTest { public class Base2 { } public class Testclass2 : Base2 { private static event EventHandler Event1, Eve[||]nt3, Event4; } }"; var expected = @" using System; namespace PushUpTest { public class Base2 { private static event EventHandler Event1; private static event EventHandler Event3; private static event EventHandler Event4; } public class Testclass2 : Base2 { } }"; await TestWithPullMemberDialogAsync(testText, expected, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullMultipleAbstractEventsToInterfaceViaDialog() { var testText = @" using System; namespace PushUpTest { public interface ITest { } public abstract class Testclass2 : ITest { protected abstract event EventHandler Event1, Eve[||]nt3, Event4; } }"; var expected = @" using System; namespace PushUpTest { public interface ITest { event EventHandler Event1; event EventHandler Event3; event EventHandler Event4; } public abstract class Testclass2 : ITest { public abstract event EventHandler Event1; public abstract event EventHandler Event3; public abstract event EventHandler Event4; } }"; await TestWithPullMemberDialogAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullAbstractEventToClassViaDialog() { var testText = @" using System; namespace PushUpTest { public class Base2 { } public abstract class Testclass2 : Base2 { private static abstract event EventHandler Event1, Eve[||]nt3, Event4; } }"; var expected = @" using System; namespace PushUpTest { public abstract class Base2 { private static abstract event EventHandler Event3; } public abstract class Testclass2 : Base2 { private static abstract event EventHandler Event1, Event4; } }"; await TestWithPullMemberDialogAsync(testText, expected, new (string, bool)[] { ("Event3", false) }); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullNonPublicEventToInterfaceViaDialog() { var testText = @" using System; namespace PushUpTest { public interface ITest { } public class Testclass2 : ITest { private event EventHandler Eve[||]nt3; } }"; var expected = @" using System; namespace PushUpTest { public interface ITest { event EventHandler Event3; } public class Testclass2 : ITest { public event EventHandler Event3; } }"; await TestWithPullMemberDialogAsync(testText, expected, new (string, bool)[] { ("Event3", false) }); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullSingleNonPublicEventToInterfaceViaDialog() { var testText = @" using System; namespace PushUpTest { public interface ITest { } public abstract class TestClass2 : ITest { protected event EventHandler Eve[||]nt3; } }"; var expected = @" using System; namespace PushUpTest { public interface ITest { event EventHandler Event3; } public abstract class TestClass2 : ITest { public event EventHandler Event3; } }"; await TestWithPullMemberDialogAsync(testText, expected, new (string, bool)[] { ("Event3", false) }); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullNonPublicEventWithAddAndRemoveMethodToInterfaceViaDialog() { var testText = @" using System; namespace PushUpTest { interface IInterface { } public class TestClass : IInterface { private event EventHandler Eve[||]nt1 { add { System.Console.Writeline(""This is add""); } remove { System.Console.Writeline(""This is remove""); } } } }"; var expected = @" using System; namespace PushUpTest { interface IInterface { event EventHandler Event1; } public class TestClass : IInterface { public event EventHandler Event1 { add { System.Console.Writeline(""This is add""); } remove { System.Console.Writeline(""This is remove""); } } } }"; await TestWithPullMemberDialogAsync(testText, expected, new (string, bool)[] { ("Event1", false) }); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullFieldsToClassViaDialog() { var testText = @" using System; namespace PushUpTest { public class Base2 { } public class Testclass2 : Base2 { public int i, [||]j = 10, k = 100; } }"; var expected = @" using System; namespace PushUpTest { public class Base2 { public int i; public int j = 10; public int k = 100; } public class Testclass2 : Base2 { } }"; await TestWithPullMemberDialogAsync(testText, expected, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullNonPublicPropertyWithArrowToInterfaceViaDialog() { var testText = @" using System; namespace PushUpTest { public interface ITest { } public class Testclass2 : ITest { private double Test[||]Property => 2.717; } }"; var expected = @" using System; namespace PushUpTest { public interface ITest { double TestProperty { get; } } public class Testclass2 : ITest { public readonly double TestProperty => 2.717; } }"; await TestWithPullMemberDialogAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullNonPublicPropertyToInterfaceViaDialog() { var testText = @" using System; namespace PushUpTest { public interface ITest { } public class Testclass2 : ITest { private double Test[||]Property { get; set; } } }"; var expected = @" using System; namespace PushUpTest { public interface ITest { double TestProperty { get; set; } } public class Testclass2 : ITest { public double TestProperty { get; set; } } }"; await TestWithPullMemberDialogAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullNonPublicPropertyWithSingleAccessorToInterfaceViaDialog() { var testText = @" using System; namespace PushUpTest { public interface ITest { } public class Testclass2 : ITest { private static double Test[||]Property { set; } } }"; var expected = @" using System; namespace PushUpTest { public interface ITest { double TestProperty { set; } } public class Testclass2 : ITest { public double Test[||]Property { set; } } }"; await TestWithPullMemberDialogAsync(testText, expected); } [WorkItem(34268, "https://github.com/dotnet/roslyn/issues/34268")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullPropertyToAbstractClassViaDialogWithMakeAbstractOption() { var testText = @" abstract class B { } class D : B { int [||]X => 7; }"; var expected = @" abstract class B { private abstract int X { get; } } class D : B { override int X => 7; }"; await TestWithPullMemberDialogAsync(testText, expected, selection: new[] { ("X", true) }, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullEventUpToAbstractClassViaDialogWithMakeAbstractOption() { var testText = @" using System; namespace PushUpTest { public class Base2 { } public class Testclass2 : Base2 { private event EventHandler Event1, Eve[||]nt3, Event4; } }"; var expected = @" using System; namespace PushUpTest { public abstract class Base2 { private abstract event EventHandler Event3; } public class Testclass2 : Base2 { private event EventHandler Event1, Eve[||]nt3, Event4; } }"; await TestWithPullMemberDialogAsync(testText, expected, selection: new[] { ("Event3", true) }, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullEventWithAddAndRemoveMethodToClassViaDialogWithMakeAbstractOption() { var testText = @" using System; namespace PushUpTest { public class BaseClass { } public class TestClass : BaseClass { public event EventHandler Eve[||]nt1 { add { System.Console.Writeline(""This is add""); } remove { System.Console.Writeline(""This is remove""); } } } }"; var expected = @" using System; namespace PushUpTest { public abstract class BaseClass { public abstract event EventHandler Event1; } public class TestClass : BaseClass { public override event EventHandler Event1 { add { System.Console.Writeline(""This is add""); } remove { System.Console.Writeline(""This is remove""); } } } }"; await TestWithPullMemberDialogAsync(testText, expected, new (string, bool)[] { ("Event1", true) }, index: 1); } #endregion Dialog #region Selections and caret position [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestArgsIsPartOfHeader() { var testText = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } class Test2Attribute : Attribute { } public class A { } public class B : A { [Test] [Test2] void C([||]) { } } }"; var expected = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } class Test2Attribute : Attribute { } public class A { [Test] [Test2] void C() { } } public class B : A { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestRefactoringCaretBeforeAttributes() { var testText = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } class Test2Attribute : Attribute { } public class A { } public class B : A { [||][Test] [Test2] void C() { } } }"; var expected = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } class Test2Attribute : Attribute { } public class A { [Test] [Test2] void C() { } } public class B : A { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestMissingRefactoringCaretBetweenAttributes() { var testText = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } class Test2Attribute : Attribute { } public class A { } public class B : A { [Test] [||][Test2] void C() { } } }"; await TestQuickActionNotProvidedAsync(testText); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestRefactoringSelectionWithAttributes1() { var testText = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } public class A { } public class B : A { [Test] [|void C() { }|] } }"; var expected = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } public class A { [Test] void C() { } } public class B : A { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestRefactoringSelectionWithAttributes2() { var testText = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } public class A { } public class B : A { [|[Test] void C() { }|] } }"; var expected = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } public class A { [Test] void C() { } } public class B : A { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestRefactoringSelectionWithAttributes3() { var testText = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } public class A { } public class B : A { [Test][| void C() { } |] } }"; var expected = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } public class A { [Test] void C() { } } public class B : A { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestMissingRefactoringInAttributeList() { var testText = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } public class A { } public class B : A { [[||]Test] void C() { } } }"; await TestQuickActionNotProvidedAsync(testText); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestMissingRefactoringSelectionAttributeList() { var testText = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } class Test2Attribute : Attribute { } public class A { } public class B : A { [|[Test] [Test2]|] void C() { } } }"; await TestQuickActionNotProvidedAsync(testText); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestMissingRefactoringCaretInAttributeList() { var testText = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } class Test2Attribute : Attribute { } public class A { } public class B : A { [[||]Test] [Test2] void C() { } } }"; await TestQuickActionNotProvidedAsync(testText); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestMissingRefactoringCaretBetweenAttributeLists() { var testText = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } class Test2Attribute : Attribute { } public class A { } public class B : A { [Test] [||][Test2] void C() { } } }"; await TestQuickActionNotProvidedAsync(testText); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestMissingRefactoringSelectionAttributeList2() { var testText = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } class Test2Attribute : Attribute { } public class A { } public class B : A { [|[Test]|] [Test2] void C() { } } }"; await TestQuickActionNotProvidedAsync(testText); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestMissingRefactoringSelectAttributeList() { var testText = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } public class A { } public class B : A { [|[Test]|] void C() { } } }"; await TestQuickActionNotProvidedAsync(testText); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestRefactoringCaretLocAfterAttributes1() { var testText = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } public class A { } public class B : A { [Test] [||]void C() { } } }"; var expected = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } public class A { [Test] void C() { } } public class B : A { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestRefactoringCaretLocAfterAttributes2() { var testText = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } class Test2Attribute : Attribute { } public class A { } public class B : A { [Test] // Comment1 [Test2] // Comment2 [||]void C() { } } }"; var expected = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } class Test2Attribute : Attribute { } public class A { [Test] // Comment1 [Test2] // Comment2 void C() { } } public class B : A { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestRefactoringCaretLoc1() { var testText = @" namespace PushUpTest { public class A { } public class B : A { [||]void C() { } } }"; var expected = @" namespace PushUpTest { public class A { void C() { } } public class B : A { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestRefactoringSelection() { var testText = @" namespace PushUpTest { public class A { } public class B : A { [|void C() { }|] } }"; var expected = @" namespace PushUpTest { public class A { void C() { } } public class B : A { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestRefactoringSelectionComments() { var testText = @" namespace PushUpTest { public class A { } public class B : A { [| // Comment1 void C() { }|] } }"; var expected = @" namespace PushUpTest { public class A { // Comment1 void C() { } } public class B : A { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestRefactoringSelectionComments2() { var testText = @" namespace PushUpTest { public class A { } public class B : A { [|/// <summary> /// Test /// </summary> void C() { }|] } }"; var expected = @" namespace PushUpTest { public class A { /// <summary> /// Test /// </summary> void C() { } } public class B : A { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestRefactoringSelectionComments3() { var testText = @" namespace PushUpTest { public class A { } public class B : A { /// <summary> [|/// Test /// </summary> void C() { }|] } }"; var expected = @" namespace PushUpTest { public class A { /// <summary> /// Test /// </summary> void C() { } } public class B : A { } }"; await TestInRegularAndScriptAsync(testText, expected); } #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.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CSharp.CodeRefactorings.PullMemberUp; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; using System.Collections.Immutable; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeRefactorings.PullMemberUp.Dialog; using System.Collections.Generic; using Microsoft.CodeAnalysis.Test.Utilities.PullMemberUp; using Roslyn.Test.Utilities; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.Editing; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.PullMemberUp { public class CSharpPullMemberUpTests : AbstractCSharpCodeActionTest { protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters) => new CSharpPullMemberUpCodeRefactoringProvider((IPullMemberUpOptionsService)parameters.fixProviderData); protected override ImmutableArray<CodeAction> MassageActions(ImmutableArray<CodeAction> actions) => FlattenActions(actions); #region Quick Action private async Task TestQuickActionNotProvidedAsync( string initialMarkup, TestParameters parameters = default) { using var workspace = CreateWorkspaceFromOptions(initialMarkup, parameters); var (actions, _) = await GetCodeActionsAsync(workspace, parameters); if (actions.Length == 1) { // The dialog shows up, not quick action Assert.Equal(actions.First().Title, FeaturesResources.Pull_members_up_to_base_type); } else if (actions.Length > 1) { Assert.True(false, "Pull Members Up is provided via quick action"); } else { Assert.True(true); } } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestNoRefactoringProvidedWhenPullFieldInInterfaceViaQuickAction() { var testText = @" namespace PushUpTest { public interface ITestInterface { } public class TestClass : ITestInterface { public int yo[||]u = 10086; } }"; await TestQuickActionNotProvidedAsync(testText); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestNoRefactoringProvidedWhenMethodDeclarationAlreadyExistsInInterfaceViaQuickAction() { var methodTest = @" namespace PushUpTest { public interface ITestInterface { void TestMethod(); } public class TestClass : ITestInterface { public void TestM[||]ethod() { System.Console.WriteLine(""Hello World""); } } }"; await TestQuickActionNotProvidedAsync(methodTest); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestNoRefactoringProvidedWhenPropertyDeclarationAlreadyExistsInInterfaceViaQuickAction() { var propertyTest1 = @" using System; namespace PushUpTest { interface IInterface { int TestProperty { get; } } public class TestClass : IInterface { public int TestPr[||]operty { get; private set; } } }"; await TestQuickActionNotProvidedAsync(propertyTest1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestNoRefactoringProvidedWhenEventDeclarationAlreadyExistsToInterfaceViaQuickAction() { var eventTest = @" using System; namespace PushUpTest { interface IInterface { event EventHandler Event2; } public class TestClass : IInterface { public event EventHandler Event1, Eve[||]nt2, Event3; } }"; await TestQuickActionNotProvidedAsync(eventTest); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestNoRefactoringProvidedInNestedTypesViaQuickAction() { var input = @" namespace PushUpTest { public interface ITestInterface { void Foobar(); } public class TestClass : ITestInterface { public class N[||]estedClass { } } }"; await TestQuickActionNotProvidedAsync(input); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullMethodUpToInterfaceViaQuickAction() { var testText = @" using System; namespace PushUpTest { interface IInterface { } public class TestClass : IInterface { public void TestM[||]ethod() { System.Console.WriteLine(""Hello World""); } } }"; var expected = @" using System; namespace PushUpTest { interface IInterface { void TestMethod(); } public class TestClass : IInterface { public void TestMethod() { System.Console.WriteLine(""Hello World""); } } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullAbstractMethodToInterfaceViaQuickAction() { var testText = @" namespace PushUpTest { public interface IInterface { } public abstract class TestClass : IInterface { public abstract void TestMeth[||]od(); } }"; var expected = @" namespace PushUpTest { public interface IInterface { void TestMethod(); } public abstract class TestClass : IInterface { public abstract void TestMethod(); } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullGenericsUpToInterfaceViaQuickAction() { var testText = @" using System; namespace PushUpTest { public interface IInterface { } public class TestClass : IInterface { public void TestMeth[||]od<T>() where T : IDisposable { } } }"; var expected = @" using System; namespace PushUpTest { public interface IInterface { void TestMethod<T>() where T : IDisposable; } public class TestClass : IInterface { public void TestMeth[||]od<T>() where T : IDisposable { } } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullSingleEventToInterfaceViaQuickAction() { var testText = @" using System; namespace PushUpTest { interface IInterface { } public class TestClass : IInterface { public event EventHandler Eve[||]nt1 { add { System.Console.Writeline(""This is add""); } remove { System.Console.Writeline(""This is remove""); } } } }"; var expected = @" using System; namespace PushUpTest { interface IInterface { event EventHandler Event1; } public class TestClass : IInterface { public event EventHandler Event1 { add { System.Console.Writeline(""This is add""); } remove { System.Console.Writeline(""This is remove""); } } } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullOneEventFromMultipleEventsToInterfaceViaQuickAction() { var testText = @" using System; namespace PushUpTest { interface IInterface { } public class TestClass : IInterface { public event EventHandler Event1, Eve[||]nt2, Event3; } }"; var expected = @" using System; namespace PushUpTest { interface IInterface { event EventHandler Event2; } public class TestClass : IInterface { public event EventHandler Event1, Event2, Event3; } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullPublicEventWithAccessorsToInterfaceViaQuickAction() { var testText = @" using System; namespace PushUpTest { interface IInterface { } public class TestClass : IInterface { public event EventHandler Eve[||]nt2 { add { System.Console.Writeln(""This is add in event1""); } remove { System.Console.Writeln(""This is remove in event2""); } } } }"; var expected = @" using System; namespace PushUpTest { interface IInterface { event EventHandler Event2; } public class TestClass : IInterface { public event EventHandler Event2 { add { System.Console.Writeln(""This is add in event1""); } remove { System.Console.Writeln(""This is remove in event2""); } } } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullPropertyWithPrivateSetterToInterfaceViaQuickAction() { var testText = @" using System; namespace PushUpTest { interface IInterface { } public class TestClass : IInterface { public int TestPr[||]operty { get; private set; } } }"; var expected = @" using System; namespace PushUpTest { interface IInterface { int TestProperty { get; } } public class TestClass : IInterface { public int TestProperty { get; private set; } } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullPropertyWithPrivateGetterToInterfaceViaQuickAction() { var testText = @" using System; namespace PushUpTest { interface IInterface { } public class TestClass : IInterface { public int TestProperty[||]{ private get; set; } } }"; var expected = @" using System; namespace PushUpTest { interface IInterface { int TestProperty { set; } } public class TestClass : IInterface { public int TestProperty{ private get; set; } } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullMemberFromInterfaceToInterfaceViaQuickAction() { var testText = @" using System; namespace PushUpTest { interface IInterface { } interface FooInterface : IInterface { int TestPr[||]operty { set; } } }"; var expected = @" using System; namespace PushUpTest { interface IInterface { int TestProperty { set; } } interface FooInterface : IInterface { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullIndexerWithOnlySetterToInterfaceViaQuickAction() { var testText = @" using System; namespace PushUpTest { interface IInterface { } public class TestClass : IInterface { private int j; public int th[||]is[int i] { set => j = value; } } }"; var expected = @" using System; namespace PushUpTest { interface IInterface { int this[int i] { set; } } public class TestClass : IInterface { private int j; public int this[int i] { set => j = value; } } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullIndexerWithOnlyGetterToInterfaceViaQuickAction() { var testText = @" using System; namespace PushUpTest { interface IInterface { } public class TestClass : IInterface { private int j; public int th[||]is[int i] { get => j = value; } } }"; var expected = @" using System; namespace PushUpTest { interface IInterface { int this[int i] { get; } } public class TestClass : IInterface { private int j; public int this[int i] { get => j = value; } } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullPropertyToInterfaceWithAddUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public interface IBase { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : IBase { public Uri En[||]dpoint { get; set; } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; public interface IBase { Uri Endpoint { get; set; } } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : IBase { public Uri Endpoint { get; set; } } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToInterfaceWithoutAddUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public interface IBase { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : IBase { public bool Test[||]Method() { var endpoint1 = new Uri(""http://localhost""); var endpoint2 = new Uri(""http://localhost""); return endpoint1.Equals(endpoint2); } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public interface IBase { bool TestMethod(); } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : IBase { public bool Test[||]Method() { var endpoint1 = new Uri(""http://localhost""); var endpoint2 = new Uri(""http://localhost""); return endpoint1.Equals(endpoint2); } } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodWithNewReturnTypeToInterfaceWithAddUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public interface IBase { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : IBase { public Uri Test[||]Method() { return new Uri(""http://localhost""); } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; public interface IBase { Uri TestMethod(); } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : IBase { public Uri TestMethod() { return new Uri(""http://localhost""); } } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodWithNewParamTypeToInterfaceWithAddUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public interface IBase { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : IBase { public bool Test[||]Method(Uri endpoint) { var localHost = new Uri(""http://localhost""); return endpoint.Equals(localhost); } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; public interface IBase { bool TestMethod(Uri endpoint); } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : IBase { public bool TestMethod(Uri endpoint) { var localHost = new Uri(""http://localhost""); return endpoint.Equals(localhost); } } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullEventToInterfaceWithAddUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public interface IBase { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : IBase { public event EventHandler Test[||]Event { add { Console.WriteLine(""adding event...""); } remove { Console.WriteLine(""removing event...""); } } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; public interface IBase { event EventHandler TestEvent; } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : IBase { public event EventHandler TestEvent { add { Console.WriteLine(""adding event...""); } remove { Console.WriteLine(""removing event...""); } } } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullPropertyToClassWithAddUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public class Base { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { public Uri En[||]dpoint { get; set; } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using System; public class Base { public Uri Endpoint { get; set; } } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullPropertyToClassWithAddUsingsViaQuickAction2() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">public class Base { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { public Uri En[||]dpoint { get; set; } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using System; public class Base { public Uri Endpoint { get; set; } } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullPropertyToClassWithoutDuplicatingUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; public class Base { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { public Uri En[||]dpoint { get; set; } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; public class Base { public Uri Endpoint { get; set; } } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullPropertyWithNewBodyTypeToClassWithAddUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public class Base { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { public bool Test[||]Property { get { var endpoint1 = new Uri(""http://localhost""); var endpoint2 = new Uri(""http://localhost""); return endpoint1.Equals(endpoint2); } } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using System; public class Base { public bool TestProperty { get { var endpoint1 = new Uri(""http://localhost""); var endpoint2 = new Uri(""http://localhost""); return endpoint1.Equals(endpoint2); } } } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodWithNewNonDeclaredBodyTypeToClassWithAddUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public class Base { } </Document> <Document FilePath = ""File2.cs""> using System.Linq; public class Derived : Base { public int Test[||]Method() { return Enumerable.Range(0, 5).Sum(); } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using System.Linq; public class Base { public int Test[||]Method() { return Enumerable.Range(0, 5).Sum(); } } </Document> <Document FilePath = ""File2.cs""> using System.Linq; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithOverlappingUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; using System.Threading.Tasks; public class Base { public Uri Endpoint{ get; set; } public async Task&lt;int&gt; Get5Async() { return 5; } } </Document> <Document FilePath = ""File2.cs""> using System.Linq; using System.Threading.Tasks; public class Derived : Base { public async Task&lt;int&gt; Test[||]Method() { return Enumerable.Range(0, 5).Sum(); } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; using System.Linq; using System.Threading.Tasks; public class Base { public Uri Endpoint{ get; set; } public async Task&lt;int&gt; Get5Async() { return 5; } public async Task&lt;int&gt; Test[||]Method() { return Enumerable.Range(0, 5).Sum(); } } </Document> <Document FilePath = ""File2.cs""> using System.Linq; using System.Threading.Tasks; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithUnnecessaryFirstUsingViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System.Threading.Tasks; public class Base { public async Task&lt;int&gt; Get5Async() { return 5; } } </Document> <Document FilePath = ""File2.cs""> using System; using System.Linq; using System.Threading.Tasks; public class Derived : Base { public async Task&lt;int&gt; Test[||]Method() { return Enumerable.Range(0, 5).Sum(); } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using System.Linq; using System.Threading.Tasks; public class Base { public async Task&lt;int&gt; Get5Async() { return 5; } public async Task&lt;int&gt; Test[||]Method() { return Enumerable.Range(0, 5).Sum(); } } </Document> <Document FilePath = ""File2.cs""> using System; using System.Linq; using System.Threading.Tasks; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithUnusedBaseUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; using System.Threading.Tasks; public class Base { public Uri Endpoint{ get; set; } } </Document> <Document FilePath = ""File2.cs""> using System.Linq; public class Derived : Base { public int Test[||]Method() { return Enumerable.Range(0, 5).Sum(); } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; using System.Linq; using System.Threading.Tasks; public class Base { public Uri Endpoint{ get; set; } public int TestMethod() { return Enumerable.Range(0, 5).Sum(); } } </Document> <Document FilePath = ""File2.cs""> using System.Linq; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithRetainCommentsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> // blah blah public class Base { } </Document> <Document FilePath = ""File2.cs""> using System.Linq; public class Derived : Base { public int Test[||]Method() { return 5; } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> // blah blah public class Base { public int TestMethod() { return 5; } } </Document> <Document FilePath = ""File2.cs""> using System.Linq; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithRetainPreImportCommentsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> // blah blah using System.Linq; public class Base { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { public Uri End[||]point { get; set; } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> // blah blah using System; using System.Linq; public class Base { public Uri Endpoint { get; set; } } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithRetainPostImportCommentsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System.Linq; // blah blah public class Base { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { public Uri End[||]point { get; set; } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; using System.Linq; // blah blah public class Base { public Uri Endpoint { get; set; } } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithLambdaUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public class Base { } </Document> <Document FilePath = ""File2.cs""> using System; using System.Linq; public class Derived : Base { public int Test[||]Method() { return Enumerable.Range(0, 5). Select((n) => new Uri(""http://"" + n)). Count((uri) => uri != null); } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using System; using System.Linq; public class Base { public int TestMethod() { return Enumerable.Range(0, 5). Select((n) => new Uri(""http://"" + n)). Count((uri) => uri != null); } } </Document> <Document FilePath = ""File2.cs""> using System; using System.Linq; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithUnusedUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; public class Base { public Uri Endpoint{ get; set; } } </Document> <Document FilePath = ""File2.cs""> using System.Linq; using System.Threading.Tasks; public class Derived : Base { public int Test[||]Method() { return Enumerable.Range(0, 5).Sum(); } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; using System.Linq; public class Base { public Uri Endpoint{ get; set; } public int TestMethod() { return Enumerable.Range(0, 5).Sum(); } } </Document> <Document FilePath = ""File2.cs""> using System.Linq; using System.Threading.Tasks; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassKeepSystemFirstViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace TestNs1 { using System; public class Base { public Uri Endpoint{ get; set; } } } </Document> <Document FilePath = ""File2.cs""> namespace A_TestNs2 { using TestNs1; public class Derived : Base { public Foo Test[||]Method() { return null; } } public class Foo { } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace TestNs1 { using System; using A_TestNs2; public class Base { public Uri Endpoint{ get; set; } public Foo TestMethod() { return null; } } } </Document> <Document FilePath = ""File2.cs""> namespace A_TestNs2 { using TestNs1; public class Derived : Base { } public class Foo { } } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassKeepSystemFirstViaQuickAction2() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace TestNs1 { public class Base { } } </Document> <Document FilePath = ""File2.cs""> namespace A_TestNs2 { using System; using TestNs1; public class Derived : Base { public Foo Test[||]Method() { var uri = new Uri(""http://localhost""); return null; } } public class Foo { } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using System; using A_TestNs2; namespace TestNs1 { public class Base { public Foo TestMethod() { var uri = new Uri(""http://localhost""); return null; } } } </Document> <Document FilePath = ""File2.cs""> namespace A_TestNs2 { using System; using TestNs1; public class Derived : Base { } public class Foo { } } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithExtensionViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace TestNs1 { public class Base { } public class Foo { } } </Document> <Document FilePath = ""File2.cs""> namespace TestNs2 { using TestNs1; public class Derived : Base { public int Test[||]Method() { var foo = new Foo(); return foo.FooBar(); } } public static class FooExtensions { public static int FooBar(this Foo foo) { return 5; } } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using TestNs2; namespace TestNs1 { public class Base { public int TestMethod() { var foo = new Foo(); return foo.FooBar(); } } public class Foo { } } </Document> <Document FilePath = ""File2.cs""> namespace TestNs2 { using TestNs1; public class Derived : Base { } public static class FooExtensions { public static int FooBar(this Foo foo) { return 5; } } } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithExtensionViaQuickAction2() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace TestNs1 { public class Base { } } </Document> <Document FilePath = ""File2.cs""> using TestNs1; using TestNs3; using TestNs4; namespace TestNs2 { public class Derived : Base { public int Test[||]Method() { var foo = new Foo(); return foo.FooBar(); } } } </Document> <Document FilePath = ""File3.cs""> namespace TestNs3 { public class Foo { } } </Document> <Document FilePath = ""File4.cs""> using TestNs3; namespace TestNs4 { public static class FooExtensions { public static int FooBar(this Foo foo) { return 5; } } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using TestNs3; using TestNs4; namespace TestNs1 { public class Base { public int TestMethod() { var foo = new Foo(); return foo.FooBar(); } } } </Document> <Document FilePath = ""File2.cs""> using TestNs1; using TestNs3; using TestNs4; namespace TestNs2 { public class Derived : Base { } } </Document> <Document FilePath = ""File3.cs""> namespace TestNs3 { public class Foo { } } </Document> <Document FilePath = ""File4.cs""> using TestNs3; namespace TestNs4 { public static class FooExtensions { public static int FooBar(this Foo foo) { return 5; } } } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithAliasUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; public class Base { public Uri Endpoint{ get; set; } } </Document> <Document FilePath = ""File2.cs""> using Enumer = System.Linq.Enumerable; using Sys = System; public class Derived : Base { public void Test[||]Method() { Sys.Console.WriteLine(Enumer.Range(0, 5).Sum()); } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; using Enumer = System.Linq.Enumerable; using Sys = System; public class Base { public Uri Endpoint{ get; set; } public void TestMethod() { Sys.Console.WriteLine(Enumer.Range(0, 5).Sum()); } } </Document> <Document FilePath = ""File2.cs""> using Enumer = System.Linq.Enumerable; using Sys = System; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullPropertyToClassWithBaseAliasUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using Enumer = System.Linq.Enumerable; public class Base { public void TestMethod() { System.Console.WriteLine(Enumer.Range(0, 5).Sum()); } } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { public Uri End[||]point{ get; set; } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; using Enumer = System.Linq.Enumerable; public class Base { public Uri Endpoint{ get; set; } public void TestMethod() { System.Console.WriteLine(Enumer.Range(0, 5).Sum()); } } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithMultipleNamespacedUsingsViaQuickAction() { var testText = @" namespace TestNs1 { using System; public class Base { public Uri Endpoint{ get; set; } } } namespace TestNs2 { using System.Linq; using TestNs1; public class Derived : Base { public int Test[||]Method() { return Enumerable.Range(0, 5).Sum(); } } } "; var expected = @" namespace TestNs1 { using System; using System.Linq; public class Base { public Uri Endpoint{ get; set; } public int TestMethod() { return Enumerable.Range(0, 5).Sum(); } } } namespace TestNs2 { using System.Linq; using TestNs1; public class Derived : Base { } } "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithNestedNamespacedUsingsViaQuickAction() { var testText = @" namespace TestNs1 { namespace InnerNs1 { using System; public class Base { public Uri Endpoint { get; set; } } } } namespace TestNs2 { namespace InnerNs2 { using System.Linq; using TestNs1.InnerNs1; public class Derived : Base { public int Test[||]Method() { return Foo.Bar(Enumerable.Range(0, 5).Sum()); } } public class Foo { public static int Bar(int num) { return num + 1; } } } } "; var expected = @" namespace TestNs1 { namespace InnerNs1 { using System; using System.Linq; using TestNs2.InnerNs2; public class Base { public Uri Endpoint { get; set; } public int TestMethod() { return Foo.Bar(Enumerable.Range(0, 5).Sum()); } } } } namespace TestNs2 { namespace InnerNs2 { using System.Linq; using TestNs1.InnerNs1; public class Derived : Base { } public class Foo { public static int Bar(int num) { return num + 1; } } } } "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithNewNamespaceUsingViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace A.B { class Base { } } </Document> <Document FilePath = ""File2.cs""> namespace X.Y { class Derived : A.B.Base { public Other Get[||]Other() => null; } class Other { } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using X.Y; namespace A.B { class Base { public Other GetOther() => null; } } </Document> <Document FilePath = ""File2.cs""> namespace X.Y { class Derived : A.B.Base { } class Other { } } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithFileNamespaceUsingViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace A.B; class Base { } </Document> <Document FilePath = ""File2.cs""> namespace X.Y; class Derived : A.B.Base { public Other Get[||]Other() => null; } class Other { } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using X.Y; namespace A.B; class Base { public Other GetOther() => null; } </Document> <Document FilePath = ""File2.cs""> namespace X.Y; class Derived : A.B.Base { } class Other { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithUnusedNamespaceUsingViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace A.B { class Base { } } </Document> <Document FilePath = ""File2.cs""> namespace X.Y { class Derived : A.B.Base { public int Get[||]Five() => 5; } class Other { } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace A.B { class Base { public int GetFive() => 5; } } </Document> <Document FilePath = ""File2.cs""> namespace X.Y { class Derived : A.B.Base { } class Other { } } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithMultipleNamespacesAndCommentsViaQuickAction() { var testText = @" // comment 1 namespace TestNs1 { // comment 2 // comment 3 public class Base { } } namespace TestNs2 { // comment 4 using System.Linq; using TestNs1; public class Derived : Base { public int Test[||]Method() { return 5; } } } "; var expected = @" // comment 1 namespace TestNs1 { // comment 2 // comment 3 public class Base { public int TestMethod() { return 5; } } } namespace TestNs2 { // comment 4 using System.Linq; using TestNs1; public class Derived : Base { } } "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithMultipleNamespacedUsingsAndCommentsViaQuickAction() { var testText = @" // comment 1 namespace TestNs1 { // comment 2 using System; // comment 3 public class Base { } } namespace TestNs2 { // comment 4 using System.Linq; using TestNs1; public class Derived : Base { public int Test[||]Method() { return Enumerable.Range(0, 5).Sum(); } } } "; var expected = @" // comment 1 namespace TestNs1 { // comment 2 using System; using System.Linq; // comment 3 public class Base { public int TestMethod() { return Enumerable.Range(0, 5).Sum(); } } } namespace TestNs2 { // comment 4 using System.Linq; using TestNs1; public class Derived : Base { } } "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithNamespacedUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace ClassLibrary1 { using System; public class Base { public Uri Endpoint{ get; set; } } } </Document> <Document FilePath = ""File2.cs""> namespace ClassLibrary1 { using System.Linq; public class Derived : Base { public int Test[||]Method() { return Enumerable.Range(0, 5).Sum(); } } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace ClassLibrary1 { using System; using System.Linq; public class Base { public Uri Endpoint{ get; set; } public int Test[||]Method() { return Enumerable.Range(0, 5).Sum(); } } } </Document> <Document FilePath = ""File2.cs""> namespace ClassLibrary1 { using System.Linq; public class Derived : Base { } } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithDuplicateNamespacedUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace ClassLibrary1 { using System; public class Base { public Uri Endpoint{ get; set; } } } </Document> <Document FilePath = ""File2.cs""> using System.Linq; namespace ClassLibrary1 { using System.Linq; public class Derived : Base { public int Test[||]Method() { return Enumerable.Range(0, 5).Sum(); } } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace ClassLibrary1 { using System; using System.Linq; public class Base { public Uri Endpoint{ get; set; } public int Test[||]Method() { return Enumerable.Range(0, 5).Sum(); } } } </Document> <Document FilePath = ""File2.cs""> using System.Linq; namespace ClassLibrary1 { using System.Linq; public class Derived : Base { } } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodWithNewReturnTypeToClassWithAddUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public class Base { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { public Uri En[||]dpoint() { return new Uri(""http://localhost""); } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using System; public class Base { public Uri Endpoint() { return new Uri(""http://localhost""); } } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodWithNewParamTypeToClassWithAddUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public class Base { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { public bool Test[||]Method(Uri endpoint) { var localHost = new Uri(""http://localhost""); return endpoint.Equals(localhost); } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using System; public class Base { public bool TestMethod(Uri endpoint) { var localHost = new Uri(""http://localhost""); return endpoint.Equals(localhost); } } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodWithNewBodyTypeToClassWithAddUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public class Base { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { public bool Test[||]Method() { var endpoint1 = new Uri(""http://localhost""); var endpoint2 = new Uri(""http://localhost""); return endpoint1.Equals(endpoint2); } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using System; public class Base { public bool TestMethod() { var endpoint1 = new Uri(""http://localhost""); var endpoint2 = new Uri(""http://localhost""); return endpoint1.Equals(endpoint2); } } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullEventToClassWithAddUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public class Base { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { public event EventHandler Test[||]Event { add { Console.WriteLine(""adding event...""); } remove { Console.WriteLine(""removing event...""); } } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using System; public class Base { public event EventHandler Test[||]Event { add { Console.WriteLine(""adding event...""); } remove { Console.WriteLine(""removing event...""); } } } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullFieldToClassWithAddUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public class Base { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { public var en[||]dpoint = new Uri(""http://localhost""); } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using System; public class Base { public var endpoint = new Uri(""http://localhost""); } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullFieldToClassNoConstructorWithAddUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public class Base { } </Document> <Document FilePath = ""File2.cs""> using System.Linq; public class Derived : Base { public var ran[||]ge = Enumerable.Range(0, 5); } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using System.Linq; public class Base { public var range = Enumerable.Range(0, 5); } </Document> <Document FilePath = ""File2.cs""> using System.Linq; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestNoRefactoringProvidedWhenPullOverrideMethodUpToClassViaQuickAction() { var methodTest = @" namespace PushUpTest { public class Base { public virtual void TestMethod() => System.Console.WriteLine(""foo bar bar foo""); } public class TestClass : Base { public override void TestMeth[||]od() { System.Console.WriteLine(""Hello World""); } } }"; await TestQuickActionNotProvidedAsync(methodTest); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestNoRefactoringProvidedWhenPullOverridePropertyUpToClassViaQuickAction() { var propertyTest = @" using System; namespace PushUpTest { public class Base { public virtual int TestProperty { get => 111; private set; } } public class TestClass : Base { public override int TestPr[||]operty { get; private set; } } }"; await TestQuickActionNotProvidedAsync(propertyTest); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestNoRefactoringProvidedWhenPullOverrideEventUpToClassViaQuickAction() { var eventTest = @" using System; namespace PushUpTest { public class Base2 { protected virtual event EventHandler Event3 { add { System.Console.WriteLine(""Hello""); } remove { System.Console.WriteLine(""World""); } }; } public class TestClass2 : Base2 { protected override event EventHandler E[||]vent3 { add { System.Console.WriteLine(""foo""); } remove { System.Console.WriteLine(""bar""); } }; } }"; await TestQuickActionNotProvidedAsync(eventTest); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestNoRefactoringProvidedWhenPullSameNameFieldUpToClassViaQuickAction() { // Fields share the same name will be thought as 'override', since it will cause error // if two same name fields exist in one class var fieldTest = @" namespace PushUpTest { public class Base { public int you = -100000; } public class TestClass : Base { public int y[||]ou = 10086; } }"; await TestQuickActionNotProvidedAsync(fieldTest); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullMethodToOrdinaryClassViaQuickAction() { var testText = @" namespace PushUpTest { public class Base { } public class TestClass : Base { public void TestMeth[||]od() { System.Console.WriteLine(""Hello World""); } } }"; var expected = @" namespace PushUpTest { public class Base { public void TestMethod() { System.Console.WriteLine(""Hello World""); } } public class TestClass : Base { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullOneFieldsToClassViaQuickAction() { var testText = @" namespace PushUpTest { public class Base { } public class TestClass : Base { public int you[||]= 10086; } }"; var expected = @" namespace PushUpTest { public class Base { public int you = 10086; } public class TestClass : Base { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullGenericsUpToClassViaQuickAction() { var testText = @" using System; namespace PushUpTest { public class BaseClass { } public class TestClass : BaseClass { public void TestMeth[||]od<T>() where T : IDisposable { } } }"; var expected = @" using System; namespace PushUpTest { public class BaseClass { public void TestMethod<T>() where T : IDisposable { } } public class TestClass : BaseClass { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullOneFieldFromMultipleFieldsToClassViaQuickAction() { var testText = @" namespace PushUpTest { public class Base { } public class TestClass : Base { public int you, a[||]nd, someone = 10086; } }"; var expected = @" namespace PushUpTest { public class Base { public int and; } public class TestClass : Base { public int you, someone = 10086; } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullMiddleFieldWithValueToClassViaQuickAction() { var testText = @" namespace PushUpTest { public class Base { } public class TestClass : Base { public int you, a[||]nd = 4000, someone = 10086; } }"; var expected = @" namespace PushUpTest { public class Base { public int and = 4000; } public class TestClass : Base { public int you, someone = 10086; } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullOneEventFromMultipleToClassViaQuickAction() { var testText = @" using System; namespace PushUpTest { public class Base2 { } public class Testclass2 : Base2 { private static event EventHandler Event1, Eve[||]nt3, Event4; } }"; var expected = @" using System; namespace PushUpTest { public class Base2 { private static event EventHandler Event3; } public class Testclass2 : Base2 { private static event EventHandler Event1, Event4; } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullEventToClassViaQuickAction() { var testText = @" using System; namespace PushUpTest { public class Base2 { } public class TestClass2 : Base2 { private static event EventHandler Eve[||]nt3; } }"; var expected = @" using System; namespace PushUpTest { public class Base2 { private static event EventHandler Event3; } public class TestClass2 : Base2 { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullEventWithBodyToClassViaQuickAction() { var testText = @" using System; namespace PushUpTest { public class Base2 { } public class TestClass2 : Base2 { private static event EventHandler Eve[||]nt3 { add { System.Console.Writeln(""Hello""); } remove { System.Console.Writeln(""World""); } }; } }"; var expected = @" using System; namespace PushUpTest { public class Base2 { private static event EventHandler Event3 { add { System.Console.Writeln(""Hello""); } remove { System.Console.Writeln(""World""); } }; } public class TestClass2 : Base2 { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullPropertyToClassViaQuickAction() { var testText = @" using System; namespace PushUpTest { public class Base { } public class TestClass : Base { public int TestPr[||]operty { get; private set; } } }"; var expected = @" using System; namespace PushUpTest { public class Base { public int TestProperty { get; private set; } } public class TestClass : Base { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullIndexerToClassViaQuickAction() { var testText = @" namespace PushUpTest { public class Base { } public class TestClass : Base { private int j; public int th[||]is[int i] { get => j; set => j = value; } } }"; var expected = @" namespace PushUpTest { public class Base { public int this[int i] { get => j; set => j = value; } } public class TestClass : Base { private int j; } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullMethodUpAcrossProjectViaQuickAction() { var testText = @" <Workspace> <Project Language=""C#"" AssemblyName=""CSAssembly1"" CommonReferences=""true""> <ProjectReference>CSAssembly2</ProjectReference> <Document> using Destination; public class TestClass : IInterface { public int Bar[||]Bar() { return 12345; } } </Document> </Project> <Project Language=""C#"" AssemblyName=""CSAssembly2"" CommonReferences=""true""> <Document> namespace Destination { public interface IInterface { } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""CSAssembly1"" CommonReferences=""true""> <ProjectReference>CSAssembly2</ProjectReference> <Document> using Destination; public class TestClass : IInterface { public int Bar[||]Bar() { return 12345; } } </Document> </Project> <Project Language=""C#"" AssemblyName=""CSAssembly2"" CommonReferences=""true""> <Document> namespace Destination { public interface IInterface { int BarBar(); } } </Document> </Project> </Workspace>"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullPropertyUpAcrossProjectViaQuickAction() { var testText = @" <Workspace> <Project Language=""C#"" AssemblyName=""CSAssembly1"" CommonReferences=""true""> <ProjectReference>CSAssembly2</ProjectReference> <Document> using Destination; public class TestClass : IInterface { public int F[||]oo { get; set; } } </Document> </Project> <Project Language=""C#"" AssemblyName=""CSAssembly2"" CommonReferences=""true""> <Document> namespace Destination { public interface IInterface { } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""CSAssembly1"" CommonReferences=""true""> <ProjectReference>CSAssembly2</ProjectReference> <Document> using Destination; public class TestClass : IInterface { public int Foo { get; set; } } </Document> </Project> <Project Language=""C#"" AssemblyName=""CSAssembly2"" CommonReferences=""true""> <Document> namespace Destination { public interface IInterface { int Foo { get; set; } } } </Document> </Project> </Workspace>"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullFieldUpAcrossProjectViaQuickAction() { var testText = @" <Workspace> <Project Language=""C#"" AssemblyName=""CSAssembly1"" CommonReferences=""true""> <ProjectReference>CSAssembly2</ProjectReference> <Document> using Destination; public class TestClass : BaseClass { private int i, j, [||]k = 10; } </Document> </Project> <Project Language=""C#"" AssemblyName=""CSAssembly2"" CommonReferences=""true""> <Document> namespace Destination { public class BaseClass { } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""CSAssembly1"" CommonReferences=""true""> <ProjectReference>CSAssembly2</ProjectReference> <Document> using Destination; public class TestClass : BaseClass { private int i, j; } </Document> </Project> <Project Language=""C#"" AssemblyName=""CSAssembly2"" CommonReferences=""true""> <Document> namespace Destination { public class BaseClass { private int k = 10; } } </Document> </Project> </Workspace>"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullMethodUpToVBClassViaQuickAction() { // Moving member from C# to Visual Basic is not supported currently since the FindMostRelevantDeclarationAsync method in // AbstractCodeGenerationService will return null. var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""CSAssembly"" CommonReferences=""true""> <ProjectReference>VBAssembly</ProjectReference> <Document> using VBAssembly; public class TestClass : VBClass { public int Bar[||]bar() { return 12345; } } </Document> </Project> <Project Language=""Visual Basic"" AssemblyName=""VBAssembly"" CommonReferences=""true""> <Document> Public Class VBClass End Class </Document> </Project> </Workspace>"; await TestQuickActionNotProvidedAsync(input); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullMethodUpToVBInterfaceViaQuickAction() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""CSAssembly"" CommonReferences=""true""> <ProjectReference>VBAssembly</ProjectReference> <Document> public class TestClass : VBInterface { public int Bar[||]bar() { return 12345; } } </Document> </Project> <Project Language=""Visual Basic"" AssemblyName=""VBAssembly"" CommonReferences=""true""> <Document> Public Interface VBInterface End Interface </Document> </Project> </Workspace> "; await TestQuickActionNotProvidedAsync(input); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullFieldUpToVBClassViaQuickAction() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""CSAssembly"" CommonReferences=""true""> <ProjectReference>VBAssembly</ProjectReference> <Document> using VBAssembly; public class TestClass : VBClass { public int fo[||]obar = 0; } </Document> </Project> <Project Language=""Visual Basic"" AssemblyName=""VBAssembly"" CommonReferences=""true""> <Document> Public Class VBClass End Class </Document> </Project> </Workspace>"; await TestQuickActionNotProvidedAsync(input); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullPropertyUpToVBClassViaQuickAction() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""CSAssembly"" CommonReferences=""true""> <ProjectReference>VBAssembly</ProjectReference> <Document> using VBAssembly; public class TestClass : VBClass { public int foo[||]bar { get; set; } }</Document> </Project> <Project Language=""Visual Basic"" AssemblyName=""VBAssembly"" CommonReferences=""true""> <Document> Public Class VBClass End Class </Document> </Project> </Workspace> "; await TestQuickActionNotProvidedAsync(input); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullPropertyUpToVBInterfaceViaQuickAction() { var input = @"<Workspace> <Project Language=""C#"" AssemblyName=""CSAssembly"" CommonReferences=""true""> <ProjectReference>VBAssembly</ProjectReference> <Document> using VBAssembly; public class TestClass : VBInterface { public int foo[||]bar { get; set; } } </Document> </Project> <Project Language = ""Visual Basic"" AssemblyName=""VBAssembly"" CommonReferences=""true""> <Document> Public Interface VBInterface End Interface </Document> </Project> </Workspace>"; await TestQuickActionNotProvidedAsync(input); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullEventUpToVBClassViaQuickAction() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""CSAssembly"" CommonReferences=""true""> <ProjectReference>VBAssembly</ProjectReference> <Document> using VBAssembly; public class TestClass : VBClass { public event EventHandler BarEve[||]nt; } </Document> </Project> <Project Language=""Visual Basic"" AssemblyName=""VBAssembly"" CommonReferences=""true""> <Document> Public Class VBClass End Class </Document> </Project> </Workspace>"; await TestQuickActionNotProvidedAsync(input); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullEventUpToVBInterfaceViaQuickAction() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""CSAssembly"" CommonReferences=""true""> <ProjectReference>VBAssembly</ProjectReference> <Document> using VBAssembly; public class TestClass : VBInterface { public event EventHandler BarEve[||]nt; } </Document> </Project> <Project Language=""Visual Basic"" AssemblyName=""VBAssembly"" CommonReferences=""true""> <Document> Public Interface VBInterface End Interface </Document> </Project> </Workspace>"; await TestQuickActionNotProvidedAsync(input); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(55746, "https://github.com/dotnet/roslyn/issues/55746")] public async Task TestPullMethodWithToClassWithAddUsingsInsideNamespaceViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace N { public class Base { } } </Document> <Document FilePath = ""File2.cs""> using System; namespace N { public class Derived : Base { public Uri En[||]dpoint() { return new Uri(""http://localhost""); } } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace N { using System; public class Base { public Uri Endpoint() { return new Uri(""http://localhost""); } } } </Document> <Document FilePath = ""File2.cs""> using System; namespace N { public class Derived : Base { } } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync( testText, expected, options: Option(CSharpCodeStyleOptions.PreferredUsingDirectivePlacement, CodeAnalysis.AddImports.AddImportPlacement.InsideNamespace, CodeStyle.NotificationOption2.Silent)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(55746, "https://github.com/dotnet/roslyn/issues/55746")] public async Task TestPullMethodWithToClassWithAddUsingsSystemUsingsLastViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace N1 { public class Base { } } </Document> <Document FilePath = ""File2.cs""> using System; using N2; namespace N1 { public class Derived : Base { public Goo Ge[||]tGoo() { return new Goo(String.Empty); } } } namespace N2 { public class Goo { public Goo(String s) { } } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using N2; using System; namespace N1 { public class Base { public Goo GetGoo() { return new Goo(String.Empty); } } } </Document> <Document FilePath = ""File2.cs""> using System; using N2; namespace N1 { public class Derived : Base { } } namespace N2 { public class Goo { public Goo(String s) { } } } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync( testText, expected, options: new(GetLanguage()) { { GenerationOptions.PlaceSystemNamespaceFirst, false }, }); } #endregion Quick Action #region Dialog internal Task TestWithPullMemberDialogAsync( string initialMarkUp, string expectedResult, IEnumerable<(string name, bool makeAbstract)> selection = null, string destinationName = null, int index = 0, TestParameters parameters = default) { var service = new TestPullMemberUpService(selection, destinationName); return TestInRegularAndScript1Async( initialMarkUp, expectedResult, index, parameters.WithFixProviderData(service)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullPartialMethodUpToInterfaceViaDialog() { var testText = @" using System; namespace PushUpTest { partial interface IInterface { } public partial class TestClass : IInterface { partial void Bar[||]Bar() } public partial class TestClass { partial void BarBar() {} } partial interface IInterface { } }"; var expected = @" using System; namespace PushUpTest { partial interface IInterface { void BarBar(); } public partial class TestClass : IInterface { void BarBar() } public partial class TestClass { partial void BarBar() {} } partial interface IInterface { } }"; await TestWithPullMemberDialogAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullExtendedPartialMethodUpToInterfaceViaDialog() { var testText = @" using System; namespace PushUpTest { partial interface IInterface { } public partial class TestClass : IInterface { public partial void Bar[||]Bar() } public partial class TestClass { public partial void BarBar() {} } partial interface IInterface { } }"; var expected = @" using System; namespace PushUpTest { partial interface IInterface { void BarBar(); } public partial class TestClass : IInterface { public partial void BarBar() } public partial class TestClass { public partial void BarBar() {} } partial interface IInterface { } }"; await TestWithPullMemberDialogAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullMultipleNonPublicMethodsToInterfaceViaDialog() { var testText = @" using System; namespace PushUpTest { interface IInterface { } public class TestClass : IInterface { public void TestMethod() { System.Console.WriteLine(""Hello World""); } protected void F[||]oo(int i) { // do awesome things } private static string Bar(string x) {} } }"; var expected = @" using System; namespace PushUpTest { interface IInterface { string Bar(string x); void Foo(int i); void TestMethod(); } public class TestClass : IInterface { public void TestMethod() { System.Console.WriteLine(""Hello World""); } public void Foo(int i) { // do awesome things } public string Bar(string x) {} } }"; await TestWithPullMemberDialogAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullMultipleNonPublicEventsToInterface() { var testText = @" using System; namespace PushUpTest { interface IInterface { } public class TestClass : IInterface { private event EventHandler Event1, Eve[||]nt2, Event3; } }"; var expected = @" using System; namespace PushUpTest { interface IInterface { event EventHandler Event1; event EventHandler Event2; event EventHandler Event3; } public class TestClass : IInterface { public event EventHandler Event1; public event EventHandler Event2; public event EventHandler Event3; } }"; await TestWithPullMemberDialogAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullMethodToInnerInterfaceViaDialog() { var testText = @" using System; namespace PushUpTest { public class TestClass : TestClass.IInterface { private void Bar[||]Bar() { } interface IInterface { } } }"; var expected = @" using System; namespace PushUpTest { public class TestClass : TestClass.IInterface { public void BarBar() { } interface IInterface { void BarBar(); } } }"; await TestWithPullMemberDialogAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullDifferentMembersFromClassToPartialInterfaceViaDialog() { var testText = @" using System; namespace PushUpTest { partial interface IInterface { } public class TestClass : IInterface { public int th[||]is[int i] { get => j = value; } private static void BarBar() {} protected static event EventHandler event1, event2; internal static int Foo { get; set; } } partial interface IInterface { } }"; var expected = @" using System; namespace PushUpTest { partial interface IInterface { int this[int i] { get; } int Foo { get; set; } event EventHandler event1; event EventHandler event2; void BarBar(); } public class TestClass : IInterface { public int this[int i] { get => j = value; } public void BarBar() {} public event EventHandler event1; public event EventHandler event2; public int Foo { get; set; } } partial interface IInterface { } }"; await TestWithPullMemberDialogAsync(testText, expected, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullAsyncMethod() { var testText = @" using System.Threading.Tasks; internal interface IPullUp { } internal class PullUp : IPullUp { internal async Task PullU[||]pAsync() { await Task.Delay(1000); } }"; var expectedText = @" using System.Threading.Tasks; internal interface IPullUp { Task PullUpAsync(); } internal class PullUp : IPullUp { public async Task PullUpAsync() { await Task.Delay(1000); } }"; await TestWithPullMemberDialogAsync(testText, expectedText); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullMethodWithAbstractOptionToClassViaDialog() { var testText = @" namespace PushUpTest { public class Base { } public class TestClass : Base { public void TestMeth[||]od() { System.Console.WriteLine(""Hello World""); } } }"; var expected = @" namespace PushUpTest { public abstract class Base { public abstract void TestMethod(); } public class TestClass : Base { public override void TestMeth[||]od() { System.Console.WriteLine(""Hello World""); } } }"; await TestWithPullMemberDialogAsync(testText, expected, new (string, bool)[] { ("TestMethod", true) }, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullAbstractMethodToClassViaDialog() { var testText = @" namespace PushUpTest { public class Base { } public abstract class TestClass : Base { public abstract void TestMeth[||]od(); } }"; var expected = @" namespace PushUpTest { public abstract class Base { public abstract void TestMethod(); } public abstract class TestClass : Base { } }"; await TestWithPullMemberDialogAsync(testText, expected, new (string, bool)[] { ("TestMethod", true) }, index: 0); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullMultipleEventsToClassViaDialog() { var testText = @" using System; namespace PushUpTest { public class Base2 { } public class Testclass2 : Base2 { private static event EventHandler Event1, Eve[||]nt3, Event4; } }"; var expected = @" using System; namespace PushUpTest { public class Base2 { private static event EventHandler Event1; private static event EventHandler Event3; private static event EventHandler Event4; } public class Testclass2 : Base2 { } }"; await TestWithPullMemberDialogAsync(testText, expected, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullMultipleAbstractEventsToInterfaceViaDialog() { var testText = @" using System; namespace PushUpTest { public interface ITest { } public abstract class Testclass2 : ITest { protected abstract event EventHandler Event1, Eve[||]nt3, Event4; } }"; var expected = @" using System; namespace PushUpTest { public interface ITest { event EventHandler Event1; event EventHandler Event3; event EventHandler Event4; } public abstract class Testclass2 : ITest { public abstract event EventHandler Event1; public abstract event EventHandler Event3; public abstract event EventHandler Event4; } }"; await TestWithPullMemberDialogAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullAbstractEventToClassViaDialog() { var testText = @" using System; namespace PushUpTest { public class Base2 { } public abstract class Testclass2 : Base2 { private static abstract event EventHandler Event1, Eve[||]nt3, Event4; } }"; var expected = @" using System; namespace PushUpTest { public abstract class Base2 { private static abstract event EventHandler Event3; } public abstract class Testclass2 : Base2 { private static abstract event EventHandler Event1, Event4; } }"; await TestWithPullMemberDialogAsync(testText, expected, new (string, bool)[] { ("Event3", false) }); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullNonPublicEventToInterfaceViaDialog() { var testText = @" using System; namespace PushUpTest { public interface ITest { } public class Testclass2 : ITest { private event EventHandler Eve[||]nt3; } }"; var expected = @" using System; namespace PushUpTest { public interface ITest { event EventHandler Event3; } public class Testclass2 : ITest { public event EventHandler Event3; } }"; await TestWithPullMemberDialogAsync(testText, expected, new (string, bool)[] { ("Event3", false) }); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullSingleNonPublicEventToInterfaceViaDialog() { var testText = @" using System; namespace PushUpTest { public interface ITest { } public abstract class TestClass2 : ITest { protected event EventHandler Eve[||]nt3; } }"; var expected = @" using System; namespace PushUpTest { public interface ITest { event EventHandler Event3; } public abstract class TestClass2 : ITest { public event EventHandler Event3; } }"; await TestWithPullMemberDialogAsync(testText, expected, new (string, bool)[] { ("Event3", false) }); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullNonPublicEventWithAddAndRemoveMethodToInterfaceViaDialog() { var testText = @" using System; namespace PushUpTest { interface IInterface { } public class TestClass : IInterface { private event EventHandler Eve[||]nt1 { add { System.Console.Writeline(""This is add""); } remove { System.Console.Writeline(""This is remove""); } } } }"; var expected = @" using System; namespace PushUpTest { interface IInterface { event EventHandler Event1; } public class TestClass : IInterface { public event EventHandler Event1 { add { System.Console.Writeline(""This is add""); } remove { System.Console.Writeline(""This is remove""); } } } }"; await TestWithPullMemberDialogAsync(testText, expected, new (string, bool)[] { ("Event1", false) }); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullFieldsToClassViaDialog() { var testText = @" using System; namespace PushUpTest { public class Base2 { } public class Testclass2 : Base2 { public int i, [||]j = 10, k = 100; } }"; var expected = @" using System; namespace PushUpTest { public class Base2 { public int i; public int j = 10; public int k = 100; } public class Testclass2 : Base2 { } }"; await TestWithPullMemberDialogAsync(testText, expected, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullNonPublicPropertyWithArrowToInterfaceViaDialog() { var testText = @" using System; namespace PushUpTest { public interface ITest { } public class Testclass2 : ITest { private double Test[||]Property => 2.717; } }"; var expected = @" using System; namespace PushUpTest { public interface ITest { double TestProperty { get; } } public class Testclass2 : ITest { public readonly double TestProperty => 2.717; } }"; await TestWithPullMemberDialogAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullNonPublicPropertyToInterfaceViaDialog() { var testText = @" using System; namespace PushUpTest { public interface ITest { } public class Testclass2 : ITest { private double Test[||]Property { get; set; } } }"; var expected = @" using System; namespace PushUpTest { public interface ITest { double TestProperty { get; set; } } public class Testclass2 : ITest { public double TestProperty { get; set; } } }"; await TestWithPullMemberDialogAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullNonPublicPropertyWithSingleAccessorToInterfaceViaDialog() { var testText = @" using System; namespace PushUpTest { public interface ITest { } public class Testclass2 : ITest { private static double Test[||]Property { set; } } }"; var expected = @" using System; namespace PushUpTest { public interface ITest { double TestProperty { set; } } public class Testclass2 : ITest { public double Test[||]Property { set; } } }"; await TestWithPullMemberDialogAsync(testText, expected); } [WorkItem(34268, "https://github.com/dotnet/roslyn/issues/34268")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullPropertyToAbstractClassViaDialogWithMakeAbstractOption() { var testText = @" abstract class B { } class D : B { int [||]X => 7; }"; var expected = @" abstract class B { private abstract int X { get; } } class D : B { override int X => 7; }"; await TestWithPullMemberDialogAsync(testText, expected, selection: new[] { ("X", true) }, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullEventUpToAbstractClassViaDialogWithMakeAbstractOption() { var testText = @" using System; namespace PushUpTest { public class Base2 { } public class Testclass2 : Base2 { private event EventHandler Event1, Eve[||]nt3, Event4; } }"; var expected = @" using System; namespace PushUpTest { public abstract class Base2 { private abstract event EventHandler Event3; } public class Testclass2 : Base2 { private event EventHandler Event1, Eve[||]nt3, Event4; } }"; await TestWithPullMemberDialogAsync(testText, expected, selection: new[] { ("Event3", true) }, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullEventWithAddAndRemoveMethodToClassViaDialogWithMakeAbstractOption() { var testText = @" using System; namespace PushUpTest { public class BaseClass { } public class TestClass : BaseClass { public event EventHandler Eve[||]nt1 { add { System.Console.Writeline(""This is add""); } remove { System.Console.Writeline(""This is remove""); } } } }"; var expected = @" using System; namespace PushUpTest { public abstract class BaseClass { public abstract event EventHandler Event1; } public class TestClass : BaseClass { public override event EventHandler Event1 { add { System.Console.Writeline(""This is add""); } remove { System.Console.Writeline(""This is remove""); } } } }"; await TestWithPullMemberDialogAsync(testText, expected, new (string, bool)[] { ("Event1", true) }, index: 1); } #endregion Dialog #region Selections and caret position [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestArgsIsPartOfHeader() { var testText = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } class Test2Attribute : Attribute { } public class A { } public class B : A { [Test] [Test2] void C([||]) { } } }"; var expected = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } class Test2Attribute : Attribute { } public class A { [Test] [Test2] void C() { } } public class B : A { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestRefactoringCaretBeforeAttributes() { var testText = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } class Test2Attribute : Attribute { } public class A { } public class B : A { [||][Test] [Test2] void C() { } } }"; var expected = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } class Test2Attribute : Attribute { } public class A { [Test] [Test2] void C() { } } public class B : A { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestMissingRefactoringCaretBetweenAttributes() { var testText = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } class Test2Attribute : Attribute { } public class A { } public class B : A { [Test] [||][Test2] void C() { } } }"; await TestQuickActionNotProvidedAsync(testText); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestRefactoringSelectionWithAttributes1() { var testText = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } public class A { } public class B : A { [Test] [|void C() { }|] } }"; var expected = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } public class A { [Test] void C() { } } public class B : A { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestRefactoringSelectionWithAttributes2() { var testText = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } public class A { } public class B : A { [|[Test] void C() { }|] } }"; var expected = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } public class A { [Test] void C() { } } public class B : A { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestRefactoringSelectionWithAttributes3() { var testText = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } public class A { } public class B : A { [Test][| void C() { } |] } }"; var expected = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } public class A { [Test] void C() { } } public class B : A { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestMissingRefactoringInAttributeList() { var testText = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } public class A { } public class B : A { [[||]Test] void C() { } } }"; await TestQuickActionNotProvidedAsync(testText); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestMissingRefactoringSelectionAttributeList() { var testText = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } class Test2Attribute : Attribute { } public class A { } public class B : A { [|[Test] [Test2]|] void C() { } } }"; await TestQuickActionNotProvidedAsync(testText); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestMissingRefactoringCaretInAttributeList() { var testText = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } class Test2Attribute : Attribute { } public class A { } public class B : A { [[||]Test] [Test2] void C() { } } }"; await TestQuickActionNotProvidedAsync(testText); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestMissingRefactoringCaretBetweenAttributeLists() { var testText = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } class Test2Attribute : Attribute { } public class A { } public class B : A { [Test] [||][Test2] void C() { } } }"; await TestQuickActionNotProvidedAsync(testText); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestMissingRefactoringSelectionAttributeList2() { var testText = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } class Test2Attribute : Attribute { } public class A { } public class B : A { [|[Test]|] [Test2] void C() { } } }"; await TestQuickActionNotProvidedAsync(testText); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestMissingRefactoringSelectAttributeList() { var testText = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } public class A { } public class B : A { [|[Test]|] void C() { } } }"; await TestQuickActionNotProvidedAsync(testText); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestRefactoringCaretLocAfterAttributes1() { var testText = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } public class A { } public class B : A { [Test] [||]void C() { } } }"; var expected = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } public class A { [Test] void C() { } } public class B : A { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestRefactoringCaretLocAfterAttributes2() { var testText = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } class Test2Attribute : Attribute { } public class A { } public class B : A { [Test] // Comment1 [Test2] // Comment2 [||]void C() { } } }"; var expected = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } class Test2Attribute : Attribute { } public class A { [Test] // Comment1 [Test2] // Comment2 void C() { } } public class B : A { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestRefactoringCaretLoc1() { var testText = @" namespace PushUpTest { public class A { } public class B : A { [||]void C() { } } }"; var expected = @" namespace PushUpTest { public class A { void C() { } } public class B : A { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestRefactoringSelection() { var testText = @" namespace PushUpTest { public class A { } public class B : A { [|void C() { }|] } }"; var expected = @" namespace PushUpTest { public class A { void C() { } } public class B : A { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestRefactoringSelectionComments() { var testText = @" namespace PushUpTest { public class A { } public class B : A { [| // Comment1 void C() { }|] } }"; var expected = @" namespace PushUpTest { public class A { // Comment1 void C() { } } public class B : A { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestRefactoringSelectionComments2() { var testText = @" namespace PushUpTest { public class A { } public class B : A { [|/// <summary> /// Test /// </summary> void C() { }|] } }"; var expected = @" namespace PushUpTest { public class A { /// <summary> /// Test /// </summary> void C() { } } public class B : A { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestRefactoringSelectionComments3() { var testText = @" namespace PushUpTest { public class A { } public class B : A { /// <summary> [|/// Test /// </summary> void C() { }|] } }"; var expected = @" namespace PushUpTest { public class A { /// <summary> /// Test /// </summary> void C() { } } public class B : A { } }"; await TestInRegularAndScriptAsync(testText, expected); } #endregion } }
-1
dotnet/roslyn
56,450
Implement INamespaceTypeReference.GetUnit for RootModuleType
Fixes #56412.
AlekseyTs
"2021-09-16T16:44:04Z"
"2021-09-17T18:21:59Z"
4b06ee428bafa0141c9eb3250003a19109dcfc86
d695369176aa109f0e0fb8b0019294aaa0823a54
Implement INamespaceTypeReference.GetUnit for RootModuleType. Fixes #56412.
./src/Interactive/HostTest/StressTests.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. extern alias InteractiveHost; using System; using System.Diagnostics; using System.Globalization; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Scripting.Hosting; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests.Interactive { using InteractiveHost::Microsoft.CodeAnalysis.Interactive; public sealed class StressTests { [Fact] public async Task TestKill() { for (int sleep = 0; sleep < 20; sleep++) { await TestKillAfterAsync(sleep).ConfigureAwait(false); } } private async Task TestKillAfterAsync(int milliseconds) { using var host = new InteractiveHost(typeof(CSharpReplServiceProvider), ".", millisecondsTimeout: 1, joinOutputWritingThreadsOnDisposal: true); var options = InteractiveHostOptions.CreateFromDirectory(TestUtils.HostRootPath, initializationFileName: null, CultureInfo.InvariantCulture, InteractiveHostPlatform.Desktop64); host.InteractiveHostProcessCreated += new Action<Process>(proc => { _ = Task.Run(async () => { await Task.Delay(milliseconds).ConfigureAwait(false); try { proc.Kill(); } catch { } }); }); await host.ResetAsync(options).ConfigureAwait(false); for (int j = 0; j < 10; j++) { await host.ExecuteAsync("1+1").ConfigureAwait(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. extern alias InteractiveHost; using System; using System.Diagnostics; using System.Globalization; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Scripting.Hosting; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests.Interactive { using InteractiveHost::Microsoft.CodeAnalysis.Interactive; public sealed class StressTests { [Fact] public async Task TestKill() { for (int sleep = 0; sleep < 20; sleep++) { await TestKillAfterAsync(sleep).ConfigureAwait(false); } } private async Task TestKillAfterAsync(int milliseconds) { using var host = new InteractiveHost(typeof(CSharpReplServiceProvider), ".", millisecondsTimeout: 1, joinOutputWritingThreadsOnDisposal: true); var options = InteractiveHostOptions.CreateFromDirectory(TestUtils.HostRootPath, initializationFileName: null, CultureInfo.InvariantCulture, InteractiveHostPlatform.Desktop64); host.InteractiveHostProcessCreated += new Action<Process>(proc => { _ = Task.Run(async () => { await Task.Delay(milliseconds).ConfigureAwait(false); try { proc.Kill(); } catch { } }); }); await host.ResetAsync(options).ConfigureAwait(false); for (int j = 0; j < 10; j++) { await host.ExecuteAsync("1+1").ConfigureAwait(false); } } } }
-1
dotnet/roslyn
56,450
Implement INamespaceTypeReference.GetUnit for RootModuleType
Fixes #56412.
AlekseyTs
"2021-09-16T16:44:04Z"
"2021-09-17T18:21:59Z"
4b06ee428bafa0141c9eb3250003a19109dcfc86
d695369176aa109f0e0fb8b0019294aaa0823a54
Implement INamespaceTypeReference.GetUnit for RootModuleType. Fixes #56412.
./src/Compilers/CSharp/Portable/Binder/BinderFlagsExtensions.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 { /// <summary> /// Extension methods for the <see cref="BinderFlags"/> type. /// </summary> internal static class BinderFlagsExtensions { public static bool Includes(this BinderFlags self, BinderFlags other) { return (self & other) == other; } public static bool IncludesAny(this BinderFlags self, BinderFlags other) { return (self & other) != 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 namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// Extension methods for the <see cref="BinderFlags"/> type. /// </summary> internal static class BinderFlagsExtensions { public static bool Includes(this BinderFlags self, BinderFlags other) { return (self & other) == other; } public static bool IncludesAny(this BinderFlags self, BinderFlags other) { return (self & other) != 0; } } }
-1
dotnet/roslyn
56,450
Implement INamespaceTypeReference.GetUnit for RootModuleType
Fixes #56412.
AlekseyTs
"2021-09-16T16:44:04Z"
"2021-09-17T18:21:59Z"
4b06ee428bafa0141c9eb3250003a19109dcfc86
d695369176aa109f0e0fb8b0019294aaa0823a54
Implement INamespaceTypeReference.GetUnit for RootModuleType. Fixes #56412.
./src/Compilers/Core/Portable/Emit/StateMachineMoveNextDebugInfo.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.Diagnostics; namespace Microsoft.CodeAnalysis.Emit { /// <summary> /// Information associated with method body of a state machine MoveNext method. /// </summary> internal abstract class StateMachineMoveNextBodyDebugInfo { /// <summary> /// Original async/iterator method transformed into MoveNext() /// </summary> public readonly Cci.IMethodDefinition KickoffMethod; public StateMachineMoveNextBodyDebugInfo(Cci.IMethodDefinition kickoffMethod) { Debug.Assert(kickoffMethod != null); KickoffMethod = kickoffMethod; } } }
// Licensed to the .NET Foundation under one or more 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.Diagnostics; namespace Microsoft.CodeAnalysis.Emit { /// <summary> /// Information associated with method body of a state machine MoveNext method. /// </summary> internal abstract class StateMachineMoveNextBodyDebugInfo { /// <summary> /// Original async/iterator method transformed into MoveNext() /// </summary> public readonly Cci.IMethodDefinition KickoffMethod; public StateMachineMoveNextBodyDebugInfo(Cci.IMethodDefinition kickoffMethod) { Debug.Assert(kickoffMethod != null); KickoffMethod = kickoffMethod; } } }
-1
dotnet/roslyn
56,450
Implement INamespaceTypeReference.GetUnit for RootModuleType
Fixes #56412.
AlekseyTs
"2021-09-16T16:44:04Z"
"2021-09-17T18:21:59Z"
4b06ee428bafa0141c9eb3250003a19109dcfc86
d695369176aa109f0e0fb8b0019294aaa0823a54
Implement INamespaceTypeReference.GetUnit for RootModuleType. Fixes #56412.
./src/Features/Core/Portable/EmbeddedLanguages/RegularExpressions/RegexItem.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.Completion; namespace Microsoft.CodeAnalysis.Features.EmbeddedLanguages.RegularExpressions { internal partial class RegexEmbeddedCompletionProvider { private readonly struct RegexItem { public readonly string DisplayText; public readonly string InlineDescription; public readonly string FullDescription; public readonly CompletionChange Change; public RegexItem( string displayText, string inlineDescription, string fullDescription, CompletionChange change) { DisplayText = displayText; InlineDescription = inlineDescription; FullDescription = fullDescription; Change = change; } } } }
// Licensed to the .NET Foundation under one or more 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.Completion; namespace Microsoft.CodeAnalysis.Features.EmbeddedLanguages.RegularExpressions { internal partial class RegexEmbeddedCompletionProvider { private readonly struct RegexItem { public readonly string DisplayText; public readonly string InlineDescription; public readonly string FullDescription; public readonly CompletionChange Change; public RegexItem( string displayText, string inlineDescription, string fullDescription, CompletionChange change) { DisplayText = displayText; InlineDescription = inlineDescription; FullDescription = fullDescription; Change = change; } } } }
-1
dotnet/roslyn
56,450
Implement INamespaceTypeReference.GetUnit for RootModuleType
Fixes #56412.
AlekseyTs
"2021-09-16T16:44:04Z"
"2021-09-17T18:21:59Z"
4b06ee428bafa0141c9eb3250003a19109dcfc86
d695369176aa109f0e0fb8b0019294aaa0823a54
Implement INamespaceTypeReference.GetUnit for RootModuleType. Fixes #56412.
./src/Compilers/CSharp/Test/Syntax/Parsing/ReadOnlyStructs.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 Xunit; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Parsing { [CompilerTrait(CompilerFeature.ReadOnlyReferences)] public class ReadOnlyStructs : ParsingTests { public ReadOnlyStructs(ITestOutputHelper output) : base(output) { } protected override SyntaxTree ParseTree(string text, CSharpParseOptions options) { return SyntaxFactory.ParseSyntaxTree(text, options: options); } [Fact] public void ReadOnlyStructSimple() { var text = @" class Program { readonly struct S1{} public readonly struct S2{} readonly public struct S3{} } "; var comp = CreateCompilationWithMscorlib45(text, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.Latest), options: TestOptions.DebugDll); comp.VerifyDiagnostics( ); var s1 = comp.GetTypeByMetadataName("Program+S1"); Assert.False(s1.IsRefLikeType); Assert.True(s1.IsReadOnly); Assert.Equal(Accessibility.Private, s1.DeclaredAccessibility); Assert.Equal(TypeKind.Struct, s1.TypeKind); var s2 = comp.GetTypeByMetadataName("Program+S2"); Assert.False(s2.IsRefLikeType); Assert.True(s2.IsReadOnly); Assert.Equal(Accessibility.Public, s2.DeclaredAccessibility); Assert.Equal(TypeKind.Struct, s2.TypeKind); var s3 = comp.GetTypeByMetadataName("Program+S3"); Assert.False(s3.IsRefLikeType); Assert.True(s3.IsReadOnly); Assert.Equal(Accessibility.Public, s3.DeclaredAccessibility); Assert.Equal(TypeKind.Struct, s3.TypeKind); } [Fact] public void ReadOnlyStructSimpleLangVer() { var text = @" class Program { readonly struct S1{} public readonly struct S2{} readonly public struct S3{} } "; var comp = CreateCompilationWithMscorlib45(text, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7), options: TestOptions.DebugDll); comp.VerifyDiagnostics( // (4,5): error CS8107: Feature 'readonly structs' is not available in C# 7. Please use language version 7.2 or greater. // readonly struct S1{} Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "readonly").WithArguments("readonly structs", "7.2").WithLocation(4, 5), // (6,12): error CS8107: Feature 'readonly structs' is not available in C# 7. Please use language version 7.2 or greater. // public readonly struct S2{} Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "readonly").WithArguments("readonly structs", "7.2").WithLocation(6, 12), // (8,5): error CS8107: Feature 'readonly structs' is not available in C# 7. Please use language version 7.2 or greater. // readonly public struct S3{} Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "readonly").WithArguments("readonly structs", "7.2").WithLocation(8, 5) ); } [Fact] public void ReadOnlyClassErr() { var text = @" class Program { readonly class S1{} public readonly delegate ref readonly int S2(); readonly public interface S3{} } "; var comp = CreateCompilationWithMscorlib45(text, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.Latest), options: TestOptions.DebugDll); comp.VerifyDiagnostics( // (4,20): error CS0106: The modifier 'readonly' is not valid for this item // readonly class S1{} Diagnostic(ErrorCode.ERR_BadMemberFlag, "S1").WithArguments("readonly").WithLocation(4, 20), // (6,47): error CS0106: The modifier 'readonly' is not valid for this item // public readonly delegate ref readonly int S2(); Diagnostic(ErrorCode.ERR_BadMemberFlag, "S2").WithArguments("readonly").WithLocation(6, 47), // (8,31): error CS0106: The modifier 'readonly' is not valid for this item // readonly public interface S3{} Diagnostic(ErrorCode.ERR_BadMemberFlag, "S3").WithArguments("readonly").WithLocation(8, 31) ); var s1 = comp.GetTypeByMetadataName("Program+S1"); Assert.False(s1.IsRefLikeType); Assert.False(s1.IsReadOnly); Assert.Equal(Accessibility.Private, s1.DeclaredAccessibility); Assert.Equal(TypeKind.Class, s1.TypeKind); var s2 = comp.GetTypeByMetadataName("Program+S2"); Assert.False(s2.IsRefLikeType); Assert.False(s2.IsReadOnly); Assert.Equal(Accessibility.Public, s2.DeclaredAccessibility); Assert.Equal(TypeKind.Delegate, s2.TypeKind); var s3 = comp.GetTypeByMetadataName("Program+S3"); Assert.False(s3.IsRefLikeType); Assert.False(s3.IsReadOnly); Assert.Equal(Accessibility.Public, s3.DeclaredAccessibility); Assert.Equal(TypeKind.Interface, s3.TypeKind); } [Fact] public void ReadOnlyRefStruct() { var text = @" class Program { readonly ref struct S1{} unsafe readonly public ref struct S2{} } "; var comp = CreateCompilationWithMscorlib45(text, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.Latest), options: TestOptions.DebugDll.WithAllowUnsafe(true)); comp.VerifyDiagnostics( ); var s1 = comp.GetTypeByMetadataName("Program+S1"); Assert.True(s1.IsRefLikeType); Assert.True(s1.IsReadOnly); Assert.Equal(Accessibility.Private, s1.DeclaredAccessibility); Assert.Equal(TypeKind.Struct, s1.TypeKind); var s2 = comp.GetTypeByMetadataName("Program+S2"); Assert.True(s2.IsRefLikeType); Assert.True(s2.IsReadOnly); Assert.Equal(Accessibility.Public, s2.DeclaredAccessibility); Assert.Equal(TypeKind.Struct, s2.TypeKind); } [Fact] public void ReadOnlyStructPartialMatchingModifiers() { var text = @" class Program { readonly partial struct S1{} readonly partial struct S1{} readonly ref partial struct S2{} readonly ref partial struct S2{} } "; var comp = CreateCompilationWithMscorlib45(text, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.Latest), options: TestOptions.DebugDll); comp.VerifyDiagnostics( ); var s1 = comp.GetTypeByMetadataName("Program+S1"); Assert.False(s1.IsRefLikeType); Assert.True(s1.IsReadOnly); var s2 = comp.GetTypeByMetadataName("Program+S2"); Assert.True(s2.IsRefLikeType); Assert.True(s2.IsReadOnly); } [WorkItem(19808, "https://github.com/dotnet/roslyn/issues/19808")] [Fact] public void ReadOnlyStructPartialNotMatchingModifiers() { var text = @" class Program { readonly partial struct S1{} readonly ref partial struct S1{} readonly partial struct S2{} partial struct S2{} readonly ref partial struct S3{} partial struct S3{} } "; var comp = CreateCompilationWithMscorlib45(text, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.Latest), options: TestOptions.DebugDll); comp.VerifyDiagnostics( ); var s1 = comp.GetTypeByMetadataName("Program+S1"); Assert.True(s1.IsRefLikeType); Assert.True(s1.IsReadOnly); var s2 = comp.GetTypeByMetadataName("Program+S2"); Assert.False(s2.IsRefLikeType); Assert.True(s2.IsReadOnly); var s3 = comp.GetTypeByMetadataName("Program+S3"); Assert.True(s3.IsRefLikeType); Assert.True(s3.IsReadOnly); } } }
// Licensed to the .NET Foundation under one or more 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 Xunit; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Parsing { [CompilerTrait(CompilerFeature.ReadOnlyReferences)] public class ReadOnlyStructs : ParsingTests { public ReadOnlyStructs(ITestOutputHelper output) : base(output) { } protected override SyntaxTree ParseTree(string text, CSharpParseOptions options) { return SyntaxFactory.ParseSyntaxTree(text, options: options); } [Fact] public void ReadOnlyStructSimple() { var text = @" class Program { readonly struct S1{} public readonly struct S2{} readonly public struct S3{} } "; var comp = CreateCompilationWithMscorlib45(text, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.Latest), options: TestOptions.DebugDll); comp.VerifyDiagnostics( ); var s1 = comp.GetTypeByMetadataName("Program+S1"); Assert.False(s1.IsRefLikeType); Assert.True(s1.IsReadOnly); Assert.Equal(Accessibility.Private, s1.DeclaredAccessibility); Assert.Equal(TypeKind.Struct, s1.TypeKind); var s2 = comp.GetTypeByMetadataName("Program+S2"); Assert.False(s2.IsRefLikeType); Assert.True(s2.IsReadOnly); Assert.Equal(Accessibility.Public, s2.DeclaredAccessibility); Assert.Equal(TypeKind.Struct, s2.TypeKind); var s3 = comp.GetTypeByMetadataName("Program+S3"); Assert.False(s3.IsRefLikeType); Assert.True(s3.IsReadOnly); Assert.Equal(Accessibility.Public, s3.DeclaredAccessibility); Assert.Equal(TypeKind.Struct, s3.TypeKind); } [Fact] public void ReadOnlyStructSimpleLangVer() { var text = @" class Program { readonly struct S1{} public readonly struct S2{} readonly public struct S3{} } "; var comp = CreateCompilationWithMscorlib45(text, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7), options: TestOptions.DebugDll); comp.VerifyDiagnostics( // (4,5): error CS8107: Feature 'readonly structs' is not available in C# 7. Please use language version 7.2 or greater. // readonly struct S1{} Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "readonly").WithArguments("readonly structs", "7.2").WithLocation(4, 5), // (6,12): error CS8107: Feature 'readonly structs' is not available in C# 7. Please use language version 7.2 or greater. // public readonly struct S2{} Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "readonly").WithArguments("readonly structs", "7.2").WithLocation(6, 12), // (8,5): error CS8107: Feature 'readonly structs' is not available in C# 7. Please use language version 7.2 or greater. // readonly public struct S3{} Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "readonly").WithArguments("readonly structs", "7.2").WithLocation(8, 5) ); } [Fact] public void ReadOnlyClassErr() { var text = @" class Program { readonly class S1{} public readonly delegate ref readonly int S2(); readonly public interface S3{} } "; var comp = CreateCompilationWithMscorlib45(text, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.Latest), options: TestOptions.DebugDll); comp.VerifyDiagnostics( // (4,20): error CS0106: The modifier 'readonly' is not valid for this item // readonly class S1{} Diagnostic(ErrorCode.ERR_BadMemberFlag, "S1").WithArguments("readonly").WithLocation(4, 20), // (6,47): error CS0106: The modifier 'readonly' is not valid for this item // public readonly delegate ref readonly int S2(); Diagnostic(ErrorCode.ERR_BadMemberFlag, "S2").WithArguments("readonly").WithLocation(6, 47), // (8,31): error CS0106: The modifier 'readonly' is not valid for this item // readonly public interface S3{} Diagnostic(ErrorCode.ERR_BadMemberFlag, "S3").WithArguments("readonly").WithLocation(8, 31) ); var s1 = comp.GetTypeByMetadataName("Program+S1"); Assert.False(s1.IsRefLikeType); Assert.False(s1.IsReadOnly); Assert.Equal(Accessibility.Private, s1.DeclaredAccessibility); Assert.Equal(TypeKind.Class, s1.TypeKind); var s2 = comp.GetTypeByMetadataName("Program+S2"); Assert.False(s2.IsRefLikeType); Assert.False(s2.IsReadOnly); Assert.Equal(Accessibility.Public, s2.DeclaredAccessibility); Assert.Equal(TypeKind.Delegate, s2.TypeKind); var s3 = comp.GetTypeByMetadataName("Program+S3"); Assert.False(s3.IsRefLikeType); Assert.False(s3.IsReadOnly); Assert.Equal(Accessibility.Public, s3.DeclaredAccessibility); Assert.Equal(TypeKind.Interface, s3.TypeKind); } [Fact] public void ReadOnlyRefStruct() { var text = @" class Program { readonly ref struct S1{} unsafe readonly public ref struct S2{} } "; var comp = CreateCompilationWithMscorlib45(text, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.Latest), options: TestOptions.DebugDll.WithAllowUnsafe(true)); comp.VerifyDiagnostics( ); var s1 = comp.GetTypeByMetadataName("Program+S1"); Assert.True(s1.IsRefLikeType); Assert.True(s1.IsReadOnly); Assert.Equal(Accessibility.Private, s1.DeclaredAccessibility); Assert.Equal(TypeKind.Struct, s1.TypeKind); var s2 = comp.GetTypeByMetadataName("Program+S2"); Assert.True(s2.IsRefLikeType); Assert.True(s2.IsReadOnly); Assert.Equal(Accessibility.Public, s2.DeclaredAccessibility); Assert.Equal(TypeKind.Struct, s2.TypeKind); } [Fact] public void ReadOnlyStructPartialMatchingModifiers() { var text = @" class Program { readonly partial struct S1{} readonly partial struct S1{} readonly ref partial struct S2{} readonly ref partial struct S2{} } "; var comp = CreateCompilationWithMscorlib45(text, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.Latest), options: TestOptions.DebugDll); comp.VerifyDiagnostics( ); var s1 = comp.GetTypeByMetadataName("Program+S1"); Assert.False(s1.IsRefLikeType); Assert.True(s1.IsReadOnly); var s2 = comp.GetTypeByMetadataName("Program+S2"); Assert.True(s2.IsRefLikeType); Assert.True(s2.IsReadOnly); } [WorkItem(19808, "https://github.com/dotnet/roslyn/issues/19808")] [Fact] public void ReadOnlyStructPartialNotMatchingModifiers() { var text = @" class Program { readonly partial struct S1{} readonly ref partial struct S1{} readonly partial struct S2{} partial struct S2{} readonly ref partial struct S3{} partial struct S3{} } "; var comp = CreateCompilationWithMscorlib45(text, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.Latest), options: TestOptions.DebugDll); comp.VerifyDiagnostics( ); var s1 = comp.GetTypeByMetadataName("Program+S1"); Assert.True(s1.IsRefLikeType); Assert.True(s1.IsReadOnly); var s2 = comp.GetTypeByMetadataName("Program+S2"); Assert.False(s2.IsRefLikeType); Assert.True(s2.IsReadOnly); var s3 = comp.GetTypeByMetadataName("Program+S3"); Assert.True(s3.IsRefLikeType); Assert.True(s3.IsReadOnly); } } }
-1
dotnet/roslyn
56,450
Implement INamespaceTypeReference.GetUnit for RootModuleType
Fixes #56412.
AlekseyTs
"2021-09-16T16:44:04Z"
"2021-09-17T18:21:59Z"
4b06ee428bafa0141c9eb3250003a19109dcfc86
d695369176aa109f0e0fb8b0019294aaa0823a54
Implement INamespaceTypeReference.GetUnit for RootModuleType. Fixes #56412.
./src/Compilers/CSharp/Portable/Binder/Semantics/Operators/UnaryOperatorOverloadResolutionResult.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.Text; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal sealed class UnaryOperatorOverloadResolutionResult { public readonly ArrayBuilder<UnaryOperatorAnalysisResult> Results; public UnaryOperatorOverloadResolutionResult() { this.Results = new ArrayBuilder<UnaryOperatorAnalysisResult>(10); } public bool AnyValid() { foreach (var result in Results) { if (result.IsValid) { return true; } } return false; } public bool SingleValid() { bool oneValid = false; foreach (var result in Results) { if (result.IsValid) { if (oneValid) { return false; } oneValid = true; } } return oneValid; } public UnaryOperatorAnalysisResult Best { get { UnaryOperatorAnalysisResult best = default(UnaryOperatorAnalysisResult); foreach (var result in Results) { if (result.IsValid) { if (best.IsValid) { // More than one best applicable method return default(UnaryOperatorAnalysisResult); } best = result; } } return best; } } #if DEBUG public string Dump() { if (Results.Count == 0) { return "Overload resolution failed because there were no candidate operators."; } var sb = new StringBuilder(); if (this.Best.HasValue) { sb.AppendLine("Overload resolution succeeded and chose " + this.Best.Signature.ToString()); } else if (CountKind(OperatorAnalysisResultKind.Applicable) > 1) { sb.AppendLine("Overload resolution failed because of ambiguous possible best operators."); } else { sb.AppendLine("Overload resolution failed because no operator was applicable."); } sb.AppendLine("Detailed results:"); foreach (var result in Results) { sb.AppendFormat("operator: {0} reason: {1}\n", result.Signature.ToString(), result.Kind.ToString()); } return sb.ToString(); } private int CountKind(OperatorAnalysisResultKind kind) { int count = 0; for (int i = 0, n = this.Results.Count; i < n; i++) { if (this.Results[i].Kind == kind) { count++; } } return count; } #endif #region "Poolable" public static UnaryOperatorOverloadResolutionResult GetInstance() { return Pool.Allocate(); } public void Free() { this.Results.Clear(); Pool.Free(this); } //2) Expose the pool or the way to create a pool or the way to get an instance. // for now we will expose both and figure which way works better public static readonly ObjectPool<UnaryOperatorOverloadResolutionResult> Pool = CreatePool(); private static ObjectPool<UnaryOperatorOverloadResolutionResult> CreatePool() { ObjectPool<UnaryOperatorOverloadResolutionResult> pool = null; pool = new ObjectPool<UnaryOperatorOverloadResolutionResult>(() => new UnaryOperatorOverloadResolutionResult(), 10); return pool; } #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.Text; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal sealed class UnaryOperatorOverloadResolutionResult { public readonly ArrayBuilder<UnaryOperatorAnalysisResult> Results; public UnaryOperatorOverloadResolutionResult() { this.Results = new ArrayBuilder<UnaryOperatorAnalysisResult>(10); } public bool AnyValid() { foreach (var result in Results) { if (result.IsValid) { return true; } } return false; } public bool SingleValid() { bool oneValid = false; foreach (var result in Results) { if (result.IsValid) { if (oneValid) { return false; } oneValid = true; } } return oneValid; } public UnaryOperatorAnalysisResult Best { get { UnaryOperatorAnalysisResult best = default(UnaryOperatorAnalysisResult); foreach (var result in Results) { if (result.IsValid) { if (best.IsValid) { // More than one best applicable method return default(UnaryOperatorAnalysisResult); } best = result; } } return best; } } #if DEBUG public string Dump() { if (Results.Count == 0) { return "Overload resolution failed because there were no candidate operators."; } var sb = new StringBuilder(); if (this.Best.HasValue) { sb.AppendLine("Overload resolution succeeded and chose " + this.Best.Signature.ToString()); } else if (CountKind(OperatorAnalysisResultKind.Applicable) > 1) { sb.AppendLine("Overload resolution failed because of ambiguous possible best operators."); } else { sb.AppendLine("Overload resolution failed because no operator was applicable."); } sb.AppendLine("Detailed results:"); foreach (var result in Results) { sb.AppendFormat("operator: {0} reason: {1}\n", result.Signature.ToString(), result.Kind.ToString()); } return sb.ToString(); } private int CountKind(OperatorAnalysisResultKind kind) { int count = 0; for (int i = 0, n = this.Results.Count; i < n; i++) { if (this.Results[i].Kind == kind) { count++; } } return count; } #endif #region "Poolable" public static UnaryOperatorOverloadResolutionResult GetInstance() { return Pool.Allocate(); } public void Free() { this.Results.Clear(); Pool.Free(this); } //2) Expose the pool or the way to create a pool or the way to get an instance. // for now we will expose both and figure which way works better public static readonly ObjectPool<UnaryOperatorOverloadResolutionResult> Pool = CreatePool(); private static ObjectPool<UnaryOperatorOverloadResolutionResult> CreatePool() { ObjectPool<UnaryOperatorOverloadResolutionResult> pool = null; pool = new ObjectPool<UnaryOperatorOverloadResolutionResult>(() => new UnaryOperatorOverloadResolutionResult(), 10); return pool; } #endregion } }
-1
dotnet/roslyn
56,450
Implement INamespaceTypeReference.GetUnit for RootModuleType
Fixes #56412.
AlekseyTs
"2021-09-16T16:44:04Z"
"2021-09-17T18:21:59Z"
4b06ee428bafa0141c9eb3250003a19109dcfc86
d695369176aa109f0e0fb8b0019294aaa0823a54
Implement INamespaceTypeReference.GetUnit for RootModuleType. Fixes #56412.
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/BKTree.Node.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.Text; namespace Roslyn.Utilities { internal partial class BKTree { private struct Node { /// <summary> /// The string this node corresponds to. Specifically, this span is the range of /// <see cref="_concatenatedLowerCaseWords"/> for that string. /// </summary> public readonly TextSpan WordSpan; ///<summary>How many child edges this node has.</summary> public readonly int EdgeCount; ///<summary>Where the first edge can be found in <see cref="_edges"/>. The edges ///are in the range _edges[FirstEdgeIndex, FirstEdgeIndex + EdgeCount) ///</summary> public readonly int FirstEdgeIndex; public Node(TextSpan wordSpan, int edgeCount, int firstEdgeIndex) { WordSpan = wordSpan; EdgeCount = edgeCount; FirstEdgeIndex = firstEdgeIndex; } internal void WriteTo(ObjectWriter writer) { writer.WriteInt32(WordSpan.Start); writer.WriteInt32(WordSpan.Length); writer.WriteInt32(EdgeCount); writer.WriteInt32(FirstEdgeIndex); } internal static Node ReadFrom(ObjectReader reader) { return new Node( new TextSpan(start: reader.ReadInt32(), length: reader.ReadInt32()), edgeCount: reader.ReadInt32(), firstEdgeIndex: reader.ReadInt32()); } } } }
// Licensed to the .NET Foundation under one or more 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.Text; namespace Roslyn.Utilities { internal partial class BKTree { private struct Node { /// <summary> /// The string this node corresponds to. Specifically, this span is the range of /// <see cref="_concatenatedLowerCaseWords"/> for that string. /// </summary> public readonly TextSpan WordSpan; ///<summary>How many child edges this node has.</summary> public readonly int EdgeCount; ///<summary>Where the first edge can be found in <see cref="_edges"/>. The edges ///are in the range _edges[FirstEdgeIndex, FirstEdgeIndex + EdgeCount) ///</summary> public readonly int FirstEdgeIndex; public Node(TextSpan wordSpan, int edgeCount, int firstEdgeIndex) { WordSpan = wordSpan; EdgeCount = edgeCount; FirstEdgeIndex = firstEdgeIndex; } internal void WriteTo(ObjectWriter writer) { writer.WriteInt32(WordSpan.Start); writer.WriteInt32(WordSpan.Length); writer.WriteInt32(EdgeCount); writer.WriteInt32(FirstEdgeIndex); } internal static Node ReadFrom(ObjectReader reader) { return new Node( new TextSpan(start: reader.ReadInt32(), length: reader.ReadInt32()), edgeCount: reader.ReadInt32(), firstEdgeIndex: reader.ReadInt32()); } } } }
-1
dotnet/roslyn
56,450
Implement INamespaceTypeReference.GetUnit for RootModuleType
Fixes #56412.
AlekseyTs
"2021-09-16T16:44:04Z"
"2021-09-17T18:21:59Z"
4b06ee428bafa0141c9eb3250003a19109dcfc86
d695369176aa109f0e0fb8b0019294aaa0823a54
Implement INamespaceTypeReference.GetUnit for RootModuleType. Fixes #56412.
./src/Features/Core/Portable/ClassifiedSpansAndHighlightSpan.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.Text; namespace Microsoft.CodeAnalysis.Classification { internal readonly struct ClassifiedSpansAndHighlightSpan { public const string Key = nameof(ClassifiedSpansAndHighlightSpan); public readonly ImmutableArray<ClassifiedSpan> ClassifiedSpans; public readonly TextSpan HighlightSpan; public ClassifiedSpansAndHighlightSpan( ImmutableArray<ClassifiedSpan> classifiedSpans, TextSpan highlightSpan) { ClassifiedSpans = classifiedSpans; HighlightSpan = highlightSpan; } } }
// Licensed to the .NET Foundation under one or more 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.Text; namespace Microsoft.CodeAnalysis.Classification { internal readonly struct ClassifiedSpansAndHighlightSpan { public const string Key = nameof(ClassifiedSpansAndHighlightSpan); public readonly ImmutableArray<ClassifiedSpan> ClassifiedSpans; public readonly TextSpan HighlightSpan; public ClassifiedSpansAndHighlightSpan( ImmutableArray<ClassifiedSpan> classifiedSpans, TextSpan highlightSpan) { ClassifiedSpans = classifiedSpans; HighlightSpan = highlightSpan; } } }
-1
dotnet/roslyn
56,450
Implement INamespaceTypeReference.GetUnit for RootModuleType
Fixes #56412.
AlekseyTs
"2021-09-16T16:44:04Z"
"2021-09-17T18:21:59Z"
4b06ee428bafa0141c9eb3250003a19109dcfc86
d695369176aa109f0e0fb8b0019294aaa0823a54
Implement INamespaceTypeReference.GetUnit for RootModuleType. Fixes #56412.
./src/Analyzers/CSharp/Tests/InlineDeclaration/CSharpInlineDeclarationTests_FixAllTests.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.Tasks; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.InlineDeclaration { public partial class CSharpInlineDeclarationTests { [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task FixAllInDocument1() { await TestInRegularAndScriptAsync( @"class C { void M() { int {|FixAllInDocument:i|}, j; if (int.TryParse(v, out i, out j)) { } } }", @"class C { void M() { if (int.TryParse(v, out int i, out int j)) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task FixAllInDocument2() { await TestInRegularAndScriptAsync( @"class C { void M() { {|FixAllInDocument:int|} i; if (int.TryParse(v, out i)) { } } void M1() { int i; if (int.TryParse(v, out i)) { } } }", @"class C { void M() { if (int.TryParse(v, out int i)) { } } void M1() { if (int.TryParse(v, out int i)) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task FixAllInDocument3() { await TestInRegularAndScriptAsync( @"class C { void M() { // Now get final exe and args. CTtrl-F5 wraps exe in cmd prompt string {|FixAllInDocument:finalExecutable|}, finalArguments; GetExeAndArguments(useCmdShell, executable, arguments, out finalExecutable, out finalArguments); } }", @"class C { void M() { // Now get final exe and args. CTtrl-F5 wraps exe in cmd prompt GetExeAndArguments(useCmdShell, executable, arguments, out string finalExecutable, out string finalArguments); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] [WorkItem(29935, "https://github.com/dotnet/roslyn/issues/29935")] public async Task FixAllInDocumentSymbolResolution() { await TestInRegularAndScriptAsync( @"class C { void M() { string {|FixAllInDocument:s|}; bool b; A(out s, out b); } void A(out string s, out bool b) { s = string.Empty; b = false; } void A(out string s, out string s2) { s = s2 = string.Empty; } }", @"class C { void M() { A(out string s, out bool b); } void A(out string s, out bool b) { s = string.Empty; b = false; } void A(out string s, out string s2) { s = s2 = string.Empty; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] [WorkItem(28323, "https://github.com/dotnet/roslyn/issues/28323")] public async Task FixAllInDocument4() { await TestInRegularAndScriptAsync( @"class C { void M() { int {|FixAllInDocument:i1|}; int i2; int.TryParse(v, out i1); int.TryParse(v, out i2); } }", @"class C { void M() { int.TryParse(v, out int i1); int.TryParse(v, out int i2); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] [WorkItem(28323, "https://github.com/dotnet/roslyn/issues/28323")] public async Task FixAllInDocument5() { await TestInRegularAndScriptAsync( @"class C { void M() { int dummy; int {|FixAllInDocument:i1|}; int i2; int.TryParse(v, out i1); int.TryParse(v, out i2); dummy = 42; } }", @"class C { void M() { int dummy; int.TryParse(v, out int i1); int.TryParse(v, out int i2); dummy = 42; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] [WorkItem(28323, "https://github.com/dotnet/roslyn/issues/28323")] public async Task FixAllInDocument6() { await TestInRegularAndScriptAsync( @"class C { void M() { int {|FixAllInDocument:i1|}; int dummy; int i2; int.TryParse(v, out i1); int.TryParse(v, out i2); dummy = 42; } }", @"class C { void M() { int dummy; int.TryParse(v, out int i1); int.TryParse(v, out int i2); dummy = 42; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] [WorkItem(28323, "https://github.com/dotnet/roslyn/issues/28323")] public async Task FixAllInDocument7() { await TestInRegularAndScriptAsync( @"class C { void M() { int {|FixAllInDocument:i1|}; int i2; int dummy; int.TryParse(v, out i1); int.TryParse(v, out i2); dummy = 42; } }", @"class C { void M() { int dummy; int.TryParse(v, out int i1); int.TryParse(v, out int i2); dummy = 42; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task FixAllInDocument8() { await TestInRegularAndScriptAsync( @"class C { void M() { int dummy, {|FixAllInDocument:i1|}, i2; int.TryParse(v, out i1); int.TryParse(v, out i2); dummy = 42; } }", @"class C { void M() { int dummy; int.TryParse(v, out int i1); int.TryParse(v, out int i2); dummy = 42; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task FixAllInDocument9() { await TestInRegularAndScriptAsync( @"class C { void M() { int {|FixAllInDocument:i1|}, dummy, i2; int.TryParse(v, out i1); int.TryParse(v, out i2); dummy = 42; } }", @"class C { void M() { int dummy; int.TryParse(v, out int i1); int.TryParse(v, out int i2); dummy = 42; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task FixAllInDocument10() { await TestInRegularAndScriptAsync( @"class C { void M() { int {|FixAllInDocument:i1|}, i2, dummy; int.TryParse(v, out i1); int.TryParse(v, out i2); dummy = 42; } }", @"class C { void M() { int dummy; int.TryParse(v, out int i1); int.TryParse(v, out int i2); dummy = 42; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task FixAllInDocument11() { await TestInRegularAndScriptAsync( @"class C { void M() { int {|FixAllInDocument:i1|}, i2; int.TryParse(v, out i1); int.TryParse(v, out i2); } }", @"class C { void M() { int.TryParse(v, out int i1); int.TryParse(v, out int i2); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] [WorkItem(28323, "https://github.com/dotnet/roslyn/issues/28323")] public async Task FixAllInDocumentComments1() { await TestInRegularAndScriptAsync( @"class C { void M() { /* leading */ int {|FixAllInDocument:i1|}; int i2; // trailing int.TryParse(v, out i1); int.TryParse(v, out i2); } }", @"class C { void M() { /* leading */ // trailing int.TryParse(v, out int i1); int.TryParse(v, out int i2); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] [WorkItem(28323, "https://github.com/dotnet/roslyn/issues/28323")] public async Task FixAllInDocumentComments2() { await TestInRegularAndScriptAsync( @"class C { void M() { /* leading */ int dummy; /* in-between */ int {|FixAllInDocument:i1|}; int i2; // trailing int.TryParse(v, out i1); int.TryParse(v, out i2); dummy = 42; } }", @"class C { void M() { /* leading */ int dummy; /* in-between */ // trailing int.TryParse(v, out int i1); int.TryParse(v, out int i2); dummy = 42; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] [WorkItem(28323, "https://github.com/dotnet/roslyn/issues/28323")] public async Task FixAllInDocumentComments3() { await TestInRegularAndScriptAsync( @"class C { void M() { int {|FixAllInDocument:i1|}; /* 0 */int /* 1 */ dummy /* 2 */; /* 3*/ int i2; int.TryParse(v, out i1); int.TryParse(v, out i2); dummy = 42; } }", @"class C { void M() { /* 0 */ int /* 1 */ dummy /* 2 */; /* 3*/ int.TryParse(v, out int i1); int.TryParse(v, out int i2); dummy = 42; } }"); } } }
// Licensed to the .NET Foundation under one or more 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.Tasks; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.InlineDeclaration { public partial class CSharpInlineDeclarationTests { [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task FixAllInDocument1() { await TestInRegularAndScriptAsync( @"class C { void M() { int {|FixAllInDocument:i|}, j; if (int.TryParse(v, out i, out j)) { } } }", @"class C { void M() { if (int.TryParse(v, out int i, out int j)) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task FixAllInDocument2() { await TestInRegularAndScriptAsync( @"class C { void M() { {|FixAllInDocument:int|} i; if (int.TryParse(v, out i)) { } } void M1() { int i; if (int.TryParse(v, out i)) { } } }", @"class C { void M() { if (int.TryParse(v, out int i)) { } } void M1() { if (int.TryParse(v, out int i)) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task FixAllInDocument3() { await TestInRegularAndScriptAsync( @"class C { void M() { // Now get final exe and args. CTtrl-F5 wraps exe in cmd prompt string {|FixAllInDocument:finalExecutable|}, finalArguments; GetExeAndArguments(useCmdShell, executable, arguments, out finalExecutable, out finalArguments); } }", @"class C { void M() { // Now get final exe and args. CTtrl-F5 wraps exe in cmd prompt GetExeAndArguments(useCmdShell, executable, arguments, out string finalExecutable, out string finalArguments); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] [WorkItem(29935, "https://github.com/dotnet/roslyn/issues/29935")] public async Task FixAllInDocumentSymbolResolution() { await TestInRegularAndScriptAsync( @"class C { void M() { string {|FixAllInDocument:s|}; bool b; A(out s, out b); } void A(out string s, out bool b) { s = string.Empty; b = false; } void A(out string s, out string s2) { s = s2 = string.Empty; } }", @"class C { void M() { A(out string s, out bool b); } void A(out string s, out bool b) { s = string.Empty; b = false; } void A(out string s, out string s2) { s = s2 = string.Empty; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] [WorkItem(28323, "https://github.com/dotnet/roslyn/issues/28323")] public async Task FixAllInDocument4() { await TestInRegularAndScriptAsync( @"class C { void M() { int {|FixAllInDocument:i1|}; int i2; int.TryParse(v, out i1); int.TryParse(v, out i2); } }", @"class C { void M() { int.TryParse(v, out int i1); int.TryParse(v, out int i2); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] [WorkItem(28323, "https://github.com/dotnet/roslyn/issues/28323")] public async Task FixAllInDocument5() { await TestInRegularAndScriptAsync( @"class C { void M() { int dummy; int {|FixAllInDocument:i1|}; int i2; int.TryParse(v, out i1); int.TryParse(v, out i2); dummy = 42; } }", @"class C { void M() { int dummy; int.TryParse(v, out int i1); int.TryParse(v, out int i2); dummy = 42; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] [WorkItem(28323, "https://github.com/dotnet/roslyn/issues/28323")] public async Task FixAllInDocument6() { await TestInRegularAndScriptAsync( @"class C { void M() { int {|FixAllInDocument:i1|}; int dummy; int i2; int.TryParse(v, out i1); int.TryParse(v, out i2); dummy = 42; } }", @"class C { void M() { int dummy; int.TryParse(v, out int i1); int.TryParse(v, out int i2); dummy = 42; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] [WorkItem(28323, "https://github.com/dotnet/roslyn/issues/28323")] public async Task FixAllInDocument7() { await TestInRegularAndScriptAsync( @"class C { void M() { int {|FixAllInDocument:i1|}; int i2; int dummy; int.TryParse(v, out i1); int.TryParse(v, out i2); dummy = 42; } }", @"class C { void M() { int dummy; int.TryParse(v, out int i1); int.TryParse(v, out int i2); dummy = 42; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task FixAllInDocument8() { await TestInRegularAndScriptAsync( @"class C { void M() { int dummy, {|FixAllInDocument:i1|}, i2; int.TryParse(v, out i1); int.TryParse(v, out i2); dummy = 42; } }", @"class C { void M() { int dummy; int.TryParse(v, out int i1); int.TryParse(v, out int i2); dummy = 42; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task FixAllInDocument9() { await TestInRegularAndScriptAsync( @"class C { void M() { int {|FixAllInDocument:i1|}, dummy, i2; int.TryParse(v, out i1); int.TryParse(v, out i2); dummy = 42; } }", @"class C { void M() { int dummy; int.TryParse(v, out int i1); int.TryParse(v, out int i2); dummy = 42; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task FixAllInDocument10() { await TestInRegularAndScriptAsync( @"class C { void M() { int {|FixAllInDocument:i1|}, i2, dummy; int.TryParse(v, out i1); int.TryParse(v, out i2); dummy = 42; } }", @"class C { void M() { int dummy; int.TryParse(v, out int i1); int.TryParse(v, out int i2); dummy = 42; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task FixAllInDocument11() { await TestInRegularAndScriptAsync( @"class C { void M() { int {|FixAllInDocument:i1|}, i2; int.TryParse(v, out i1); int.TryParse(v, out i2); } }", @"class C { void M() { int.TryParse(v, out int i1); int.TryParse(v, out int i2); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] [WorkItem(28323, "https://github.com/dotnet/roslyn/issues/28323")] public async Task FixAllInDocumentComments1() { await TestInRegularAndScriptAsync( @"class C { void M() { /* leading */ int {|FixAllInDocument:i1|}; int i2; // trailing int.TryParse(v, out i1); int.TryParse(v, out i2); } }", @"class C { void M() { /* leading */ // trailing int.TryParse(v, out int i1); int.TryParse(v, out int i2); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] [WorkItem(28323, "https://github.com/dotnet/roslyn/issues/28323")] public async Task FixAllInDocumentComments2() { await TestInRegularAndScriptAsync( @"class C { void M() { /* leading */ int dummy; /* in-between */ int {|FixAllInDocument:i1|}; int i2; // trailing int.TryParse(v, out i1); int.TryParse(v, out i2); dummy = 42; } }", @"class C { void M() { /* leading */ int dummy; /* in-between */ // trailing int.TryParse(v, out int i1); int.TryParse(v, out int i2); dummy = 42; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] [WorkItem(28323, "https://github.com/dotnet/roslyn/issues/28323")] public async Task FixAllInDocumentComments3() { await TestInRegularAndScriptAsync( @"class C { void M() { int {|FixAllInDocument:i1|}; /* 0 */int /* 1 */ dummy /* 2 */; /* 3*/ int i2; int.TryParse(v, out i1); int.TryParse(v, out i2); dummy = 42; } }", @"class C { void M() { /* 0 */ int /* 1 */ dummy /* 2 */; /* 3*/ int.TryParse(v, out int i1); int.TryParse(v, out int i2); dummy = 42; } }"); } } }
-1
dotnet/roslyn
56,450
Implement INamespaceTypeReference.GetUnit for RootModuleType
Fixes #56412.
AlekseyTs
"2021-09-16T16:44:04Z"
"2021-09-17T18:21:59Z"
4b06ee428bafa0141c9eb3250003a19109dcfc86
d695369176aa109f0e0fb8b0019294aaa0823a54
Implement INamespaceTypeReference.GetUnit for RootModuleType. Fixes #56412.
./src/Compilers/Core/CodeAnalysisTest/CommonSqmUtilitiesTests.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 System.Threading.Tasks; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests { public class CommonSqmUtilitiesTests { [Fact] public void TryGetCompilerDiagnosticCode_Valid() { string diagnosticId = "CS1011"; uint code; var result = CommonCompiler.TryGetCompilerDiagnosticCode(diagnosticId, "CS", out code); Assert.True(result); Assert.Equal(expected: 1011U, actual: code); } [Fact] public void TryGetCompilerDiagnosticCode_Invalid() { string diagnosticId = "MyAwesomeDiagnostic"; uint code; var result = CommonCompiler.TryGetCompilerDiagnosticCode(diagnosticId, "CS", out code); Assert.False(result); } [Fact] public void TryGetCompilerDiagnosticCode_WrongPrefix() { string diagnosticId = "AB1011"; uint code; var result = CommonCompiler.TryGetCompilerDiagnosticCode(diagnosticId, "CS", out code); Assert.False(result); } } }
// Licensed to the .NET Foundation under one or more 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 System.Threading.Tasks; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests { public class CommonSqmUtilitiesTests { [Fact] public void TryGetCompilerDiagnosticCode_Valid() { string diagnosticId = "CS1011"; uint code; var result = CommonCompiler.TryGetCompilerDiagnosticCode(diagnosticId, "CS", out code); Assert.True(result); Assert.Equal(expected: 1011U, actual: code); } [Fact] public void TryGetCompilerDiagnosticCode_Invalid() { string diagnosticId = "MyAwesomeDiagnostic"; uint code; var result = CommonCompiler.TryGetCompilerDiagnosticCode(diagnosticId, "CS", out code); Assert.False(result); } [Fact] public void TryGetCompilerDiagnosticCode_WrongPrefix() { string diagnosticId = "AB1011"; uint code; var result = CommonCompiler.TryGetCompilerDiagnosticCode(diagnosticId, "CS", out code); Assert.False(result); } } }
-1
dotnet/roslyn
56,450
Implement INamespaceTypeReference.GetUnit for RootModuleType
Fixes #56412.
AlekseyTs
"2021-09-16T16:44:04Z"
"2021-09-17T18:21:59Z"
4b06ee428bafa0141c9eb3250003a19109dcfc86
d695369176aa109f0e0fb8b0019294aaa0823a54
Implement INamespaceTypeReference.GetUnit for RootModuleType. Fixes #56412.
./src/Features/Core/Portable/InvertLogical/AbstractInvertLogicalCodeRefactoringProvider.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.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.InvertLogical { /// <summary> /// Code refactoring to help convert code like `!a || !b` to `!(a &amp;&amp; b)` /// </summary> internal abstract class AbstractInvertLogicalCodeRefactoringProvider< TSyntaxKind, TExpressionSyntax, TBinaryExpressionSyntax> : CodeRefactoringProvider where TSyntaxKind : struct where TExpressionSyntax : SyntaxNode where TBinaryExpressionSyntax : TExpressionSyntax { /// <summary> /// See comment in <see cref="InvertLogicalAsync"/> to understand the need for this annotation. /// </summary> private static readonly SyntaxAnnotation s_annotation = new(); protected abstract string GetOperatorText(TSyntaxKind binaryExprKind); public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context) { var (document, span, cancellationToken) = context; var expression = (SyntaxNode?)await context.TryGetRelevantNodeAsync<TBinaryExpressionSyntax>().ConfigureAwait(false); var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); var syntaxKinds = document.GetRequiredLanguageService<ISyntaxKindsService>(); if (expression == null || (!syntaxFacts.IsLogicalAndExpression(expression) && !syntaxFacts.IsLogicalOrExpression(expression))) { return; } if (span.IsEmpty) { // Walk up to the topmost binary of the same type. When converting || to && (or vice versa) // we want to grab the entire set. i.e. `!a && !b && !c` should become `!(a || b || c)` not // `!(a || b) && !c` while (expression.Parent?.RawKind == expression.RawKind) { expression = expression.Parent; } } else { // When selection is non-empty -> allow only top-level full selections. // Currently the refactoring can't handle invert of arbitrary nodes but only whole subtrees // and allowing it just for selection of those nodes that - by chance - form a full subtree // would produce only confusion. if (CodeRefactoringHelpers.IsNodeUnderselected(expression, span) || syntaxFacts.IsLogicalAndExpression(expression.Parent) || syntaxFacts.IsLogicalOrExpression(expression.Parent)) { return; } } context.RegisterRefactoring( new MyCodeAction( GetTitle(syntaxKinds, expression.RawKind), c => InvertLogicalAsync(document, expression, c)), expression.Span); } private static async Task<Document> InvertLogicalAsync( Document document1, SyntaxNode binaryExpression, CancellationToken cancellationToken) { // We invert in two steps. To invert `a op b` we are effectively generating two negations: // `!(!(a op b)`. The inner `!` will distribute on the inside to make `!a op' !b` leaving // us with `!(!a op' !b)`. // Because we need to do two negations, we actually perform the inner one, marking the // result with an annotation, then we do the outer one (making sure we don't descend in // and undo the work we just did). Because our negation helper needs semantics, we generate // a new document at each step so that we'll be able to properly analyze things as we go // along. var document2 = await InvertInnerExpressionAsync(document1, binaryExpression, cancellationToken).ConfigureAwait(false); var document3 = await InvertOuterExpressionAsync(document2, cancellationToken).ConfigureAwait(false); return document3; } private static async Task<Document> InvertInnerExpressionAsync( Document document, SyntaxNode binaryExpression, CancellationToken cancellationToken) { var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var generator = SyntaxGenerator.GetGenerator(document); var newBinary = generator.Negate(generator.SyntaxGeneratorInternal, binaryExpression, semanticModel, cancellationToken); return document.WithSyntaxRoot(root.ReplaceNode( binaryExpression, newBinary.WithAdditionalAnnotations(s_annotation))); } private static async Task<Document> InvertOuterExpressionAsync( Document document, CancellationToken cancellationToken) { var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); var expression = root.GetAnnotatedNodes(s_annotation).Single()!; // Walk up parens and !'s. That way we don't end up with something like !!. // It also ensures that this refactoring reverses itself when invoked twice. while (syntaxFacts.IsParenthesizedExpression(expression.Parent) || syntaxFacts.IsLogicalNotExpression(expression.Parent)) { expression = expression.Parent; } var generator = SyntaxGenerator.GetGenerator(document); // Negate the containing binary expr. Pass the 'negateBinary:false' flag so we don't // just negate the work we're actually doing right now. return document.WithSyntaxRoot(root.ReplaceNode( expression, generator.Negate(generator.SyntaxGeneratorInternal, expression, semanticModel, negateBinary: false, cancellationToken))); } private string GetTitle(ISyntaxKindsService syntaxKinds, int binaryExprKind) => string.Format(FeaturesResources.Replace_0_with_1, GetOperatorText(syntaxKinds.Convert<TSyntaxKind>(binaryExprKind)), GetOperatorText(syntaxKinds.Convert<TSyntaxKind>(InvertedKind(syntaxKinds, binaryExprKind)))); private static int InvertedKind(ISyntaxKindsService syntaxKinds, int binaryExprKind) => binaryExprKind == syntaxKinds.LogicalAndExpression ? syntaxKinds.LogicalOrExpression : syntaxKinds.LogicalAndExpression; private class MyCodeAction : CodeAction.DocumentChangeAction { public MyCodeAction(string title, Func<CancellationToken, Task<Document>> createChangedDocument) : base(title, createChangedDocument, title) { } } } }
// Licensed to the .NET Foundation under one or more 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.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.InvertLogical { /// <summary> /// Code refactoring to help convert code like `!a || !b` to `!(a &amp;&amp; b)` /// </summary> internal abstract class AbstractInvertLogicalCodeRefactoringProvider< TSyntaxKind, TExpressionSyntax, TBinaryExpressionSyntax> : CodeRefactoringProvider where TSyntaxKind : struct where TExpressionSyntax : SyntaxNode where TBinaryExpressionSyntax : TExpressionSyntax { /// <summary> /// See comment in <see cref="InvertLogicalAsync"/> to understand the need for this annotation. /// </summary> private static readonly SyntaxAnnotation s_annotation = new(); protected abstract string GetOperatorText(TSyntaxKind binaryExprKind); public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context) { var (document, span, cancellationToken) = context; var expression = (SyntaxNode?)await context.TryGetRelevantNodeAsync<TBinaryExpressionSyntax>().ConfigureAwait(false); var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); var syntaxKinds = document.GetRequiredLanguageService<ISyntaxKindsService>(); if (expression == null || (!syntaxFacts.IsLogicalAndExpression(expression) && !syntaxFacts.IsLogicalOrExpression(expression))) { return; } if (span.IsEmpty) { // Walk up to the topmost binary of the same type. When converting || to && (or vice versa) // we want to grab the entire set. i.e. `!a && !b && !c` should become `!(a || b || c)` not // `!(a || b) && !c` while (expression.Parent?.RawKind == expression.RawKind) { expression = expression.Parent; } } else { // When selection is non-empty -> allow only top-level full selections. // Currently the refactoring can't handle invert of arbitrary nodes but only whole subtrees // and allowing it just for selection of those nodes that - by chance - form a full subtree // would produce only confusion. if (CodeRefactoringHelpers.IsNodeUnderselected(expression, span) || syntaxFacts.IsLogicalAndExpression(expression.Parent) || syntaxFacts.IsLogicalOrExpression(expression.Parent)) { return; } } context.RegisterRefactoring( new MyCodeAction( GetTitle(syntaxKinds, expression.RawKind), c => InvertLogicalAsync(document, expression, c)), expression.Span); } private static async Task<Document> InvertLogicalAsync( Document document1, SyntaxNode binaryExpression, CancellationToken cancellationToken) { // We invert in two steps. To invert `a op b` we are effectively generating two negations: // `!(!(a op b)`. The inner `!` will distribute on the inside to make `!a op' !b` leaving // us with `!(!a op' !b)`. // Because we need to do two negations, we actually perform the inner one, marking the // result with an annotation, then we do the outer one (making sure we don't descend in // and undo the work we just did). Because our negation helper needs semantics, we generate // a new document at each step so that we'll be able to properly analyze things as we go // along. var document2 = await InvertInnerExpressionAsync(document1, binaryExpression, cancellationToken).ConfigureAwait(false); var document3 = await InvertOuterExpressionAsync(document2, cancellationToken).ConfigureAwait(false); return document3; } private static async Task<Document> InvertInnerExpressionAsync( Document document, SyntaxNode binaryExpression, CancellationToken cancellationToken) { var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var generator = SyntaxGenerator.GetGenerator(document); var newBinary = generator.Negate(generator.SyntaxGeneratorInternal, binaryExpression, semanticModel, cancellationToken); return document.WithSyntaxRoot(root.ReplaceNode( binaryExpression, newBinary.WithAdditionalAnnotations(s_annotation))); } private static async Task<Document> InvertOuterExpressionAsync( Document document, CancellationToken cancellationToken) { var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); var expression = root.GetAnnotatedNodes(s_annotation).Single()!; // Walk up parens and !'s. That way we don't end up with something like !!. // It also ensures that this refactoring reverses itself when invoked twice. while (syntaxFacts.IsParenthesizedExpression(expression.Parent) || syntaxFacts.IsLogicalNotExpression(expression.Parent)) { expression = expression.Parent; } var generator = SyntaxGenerator.GetGenerator(document); // Negate the containing binary expr. Pass the 'negateBinary:false' flag so we don't // just negate the work we're actually doing right now. return document.WithSyntaxRoot(root.ReplaceNode( expression, generator.Negate(generator.SyntaxGeneratorInternal, expression, semanticModel, negateBinary: false, cancellationToken))); } private string GetTitle(ISyntaxKindsService syntaxKinds, int binaryExprKind) => string.Format(FeaturesResources.Replace_0_with_1, GetOperatorText(syntaxKinds.Convert<TSyntaxKind>(binaryExprKind)), GetOperatorText(syntaxKinds.Convert<TSyntaxKind>(InvertedKind(syntaxKinds, binaryExprKind)))); private static int InvertedKind(ISyntaxKindsService syntaxKinds, int binaryExprKind) => binaryExprKind == syntaxKinds.LogicalAndExpression ? syntaxKinds.LogicalOrExpression : syntaxKinds.LogicalAndExpression; private class MyCodeAction : CodeAction.DocumentChangeAction { public MyCodeAction(string title, Func<CancellationToken, Task<Document>> createChangedDocument) : base(title, createChangedDocument, title) { } } } }
-1
dotnet/roslyn
56,450
Implement INamespaceTypeReference.GetUnit for RootModuleType
Fixes #56412.
AlekseyTs
"2021-09-16T16:44:04Z"
"2021-09-17T18:21:59Z"
4b06ee428bafa0141c9eb3250003a19109dcfc86
d695369176aa109f0e0fb8b0019294aaa0823a54
Implement INamespaceTypeReference.GetUnit for RootModuleType. Fixes #56412.
./src/EditorFeatures/Test/EditAndContinue/EditAndContinueWorkspaceServiceTests.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.IO; using System.Linq; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using System.Reflection.PortableExecutable; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Debugging; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.ExternalAccess.UnitTesting.Api; using Microsoft.CodeAnalysis.ExternalAccess.Watch.Api; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.UnitTests; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; using Roslyn.Test.Utilities; using Roslyn.Test.Utilities.TestGenerators; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.EditAndContinue.UnitTests { using static ActiveStatementTestHelpers; [UseExportProvider] public sealed partial class EditAndContinueWorkspaceServiceTests : TestBase { private static readonly TestComposition s_composition = FeaturesTestCompositions.Features; private static readonly ActiveStatementSpanProvider s_noActiveSpans = (_, _, _) => new(ImmutableArray<ActiveStatementSpan>.Empty); private const TargetFramework DefaultTargetFramework = TargetFramework.NetStandard20; private Func<Project, CompilationOutputs> _mockCompilationOutputsProvider; private readonly List<string> _telemetryLog; private int _telemetryId; private readonly MockManagedEditAndContinueDebuggerService _debuggerService; public EditAndContinueWorkspaceServiceTests() { _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(Guid.NewGuid()); _telemetryLog = new List<string>(); _debuggerService = new MockManagedEditAndContinueDebuggerService() { LoadedModules = new Dictionary<Guid, ManagedEditAndContinueAvailability>() }; } private TestWorkspace CreateWorkspace(out Solution solution, out EditAndContinueWorkspaceService service, Type[] additionalParts = null) { var workspace = new TestWorkspace(composition: s_composition.AddParts(additionalParts)); solution = workspace.CurrentSolution; service = GetEditAndContinueService(workspace); return workspace; } private static SourceText GetAnalyzerConfigText((string key, string value)[] analyzerConfig) => SourceText.From("[*.*]" + Environment.NewLine + string.Join(Environment.NewLine, analyzerConfig.Select(c => $"{c.key} = {c.value}"))); private static (Solution, Document) AddDefaultTestProject( Solution solution, string source, ISourceGenerator generator = null, string additionalFileText = null, (string key, string value)[] analyzerConfig = null) { solution = AddDefaultTestProject(solution, new[] { source }, generator, additionalFileText, analyzerConfig); return (solution, solution.Projects.Single().Documents.Single()); } private static Solution AddDefaultTestProject( Solution solution, string[] sources, ISourceGenerator generator = null, string additionalFileText = null, (string key, string value)[] analyzerConfig = null) { var project = solution. AddProject("proj", "proj", LanguageNames.CSharp). WithMetadataReferences(TargetFrameworkUtil.GetReferences(DefaultTargetFramework)); solution = project.Solution; if (generator != null) { solution = solution.AddAnalyzerReference(project.Id, new TestGeneratorReference(generator)); } if (additionalFileText != null) { solution = solution.AddAdditionalDocument(DocumentId.CreateNewId(project.Id), "additional", SourceText.From(additionalFileText)); } if (analyzerConfig != null) { solution = solution.AddAnalyzerConfigDocument( DocumentId.CreateNewId(project.Id), name: "config", GetAnalyzerConfigText(analyzerConfig), filePath: Path.Combine(TempRoot.Root, "config")); } Document document = null; var i = 1; foreach (var source in sources) { var fileName = $"test{i++}.cs"; document = solution.GetProject(project.Id). AddDocument(fileName, SourceText.From(source, Encoding.UTF8), filePath: Path.Combine(TempRoot.Root, fileName)); solution = document.Project.Solution; } return document.Project.Solution; } private EditAndContinueWorkspaceService GetEditAndContinueService(Workspace workspace) { var service = (EditAndContinueWorkspaceService)workspace.Services.GetRequiredService<IEditAndContinueWorkspaceService>(); var accessor = service.GetTestAccessor(); accessor.SetOutputProvider(project => _mockCompilationOutputsProvider(project)); return service; } private async Task<DebuggingSession> StartDebuggingSessionAsync( EditAndContinueWorkspaceService service, Solution solution, CommittedSolution.DocumentState initialState = CommittedSolution.DocumentState.MatchesBuildOutput) { var sessionId = await service.StartDebuggingSessionAsync( solution, _debuggerService, captureMatchingDocuments: ImmutableArray<DocumentId>.Empty, captureAllMatchingDocuments: false, reportDiagnostics: true, CancellationToken.None); var session = service.GetTestAccessor().GetDebuggingSession(sessionId); if (initialState != CommittedSolution.DocumentState.None) { SetDocumentsState(session, solution, initialState); } session.GetTestAccessor().SetTelemetryLogger((id, message) => _telemetryLog.Add($"{id}: {message.GetMessage()}"), () => ++_telemetryId); return session; } private void EnterBreakState( DebuggingSession session, ImmutableArray<ManagedActiveStatementDebugInfo> activeStatements = default, ImmutableArray<DocumentId> documentsWithRudeEdits = default) { _debuggerService.GetActiveStatementsImpl = () => activeStatements.NullToEmpty(); session.BreakStateChanged(inBreakState: true, out var documentsToReanalyze); AssertEx.Equal(documentsWithRudeEdits.NullToEmpty(), documentsToReanalyze); } private void ExitBreakState( DebuggingSession session, ImmutableArray<DocumentId> documentsWithRudeEdits = default) { _debuggerService.GetActiveStatementsImpl = () => ImmutableArray<ManagedActiveStatementDebugInfo>.Empty; session.BreakStateChanged(inBreakState: false, out var documentsToReanalyze); AssertEx.Equal(documentsWithRudeEdits.NullToEmpty(), documentsToReanalyze); } private static void CommitSolutionUpdate(DebuggingSession session, ImmutableArray<DocumentId> documentsWithRudeEdits = default) { session.CommitSolutionUpdate(out var documentsToReanalyze); AssertEx.Equal(documentsWithRudeEdits.NullToEmpty(), documentsToReanalyze); } private static void EndDebuggingSession(DebuggingSession session, ImmutableArray<DocumentId> documentsWithRudeEdits = default) { session.EndSession(out var documentsToReanalyze, out _); AssertEx.Equal(documentsWithRudeEdits.NullToEmpty(), documentsToReanalyze); } private static async Task<(ManagedModuleUpdates updates, ImmutableArray<DiagnosticData> diagnostics)> EmitSolutionUpdateAsync( DebuggingSession session, Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider = null) { var result = await session.EmitSolutionUpdateAsync(solution, activeStatementSpanProvider ?? s_noActiveSpans, CancellationToken.None); return (result.ModuleUpdates, result.GetDiagnosticData(solution)); } internal static void SetDocumentsState(DebuggingSession session, Solution solution, CommittedSolution.DocumentState state) { foreach (var project in solution.Projects) { foreach (var document in project.Documents) { session.LastCommittedSolution.Test_SetDocumentState(document.Id, state); } } } private static IEnumerable<string> InspectDiagnostics(ImmutableArray<DiagnosticData> actual) => actual.Select(d => $"{d.ProjectId} {InspectDiagnostic(d)}"); private static string InspectDiagnostic(DiagnosticData diagnostic) => $"{diagnostic.Severity} {diagnostic.Id}: {diagnostic.Message}"; internal static Guid ReadModuleVersionId(Stream stream) { using var peReader = new PEReader(stream); var metadataReader = peReader.GetMetadataReader(); var mvidHandle = metadataReader.GetModuleDefinition().Mvid; return metadataReader.GetGuid(mvidHandle); } private Guid EmitAndLoadLibraryToDebuggee(string source, string sourceFilePath = null, Encoding encoding = null, string assemblyName = "") { var moduleId = EmitLibrary(source, sourceFilePath, encoding, assemblyName); LoadLibraryToDebuggee(moduleId); return moduleId; } private void LoadLibraryToDebuggee(Guid moduleId, ManagedEditAndContinueAvailability availability = default) { _debuggerService.LoadedModules.Add(moduleId, availability); } private Guid EmitLibrary( string source, string sourceFilePath = null, Encoding encoding = null, string assemblyName = "", DebugInformationFormat pdbFormat = DebugInformationFormat.PortablePdb, ISourceGenerator generator = null, string additionalFileText = null, IEnumerable<(string, string)> analyzerOptions = null) { return EmitLibrary(new[] { (source, sourceFilePath ?? Path.Combine(TempRoot.Root, "test1.cs")) }, encoding, assemblyName, pdbFormat, generator, additionalFileText, analyzerOptions); } private Guid EmitLibrary( (string content, string filePath)[] sources, Encoding encoding = null, string assemblyName = "", DebugInformationFormat pdbFormat = DebugInformationFormat.PortablePdb, ISourceGenerator generator = null, string additionalFileText = null, IEnumerable<(string, string)> analyzerOptions = null) { encoding ??= Encoding.UTF8; var parseOptions = TestOptions.RegularPreview; var trees = sources.Select(source => { var sourceText = SourceText.From(new MemoryStream(encoding.GetBytes(source.content)), encoding, checksumAlgorithm: SourceHashAlgorithm.Sha256); return SyntaxFactory.ParseSyntaxTree(sourceText, parseOptions, source.filePath); }); Compilation compilation = CSharpTestBase.CreateCompilation(trees.ToArray(), options: TestOptions.DebugDll, targetFramework: DefaultTargetFramework, assemblyName: assemblyName); if (generator != null) { var optionsProvider = (analyzerOptions != null) ? new EditAndContinueTestAnalyzerConfigOptionsProvider(analyzerOptions) : null; var additionalTexts = (additionalFileText != null) ? new[] { new InMemoryAdditionalText("additional_file", additionalFileText) } : null; var generatorDriver = CSharpGeneratorDriver.Create(new[] { generator }, additionalTexts, parseOptions, optionsProvider); generatorDriver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics); generatorDiagnostics.Verify(); compilation = outputCompilation; } return EmitLibrary(compilation, pdbFormat); } private Guid EmitLibrary(Compilation compilation, DebugInformationFormat pdbFormat = DebugInformationFormat.PortablePdb) { var (peImage, pdbImage) = compilation.EmitToArrays(new EmitOptions(debugInformationFormat: pdbFormat)); var symReader = SymReaderTestHelpers.OpenDummySymReader(pdbImage); var moduleMetadata = ModuleMetadata.CreateFromImage(peImage); var moduleId = moduleMetadata.GetModuleVersionId(); // associate the binaries with the project (assumes a single project) _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(moduleId) { OpenAssemblyStreamImpl = () => { var stream = new MemoryStream(); peImage.WriteToStream(stream); stream.Position = 0; return stream; }, OpenPdbStreamImpl = () => { var stream = new MemoryStream(); pdbImage.WriteToStream(stream); stream.Position = 0; return stream; } }; return moduleId; } private static SourceText CreateSourceTextFromFile(string path) { using var stream = File.OpenRead(path); return SourceText.From(stream, Encoding.UTF8, SourceHashAlgorithm.Sha256); } private static TextSpan GetSpan(string str, string substr) => new TextSpan(str.IndexOf(substr), substr.Length); private static void VerifyReadersDisposed(IEnumerable<IDisposable> readers) { foreach (var reader in readers) { Assert.Throws<ObjectDisposedException>(() => { if (reader is MetadataReaderProvider md) { md.GetMetadataReader(); } else { ((DebugInformationReaderProvider)reader).CreateEditAndContinueMethodDebugInfoReader(); } }); } } private static DocumentInfo CreateDesignTimeOnlyDocument(ProjectId projectId, string name = "design-time-only.cs", string path = "design-time-only.cs") => DocumentInfo.Create( DocumentId.CreateNewId(projectId, name), name: name, folders: Array.Empty<string>(), sourceCodeKind: SourceCodeKind.Regular, loader: TextLoader.From(TextAndVersion.Create(SourceText.From("class DTO {}"), VersionStamp.Create(), path)), filePath: path, isGenerated: false, designTimeOnly: true, documentServiceProvider: null); internal sealed class FailingTextLoader : TextLoader { public override Task<TextAndVersion> LoadTextAndVersionAsync(Workspace workspace, DocumentId documentId, CancellationToken cancellationToken) { Assert.True(false, $"Content of document {documentId} should never be loaded"); throw ExceptionUtilities.Unreachable; } } private static EditAndContinueLogEntry Row(int rowNumber, TableIndex table, EditAndContinueOperation operation) => new(MetadataTokens.Handle(table, rowNumber), operation); private static unsafe void VerifyEncLogMetadata(ImmutableArray<byte> delta, params EditAndContinueLogEntry[] expectedRows) { fixed (byte* ptr = delta.ToArray()) { var reader = new MetadataReader(ptr, delta.Length); AssertEx.Equal(expectedRows, reader.GetEditAndContinueLogEntries(), itemInspector: EncLogRowToString); } static string EncLogRowToString(EditAndContinueLogEntry row) { TableIndex tableIndex; MetadataTokens.TryGetTableIndex(row.Handle.Kind, out tableIndex); return string.Format( "Row({0}, TableIndex.{1}, EditAndContinueOperation.{2})", MetadataTokens.GetRowNumber(row.Handle), tableIndex, row.Operation); } } private static void GenerateSource(GeneratorExecutionContext context) { foreach (var syntaxTree in context.Compilation.SyntaxTrees) { var fileName = PathUtilities.GetFileName(syntaxTree.FilePath); Generate(syntaxTree.GetText().ToString(), fileName); if (context.AnalyzerConfigOptions.GetOptions(syntaxTree).TryGetValue("enc_generator_output", out var optionValue)) { context.AddSource("GeneratedFromOptions_" + fileName, $"class G {{ int X => {optionValue}; }}"); } } foreach (var additionalFile in context.AdditionalFiles) { Generate(additionalFile.GetText()!.ToString(), PathUtilities.GetFileName(additionalFile.Path)); } void Generate(string source, string fileName) { var generatedSource = GetGeneratedCodeFromMarkedSource(source); if (generatedSource != null) { context.AddSource($"Generated_{fileName}", generatedSource); } } } private static string GetGeneratedCodeFromMarkedSource(string markedSource) { const string OpeningMarker = "/* GENERATE:"; const string ClosingMarker = "*/"; var index = markedSource.IndexOf(OpeningMarker); if (index > 0) { index += OpeningMarker.Length; var closing = markedSource.IndexOf(ClosingMarker, index); return markedSource[index..closing].Trim(); } return null; } [Theory] [CombinatorialData] public async Task StartDebuggingSession_CapturingDocuments(bool captureAllDocuments) { var encodingA = Encoding.BigEndianUnicode; var encodingB = Encoding.Unicode; var encodingC = Encoding.GetEncoding("SJIS"); var encodingE = Encoding.UTF8; var sourceA1 = "class A {}"; var sourceB1 = "class B { int F() => 1; }"; var sourceB2 = "class B { int F() => 2; }"; var sourceB3 = "class B { int F() => 3; }"; var sourceC1 = "class C { const char L = 'ワ'; }"; var sourceD1 = "dummy code"; var sourceE1 = "class E { }"; var sourceBytesA1 = encodingA.GetBytes(sourceA1); var sourceBytesB1 = encodingB.GetBytes(sourceB1); var sourceBytesC1 = encodingC.GetBytes(sourceC1); var sourceBytesE1 = encodingE.GetBytes(sourceE1); var dir = Temp.CreateDirectory(); var sourceFileA = dir.CreateFile("A.cs").WriteAllBytes(sourceBytesA1); var sourceFileB = dir.CreateFile("B.cs").WriteAllBytes(sourceBytesB1); var sourceFileC = dir.CreateFile("C.cs").WriteAllBytes(sourceBytesC1); var sourceFileD = dir.CreateFile("dummy").WriteAllText(sourceD1); var sourceFileE = dir.CreateFile("E.cs").WriteAllBytes(sourceBytesE1); var sourceTreeA1 = SyntaxFactory.ParseSyntaxTree(SourceText.From(sourceBytesA1, sourceBytesA1.Length, encodingA, SourceHashAlgorithm.Sha256), TestOptions.Regular, sourceFileA.Path); var sourceTreeB1 = SyntaxFactory.ParseSyntaxTree(SourceText.From(sourceBytesB1, sourceBytesB1.Length, encodingB, SourceHashAlgorithm.Sha256), TestOptions.Regular, sourceFileB.Path); var sourceTreeC1 = SyntaxFactory.ParseSyntaxTree(SourceText.From(sourceBytesC1, sourceBytesC1.Length, encodingC, SourceHashAlgorithm.Sha1), TestOptions.Regular, sourceFileC.Path); // E is not included in the compilation: var compilation = CSharpTestBase.CreateCompilation(new[] { sourceTreeA1, sourceTreeB1, sourceTreeC1 }, options: TestOptions.DebugDll, targetFramework: DefaultTargetFramework, assemblyName: "P"); EmitLibrary(compilation); // change content of B on disk: sourceFileB.WriteAllText(sourceB2, encodingB); // prepare workspace as if it was loaded from project files: using var _ = CreateWorkspace(out var solution, out var service, new[] { typeof(DummyLanguageService) }); var projectP = solution.AddProject("P", "P", LanguageNames.CSharp); solution = projectP.Solution; var documentIdA = DocumentId.CreateNewId(projectP.Id, debugName: "A"); solution = solution.AddDocument(DocumentInfo.Create( id: documentIdA, name: "A", loader: new FileTextLoader(sourceFileA.Path, encodingA), filePath: sourceFileA.Path)); var documentIdB = DocumentId.CreateNewId(projectP.Id, debugName: "B"); solution = solution.AddDocument(DocumentInfo.Create( id: documentIdB, name: "B", loader: new FileTextLoader(sourceFileB.Path, encodingB), filePath: sourceFileB.Path)); var documentIdC = DocumentId.CreateNewId(projectP.Id, debugName: "C"); solution = solution.AddDocument(DocumentInfo.Create( id: documentIdC, name: "C", loader: new FileTextLoader(sourceFileC.Path, encodingC), filePath: sourceFileC.Path)); var documentIdE = DocumentId.CreateNewId(projectP.Id, debugName: "E"); solution = solution.AddDocument(DocumentInfo.Create( id: documentIdE, name: "E", loader: new FileTextLoader(sourceFileE.Path, encodingE), filePath: sourceFileE.Path)); // check that are testing documents whose hash algorithm does not match the PDB (but the hash itself does): Assert.Equal(SourceHashAlgorithm.Sha1, solution.GetDocument(documentIdA).GetTextSynchronously(default).ChecksumAlgorithm); Assert.Equal(SourceHashAlgorithm.Sha1, solution.GetDocument(documentIdB).GetTextSynchronously(default).ChecksumAlgorithm); Assert.Equal(SourceHashAlgorithm.Sha1, solution.GetDocument(documentIdC).GetTextSynchronously(default).ChecksumAlgorithm); Assert.Equal(SourceHashAlgorithm.Sha1, solution.GetDocument(documentIdE).GetTextSynchronously(default).ChecksumAlgorithm); // design-time-only document with and without absolute path: solution = solution. AddDocument(CreateDesignTimeOnlyDocument(projectP.Id, name: "dt1.cs", path: Path.Combine(dir.Path, "dt1.cs"))). AddDocument(CreateDesignTimeOnlyDocument(projectP.Id, name: "dt2.cs", path: "dt2.cs")); // project that does not support EnC - the contents of documents in this project shouldn't be loaded: var projectQ = solution.AddProject("Q", "Q", DummyLanguageService.LanguageName); solution = projectQ.Solution; solution = solution.AddDocument(DocumentInfo.Create( id: DocumentId.CreateNewId(projectQ.Id, debugName: "D"), name: "D", loader: new FailingTextLoader(), filePath: sourceFileD.Path)); var captureMatchingDocuments = captureAllDocuments ? ImmutableArray<DocumentId>.Empty : (from project in solution.Projects from documentId in project.DocumentIds select documentId).ToImmutableArray(); var sessionId = await service.StartDebuggingSessionAsync(solution, _debuggerService, captureMatchingDocuments, captureAllDocuments, reportDiagnostics: true, CancellationToken.None); var debuggingSession = service.GetTestAccessor().GetDebuggingSession(sessionId); var matchingDocuments = debuggingSession.LastCommittedSolution.Test_GetDocumentStates(); AssertEx.Equal(new[] { "(A, MatchesBuildOutput)", "(C, MatchesBuildOutput)" }, matchingDocuments.Select(e => (solution.GetDocument(e.id).Name, e.state)).OrderBy(e => e.Name).Select(e => e.ToString())); // change content of B on disk again: sourceFileB.WriteAllText(sourceB3, encodingB); solution = solution.WithDocumentTextLoader(documentIdB, new FileTextLoader(sourceFileB.Path, encodingB), PreservationMode.PreserveValue); EnterBreakState(debuggingSession); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(updates.Updates); AssertEx.Equal(new[] { $"{projectP.Id} Warning ENC1005: {string.Format(FeaturesResources.DocumentIsOutOfSyncWithDebuggee, sourceFileB.Path)}" }, InspectDiagnostics(emitDiagnostics)); EndDebuggingSession(debuggingSession); } [Fact] public async Task ProjectNotBuilt() { using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, "class C1 { void M() { System.Console.WriteLine(1); } }"); _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(Guid.Empty); await StartDebuggingSessionAsync(service, solution); // no changes: var diagnostics = await service.GetDocumentDiagnosticsAsync(document1, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); // change the source: solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { System.Console.WriteLine(2); } }")); var document2 = solution.GetDocument(document1.Id); diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); } [Fact] public async Task DifferentDocumentWithSameContent() { var source = "class C1 { void M1() { System.Console.WriteLine(1); } }"; var moduleFile = Temp.CreateFile().WriteAllBytes(TestResources.Basic.Members); using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, source); solution = solution.WithProjectOutputFilePath(document.Project.Id, moduleFile.Path); _mockCompilationOutputsProvider = _ => new CompilationOutputFiles(moduleFile.Path); var debuggingSession = await StartDebuggingSessionAsync(service, solution); // update the document var document1 = solution.GetDocument(document.Id); solution = solution.WithDocumentText(document.Id, SourceText.From(source)); var document2 = solution.GetDocument(document.Id); Assert.Equal(document1.Id, document2.Id); Assert.NotSame(document1, document2); var diagnostics2 = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics2); // validate solution update status and emit - changes made during run mode are ignored: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); EndDebuggingSession(debuggingSession); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=0|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=1" }, _telemetryLog); } [Theory] [CombinatorialData] public async Task ProjectThatDoesNotSupportEnC(bool breakMode) { using var _ = CreateWorkspace(out var solution, out var service, new[] { typeof(DummyLanguageService) }); var project = solution.AddProject("dummy_proj", "dummy_proj", DummyLanguageService.LanguageName); var document = project.AddDocument("test", SourceText.From("dummy1")); solution = document.Project.Solution; var debuggingSession = await StartDebuggingSessionAsync(service, solution); if (breakMode) { EnterBreakState(debuggingSession); } // no changes: var document1 = solution.Projects.Single().Documents.Single(); var diagnostics = await service.GetDocumentDiagnosticsAsync(document1, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); // change the source: solution = solution.WithDocumentText(document1.Id, SourceText.From("dummy2")); // validate solution update status and emit: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); var document2 = solution.GetDocument(document1.Id); diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); } [Fact] public async Task DesignTimeOnlyDocument() { var moduleFile = Temp.CreateFile().WriteAllBytes(TestResources.Basic.Members); using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, "class C1 { void M() { System.Console.WriteLine(1); } }"); var documentInfo = CreateDesignTimeOnlyDocument(document1.Project.Id); solution = solution.WithProjectOutputFilePath(document1.Project.Id, moduleFile.Path).AddDocument(documentInfo); _mockCompilationOutputsProvider = _ => new CompilationOutputFiles(moduleFile.Path); var debuggingSession = await StartDebuggingSessionAsync(service, solution); // update a design-time-only source file: solution = solution.WithDocumentText(documentInfo.Id, SourceText.From("class UpdatedC2 {}")); var document2 = solution.GetDocument(documentInfo.Id); // no updates: var diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); // validate solution update status and emit - changes made in design-time-only documents are ignored: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); EndDebuggingSession(debuggingSession); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=0|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=1" }, _telemetryLog); } [Fact] public async Task DesignTimeOnlyDocument_Dynamic() { using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, "class C {}"); var documentInfo = DocumentInfo.Create( DocumentId.CreateNewId(document.Project.Id), name: "design-time-only.cs", folders: Array.Empty<string>(), sourceCodeKind: SourceCodeKind.Regular, loader: TextLoader.From(TextAndVersion.Create(SourceText.From("class D {}"), VersionStamp.Create(), "design-time-only.cs")), filePath: "design-time-only.cs", isGenerated: false, designTimeOnly: true, documentServiceProvider: null); solution = solution.AddDocument(documentInfo); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source: var document1 = solution.GetDocument(documentInfo.Id); solution = solution.WithDocumentText(document1.Id, SourceText.From("class E {}")); // validate solution update status and emit: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); } [Theory] [InlineData(true)] [InlineData(false)] public async Task DesignTimeOnlyDocument_Wpf(bool delayLoad) { var sourceA = "class A { public void M() { } }"; var sourceB = "class B { public void M() { } }"; var sourceC = "class C { public void M() { } }"; var dir = Temp.CreateDirectory(); var sourceFileA = dir.CreateFile("a.cs").WriteAllText(sourceA); using var _ = CreateWorkspace(out var solution, out var service); // the workspace starts with a version of the source that's not updated with the output of single file generator (or design-time build): var documentA = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)). AddDocument("a.cs", SourceText.From(sourceA, Encoding.UTF8), filePath: sourceFileA.Path); var documentB = documentA.Project. AddDocument("b.g.i.cs", SourceText.From(sourceB, Encoding.UTF8), filePath: "b.g.i.cs"); var documentC = documentB.Project. AddDocument("c.g.i.vb", SourceText.From(sourceC, Encoding.UTF8), filePath: "c.g.i.vb"); solution = documentC.Project.Solution; // only compile A; B and C are design-time-only: var moduleId = EmitLibrary(sourceA, sourceFilePath: sourceFileA.Path); if (!delayLoad) { LoadLibraryToDebuggee(moduleId); } var sessionId = await service.StartDebuggingSessionAsync(solution, _debuggerService, captureMatchingDocuments: ImmutableArray<DocumentId>.Empty, captureAllMatchingDocuments: false, reportDiagnostics: true, CancellationToken.None); var debuggingSession = service.GetTestAccessor().GetDebuggingSession(sessionId); EnterBreakState(debuggingSession); // change the source (rude edit): solution = solution.WithDocumentText(documentB.Id, SourceText.From("class B { public void RenamedMethod() { } }")); solution = solution.WithDocumentText(documentC.Id, SourceText.From("class C { public void RenamedMethod() { } }")); var documentB2 = solution.GetDocument(documentB.Id); var documentC2 = solution.GetDocument(documentC.Id); // no Rude Edits reported: Assert.Empty(await service.GetDocumentDiagnosticsAsync(documentB2, s_noActiveSpans, CancellationToken.None)); Assert.Empty(await service.GetDocumentDiagnosticsAsync(documentC2, s_noActiveSpans, CancellationToken.None)); // validate solution update status and emit: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(emitDiagnostics); if (delayLoad) { LoadLibraryToDebuggee(moduleId); // validate solution update status and emit: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(emitDiagnostics); } EndDebuggingSession(debuggingSession); } [Theory] [CombinatorialData] public async Task ErrorReadingModuleFile(bool breakMode) { // module file is empty, which will cause a read error: var moduleFile = Temp.CreateFile(); string expectedErrorMessage = null; try { using var stream = File.OpenRead(moduleFile.Path); using var peReader = new PEReader(stream); _ = peReader.GetMetadataReader(); } catch (Exception e) { expectedErrorMessage = e.Message; } using var _w = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, "class C1 { void M() { System.Console.WriteLine(1); } }"); _mockCompilationOutputsProvider = _ => new CompilationOutputFiles(moduleFile.Path); var debuggingSession = await StartDebuggingSessionAsync(service, solution); if (breakMode) { EnterBreakState(debuggingSession); } // change the source: solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { System.Console.WriteLine(2); } }")); var document2 = solution.GetDocument(document1.Id); // error not reported here since it might be intermittent and will be reported if the issue persist when applying the update: var diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); AssertEx.Equal(new[] { $"{document2.Project.Id} Error ENC1001: {string.Format(FeaturesResources.ErrorReadingFile, moduleFile.Path, expectedErrorMessage)}" }, InspectDiagnostics(emitDiagnostics)); if (breakMode) { ExitBreakState(debuggingSession); } EndDebuggingSession(debuggingSession); if (breakMode) { AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=2", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=1|InBreakState=True|Capabilities=31", "Debugging_EncSession_EditSession_EmitDeltaErrorId: SessionId=1|EditSessionId=2|ErrorId=ENC1001" }, _telemetryLog); } else { AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=0|EmptySessionCount=0|HotReloadSessionCount=1|EmptyHotReloadSessionCount=0", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=1|InBreakState=False|Capabilities=31", "Debugging_EncSession_EditSession_EmitDeltaErrorId: SessionId=1|EditSessionId=2|ErrorId=ENC1001" }, _telemetryLog); } } [Fact] public async Task ErrorReadingPdbFile() { var source1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("a.cs").WriteAllText(source1); using var _ = CreateWorkspace(out var solution, out var service); var document1 = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)). AddDocument("a.cs", SourceText.From(source1, Encoding.UTF8), filePath: sourceFile.Path); var project = document1.Project; solution = project.Solution; var moduleId = EmitAndLoadLibraryToDebuggee(source1, sourceFilePath: sourceFile.Path); _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(moduleId) { OpenPdbStreamImpl = () => { throw new IOException("Error"); } }; var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); EnterBreakState(debuggingSession); // change the source: solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { System.Console.WriteLine(2); } }", Encoding.UTF8)); var document2 = solution.GetDocument(document1.Id); // error not reported here since it might be intermittent and will be reported if the issue persist when applying the update: var diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); // an error occurred so we need to call update to determine whether we have changes to apply or not: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(updates.Updates); AssertEx.Equal(new[] { $"{project.Id} Warning ENC1006: {string.Format(FeaturesResources.UnableToReadSourceFileOrPdb, sourceFile.Path)}" }, InspectDiagnostics(emitDiagnostics)); EndDebuggingSession(debuggingSession); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=0|EmptySessionCount=1|HotReloadSessionCount=0|EmptyHotReloadSessionCount=1" }, _telemetryLog); } [Fact] public async Task ErrorReadingSourceFile() { var source1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("a.cs").WriteAllText(source1); using var _ = CreateWorkspace(out var solution, out var service); var document1 = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(DefaultTargetFramework)). AddDocument("a.cs", SourceText.From(source1, Encoding.UTF8), filePath: sourceFile.Path); var project = document1.Project; solution = project.Solution; var moduleId = EmitAndLoadLibraryToDebuggee(source1, sourceFilePath: sourceFile.Path); var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); EnterBreakState(debuggingSession); // change the source: solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { System.Console.WriteLine(2); } }", Encoding.UTF8)); var document2 = solution.GetDocument(document1.Id); using var fileLock = File.Open(sourceFile.Path, FileMode.Open, FileAccess.Read, FileShare.None); // error not reported here since it might be intermittent and will be reported if the issue persist when applying the update: var diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); // an error occurred so we need to call update to determine whether we have changes to apply or not: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); // try apply changes: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(updates.Updates); AssertEx.Equal(new[] { $"{project.Id} Warning ENC1006: {string.Format(FeaturesResources.UnableToReadSourceFileOrPdb, sourceFile.Path)}" }, InspectDiagnostics(emitDiagnostics)); fileLock.Dispose(); // try apply changes again: (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); Assert.NotEmpty(updates.Updates); Assert.Empty(emitDiagnostics); EndDebuggingSession(debuggingSession); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=1", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=0|InBreakState=True|Capabilities=31" }, _telemetryLog); } [Theory] [CombinatorialData] public async Task FileAdded(bool breakMode) { var sourceA = "class C1 { void M() { System.Console.WriteLine(1); } }"; var sourceB = "class C2 {}"; var sourceFileA = Temp.CreateFile().WriteAllText(sourceA); var sourceFileB = Temp.CreateFile().WriteAllText(sourceB); using var _ = CreateWorkspace(out var solution, out var service); var documentA = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)). AddDocument("test.cs", SourceText.From(sourceA, Encoding.UTF8), filePath: sourceFileA.Path); solution = documentA.Project.Solution; // Source B will be added while debugging. EmitAndLoadLibraryToDebuggee(sourceA, sourceFilePath: sourceFileA.Path); var project = documentA.Project; var debuggingSession = await StartDebuggingSessionAsync(service, solution); if (breakMode) { EnterBreakState(debuggingSession); } // add a source file: var documentB = project.AddDocument("file2.cs", SourceText.From(sourceB, Encoding.UTF8), filePath: sourceFileB.Path); solution = documentB.Project.Solution; documentB = solution.GetDocument(documentB.Id); var diagnostics2 = await service.GetDocumentDiagnosticsAsync(documentB, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics2); Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); if (breakMode) { ExitBreakState(debuggingSession); } EndDebuggingSession(debuggingSession); if (breakMode) { AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=2", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=0|InBreakState=True|Capabilities=31" }, _telemetryLog); } else { AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=0|EmptySessionCount=0|HotReloadSessionCount=1|EmptyHotReloadSessionCount=0", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=0|InBreakState=False|Capabilities=31" }, _telemetryLog); } } [Fact] public async Task ModuleDisallowsEditAndContinue() { var moduleId = Guid.NewGuid(); var source1 = @" class C1 { void M() { System.Console.WriteLine(1); System.Console.WriteLine(2); System.Console.WriteLine(3); } }"; var source2 = @" class C1 { void M() { System.Console.WriteLine(9); System.Console.WriteLine(); System.Console.WriteLine(30); } }"; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, source1); _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(moduleId); LoadLibraryToDebuggee(moduleId, new ManagedEditAndContinueAvailability(ManagedEditAndContinueAvailabilityStatus.NotAllowedForRuntime, "*message*")); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source: var document1 = solution.Projects.Single().Documents.Single(); solution = solution.WithDocumentText(document1.Id, SourceText.From(source2)); var document2 = solution.GetDocument(document1.Id); // We do not report module diagnostics until emit. // This is to make the analysis deterministic (not dependent on the current state of the debuggee). var diagnostics1 = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Empty(diagnostics1); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); AssertEx.Equal(new[] { $"{document2.Project.Id} Error ENC2016: {string.Format(FeaturesResources.EditAndContinueDisallowedByProject, document2.Project.Name, "*message*")}" }, InspectDiagnostics(emitDiagnostics)); EndDebuggingSession(debuggingSession); AssertEx.SetEqual(new[] { moduleId }, debuggingSession.GetTestAccessor().GetModulesPreparedForUpdate()); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=1", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=1|InBreakState=True|Capabilities=31", "Debugging_EncSession_EditSession_EmitDeltaErrorId: SessionId=1|EditSessionId=2|ErrorId=ENC2016" }, _telemetryLog); } [Fact] public async Task Encodings() { var source1 = "class C1 { void M() { System.Console.WriteLine(\"ã\"); } }"; var encoding = Encoding.GetEncoding(1252); var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("test.cs").WriteAllText(source1, encoding); using var _ = CreateWorkspace(out var solution, out var service); var document1 = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)). AddDocument("test.cs", SourceText.From(source1, encoding), filePath: sourceFile.Path); var documentId = document1.Id; var project = document1.Project; solution = project.Solution; var moduleId = EmitAndLoadLibraryToDebuggee(source1, sourceFilePath: sourceFile.Path, encoding: encoding); var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); EnterBreakState(debuggingSession); // Emulate opening the file, which will trigger "out-of-sync" check. // Since we find content matching the PDB checksum we update the committed solution with this source text. // If we used wrong encoding this would lead to a false change detected below. var currentDocument = solution.GetDocument(documentId); await debuggingSession.OnSourceFileUpdatedAsync(currentDocument); // EnC service queries for a document, which triggers read of the source file from disk. Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); EndDebuggingSession(debuggingSession); } [Theory] [CombinatorialData] public async Task RudeEdits(bool breakMode) { var source1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var source2 = "class C1 { void M1() { System.Console.WriteLine(1); } }"; var moduleId = Guid.NewGuid(); using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, source1); _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); if (breakMode) { EnterBreakState(debuggingSession); } // change the source (rude edit): var document1 = solution.Projects.Single().Documents.Single(); solution = solution.WithDocumentText(document1.Id, SourceText.From(source2, Encoding.UTF8)); var document2 = solution.GetDocument(document1.Id); var diagnostics1 = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Equal(new[] { "ENC0020: " + string.Format(FeaturesResources.Renaming_0_requires_restarting_the_application, FeaturesResources.method) }, diagnostics1.Select(d => $"{d.Id}: {d.GetMessage()}")); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); if (breakMode) { ExitBreakState(debuggingSession, documentsWithRudeEdits: ImmutableArray.Create(document2.Id)); EndDebuggingSession(debuggingSession); } else { EndDebuggingSession(debuggingSession, documentsWithRudeEdits: ImmutableArray.Create(document2.Id)); } AssertEx.SetEqual(new[] { moduleId }, debuggingSession.GetTestAccessor().GetModulesPreparedForUpdate()); if (breakMode) { AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=2", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=True|HadValidChanges=False|HadValidInsignificantChanges=False|RudeEditsCount=1|EmitDeltaErrorIdCount=0|InBreakState=True|Capabilities=31", "Debugging_EncSession_EditSession_RudeEdit: SessionId=1|EditSessionId=2|RudeEditKind=20|RudeEditSyntaxKind=8875|RudeEditBlocking=True" }, _telemetryLog); } else { AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=0|EmptySessionCount=0|HotReloadSessionCount=1|EmptyHotReloadSessionCount=0", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=True|HadValidChanges=False|HadValidInsignificantChanges=False|RudeEditsCount=1|EmitDeltaErrorIdCount=0|InBreakState=False|Capabilities=31", "Debugging_EncSession_EditSession_RudeEdit: SessionId=1|EditSessionId=2|RudeEditKind=20|RudeEditSyntaxKind=8875|RudeEditBlocking=True" }, _telemetryLog); } } [Fact] public async Task RudeEdits_SourceGenerators() { var sourceV1 = @" /* GENERATE: class G { int X1 => 1; } */ class C { int Y => 1; } "; var sourceV2 = @" /* GENERATE: class G { int X2 => 1; } */ class C { int Y => 2; } "; var generator = new TestSourceGenerator() { ExecuteImpl = GenerateSource }; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, sourceV1, generator: generator); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source: var document1 = solution.Projects.Single().Documents.Single(); solution = solution.WithDocumentText(document1.Id, SourceText.From(sourceV2, Encoding.UTF8)); var generatedDocument = (await solution.Projects.Single().GetSourceGeneratedDocumentsAsync()).Single(); var diagnostics1 = await service.GetDocumentDiagnosticsAsync(generatedDocument, s_noActiveSpans, CancellationToken.None); AssertEx.Equal(new[] { "ENC0020: " + string.Format(FeaturesResources.Renaming_0_requires_restarting_the_application, FeaturesResources.property_) }, diagnostics1.Select(d => $"{d.Id}: {d.GetMessage()}")); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); EndDebuggingSession(debuggingSession, documentsWithRudeEdits: ImmutableArray.Create(generatedDocument.Id)); } [Theory] [CombinatorialData] public async Task RudeEdits_DocumentOutOfSync(bool breakMode) { var source0 = "class C1 { void M() { System.Console.WriteLine(0); } }"; var source1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var source2 = "class C1 { void RenamedMethod() { System.Console.WriteLine(1); } }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("a.cs"); using var _ = CreateWorkspace(out var solution, out var service); var project = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)); solution = project.Solution; // compile with source0: var moduleId = EmitAndLoadLibraryToDebuggee(source0, sourceFilePath: sourceFile.Path); // update the file with source1 before session starts: sourceFile.WriteAllText(source1); // source1 is reflected in workspace before session starts: var document1 = project.AddDocument("a.cs", SourceText.From(source1, Encoding.UTF8), filePath: sourceFile.Path); solution = document1.Project.Solution; var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); if (breakMode) { EnterBreakState(debuggingSession); } // change the source (rude edit): solution = solution.WithDocumentText(document1.Id, SourceText.From(source2)); var document2 = solution.GetDocument(document1.Id); // no Rude Edits, since the document is out-of-sync var diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); // since the document is out-of-sync we need to call update to determine whether we have changes to apply or not: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(updates.Updates); AssertEx.Equal(new[] { $"{project.Id} Warning ENC1005: {string.Format(FeaturesResources.DocumentIsOutOfSyncWithDebuggee, sourceFile.Path)}" }, InspectDiagnostics(emitDiagnostics)); // update the file to match the build: sourceFile.WriteAllText(source0); // we do not reload the content of out-of-sync file for analyzer query: diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); // debugger query will trigger reload of out-of-sync file content: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); // now we see the rude edit: diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Equal(new[] { "ENC0020: " + string.Format(FeaturesResources.Renaming_0_requires_restarting_the_application, FeaturesResources.method) }, diagnostics.Select(d => $"{d.Id}: {d.GetMessage()}")); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); if (breakMode) { ExitBreakState(debuggingSession, documentsWithRudeEdits: ImmutableArray.Create(document2.Id)); EndDebuggingSession(debuggingSession); } else { EndDebuggingSession(debuggingSession, documentsWithRudeEdits: ImmutableArray.Create(document2.Id)); } AssertEx.SetEqual(new[] { moduleId }, debuggingSession.GetTestAccessor().GetModulesPreparedForUpdate()); if (breakMode) { AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=2", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=True|HadValidChanges=False|HadValidInsignificantChanges=False|RudeEditsCount=1|EmitDeltaErrorIdCount=0|InBreakState=True|Capabilities=31", "Debugging_EncSession_EditSession_RudeEdit: SessionId=1|EditSessionId=2|RudeEditKind=20|RudeEditSyntaxKind=8875|RudeEditBlocking=True" }, _telemetryLog); } else { AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=0|EmptySessionCount=0|HotReloadSessionCount=1|EmptyHotReloadSessionCount=0", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=True|HadValidChanges=False|HadValidInsignificantChanges=False|RudeEditsCount=1|EmitDeltaErrorIdCount=0|InBreakState=False|Capabilities=31", "Debugging_EncSession_EditSession_RudeEdit: SessionId=1|EditSessionId=2|RudeEditKind=20|RudeEditSyntaxKind=8875|RudeEditBlocking=True" }, _telemetryLog); } } [Fact] public async Task RudeEdits_DocumentWithoutSequencePoints() { var source1 = "abstract class C { public abstract void M(); }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("a.cs").WriteAllText(source1); using var _ = CreateWorkspace(out var solution, out var service); // the workspace starts with a version of the source that's not updated with the output of single file generator (or design-time build): var document1 = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)). AddDocument("test.cs", SourceText.From(source1, Encoding.UTF8), filePath: sourceFile.Path); var project = document1.Project; solution = project.Solution; var moduleId = EmitAndLoadLibraryToDebuggee(source1, sourceFilePath: sourceFile.Path); // do not initialize the document state - we will detect the state based on the PDB content. var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); EnterBreakState(debuggingSession); // change the source (rude edit since the base document content matches the PDB checksum, so the document is not out-of-sync): solution = solution.WithDocumentText(document1.Id, SourceText.From("abstract class C { public abstract void M(); public abstract void N(); }")); var document2 = solution.Projects.Single().Documents.Single(); // Rude Edits reported: var diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Equal( new[] { "ENC0023: " + string.Format(FeaturesResources.Adding_an_abstract_0_or_overriding_an_inherited_0_requires_restarting_the_application, FeaturesResources.method) }, diagnostics.Select(d => $"{d.Id}: {d.GetMessage()}")); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); EndDebuggingSession(debuggingSession, documentsWithRudeEdits: ImmutableArray.Create(document2.Id)); } [Fact] public async Task RudeEdits_DelayLoadedModule() { var source1 = "class C { public void M() { } }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("a.cs").WriteAllText(source1); using var _ = CreateWorkspace(out var solution, out var service); // the workspace starts with a version of the source that's not updated with the output of single file generator (or design-time build): var document1 = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)). AddDocument("test.cs", SourceText.From(source1, Encoding.UTF8), filePath: sourceFile.Path); var project = document1.Project; solution = project.Solution; var moduleId = EmitLibrary(source1, sourceFilePath: sourceFile.Path); // do not initialize the document state - we will detect the state based on the PDB content. var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); EnterBreakState(debuggingSession); // change the source (rude edit) before the library is loaded: solution = solution.WithDocumentText(document1.Id, SourceText.From("class C { public void Renamed() { } }")); var document2 = solution.Projects.Single().Documents.Single(); // Rude Edits reported: var diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Equal( new[] { "ENC0020: " + string.Format(FeaturesResources.Renaming_0_requires_restarting_the_application, FeaturesResources.method) }, diagnostics.Select(d => $"{d.Id}: {d.GetMessage()}")); Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); // load library to the debuggee: LoadLibraryToDebuggee(moduleId); // Rude Edits still reported: diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Equal( new[] { "ENC0020: " + string.Format(FeaturesResources.Renaming_0_requires_restarting_the_application, FeaturesResources.method) }, diagnostics.Select(d => $"{d.Id}: {d.GetMessage()}")); Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); EndDebuggingSession(debuggingSession, documentsWithRudeEdits: ImmutableArray.Create(document2.Id)); } [Fact] public async Task SyntaxError() { var moduleId = Guid.NewGuid(); using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, "class C1 { void M() { System.Console.WriteLine(1); } }"); _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source (compilation error): var document1 = solution.Projects.Single().Documents.Single(); solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { ")); var document2 = solution.Projects.Single().Documents.Single(); // compilation errors are not reported via EnC diagnostic analyzer: var diagnostics1 = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Empty(diagnostics1); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); EndDebuggingSession(debuggingSession); AssertEx.SetEqual(new[] { moduleId }, debuggingSession.GetTestAccessor().GetModulesPreparedForUpdate()); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=1", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=True|HadRudeEdits=False|HadValidChanges=False|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=0|InBreakState=True|Capabilities=31" }, _telemetryLog); } [Fact] public async Task SemanticError() { var sourceV1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, sourceV1); var moduleId = EmitAndLoadLibraryToDebuggee(sourceV1); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source (compilation error): var document1 = solution.Projects.Single().Documents.Single(); solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { int i = 0L; System.Console.WriteLine(i); } }", Encoding.UTF8)); var document2 = solution.Projects.Single().Documents.Single(); // compilation errors are not reported via EnC diagnostic analyzer: var diagnostics1 = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Empty(diagnostics1); // The EnC analyzer does not check for and block on all semantic errors as they are already reported by diagnostic analyzer. // Blocking update on semantic errors would be possible, but the status check is only an optimization to avoid emitting. Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); // TODO: https://github.com/dotnet/roslyn/issues/36061 // Semantic errors should not be reported in emit diagnostics. AssertEx.Equal(new[] { $"{document2.Project.Id} Error CS0266: {string.Format(CSharpResources.ERR_NoImplicitConvCast, "long", "int")}" }, InspectDiagnostics(emitDiagnostics)); EndDebuggingSession(debuggingSession); AssertEx.SetEqual(new[] { moduleId }, debuggingSession.GetTestAccessor().GetModulesPreparedForUpdate()); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=1", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=1|InBreakState=True|Capabilities=31", "Debugging_EncSession_EditSession_EmitDeltaErrorId: SessionId=1|EditSessionId=2|ErrorId=CS0266" }, _telemetryLog); } [Fact] public async Task FileStatus_CompilationError() { using var _ = CreateWorkspace(out var solution, out var service); solution = solution. AddProject("A", "A", "C#"). AddDocument("A.cs", "class Program { void Main() { System.Console.WriteLine(1); } }", filePath: "A.cs").Project.Solution. AddProject("B", "B", "C#"). AddDocument("Common.cs", "class Common {}", filePath: "Common.cs").Project. AddDocument("B.cs", "class B {}", filePath: "B.cs").Project.Solution. AddProject("C", "C", "C#"). AddDocument("Common.cs", "class Common {}", filePath: "Common.cs").Project. AddDocument("C.cs", "class C {}", filePath: "C.cs").Project.Solution; var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change C.cs to have a compilation error: var projectC = solution.GetProjectsByName("C").Single(); var documentC = projectC.Documents.Single(d => d.Name == "C.cs"); solution = solution.WithDocumentText(documentC.Id, SourceText.From("class C { void M() { ")); // Common.cs is included in projects B and C. Both of these projects must have no errors, otherwise update is blocked. Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: "Common.cs", CancellationToken.None)); // No changes in project containing file B.cs. Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: "B.cs", CancellationToken.None)); // All projects must have no errors. Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); EndDebuggingSession(debuggingSession); } [Fact] [WorkItem(1204, "https://github.com/dotnet/roslyn/issues/1204")] [WorkItem(1371694, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371694")] public async Task Project_Add() { var sourceA1 = "class A { void M() { System.Console.WriteLine(1); } }"; var sourceB1 = "class B { int F() => 1; }"; var sourceB2 = "class B { int G() => 1; }"; var sourceB3 = "class B { int F() => 2; }"; var dir = Temp.CreateDirectory(); var sourceFileA = dir.CreateFile("a.cs").WriteAllText(sourceA1); var sourceFileB = dir.CreateFile("b.cs").WriteAllText(sourceB1); using var _ = CreateWorkspace(out var solution, out var service); solution = AddDefaultTestProject(solution, new[] { sourceA1 }); var documentA1 = solution.Projects.Single().Documents.Single(); var mvidA = EmitAndLoadLibraryToDebuggee(sourceA1, sourceFilePath: sourceFileA.Path, assemblyName: "A"); var mvidB = EmitAndLoadLibraryToDebuggee(sourceB1, sourceFilePath: sourceFileB.Path, assemblyName: "B"); var debuggingSession = await StartDebuggingSessionAsync(service, solution); // An active statement may be present in the added file since the file exists in the PDB: var activeLineSpanA1 = SourceText.From(sourceA1, Encoding.UTF8).Lines.GetLinePositionSpan(GetSpan(sourceA1, "System.Console.WriteLine(1);")); var activeLineSpanB1 = SourceText.From(sourceB1, Encoding.UTF8).Lines.GetLinePositionSpan(GetSpan(sourceB1, "1")); var activeStatements = ImmutableArray.Create( new ManagedActiveStatementDebugInfo( new ManagedInstructionId(new ManagedMethodId(mvidA, token: 0x06000001, version: 1), ilOffset: 1), sourceFileA.Path, activeLineSpanA1.ToSourceSpan(), ActiveStatementFlags.IsLeafFrame | ActiveStatementFlags.MethodUpToDate), new ManagedActiveStatementDebugInfo( new ManagedInstructionId(new ManagedMethodId(mvidB, token: 0x06000001, version: 1), ilOffset: 1), sourceFileB.Path, activeLineSpanB1.ToSourceSpan(), ActiveStatementFlags.IsLeafFrame | ActiveStatementFlags.MethodUpToDate)); EnterBreakState(debuggingSession, activeStatements); // add project that matches assembly B and update the document: var documentB2 = solution. AddProject("B", "B", LanguageNames.CSharp). AddDocument("b.cs", SourceText.From(sourceB2, Encoding.UTF8, SourceHashAlgorithm.Sha256), filePath: sourceFileB.Path); solution = documentB2.Project.Solution; // TODO: https://github.com/dotnet/roslyn/issues/1204 // Should return span in document B since the document content matches the PDB. var baseSpans = await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(documentA1.Id, documentB2.Id), CancellationToken.None); AssertEx.Equal(new[] { "<empty>", "(0,21)-(0,22)" }, baseSpans.Select(spans => spans.IsEmpty ? "<empty>" : string.Join(",", spans.Select(s => s.LineSpan.ToString())))); var trackedActiveSpans = ImmutableArray.Create( new ActiveStatementSpan(1, activeLineSpanB1, ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame, unmappedDocumentId: null)); var currentSpans = await debuggingSession.GetAdjustedActiveStatementSpansAsync(documentB2, (_, _, _) => new(trackedActiveSpans), CancellationToken.None); // TODO: https://github.com/dotnet/roslyn/issues/1204 // AssertEx.Equal(trackedActiveSpans, currentSpans); Assert.Empty(currentSpans); Assert.Equal(activeLineSpanB1, await debuggingSession.GetCurrentActiveStatementPositionAsync(documentB2.Project.Solution, (_, _, _) => new(trackedActiveSpans), activeStatements[1].ActiveInstruction, CancellationToken.None)); var diagnostics = await service.GetDocumentDiagnosticsAsync(documentB2, s_noActiveSpans, CancellationToken.None); // TODO: https://github.com/dotnet/roslyn/issues/1204 //AssertEx.Equal( // new[] { "ENC0020: " + string.Format(FeaturesResources.Renaming_0_requires_restarting_the_application, FeaturesResources.method) }, // diagnostics.Select(d => $"{d.Id}: {d.GetMessage()}")); Assert.Empty(diagnostics); // update document with a valid change: solution = solution.WithDocumentText(documentB2.Id, SourceText.From(sourceB3, Encoding.UTF8, SourceHashAlgorithm.Sha256)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); // TODO: https://github.com/dotnet/roslyn/issues/1204 // verify valid update Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); ExitBreakState(debuggingSession); EndDebuggingSession(debuggingSession); } [Fact] public async Task Capabilities() { var source1 = "class C { void M() { } }"; var source2 = "[System.Obsolete]class C { void M() { } }"; using var _ = CreateWorkspace(out var solution, out var service); solution = AddDefaultTestProject(solution, new[] { source1 }); var documentId = solution.Projects.Single().Documents.Single().Id; EmitAndLoadLibraryToDebuggee(source1); // attached to processes that allow updating custom attributes: _debuggerService.GetCapabilitiesImpl = () => ImmutableArray.Create("Baseline", "ChangeCustomAttributes"); // F5 var debuggingSession = await StartDebuggingSessionAsync(service, solution); // update document: solution = solution.WithDocumentText(documentId, SourceText.From(source2, Encoding.UTF8)); var diagnostics = await service.GetDocumentDiagnosticsAsync(solution.GetDocument(documentId), s_noActiveSpans, CancellationToken.None); AssertEx.Empty(diagnostics); EnterBreakState(debuggingSession); diagnostics = await service.GetDocumentDiagnosticsAsync(solution.GetDocument(documentId), s_noActiveSpans, CancellationToken.None); AssertEx.Empty(diagnostics); // attach to additional processes - at least one process that does not allow updating custom attributes: ExitBreakState(debuggingSession); _debuggerService.GetCapabilitiesImpl = () => ImmutableArray.Create("Baseline"); EnterBreakState(debuggingSession); diagnostics = await service.GetDocumentDiagnosticsAsync(solution.GetDocument(documentId), s_noActiveSpans, CancellationToken.None); AssertEx.Equal(new[] { "ENC0101: " + string.Format(FeaturesResources.Updating_the_attributes_of_0_requires_restarting_the_application_because_it_is_not_supported_by_the_runtime, FeaturesResources.class_) }, diagnostics.Select(d => $"{d.Id}: {d.GetMessage()}")); ExitBreakState(debuggingSession, documentsWithRudeEdits: ImmutableArray.Create(documentId)); diagnostics = await service.GetDocumentDiagnosticsAsync(solution.GetDocument(documentId), s_noActiveSpans, CancellationToken.None); AssertEx.Equal(new[] { "ENC0101: " + string.Format(FeaturesResources.Updating_the_attributes_of_0_requires_restarting_the_application_because_it_is_not_supported_by_the_runtime, FeaturesResources.class_) }, diagnostics.Select(d => $"{d.Id}: {d.GetMessage()}")); // detach from processes that do not allow updating custom attributes: _debuggerService.GetCapabilitiesImpl = () => ImmutableArray.Create("Baseline", "ChangeCustomAttributes"); EnterBreakState(debuggingSession, documentsWithRudeEdits: ImmutableArray.Create(documentId)); diagnostics = await service.GetDocumentDiagnosticsAsync(solution.GetDocument(documentId), s_noActiveSpans, CancellationToken.None); AssertEx.Empty(diagnostics); ExitBreakState(debuggingSession); EndDebuggingSession(debuggingSession); } [Fact] public async Task Capabilities_SynthesizedNewType() { var source1 = "class C { void M() { } }"; var source2 = "class C { void M() { var x = new { Goo = 1 }; } }"; using var _ = CreateWorkspace(out var solution, out var service); solution = AddDefaultTestProject(solution, new[] { source1 }); var project = solution.Projects.Single(); solution = solution.WithProjectParseOptions(project.Id, new CSharpParseOptions(LanguageVersion.CSharp10)); var documentId = solution.Projects.Single().Documents.Single().Id; EmitAndLoadLibraryToDebuggee(source1); // attached to processes that doesn't allow creating new types _debuggerService.GetCapabilitiesImpl = () => ImmutableArray.Create("Baseline"); // F5 var debuggingSession = await StartDebuggingSessionAsync(service, solution); // update document: solution = solution.WithDocumentText(documentId, SourceText.From(source2, Encoding.UTF8)); var document2 = solution.Projects.Single().Documents.Single(); // These errors aren't reported as document diagnostics var diagnostics = await service.GetDocumentDiagnosticsAsync(solution.GetDocument(documentId), s_noActiveSpans, CancellationToken.None); AssertEx.Empty(diagnostics); // They are reported as emit diagnostics var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); AssertEx.Equal(new[] { $"{document2.Project.Id} Error ENC1007: {FeaturesResources.ChangesRequiredSynthesizedType}" }, InspectDiagnostics(emitDiagnostics)); // no emitted delta: Assert.Empty(updates.Updates); EndDebuggingSession(debuggingSession); } [Fact] public async Task ValidSignificantChange_EmitError() { var sourceV1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, sourceV1); EmitAndLoadLibraryToDebuggee(sourceV1); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source (valid edit but passing no encoding to emulate emit error): var document1 = solution.Projects.Single().Documents.Single(); solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { System.Console.WriteLine(2); } }", encoding: null)); var document2 = solution.Projects.Single().Documents.Single(); var diagnostics1 = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Empty(diagnostics1); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); AssertEx.Equal(new[] { $"{document2.Project.Id} Error CS8055: {string.Format(CSharpResources.ERR_EncodinglessSyntaxTree)}" }, InspectDiagnostics(emitDiagnostics)); // no emitted delta: Assert.Empty(updates.Updates); // no pending update: Assert.Null(debuggingSession.GetTestAccessor().GetPendingSolutionUpdate()); Assert.Throws<InvalidOperationException>(() => debuggingSession.CommitSolutionUpdate(out var _)); Assert.Throws<InvalidOperationException>(() => debuggingSession.DiscardSolutionUpdate()); // no change in non-remappable regions since we didn't have any active statements: Assert.Empty(debuggingSession.EditSession.NonRemappableRegions); // solution update status after discarding an update (still has update ready): Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); EndDebuggingSession(debuggingSession); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=1", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=1|InBreakState=True|Capabilities=31", "Debugging_EncSession_EditSession_EmitDeltaErrorId: SessionId=1|EditSessionId=2|ErrorId=CS8055" }, _telemetryLog); } [Theory] [InlineData(true)] [InlineData(false)] public async Task ValidSignificantChange_ApplyBeforeFileWatcherEvent(bool saveDocument) { // Scenarios tested: // // SaveDocument=true // workspace: --V0-------------|--V2--------|------------| // file system: --V0---------V1--|-----V2-----|------------| // \--build--/ F5 ^ F10 ^ F10 // save file watcher: no-op // SaveDocument=false // workspace: --V0-------------|--V2--------|----V1------| // file system: --V0---------V1--|------------|------------| // \--build--/ F5 F10 ^ F10 // file watcher: workspace update var source1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("test.cs").WriteAllText(source1); using var _ = CreateWorkspace(out var solution, out var service); // the workspace starts with a version of the source that's not updated with the output of single file generator (or design-time build): var document1 = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(DefaultTargetFramework)). AddDocument("test.cs", SourceText.From("class C1 { void M() { System.Console.WriteLine(0); } }", Encoding.UTF8), filePath: sourceFile.Path); var documentId = document1.Id; solution = document1.Project.Solution; var moduleId = EmitAndLoadLibraryToDebuggee(source1, sourceFilePath: sourceFile.Path); var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); EnterBreakState(debuggingSession); // The user opens the source file and changes the source before Roslyn receives file watcher event. var source2 = "class C1 { void M() { System.Console.WriteLine(2); } }"; solution = solution.WithDocumentText(documentId, SourceText.From(source2, Encoding.UTF8)); var document2 = solution.GetDocument(documentId); // Save the document: if (saveDocument) { await debuggingSession.OnSourceFileUpdatedAsync(document2); sourceFile.WriteAllText(source2); } // EnC service queries for a document, which triggers read of the source file from disk. Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); CommitSolutionUpdate(debuggingSession); ExitBreakState(debuggingSession); EnterBreakState(debuggingSession); // file watcher updates the workspace: solution = solution.WithDocumentText(documentId, CreateSourceTextFromFile(sourceFile.Path)); var document3 = solution.Projects.Single().Documents.Single(); var hasChanges = await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); if (saveDocument) { Assert.False(hasChanges); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); } else { Assert.True(hasChanges); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); } ExitBreakState(debuggingSession); EndDebuggingSession(debuggingSession); } [Fact] public async Task ValidSignificantChange_FileUpdateNotObservedBeforeDebuggingSessionStart() { // workspace: --V0--------------V2-------|--------V3------------------V1--------------| // file system: --V0---------V1-----V2-----|------------------------------V1------------| // \--build--/ ^save F5 ^ ^F10 (no change) ^save F10 (ok) // file watcher: no-op // build updates file from V0 -> V1 var source1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var source2 = "class C1 { void M() { System.Console.WriteLine(2); } }"; var source3 = "class C1 { void M() { System.Console.WriteLine(3); } }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("test.cs").WriteAllText(source2); using var _ = CreateWorkspace(out var solution, out var service); // the workspace starts with a version of the source that's not updated with the output of single file generator (or design-time build): var document2 = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)). AddDocument("test.cs", SourceText.From(source2, Encoding.UTF8), filePath: sourceFile.Path); var documentId = document2.Id; var project = document2.Project; solution = project.Solution; var moduleId = EmitAndLoadLibraryToDebuggee(source1, sourceFilePath: sourceFile.Path); var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); EnterBreakState(debuggingSession); // user edits the file: solution = solution.WithDocumentText(documentId, SourceText.From(source3, Encoding.UTF8)); var document3 = solution.Projects.Single().Documents.Single(); // EnC service queries for a document, but the source file on disk doesn't match the PDB // We don't report rude edits for out-of-sync documents: var diagnostics = await service.GetDocumentDiagnosticsAsync(document3, s_noActiveSpans, CancellationToken.None); AssertEx.Empty(diagnostics); // since the document is out-of-sync we need to call update to determine whether we have changes to apply or not: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); AssertEx.Equal(new[] { $"{project.Id} Warning ENC1005: {string.Format(FeaturesResources.DocumentIsOutOfSyncWithDebuggee, sourceFile.Path)}" }, InspectDiagnostics(emitDiagnostics)); // undo: solution = solution.WithDocumentText(documentId, SourceText.From(source1, Encoding.UTF8)); var currentDocument = solution.GetDocument(documentId); // save (note that this call will fail to match the content with the PDB since it uses the content prior to the actual file write) await debuggingSession.OnSourceFileUpdatedAsync(currentDocument); var (doc, state) = await debuggingSession.LastCommittedSolution.GetDocumentAndStateAsync(documentId, currentDocument, CancellationToken.None); Assert.Null(doc); Assert.Equal(CommittedSolution.DocumentState.OutOfSync, state); sourceFile.WriteAllText(source1); Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); // the content actually hasn't changed: Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); EndDebuggingSession(debuggingSession); } [Fact] public async Task ValidSignificantChange_AddedFileNotObservedBeforeDebuggingSessionStart() { // workspace: ------|----V0---------------|---------- // file system: --V0--|---------------------|---------- // F5 ^ ^F10 (no change) // file watcher observes the file var source1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("test.cs").WriteAllText(source1); using var _ = CreateWorkspace(out var solution, out var service); // the workspace starts with no file var project = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)); solution = project.Solution; var moduleId = EmitAndLoadLibraryToDebuggee(source1, sourceFilePath: sourceFile.Path); _debuggerService.IsEditAndContinueAvailable = _ => new ManagedEditAndContinueAvailability(ManagedEditAndContinueAvailabilityStatus.Attach, localizedMessage: "*attached*"); var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); // An active statement may be present in the added file since the file exists in the PDB: var activeInstruction1 = new ManagedInstructionId(new ManagedMethodId(moduleId, token: 0x06000001, version: 1), ilOffset: 1); var activeSpan1 = GetSpan(source1, "System.Console.WriteLine(1);"); var sourceText1 = SourceText.From(source1, Encoding.UTF8); var activeLineSpan1 = sourceText1.Lines.GetLinePositionSpan(activeSpan1); var activeStatements = ImmutableArray.Create( new ManagedActiveStatementDebugInfo( activeInstruction1, "test.cs", activeLineSpan1.ToSourceSpan(), ActiveStatementFlags.IsLeafFrame)); // disallow any edits (attach scenario) EnterBreakState(debuggingSession, activeStatements); // File watcher observes the document and adds it to the workspace: var document1 = project.AddDocument("test.cs", sourceText1, filePath: sourceFile.Path); solution = document1.Project.Solution; // We don't report rude edits for the added document: var diagnostics = await service.GetDocumentDiagnosticsAsync(document1, s_noActiveSpans, CancellationToken.None); AssertEx.Empty(diagnostics); // TODO: https://github.com/dotnet/roslyn/issues/49938 // We currently create the AS map against the committed solution, which may not contain all documents. // var spans = await service.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(document1.Id), CancellationToken.None); // AssertEx.Equal(new[] { $"({activeLineSpan1}, IsLeafFrame)" }, spans.Single().Select(s => s.ToString())); // No changes. Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); AssertEx.Empty(emitDiagnostics); EndDebuggingSession(debuggingSession); } [Theory] [CombinatorialData] public async Task ValidSignificantChange_DocumentOutOfSync(bool delayLoad) { var sourceOnDisk = "class C1 { void M() { System.Console.WriteLine(1); } }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("test.cs").WriteAllText(sourceOnDisk); using var _ = CreateWorkspace(out var solution, out var service); // the workspace starts with a version of the source that's not updated with the output of single file generator (or design-time build): var document1 = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)). AddDocument("test.cs", SourceText.From("class C1 { void M() { System.Console.WriteLine(0); } }", Encoding.UTF8), filePath: sourceFile.Path); var project = document1.Project; solution = project.Solution; var moduleId = EmitLibrary(sourceOnDisk, sourceFilePath: sourceFile.Path); if (!delayLoad) { LoadLibraryToDebuggee(moduleId); } var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); EnterBreakState(debuggingSession); // no changes have been made to the project Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); // a file watcher observed a change and updated the document, so it now reflects the content on disk (the code that we compiled): solution = solution.WithDocumentText(document1.Id, SourceText.From(sourceOnDisk, Encoding.UTF8)); var document3 = solution.Projects.Single().Documents.Single(); var diagnostics = await service.GetDocumentDiagnosticsAsync(document3, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); // the content of the file is now exactly the same as the compiled document, so there is no change to be applied: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(emitDiagnostics); EndDebuggingSession(debuggingSession); Assert.Empty(debuggingSession.GetTestAccessor().GetModulesPreparedForUpdate()); } [Theory] [CombinatorialData] public async Task ValidSignificantChange_EmitSuccessful(bool breakMode, bool commitUpdate) { var sourceV1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var sourceV2 = "class C1 { void M() { System.Console.WriteLine(2); } }"; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, sourceV1); var moduleId = EmitAndLoadLibraryToDebuggee(sourceV1); var debuggingSession = await StartDebuggingSessionAsync(service, solution); if (breakMode) { EnterBreakState(debuggingSession); } // change the source (valid edit): solution = solution.WithDocumentText(document1.Id, SourceText.From(sourceV2, Encoding.UTF8)); var document2 = solution.GetDocument(document1.Id); var diagnostics1 = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Empty(diagnostics1); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); ValidateDelta(updates.Updates.Single()); void ValidateDelta(ManagedModuleUpdate delta) { // check emitted delta: Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Equal(0x06000001, delta.UpdatedMethods.Single()); Assert.Equal(0x02000002, delta.UpdatedTypes.Single()); Assert.Equal(moduleId, delta.Module); Assert.Empty(delta.ExceptionRegions); Assert.Empty(delta.SequencePoints); } // the update should be stored on the service: var pendingUpdate = debuggingSession.GetTestAccessor().GetPendingSolutionUpdate(); var (baselineProjectId, newBaseline) = pendingUpdate.EmitBaselines.Single(); AssertEx.Equal(updates.Updates, pendingUpdate.Deltas); Assert.Equal(document2.Project.Id, baselineProjectId); Assert.Equal(moduleId, newBaseline.OriginalMetadata.GetModuleVersionId()); var readers = debuggingSession.GetTestAccessor().GetBaselineModuleReaders(); Assert.Equal(2, readers.Length); Assert.NotNull(readers[0]); Assert.NotNull(readers[1]); if (commitUpdate) { // all update providers either provided updates or had no change to apply: CommitSolutionUpdate(debuggingSession); Assert.Null(debuggingSession.GetTestAccessor().GetPendingSolutionUpdate()); // no change in non-remappable regions since we didn't have any active statements: Assert.Empty(debuggingSession.EditSession.NonRemappableRegions); var baselineReaders = debuggingSession.GetTestAccessor().GetBaselineModuleReaders(); Assert.Equal(2, baselineReaders.Length); Assert.Same(readers[0], baselineReaders[0]); Assert.Same(readers[1], baselineReaders[1]); // verify that baseline is added: Assert.Same(newBaseline, debuggingSession.GetTestAccessor().GetProjectEmitBaseline(document2.Project.Id)); // solution update status after committing an update: var commitedUpdateSolutionStatus = await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None); Assert.False(commitedUpdateSolutionStatus); } else { // another update provider blocked the update: debuggingSession.DiscardSolutionUpdate(); Assert.Null(debuggingSession.GetTestAccessor().GetPendingSolutionUpdate()); // solution update status after committing an update: var discardedUpdateSolutionStatus = await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None); Assert.True(discardedUpdateSolutionStatus); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); ValidateDelta(updates.Updates.Single()); } if (breakMode) { ExitBreakState(debuggingSession); } EndDebuggingSession(debuggingSession); // open module readers should be disposed when the debugging session ends: VerifyReadersDisposed(readers); AssertEx.SetEqual(new[] { moduleId }, debuggingSession.GetTestAccessor().GetModulesPreparedForUpdate()); if (breakMode) { AssertEx.Equal(new[] { $"Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount={(commitUpdate ? 3 : 2)}", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=0|InBreakState=True|Capabilities=31", }, _telemetryLog); } else { AssertEx.Equal(new[] { $"Debugging_EncSession: SessionId=1|SessionCount=0|EmptySessionCount=0|HotReloadSessionCount=1|EmptyHotReloadSessionCount={(commitUpdate ? 1 : 0)}", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=0|InBreakState=False|Capabilities=31" }, _telemetryLog); } } [Theory] [InlineData(true)] [InlineData(false)] public async Task ValidSignificantChange_EmitSuccessful_UpdateDeferred(bool commitUpdate) { var dir = Temp.CreateDirectory(); var sourceV1 = "class C1 { void M1() { int a = 1; System.Console.WriteLine(a); } void M2() { System.Console.WriteLine(1); } }"; var compilationV1 = CSharpTestBase.CreateCompilation(sourceV1, options: TestOptions.DebugDll, targetFramework: DefaultTargetFramework, assemblyName: "lib"); var (peImage, pdbImage) = compilationV1.EmitToArrays(new EmitOptions(debugInformationFormat: DebugInformationFormat.PortablePdb)); var moduleMetadata = ModuleMetadata.CreateFromImage(peImage); var moduleFile = dir.CreateFile("lib.dll").WriteAllBytes(peImage); var pdbFile = dir.CreateFile("lib.pdb").WriteAllBytes(pdbImage); var moduleId = moduleMetadata.GetModuleVersionId(); using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, sourceV1); _mockCompilationOutputsProvider = _ => new CompilationOutputFiles(moduleFile.Path, pdbFile.Path); // set up an active statement in the first method, so that we can test preservation of local signature. var activeStatements = ImmutableArray.Create(new ManagedActiveStatementDebugInfo( new ManagedInstructionId(new ManagedMethodId(moduleId, token: 0x06000001, version: 1), ilOffset: 0), documentName: document1.Name, sourceSpan: new SourceSpan(0, 15, 0, 16), ActiveStatementFlags.IsLeafFrame)); var debuggingSession = await StartDebuggingSessionAsync(service, solution); // module is not loaded: EnterBreakState(debuggingSession, activeStatements); // change the source (valid edit): solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M1() { int a = 1; System.Console.WriteLine(a); } void M2() { System.Console.WriteLine(2); } }", Encoding.UTF8)); var document2 = solution.GetDocument(document1.Id); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); Assert.Empty(emitDiagnostics); // delta to apply: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Equal(0x06000002, delta.UpdatedMethods.Single()); Assert.Equal(0x02000002, delta.UpdatedTypes.Single()); Assert.Equal(moduleId, delta.Module); Assert.Empty(delta.ExceptionRegions); Assert.Empty(delta.SequencePoints); // the update should be stored on the service: var pendingUpdate = debuggingSession.GetTestAccessor().GetPendingSolutionUpdate(); var (baselineProjectId, newBaseline) = pendingUpdate.EmitBaselines.Single(); var readers = debuggingSession.GetTestAccessor().GetBaselineModuleReaders(); Assert.Equal(2, readers.Length); Assert.NotNull(readers[0]); Assert.NotNull(readers[1]); Assert.Equal(document2.Project.Id, baselineProjectId); Assert.Equal(moduleId, newBaseline.OriginalMetadata.GetModuleVersionId()); if (commitUpdate) { CommitSolutionUpdate(debuggingSession); Assert.Null(debuggingSession.GetTestAccessor().GetPendingSolutionUpdate()); // no change in non-remappable regions since we didn't have any active statements: Assert.Empty(debuggingSession.EditSession.NonRemappableRegions); // verify that baseline is added: Assert.Same(newBaseline, debuggingSession.GetTestAccessor().GetProjectEmitBaseline(document2.Project.Id)); // solution update status after committing an update: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); ExitBreakState(debuggingSession); // make another update: EnterBreakState(debuggingSession); // Update M1 - this method has an active statement, so we will attempt to preserve the local signature. // Since the method hasn't been edited before we'll read the baseline PDB to get the signature token. // This validates that the Portable PDB reader can be used (and is not disposed) for a second generation edit. var document3 = solution.GetDocument(document1.Id); solution = solution.WithDocumentText(document3.Id, SourceText.From("class C1 { void M1() { int a = 3; System.Console.WriteLine(a); } void M2() { System.Console.WriteLine(2); } }", Encoding.UTF8)); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); Assert.Empty(emitDiagnostics); } else { debuggingSession.DiscardSolutionUpdate(); Assert.Null(debuggingSession.GetTestAccessor().GetPendingSolutionUpdate()); } ExitBreakState(debuggingSession); EndDebuggingSession(debuggingSession); // open module readers should be disposed when the debugging session ends: VerifyReadersDisposed(readers); } [Fact] public async Task ValidSignificantChange_PartialTypes() { var sourceA1 = @" partial class C { int X = 1; void F() { X = 1; } } partial class D { int U = 1; public D() { } } partial class D { int W = 1; } partial class E { int A; public E(int a) { A = a; } } "; var sourceB1 = @" partial class C { int Y = 1; } partial class E { int B; public E(int a, int b) { A = a; B = new System.Func<int>(() => b)(); } } "; var sourceA2 = @" partial class C { int X = 2; void F() { X = 2; } } partial class D { int U = 2; } partial class D { int W = 2; public D() { } } partial class E { int A = 1; public E(int a) { A = a; } } "; var sourceB2 = @" partial class C { int Y = 2; } partial class E { int B = 2; public E(int a, int b) { A = a; B = new System.Func<int>(() => b)(); } } "; using var _ = CreateWorkspace(out var solution, out var service); solution = AddDefaultTestProject(solution, new[] { sourceA1, sourceB1 }); var project = solution.Projects.Single(); LoadLibraryToDebuggee(EmitLibrary(new[] { (sourceA1, "test1.cs"), (sourceB1, "test2.cs") })); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source (valid edit): var documentA = project.Documents.First(); var documentB = project.Documents.Skip(1).First(); solution = solution.WithDocumentText(documentA.Id, SourceText.From(sourceA2, Encoding.UTF8)); solution = solution.WithDocumentText(documentB.Id, SourceText.From(sourceB2, Encoding.UTF8)); // validate solution update status and emit: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); // check emitted delta: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Equal(6, delta.UpdatedMethods.Length); // F, C.C(), D.D(), E.E(int), E.E(int, int), lambda AssertEx.SetEqual(new[] { 0x02000002, 0x02000003, 0x02000004, 0x02000005 }, delta.UpdatedTypes, itemInspector: t => "0x" + t.ToString("X")); EndDebuggingSession(debuggingSession); } [Fact] public async Task ValidSignificantChange_SourceGenerators_DocumentUpdate_GeneratedDocumentUpdate() { var sourceV1 = @" /* GENERATE: class G { int X => 1; } */ class C { int Y => 1; } "; var sourceV2 = @" /* GENERATE: class G { int X => 2; } */ class C { int Y => 2; } "; var generator = new TestSourceGenerator() { ExecuteImpl = GenerateSource }; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, sourceV1, generator); var moduleId = EmitLibrary(sourceV1, generator: generator); LoadLibraryToDebuggee(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source (valid edit) solution = solution.WithDocumentText(document1.Id, SourceText.From(sourceV2, Encoding.UTF8)); // validate solution update status and emit: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); // check emitted delta: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Equal(2, delta.UpdatedMethods.Length); AssertEx.Equal(new[] { 0x02000002, 0x02000003 }, delta.UpdatedTypes, itemInspector: t => "0x" + t.ToString("X")); EndDebuggingSession(debuggingSession); } [Fact] public async Task ValidSignificantChange_SourceGenerators_DocumentUpdate_GeneratedDocumentUpdate_LineChanges() { var sourceV1 = @" /* GENERATE: class G { int M() { return 1; } } */ "; var sourceV2 = @" /* GENERATE: class G { int M() { return 1; } } */ "; var generator = new TestSourceGenerator() { ExecuteImpl = GenerateSource }; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, sourceV1, generator); var moduleId = EmitLibrary(sourceV1, generator: generator); LoadLibraryToDebuggee(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source (valid edit): solution = solution.WithDocumentText(document1.Id, SourceText.From(sourceV2, Encoding.UTF8)); // validate solution update status and emit: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); // check emitted delta: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); var lineUpdate = delta.SequencePoints.Single(); AssertEx.Equal(new[] { "3 -> 4" }, lineUpdate.LineUpdates.Select(edit => $"{edit.OldLine} -> {edit.NewLine}")); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Empty(delta.UpdatedMethods); Assert.Empty(delta.UpdatedTypes); EndDebuggingSession(debuggingSession); } [Fact] public async Task ValidSignificantChange_SourceGenerators_DocumentUpdate_GeneratedDocumentInsert() { var sourceV1 = @" partial class C { int X = 1; } "; var sourceV2 = @" /* GENERATE: partial class C { int Y = 2; } */ partial class C { int X = 1; } "; var generator = new TestSourceGenerator() { ExecuteImpl = GenerateSource }; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, sourceV1, generator); var moduleId = EmitLibrary(sourceV1, generator: generator); LoadLibraryToDebuggee(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source (valid edit): solution = solution.WithDocumentText(document1.Id, SourceText.From(sourceV2, Encoding.UTF8)); // validate solution update status and emit: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); // check emitted delta: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Equal(1, delta.UpdatedMethods.Length); // constructor update Assert.Equal(0x02000002, delta.UpdatedTypes.Single()); EndDebuggingSession(debuggingSession); } [Fact] public async Task ValidSignificantChange_SourceGenerators_AdditionalDocumentUpdate() { var source = @" class C { int Y => 1; } "; var additionalSourceV1 = @" /* GENERATE: class G { int X => 1; } */ "; var additionalSourceV2 = @" /* GENERATE: class G { int X => 2; } */ "; var generator = new TestSourceGenerator() { ExecuteImpl = GenerateSource }; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, source, generator, additionalFileText: additionalSourceV1); var moduleId = EmitLibrary(source, generator: generator, additionalFileText: additionalSourceV1); LoadLibraryToDebuggee(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the additional source (valid edit): var additionalDocument1 = solution.Projects.Single().AdditionalDocuments.Single(); solution = solution.WithAdditionalDocumentText(additionalDocument1.Id, SourceText.From(additionalSourceV2, Encoding.UTF8)); // validate solution update status and emit: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); // check emitted delta: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Equal(1, delta.UpdatedMethods.Length); Assert.Equal(0x02000003, delta.UpdatedTypes.Single()); EndDebuggingSession(debuggingSession); } [Fact] public async Task ValidSignificantChange_SourceGenerators_AnalyzerConfigUpdate() { var source = @" class C { int Y => 1; } "; var configV1 = new[] { ("enc_generator_output", "1") }; var configV2 = new[] { ("enc_generator_output", "2") }; var generator = new TestSourceGenerator() { ExecuteImpl = GenerateSource }; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, source, generator, analyzerConfig: configV1); var moduleId = EmitLibrary(source, generator: generator, analyzerOptions: configV1); LoadLibraryToDebuggee(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the additional source (valid edit): var configDocument1 = solution.Projects.Single().AnalyzerConfigDocuments.Single(); solution = solution.WithAnalyzerConfigDocumentText(configDocument1.Id, GetAnalyzerConfigText(configV2)); // validate solution update status and emit: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); // check emitted delta: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Equal(1, delta.UpdatedMethods.Length); Assert.Equal(0x02000003, delta.UpdatedTypes.Single()); EndDebuggingSession(debuggingSession); } [Fact] public async Task ValidSignificantChange_SourceGenerators_DocumentRemove() { var source1 = ""; var generator = new TestSourceGenerator() { ExecuteImpl = context => context.AddSource("generated", $"class G {{ int X => {context.Compilation.SyntaxTrees.Count()}; }}") }; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, source1, generator); var moduleId = EmitLibrary(source1, generator: generator); LoadLibraryToDebuggee(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // remove the source document (valid edit): solution = document1.Project.Solution.RemoveDocument(document1.Id); // validate solution update status and emit: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); // check emitted delta: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Equal(1, delta.UpdatedMethods.Length); Assert.Equal(0x02000002, delta.UpdatedTypes.Single()); EndDebuggingSession(debuggingSession); } /// <summary> /// Emulates two updates to Multi-TFM project. /// </summary> [Fact] public async Task TwoUpdatesWithLoadedAndUnloadedModule() { var dir = Temp.CreateDirectory(); var source1 = "class A { void M() { System.Console.WriteLine(1); } }"; var source2 = "class A { void M() { System.Console.WriteLine(2); } }"; var source3 = "class A { void M() { System.Console.WriteLine(3); } }"; var compilationA = CSharpTestBase.CreateCompilation(source1, options: TestOptions.DebugDll, targetFramework: DefaultTargetFramework, assemblyName: "A"); var compilationB = CSharpTestBase.CreateCompilation(source1, options: TestOptions.DebugDll, targetFramework: DefaultTargetFramework, assemblyName: "B"); var (peImageA, pdbImageA) = compilationA.EmitToArrays(new EmitOptions(debugInformationFormat: DebugInformationFormat.PortablePdb)); var moduleMetadataA = ModuleMetadata.CreateFromImage(peImageA); var moduleFileA = Temp.CreateFile("A.dll").WriteAllBytes(peImageA); var pdbFileA = dir.CreateFile("A.pdb").WriteAllBytes(pdbImageA); var moduleIdA = moduleMetadataA.GetModuleVersionId(); var (peImageB, pdbImageB) = compilationB.EmitToArrays(new EmitOptions(debugInformationFormat: DebugInformationFormat.PortablePdb)); var moduleMetadataB = ModuleMetadata.CreateFromImage(peImageB); var moduleFileB = dir.CreateFile("B.dll").WriteAllBytes(peImageB); var pdbFileB = dir.CreateFile("B.pdb").WriteAllBytes(pdbImageB); var moduleIdB = moduleMetadataB.GetModuleVersionId(); using var _ = CreateWorkspace(out var solution, out var service); (solution, var documentA) = AddDefaultTestProject(solution, source1); var projectA = documentA.Project; var projectB = solution.AddProject("B", "A", "C#").AddMetadataReferences(projectA.MetadataReferences).AddDocument("DocB", source1, filePath: "DocB.cs").Project; solution = projectB.Solution; _mockCompilationOutputsProvider = project => (project.Id == projectA.Id) ? new CompilationOutputFiles(moduleFileA.Path, pdbFileA.Path) : (project.Id == projectB.Id) ? new CompilationOutputFiles(moduleFileB.Path, pdbFileB.Path) : throw ExceptionUtilities.UnexpectedValue(project); // only module A is loaded LoadLibraryToDebuggee(moduleIdA); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // // First update. // solution = solution.WithDocumentText(projectA.Documents.Single().Id, SourceText.From(source2, Encoding.UTF8)); solution = solution.WithDocumentText(projectB.Documents.Single().Id, SourceText.From(source2, Encoding.UTF8)); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); Assert.Empty(emitDiagnostics); var deltaA = updates.Updates.Single(d => d.Module == moduleIdA); var deltaB = updates.Updates.Single(d => d.Module == moduleIdB); Assert.Equal(2, updates.Updates.Length); // the update should be stored on the service: var pendingUpdate = debuggingSession.GetTestAccessor().GetPendingSolutionUpdate(); var (_, newBaselineA1) = pendingUpdate.EmitBaselines.Single(b => b.ProjectId == projectA.Id); var (_, newBaselineB1) = pendingUpdate.EmitBaselines.Single(b => b.ProjectId == projectB.Id); var baselineA0 = newBaselineA1.GetInitialEmitBaseline(); var baselineB0 = newBaselineB1.GetInitialEmitBaseline(); var readers = debuggingSession.GetTestAccessor().GetBaselineModuleReaders(); Assert.Equal(4, readers.Length); Assert.False(readers.Any(r => r is null)); Assert.Equal(moduleIdA, newBaselineA1.OriginalMetadata.GetModuleVersionId()); Assert.Equal(moduleIdB, newBaselineB1.OriginalMetadata.GetModuleVersionId()); CommitSolutionUpdate(debuggingSession); Assert.Null(debuggingSession.GetTestAccessor().GetPendingSolutionUpdate()); // no change in non-remappable regions since we didn't have any active statements: Assert.Empty(debuggingSession.EditSession.NonRemappableRegions); // verify that baseline is added for both modules: Assert.Same(newBaselineA1, debuggingSession.GetTestAccessor().GetProjectEmitBaseline(projectA.Id)); Assert.Same(newBaselineB1, debuggingSession.GetTestAccessor().GetProjectEmitBaseline(projectB.Id)); // solution update status after committing an update: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); ExitBreakState(debuggingSession); EnterBreakState(debuggingSession); // // Second update. // solution = solution.WithDocumentText(projectA.Documents.Single().Id, SourceText.From(source3, Encoding.UTF8)); solution = solution.WithDocumentText(projectB.Documents.Single().Id, SourceText.From(source3, Encoding.UTF8)); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); Assert.Empty(emitDiagnostics); deltaA = updates.Updates.Single(d => d.Module == moduleIdA); deltaB = updates.Updates.Single(d => d.Module == moduleIdB); Assert.Equal(2, updates.Updates.Length); // the update should be stored on the service: pendingUpdate = debuggingSession.GetTestAccessor().GetPendingSolutionUpdate(); var (_, newBaselineA2) = pendingUpdate.EmitBaselines.Single(b => b.ProjectId == projectA.Id); var (_, newBaselineB2) = pendingUpdate.EmitBaselines.Single(b => b.ProjectId == projectB.Id); Assert.NotSame(newBaselineA1, newBaselineA2); Assert.NotSame(newBaselineB1, newBaselineB2); Assert.Same(baselineA0, newBaselineA2.GetInitialEmitBaseline()); Assert.Same(baselineB0, newBaselineB2.GetInitialEmitBaseline()); Assert.Same(baselineA0.OriginalMetadata, newBaselineA2.OriginalMetadata); Assert.Same(baselineB0.OriginalMetadata, newBaselineB2.OriginalMetadata); // no new module readers: var baselineReaders = debuggingSession.GetTestAccessor().GetBaselineModuleReaders(); AssertEx.Equal(readers, baselineReaders); CommitSolutionUpdate(debuggingSession); Assert.Null(debuggingSession.GetTestAccessor().GetPendingSolutionUpdate()); // no change in non-remappable regions since we didn't have any active statements: Assert.Empty(debuggingSession.EditSession.NonRemappableRegions); // module readers tracked: baselineReaders = debuggingSession.GetTestAccessor().GetBaselineModuleReaders(); AssertEx.Equal(readers, baselineReaders); // verify that baseline is updated for both modules: Assert.Same(newBaselineA2, debuggingSession.GetTestAccessor().GetProjectEmitBaseline(projectA.Id)); Assert.Same(newBaselineB2, debuggingSession.GetTestAccessor().GetProjectEmitBaseline(projectB.Id)); // solution update status after committing an update: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); ExitBreakState(debuggingSession); EndDebuggingSession(debuggingSession); // open deferred module readers should be dispose when the debugging session ends: VerifyReadersDisposed(readers); } [Fact] public async Task ValidSignificantChange_BaselineCreationFailed_NoStream() { using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, "class C1 { void M() { System.Console.WriteLine(1); } }"); _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(Guid.NewGuid()) { OpenPdbStreamImpl = () => null, OpenAssemblyStreamImpl = () => null, }; var debuggingSession = await StartDebuggingSessionAsync(service, solution); // module not loaded EnterBreakState(debuggingSession); // change the source (valid edit): solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { System.Console.WriteLine(2); } }", Encoding.UTF8)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); AssertEx.Equal(new[] { $"{document1.Project.Id} Error ENC1001: {string.Format(FeaturesResources.ErrorReadingFile, "test-pdb", new FileNotFoundException().Message)}" }, InspectDiagnostics(emitDiagnostics)); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); } [Fact] public async Task ValidSignificantChange_BaselineCreationFailed_AssemblyReadError() { var sourceV1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var compilationV1 = CSharpTestBase.CreateCompilationWithMscorlib40(sourceV1, options: TestOptions.DebugDll, assemblyName: "lib"); var pdbStream = new MemoryStream(); var peImage = compilationV1.EmitToArray(new EmitOptions(debugInformationFormat: DebugInformationFormat.PortablePdb), pdbStream: pdbStream); pdbStream.Position = 0; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, sourceV1); _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(Guid.NewGuid()) { OpenPdbStreamImpl = () => pdbStream, OpenAssemblyStreamImpl = () => throw new IOException("*message*"), }; var debuggingSession = await StartDebuggingSessionAsync(service, solution); // module not loaded EnterBreakState(debuggingSession); // change the source (valid edit): var document1 = solution.Projects.Single().Documents.Single(); solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { System.Console.WriteLine(2); } }", Encoding.UTF8)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); AssertEx.Equal(new[] { $"{document.Project.Id} Error ENC1001: {string.Format(FeaturesResources.ErrorReadingFile, "test-assembly", "*message*")}" }, InspectDiagnostics(emitDiagnostics)); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); EndDebuggingSession(debuggingSession); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=1", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=1|InBreakState=True|Capabilities=31", "Debugging_EncSession_EditSession_EmitDeltaErrorId: SessionId=1|EditSessionId=2|ErrorId=ENC1001" }, _telemetryLog); } [Fact] public async Task ActiveStatements() { var sourceV1 = "class C { void F() { G(1); } void G(int a) => System.Console.WriteLine(1); }"; var sourceV2 = "class C { int x; void F() { G(2); G(1); } void G(int a) => System.Console.WriteLine(2); }"; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, sourceV1); var activeSpan11 = GetSpan(sourceV1, "G(1);"); var activeSpan12 = GetSpan(sourceV1, "System.Console.WriteLine(1)"); var activeSpan21 = GetSpan(sourceV2, "G(2); G(1);"); var activeSpan22 = GetSpan(sourceV2, "System.Console.WriteLine(2)"); var adjustedActiveSpan1 = GetSpan(sourceV2, "G(2);"); var adjustedActiveSpan2 = GetSpan(sourceV2, "System.Console.WriteLine(2)"); var documentId = document1.Id; var documentPath = document1.FilePath; var sourceTextV1 = document1.GetTextSynchronously(CancellationToken.None); var sourceTextV2 = SourceText.From(sourceV2, Encoding.UTF8); var activeLineSpan11 = sourceTextV1.Lines.GetLinePositionSpan(activeSpan11); var activeLineSpan12 = sourceTextV1.Lines.GetLinePositionSpan(activeSpan12); var activeLineSpan21 = sourceTextV2.Lines.GetLinePositionSpan(activeSpan21); var activeLineSpan22 = sourceTextV2.Lines.GetLinePositionSpan(activeSpan22); var adjustedActiveLineSpan1 = sourceTextV2.Lines.GetLinePositionSpan(adjustedActiveSpan1); var adjustedActiveLineSpan2 = sourceTextV2.Lines.GetLinePositionSpan(adjustedActiveSpan2); var debuggingSession = await StartDebuggingSessionAsync(service, solution); // default if not called in a break state Assert.True((await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(document1.Id), CancellationToken.None)).IsDefault); var moduleId = Guid.NewGuid(); var activeInstruction1 = new ManagedInstructionId(new ManagedMethodId(moduleId, token: 0x06000001, version: 1), ilOffset: 1); var activeInstruction2 = new ManagedInstructionId(new ManagedMethodId(moduleId, token: 0x06000002, version: 1), ilOffset: 1); var activeStatements = ImmutableArray.Create( new ManagedActiveStatementDebugInfo( activeInstruction1, documentPath, activeLineSpan11.ToSourceSpan(), ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsNonLeafFrame), new ManagedActiveStatementDebugInfo( activeInstruction2, documentPath, activeLineSpan12.ToSourceSpan(), ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame)); EnterBreakState(debuggingSession, activeStatements); var activeStatementSpan11 = new ActiveStatementSpan(0, activeLineSpan11, ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsNonLeafFrame, unmappedDocumentId: null); var activeStatementSpan12 = new ActiveStatementSpan(1, activeLineSpan12, ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame, unmappedDocumentId: null); var baseSpans = await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(document1.Id), CancellationToken.None); AssertEx.Equal(new[] { activeStatementSpan11, activeStatementSpan12 }, baseSpans.Single()); var trackedActiveSpans1 = ImmutableArray.Create(activeStatementSpan11, activeStatementSpan12); var currentSpans = await debuggingSession.GetAdjustedActiveStatementSpansAsync(document1, (_, _, _) => new(trackedActiveSpans1), CancellationToken.None); AssertEx.Equal(trackedActiveSpans1, currentSpans); Assert.Equal(activeLineSpan11, await debuggingSession.GetCurrentActiveStatementPositionAsync(document1.Project.Solution, (_, _, _) => new(trackedActiveSpans1), activeInstruction1, CancellationToken.None)); Assert.Equal(activeLineSpan12, await debuggingSession.GetCurrentActiveStatementPositionAsync(document1.Project.Solution, (_, _, _) => new(trackedActiveSpans1), activeInstruction2, CancellationToken.None)); // change the source (valid edit): solution = solution.WithDocumentText(documentId, sourceTextV2); var document2 = solution.GetDocument(documentId); // tracking span update triggered by the edit: var activeStatementSpan21 = new ActiveStatementSpan(0, activeLineSpan21, ActiveStatementFlags.IsNonLeafFrame, unmappedDocumentId: null); var activeStatementSpan22 = new ActiveStatementSpan(1, activeLineSpan22, ActiveStatementFlags.IsLeafFrame, unmappedDocumentId: null); var trackedActiveSpans2 = ImmutableArray.Create(activeStatementSpan21, activeStatementSpan22); currentSpans = await debuggingSession.GetAdjustedActiveStatementSpansAsync(document2, (_, _, _) => new(trackedActiveSpans2), CancellationToken.None); AssertEx.Equal(new[] { adjustedActiveLineSpan1, adjustedActiveLineSpan2 }, currentSpans.Select(s => s.LineSpan)); Assert.Equal(adjustedActiveLineSpan1, await debuggingSession.GetCurrentActiveStatementPositionAsync(solution, (_, _, _) => new(trackedActiveSpans2), activeInstruction1, CancellationToken.None)); Assert.Equal(adjustedActiveLineSpan2, await debuggingSession.GetCurrentActiveStatementPositionAsync(solution, (_, _, _) => new(trackedActiveSpans2), activeInstruction2, CancellationToken.None)); } [Theory] [CombinatorialData] public async Task ActiveStatements_SyntaxErrorOrOutOfSyncDocument(bool isOutOfSync) { var sourceV1 = "class C { void F() => G(1); void G(int a) => System.Console.WriteLine(1); }"; // syntax error (missing ';') unless testing out-of-sync document var sourceV2 = isOutOfSync ? "class C { int x; void F() => G(1); void G(int a) => System.Console.WriteLine(2); }" : "class C { int x void F() => G(1); void G(int a) => System.Console.WriteLine(2); }"; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, sourceV1); var activeSpan11 = GetSpan(sourceV1, "G(1)"); var activeSpan12 = GetSpan(sourceV1, "System.Console.WriteLine(1)"); var documentId = document1.Id; var documentFilePath = document1.FilePath; var sourceTextV1 = await document1.GetTextAsync(CancellationToken.None); var sourceTextV2 = SourceText.From(sourceV2, Encoding.UTF8); var activeLineSpan11 = sourceTextV1.Lines.GetLinePositionSpan(activeSpan11); var activeLineSpan12 = sourceTextV1.Lines.GetLinePositionSpan(activeSpan12); var debuggingSession = await StartDebuggingSessionAsync( service, solution, isOutOfSync ? CommittedSolution.DocumentState.OutOfSync : CommittedSolution.DocumentState.MatchesBuildOutput); var moduleId = Guid.NewGuid(); var activeInstruction1 = new ManagedInstructionId(new ManagedMethodId(moduleId, token: 0x06000001, version: 1), ilOffset: 1); var activeInstruction2 = new ManagedInstructionId(new ManagedMethodId(moduleId, token: 0x06000002, version: 1), ilOffset: 1); var activeStatements = ImmutableArray.Create( new ManagedActiveStatementDebugInfo( activeInstruction1, documentFilePath, activeLineSpan11.ToSourceSpan(), ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsNonLeafFrame), new ManagedActiveStatementDebugInfo( activeInstruction2, documentFilePath, activeLineSpan12.ToSourceSpan(), ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame)); EnterBreakState(debuggingSession, activeStatements); var baseSpans = (await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(documentId), CancellationToken.None)).Single(); AssertEx.Equal(new[] { new ActiveStatementSpan(0, activeLineSpan11, ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsNonLeafFrame, unmappedDocumentId: null), new ActiveStatementSpan(1, activeLineSpan12, ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame, unmappedDocumentId: null) }, baseSpans); // change the source (valid edit): solution = solution.WithDocumentText(documentId, sourceTextV2); var document2 = solution.GetDocument(documentId); // no adjustments made due to syntax error or out-of-sync document: var currentSpans = await debuggingSession.GetAdjustedActiveStatementSpansAsync(document2, (_, _, _) => ValueTaskFactory.FromResult(baseSpans), CancellationToken.None); AssertEx.Equal(new[] { activeLineSpan11, activeLineSpan12 }, currentSpans.Select(s => s.LineSpan)); var currentSpan1 = await debuggingSession.GetCurrentActiveStatementPositionAsync(solution, (_, _, _) => ValueTaskFactory.FromResult(baseSpans), activeInstruction1, CancellationToken.None); var currentSpan2 = await debuggingSession.GetCurrentActiveStatementPositionAsync(solution, (_, _, _) => ValueTaskFactory.FromResult(baseSpans), activeInstruction2, CancellationToken.None); if (isOutOfSync) { Assert.Equal(baseSpans[0].LineSpan, currentSpan1.Value); Assert.Equal(baseSpans[1].LineSpan, currentSpan2.Value); } else { Assert.Null(currentSpan1); Assert.Null(currentSpan2); } } [Fact] public async Task ActiveStatements_ForeignDocument() { var composition = FeaturesTestCompositions.Features.AddParts(typeof(DummyLanguageService)); using var _ = CreateWorkspace(out var solution, out var service, new[] { typeof(DummyLanguageService) }); var project = solution.AddProject("dummy_proj", "dummy_proj", DummyLanguageService.LanguageName); var document = project.AddDocument("test", SourceText.From("dummy1")); solution = document.Project.Solution; var debuggingSession = await StartDebuggingSessionAsync(service, solution); var activeStatements = ImmutableArray.Create( new ManagedActiveStatementDebugInfo( new ManagedInstructionId(new ManagedMethodId(Guid.Empty, token: 0x06000001, version: 1), ilOffset: 0), documentName: document.Name, sourceSpan: new SourceSpan(0, 1, 0, 2), ActiveStatementFlags.IsNonLeafFrame)); EnterBreakState(debuggingSession, activeStatements); // active statements are not tracked in non-Roslyn projects: var currentSpans = await debuggingSession.GetAdjustedActiveStatementSpansAsync(document, s_noActiveSpans, CancellationToken.None); Assert.Empty(currentSpans); var baseSpans = await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(document.Id), CancellationToken.None); Assert.Empty(baseSpans.Single()); } [Fact, WorkItem(24320, "https://github.com/dotnet/roslyn/issues/24320")] public async Task ActiveStatements_LinkedDocuments() { var markedSources = new[] { @"class Test1 { static void Main() => <AS:2>Project2::Test1.F();</AS:2> static void F() => <AS:1>Project4::Test2.M();</AS:1> }", @"class Test2 { static void M() => <AS:0>Console.WriteLine();</AS:0> }" }; var module1 = Guid.NewGuid(); var module2 = Guid.NewGuid(); var module4 = Guid.NewGuid(); var debugInfos = GetActiveStatementDebugInfosCSharp( markedSources, methodRowIds: new[] { 1, 2, 1 }, modules: new[] { module4, module2, module1 }); // Project1: Test1.cs, Test2.cs // Project2: Test1.cs (link from P1) // Project3: Test1.cs (link from P1) // Project4: Test2.cs (link from P1) using var _ = CreateWorkspace(out var solution, out var service); solution = AddDefaultTestProject(solution, ActiveStatementsDescription.ClearTags(markedSources)); var documents = solution.Projects.Single().Documents; var doc1 = documents.First(); var doc2 = documents.Skip(1).First(); var text1 = await doc1.GetTextAsync(); var text2 = await doc2.GetTextAsync(); DocumentId AddProjectAndLinkDocument(string projectName, Document doc, SourceText text) { var p = solution.AddProject(projectName, projectName, "C#"); var linkedDocId = DocumentId.CreateNewId(p.Id, projectName + "->" + doc.Name); solution = p.Solution.AddDocument(linkedDocId, doc.Name, text, filePath: doc.FilePath); return linkedDocId; } var docId3 = AddProjectAndLinkDocument("Project2", doc1, text1); var docId4 = AddProjectAndLinkDocument("Project3", doc1, text1); var docId5 = AddProjectAndLinkDocument("Project4", doc2, text2); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession, debugInfos); // Base Active Statements var baseActiveStatementsMap = await debuggingSession.EditSession.BaseActiveStatements.GetValueAsync(CancellationToken.None).ConfigureAwait(false); var documentMap = baseActiveStatementsMap.DocumentPathMap; Assert.Equal(2, documentMap.Count); AssertEx.Equal(new[] { $"2: {doc1.FilePath}: (2,32)-(2,52) flags=[MethodUpToDate, IsNonLeafFrame]", $"1: {doc1.FilePath}: (3,29)-(3,49) flags=[MethodUpToDate, IsNonLeafFrame]" }, documentMap[doc1.FilePath].Select(InspectActiveStatement)); AssertEx.Equal(new[] { $"0: {doc2.FilePath}: (0,39)-(0,59) flags=[IsLeafFrame, MethodUpToDate]", }, documentMap[doc2.FilePath].Select(InspectActiveStatement)); Assert.Equal(3, baseActiveStatementsMap.InstructionMap.Count); var statements = baseActiveStatementsMap.InstructionMap.Values.OrderBy(v => v.Ordinal).ToArray(); var s = statements[0]; Assert.Equal(0x06000001, s.InstructionId.Method.Token); Assert.Equal(module4, s.InstructionId.Method.Module); s = statements[1]; Assert.Equal(0x06000002, s.InstructionId.Method.Token); Assert.Equal(module2, s.InstructionId.Method.Module); s = statements[2]; Assert.Equal(0x06000001, s.InstructionId.Method.Token); Assert.Equal(module1, s.InstructionId.Method.Module); var spans = await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(doc1.Id, doc2.Id, docId3, docId4, docId5), CancellationToken.None); AssertEx.Equal(new[] { "(2,32)-(2,52), (3,29)-(3,49)", // test1.cs "(0,39)-(0,59)", // test2.cs "(2,32)-(2,52), (3,29)-(3,49)", // link test1.cs "(2,32)-(2,52), (3,29)-(3,49)", // link test1.cs "(0,39)-(0,59)" // link test2.cs }, spans.Select(docSpans => string.Join(", ", docSpans.Select(span => span.LineSpan)))); } [Fact] public async Task ActiveStatements_OutOfSyncDocuments() { var markedSource1 = @"class C { static void M() { try { } catch (Exception e) { <AS:0>M();</AS:0> } } }"; var source2 = @"class C { static void M() { try { } catch (Exception e) { M(); } } }"; var markedSources = new[] { markedSource1 }; var thread1 = Guid.NewGuid(); // Thread1 stack trace: F (AS:0 leaf) var debugInfos = GetActiveStatementDebugInfosCSharp( markedSources, methodRowIds: new[] { 1 }, ilOffsets: new[] { 1 }, flags: new[] { ActiveStatementFlags.IsLeafFrame | ActiveStatementFlags.MethodUpToDate }); using var _ = CreateWorkspace(out var solution, out var service); solution = AddDefaultTestProject(solution, ActiveStatementsDescription.ClearTags(markedSources)); var project = solution.Projects.Single(); var document = project.Documents.Single(); var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.OutOfSync); EnterBreakState(debuggingSession, debugInfos); // update document to test a changed solution solution = solution.WithDocumentText(document.Id, SourceText.From(source2, Encoding.UTF8)); document = solution.GetDocument(document.Id); var baseActiveStatementMap = await debuggingSession.EditSession.BaseActiveStatements.GetValueAsync(CancellationToken.None).ConfigureAwait(false); // Active Statements - available in out-of-sync documents, as they reflect the state of the debuggee and not the base document content Assert.Single(baseActiveStatementMap.DocumentPathMap); AssertEx.Equal(new[] { $"0: {document.FilePath}: (9,18)-(9,22) flags=[IsLeafFrame, MethodUpToDate]", }, baseActiveStatementMap.DocumentPathMap[document.FilePath].Select(InspectActiveStatement)); Assert.Equal(1, baseActiveStatementMap.InstructionMap.Count); var activeStatement1 = baseActiveStatementMap.InstructionMap.Values.OrderBy(v => v.InstructionId.Method.Token).Single(); Assert.Equal(0x06000001, activeStatement1.InstructionId.Method.Token); Assert.Equal(document.FilePath, activeStatement1.FilePath); Assert.True(activeStatement1.IsLeaf); // Active statement reported as unchanged as the containing document is out-of-sync: var baseSpans = await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(document.Id), CancellationToken.None); AssertEx.Equal(new[] { $"(9,18)-(9,22)" }, baseSpans.Single().Select(s => s.LineSpan.ToString())); // Whether or not an active statement is in an exception region is unknown if the document is out-of-sync: Assert.Null(await debuggingSession.IsActiveStatementInExceptionRegionAsync(solution, activeStatement1.InstructionId, CancellationToken.None)); // Document got synchronized: debuggingSession.LastCommittedSolution.Test_SetDocumentState(document.Id, CommittedSolution.DocumentState.MatchesBuildOutput); // New location of the active statement reported: baseSpans = await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(document.Id), CancellationToken.None); AssertEx.Equal(new[] { $"(10,12)-(10,16)" }, baseSpans.Single().Select(s => s.LineSpan.ToString())); Assert.True(await debuggingSession.IsActiveStatementInExceptionRegionAsync(solution, activeStatement1.InstructionId, CancellationToken.None)); } [Fact] public async Task ActiveStatements_SourceGeneratedDocuments_LineDirectives() { var markedSource1 = @" /* GENERATE: class C { void F() { #line 1 ""a.razor"" <AS:0>F();</AS:0> #line default } } */ "; var markedSource2 = @" /* GENERATE: class C { void F() { #line 2 ""a.razor"" <AS:0>F();</AS:0> #line default } } */ "; var source1 = ActiveStatementsDescription.ClearTags(markedSource1); var source2 = ActiveStatementsDescription.ClearTags(markedSource2); var additionalFileSourceV1 = @" xxxxxxxxxxxxxxxxx "; var generator = new TestSourceGenerator() { ExecuteImpl = GenerateSource }; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, source1, generator, additionalFileText: additionalFileSourceV1); var generatedDocument1 = (await solution.Projects.Single().GetSourceGeneratedDocumentsAsync().ConfigureAwait(false)).Single(); var moduleId = EmitLibrary(source1, generator: generator, additionalFileText: additionalFileSourceV1); LoadLibraryToDebuggee(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession, GetActiveStatementDebugInfosCSharp( new[] { GetGeneratedCodeFromMarkedSource(markedSource1) }, filePaths: new[] { generatedDocument1.FilePath }, modules: new[] { moduleId }, methodRowIds: new[] { 1 }, methodVersions: new[] { 1 }, flags: new[] { ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame })); // change the source (valid edit) solution = solution.WithDocumentText(document1.Id, SourceText.From(source2, Encoding.UTF8)); // validate solution update status and emit: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); // check emitted delta: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Empty(delta.UpdatedMethods); Assert.Empty(delta.UpdatedTypes); AssertEx.Equal(new[] { "a.razor: [0 -> 1]" }, delta.SequencePoints.Inspect()); EndDebuggingSession(debuggingSession); } [Fact] [WorkItem(54347, "https://github.com/dotnet/roslyn/issues/54347")] public async Task ActiveStatements_EncSessionFollowedByHotReload() { var markedSource1 = @" class C { int F() { try { return 0; } catch { <AS:0>return 1;</AS:0> } } } "; var markedSource2 = @" class C { int F() { try { return 0; } catch { <AS:0>return 2;</AS:0> } } } "; var source1 = ActiveStatementsDescription.ClearTags(markedSource1); var source2 = ActiveStatementsDescription.ClearTags(markedSource2); using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, source1); var moduleId = EmitLibrary(source1); LoadLibraryToDebuggee(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession, GetActiveStatementDebugInfosCSharp( new[] { markedSource1 }, modules: new[] { moduleId }, methodRowIds: new[] { 1 }, methodVersions: new[] { 1 }, flags: new[] { ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame })); // change the source (rude edit) solution = solution.WithDocumentText(document.Id, SourceText.From(source2, Encoding.UTF8)); document = solution.GetDocument(document.Id); var diagnostics = await service.GetDocumentDiagnosticsAsync(document, s_noActiveSpans, CancellationToken.None); AssertEx.Equal(new[] { "ENC0063: " + string.Format(FeaturesResources.Updating_a_0_around_an_active_statement_requires_restarting_the_application, CSharpFeaturesResources.catch_clause) }, diagnostics.Select(d => $"{d.Id}: {d.GetMessage()}")); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); // undo the change solution = solution.WithDocumentText(document.Id, SourceText.From(source1, Encoding.UTF8)); document = solution.GetDocument(document.Id); ExitBreakState(debuggingSession, ImmutableArray.Create(document.Id)); // change the source (now a valid edit since there is no active statement) solution = solution.WithDocumentText(document.Id, SourceText.From(source2, Encoding.UTF8)); diagnostics = await service.GetDocumentDiagnosticsAsync(document, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); // validate solution update status and emit (Hot Reload change): (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); EndDebuggingSession(debuggingSession); } /// <summary> /// Scenario: /// F5 a program that has function F that calls G. G has a long-running loop, which starts executing. /// The user makes following operations: /// 1) Break, edit F from version 1 to version 2, continue (change is applied), G is still running in its loop /// Function remapping is produced for F v1 -> F v2. /// 2) Hot-reload edit F (without breaking) to version 3. /// Function remapping is not produced for F v2 -> F v3. If G ever returned to F it will be remapped from F v1 -> F v2, /// where F v2 is considered stale code. This is consistent with the semantic of Hot Reload: Hot Reloaded changes do not have /// an effect until the method is called again. In this case the method is not called, it it returned into hence the stale /// version executes. /// 3) Break and apply EnC edit. This edit is to F v3 (Hot Reload) of the method. We will produce remapping F v3 -> v4. /// </summary> [Fact, WorkItem(52100, "https://github.com/dotnet/roslyn/issues/52100")] public async Task BreakStateRemappingFollowedUpByRunStateUpdate() { var markedSourceV1 = @"class Test { static bool B() => true; static void G() { while (B()); <AS:0>}</AS:0> static void F() { /*insert1[1]*/B();/*insert2[5]*/B();/*insert3[10]*/B(); <AS:1>G();</AS:1> } }"; var markedSourceV2 = Update(markedSourceV1, marker: "1"); var markedSourceV3 = Update(markedSourceV2, marker: "2"); var markedSourceV4 = Update(markedSourceV3, marker: "3"); var moduleId = EmitAndLoadLibraryToDebuggee(ActiveStatementsDescription.ClearTags(markedSourceV1)); using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, ActiveStatementsDescription.ClearTags(markedSourceV1)); var documentId = document.Id; var debuggingSession = await StartDebuggingSessionAsync(service, solution); // EnC update F v1 -> v2 EnterBreakState(debuggingSession, GetActiveStatementDebugInfosCSharp( new[] { markedSourceV1 }, modules: new[] { moduleId, moduleId }, methodRowIds: new[] { 2, 3 }, methodVersions: new[] { 1, 1 }, flags: new[] { ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame, // G ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsNonLeafFrame, // F })); solution = solution.WithDocumentText(documentId, SourceText.From(ActiveStatementsDescription.ClearTags(markedSourceV2), Encoding.UTF8)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(0x06000003, updates.Updates.Single().UpdatedMethods.Single()); Assert.Equal(0x02000002, updates.Updates.Single().UpdatedTypes.Single()); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); CommitSolutionUpdate(debuggingSession); AssertEx.Equal(new[] { $"0x06000002 v1 | AS {document.FilePath}: (4,41)-(4,42) δ=0", $"0x06000003 v1 | AS {document.FilePath}: (9,14)-(9,18) δ=1", }, InspectNonRemappableRegions(debuggingSession.EditSession.NonRemappableRegions)); ExitBreakState(debuggingSession); // Hot Reload update F v2 -> v3 solution = solution.WithDocumentText(documentId, SourceText.From(ActiveStatementsDescription.ClearTags(markedSourceV3), Encoding.UTF8)); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(0x06000003, updates.Updates.Single().UpdatedMethods.Single()); Assert.Equal(0x02000002, updates.Updates.Single().UpdatedTypes.Single()); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); CommitSolutionUpdate(debuggingSession); // the regions remain unchanged AssertEx.Equal(new[] { $"0x06000002 v1 | AS {document.FilePath}: (4,41)-(4,42) δ=0", $"0x06000003 v1 | AS {document.FilePath}: (9,14)-(9,18) δ=1", }, InspectNonRemappableRegions(debuggingSession.EditSession.NonRemappableRegions)); // EnC update F v3 -> v4 EnterBreakState(debuggingSession, GetActiveStatementDebugInfosCSharp( new[] { markedSourceV1 }, // matches F v1 modules: new[] { moduleId, moduleId }, methodRowIds: new[] { 2, 3 }, methodVersions: new[] { 1, 1 }, // frame F v1 is still executing (G has not returned) flags: new[] { ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame, // G ActiveStatementFlags.IsStale | ActiveStatementFlags.IsNonLeafFrame, // F - not up-to-date anymore and since F v1 is followed by F v3 (hot-reload) it is now stale })); var spans = (await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(documentId), CancellationToken.None)).Single(); AssertEx.Equal(new[] { new ActiveStatementSpan(0, new LinePositionSpan(new(4,41), new(4,42)), ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame, unmappedDocumentId: null), }, spans); solution = solution.WithDocumentText(documentId, SourceText.From(ActiveStatementsDescription.ClearTags(markedSourceV4), Encoding.UTF8)); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(0x06000003, updates.Updates.Single().UpdatedMethods.Single()); Assert.Equal(0x02000002, updates.Updates.Single().UpdatedTypes.Single()); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); CommitSolutionUpdate(debuggingSession); // Stale active statement region is gone. AssertEx.Equal(new[] { $"0x06000002 v1 | AS {document.FilePath}: (4,41)-(4,42) δ=0", }, InspectNonRemappableRegions(debuggingSession.EditSession.NonRemappableRegions)); ExitBreakState(debuggingSession); } /// <summary> /// Scenario: /// - F5 /// - edit, but not apply the edits /// - break /// </summary> [Fact] public async Task BreakInPresenceOfUnappliedChanges() { var markedSource1 = @"class Test { static bool B() => true; static void G() { while (B()); <AS:0>}</AS:0> static void F() { <AS:1>G();</AS:1> } }"; var markedSource2 = @"class Test { static bool B() => true; static void G() { while (B()); <AS:0>}</AS:0> static void F() { B(); <AS:1>G();</AS:1> } }"; var markedSource3 = @"class Test { static bool B() => true; static void G() { while (B()); <AS:0>}</AS:0> static void F() { B(); B(); <AS:1>G();</AS:1> } }"; var moduleId = EmitAndLoadLibraryToDebuggee(ActiveStatementsDescription.ClearTags(markedSource1)); using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, ActiveStatementsDescription.ClearTags(markedSource1)); var documentId = document.Id; var debuggingSession = await StartDebuggingSessionAsync(service, solution); // Update to snapshot 2, but don't apply solution = solution.WithDocumentText(documentId, SourceText.From(ActiveStatementsDescription.ClearTags(markedSource2), Encoding.UTF8)); // EnC update F v2 -> v3 EnterBreakState(debuggingSession, GetActiveStatementDebugInfosCSharp( new[] { markedSource1 }, modules: new[] { moduleId, moduleId }, methodRowIds: new[] { 2, 3 }, methodVersions: new[] { 1, 1 }, flags: new[] { ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame, // G ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsNonLeafFrame, // F })); // check that the active statement is mapped correctly to snapshot v2: var expectedSpanG1 = new LinePositionSpan(new LinePosition(3, 41), new LinePosition(3, 42)); var expectedSpanF1 = new LinePositionSpan(new LinePosition(8, 14), new LinePosition(8, 18)); var activeInstructionF1 = new ManagedInstructionId(new ManagedMethodId(moduleId, 0x06000003, version: 1), ilOffset: 0); var span = await debuggingSession.GetCurrentActiveStatementPositionAsync(solution, s_noActiveSpans, activeInstructionF1, CancellationToken.None); Assert.Equal(expectedSpanF1, span.Value); var spans = (await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(documentId), CancellationToken.None)).Single(); AssertEx.Equal(new[] { new ActiveStatementSpan(0, expectedSpanG1, ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame, documentId), new ActiveStatementSpan(1, expectedSpanF1, ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsNonLeafFrame, documentId) }, spans); solution = solution.WithDocumentText(documentId, SourceText.From(ActiveStatementsDescription.ClearTags(markedSource3), Encoding.UTF8)); // check that the active statement is mapped correctly to snapshot v3: var expectedSpanG2 = new LinePositionSpan(new LinePosition(3, 41), new LinePosition(3, 42)); var expectedSpanF2 = new LinePositionSpan(new LinePosition(9, 14), new LinePosition(9, 18)); span = await debuggingSession.GetCurrentActiveStatementPositionAsync(solution, s_noActiveSpans, activeInstructionF1, CancellationToken.None); Assert.Equal(expectedSpanF2, span); spans = (await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(documentId), CancellationToken.None)).Single(); AssertEx.Equal(new[] { new ActiveStatementSpan(0, expectedSpanG2, ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame, documentId), new ActiveStatementSpan(1, expectedSpanF2, ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsNonLeafFrame, documentId) }, spans); // no rude edits: var document1 = solution.GetDocument(documentId); var diagnostics = await service.GetDocumentDiagnosticsAsync(document1, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(0x06000003, updates.Updates.Single().UpdatedMethods.Single()); Assert.Equal(0x02000002, updates.Updates.Single().UpdatedTypes.Single()); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); CommitSolutionUpdate(debuggingSession); AssertEx.Equal(new[] { $"0x06000002 v1 | AS {document.FilePath}: (3,41)-(3,42) δ=0", $"0x06000003 v1 | AS {document.FilePath}: (7,14)-(7,18) δ=2", }, InspectNonRemappableRegions(debuggingSession.EditSession.NonRemappableRegions)); ExitBreakState(debuggingSession); } /// <summary> /// Scenario: /// - F5 /// - edit and apply edit that deletes non-leaf active statement /// - break /// </summary> [Fact, WorkItem(52100, "https://github.com/dotnet/roslyn/issues/52100")] public async Task BreakAfterRunModeChangeDeletesNonLeafActiveStatement() { var markedSource1 = @"class Test { static bool B() => true; static void G() { while (B()); <AS:0>}</AS:0> static void F() { <AS:1>G();</AS:1> } }"; var markedSource2 = @"class Test { static bool B() => true; static void G() { while (B()); <AS:0>}</AS:0> static void F() { } }"; var moduleId = EmitAndLoadLibraryToDebuggee(ActiveStatementsDescription.ClearTags(markedSource1)); using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, ActiveStatementsDescription.ClearTags(markedSource1)); var documentId = document.Id; var debuggingSession = await StartDebuggingSessionAsync(service, solution); // Apply update: F v1 -> v2. solution = solution.WithDocumentText(documentId, SourceText.From(ActiveStatementsDescription.ClearTags(markedSource2), Encoding.UTF8)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(0x06000003, updates.Updates.Single().UpdatedMethods.Single()); Assert.Equal(0x02000002, updates.Updates.Single().UpdatedTypes.Single()); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); CommitSolutionUpdate(debuggingSession); // Break EnterBreakState(debuggingSession, GetActiveStatementDebugInfosCSharp( new[] { markedSource1 }, modules: new[] { moduleId, moduleId }, methodRowIds: new[] { 2, 3 }, methodVersions: new[] { 1, 1 }, // frame F v1 is still executing (G has not returned) flags: new[] { ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame, // G ActiveStatementFlags.IsNonLeafFrame, // F })); // check that the active statement is mapped correctly to snapshot v2: var expectedSpanF1 = new LinePositionSpan(new LinePosition(7, 14), new LinePosition(7, 18)); var expectedSpanG1 = new LinePositionSpan(new LinePosition(3, 41), new LinePosition(3, 42)); var activeInstructionG1 = new ManagedInstructionId(new ManagedMethodId(moduleId, 0x06000002, version: 1), ilOffset: 0); var span = await debuggingSession.GetCurrentActiveStatementPositionAsync(solution, s_noActiveSpans, activeInstructionG1, CancellationToken.None); Assert.Equal(expectedSpanG1, span); // Active statement in F has been deleted: var activeInstructionF1 = new ManagedInstructionId(new ManagedMethodId(moduleId, 0x06000003, version: 1), ilOffset: 0); span = await debuggingSession.GetCurrentActiveStatementPositionAsync(solution, s_noActiveSpans, activeInstructionF1, CancellationToken.None); Assert.Null(span); var spans = (await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(documentId), CancellationToken.None)).Single(); AssertEx.Equal(new[] { new ActiveStatementSpan(0, expectedSpanG1, ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame, unmappedDocumentId: null) // active statement in F has been deleted }, spans); ExitBreakState(debuggingSession); } [Fact] public async Task MultiSession() { var source1 = "class C { void M() { System.Console.WriteLine(); } }"; var source3 = "class C { void M() { WriteLine(2); } }"; var dir = Temp.CreateDirectory(); var sourceFileA = dir.CreateFile("A.cs").WriteAllText(source1); var moduleId = EmitLibrary(source1, sourceFileA.Path, Encoding.UTF8, "Proj"); using var workspace = CreateWorkspace(out var solution, out var encService); var projectP = solution. AddProject("P", "P", LanguageNames.CSharp). WithMetadataReferences(TargetFrameworkUtil.GetReferences(DefaultTargetFramework)); solution = projectP.Solution; var documentIdA = DocumentId.CreateNewId(projectP.Id, debugName: "A"); solution = solution.AddDocument(DocumentInfo.Create( id: documentIdA, name: "A", loader: new FileTextLoader(sourceFileA.Path, Encoding.UTF8), filePath: sourceFileA.Path)); var tasks = Enumerable.Range(0, 10).Select(async i => { var sessionId = await encService.StartDebuggingSessionAsync( solution, _debuggerService, captureMatchingDocuments: ImmutableArray<DocumentId>.Empty, captureAllMatchingDocuments: true, reportDiagnostics: true, CancellationToken.None); var solution1 = solution.WithDocumentText(documentIdA, SourceText.From("class C { void M() { System.Console.WriteLine(" + i + "); } }", Encoding.UTF8)); var result1 = await encService.EmitSolutionUpdateAsync(sessionId, solution1, s_noActiveSpans, CancellationToken.None); Assert.Empty(result1.Diagnostics); Assert.Equal(1, result1.ModuleUpdates.Updates.Length); var solution2 = solution1.WithDocumentText(documentIdA, SourceText.From(source3, Encoding.UTF8)); var result2 = await encService.EmitSolutionUpdateAsync(sessionId, solution2, s_noActiveSpans, CancellationToken.None); Assert.Equal("CS0103", result2.Diagnostics.Single().Diagnostics.Single().Id); Assert.Empty(result2.ModuleUpdates.Updates); encService.EndDebuggingSession(sessionId, out var _); }); await Task.WhenAll(tasks); Assert.Empty(encService.GetTestAccessor().GetActiveDebuggingSessions()); } [Fact] public async Task Disposal() { using var _1 = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, "class C { }"); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EndDebuggingSession(debuggingSession); // The folling methods shall not be called after the debugging session ended. await Assert.ThrowsAsync<ObjectDisposedException>(async () => await debuggingSession.EmitSolutionUpdateAsync(solution, s_noActiveSpans, CancellationToken.None)); await Assert.ThrowsAsync<ObjectDisposedException>(async () => await debuggingSession.GetCurrentActiveStatementPositionAsync(solution, s_noActiveSpans, instructionId: default, CancellationToken.None)); await Assert.ThrowsAsync<ObjectDisposedException>(async () => await debuggingSession.IsActiveStatementInExceptionRegionAsync(solution, instructionId: default, CancellationToken.None)); Assert.Throws<ObjectDisposedException>(() => debuggingSession.BreakStateChanged(inBreakState: true, out _)); Assert.Throws<ObjectDisposedException>(() => debuggingSession.DiscardSolutionUpdate()); Assert.Throws<ObjectDisposedException>(() => debuggingSession.CommitSolutionUpdate(out _)); Assert.Throws<ObjectDisposedException>(() => debuggingSession.EndSession(out _, out _)); // The following methods can be called at any point in time, so we must handle race with dispose gracefully. Assert.Empty(await debuggingSession.GetDocumentDiagnosticsAsync(document, s_noActiveSpans, CancellationToken.None)); Assert.Empty(await debuggingSession.GetAdjustedActiveStatementSpansAsync(document, s_noActiveSpans, CancellationToken.None)); Assert.True((await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray<DocumentId>.Empty, CancellationToken.None)).IsDefault); } [Fact] public async Task WatchHotReloadServiceTest() { // See https://github.com/dotnet/sdk/blob/main/src/BuiltInTools/dotnet-watch/HotReload/CompilationHandler.cs#L125 var source1 = "class C { void M() { System.Console.WriteLine(1); } }"; var source2 = "class C { void M() { System.Console.WriteLine(2); } }"; var source3 = "class C { void X() { System.Console.WriteLine(2); } }"; var source4 = "class C { void M() { System.Console.WriteLine(2)/* missing semicolon */ }"; var dir = Temp.CreateDirectory(); var sourceFileA = dir.CreateFile("A.cs").WriteAllText(source1); var moduleId = EmitLibrary(source1, sourceFileA.Path, Encoding.UTF8, "Proj"); using var workspace = CreateWorkspace(out var solution, out var encService); var projectP = solution. AddProject("P", "P", LanguageNames.CSharp). WithMetadataReferences(TargetFrameworkUtil.GetReferences(DefaultTargetFramework)); solution = projectP.Solution; var documentIdA = DocumentId.CreateNewId(projectP.Id, debugName: "A"); solution = solution.AddDocument(DocumentInfo.Create( id: documentIdA, name: "A", loader: new FileTextLoader(sourceFileA.Path, Encoding.UTF8), filePath: sourceFileA.Path)); var hotReload = new WatchHotReloadService(workspace.Services, ImmutableArray.Create("Baseline", "AddDefinitionToExistingType", "NewTypeDefinition")); await hotReload.StartSessionAsync(solution, CancellationToken.None); var sessionId = hotReload.GetTestAccessor().SessionId; var session = encService.GetTestAccessor().GetDebuggingSession(sessionId); var matchingDocuments = session.LastCommittedSolution.Test_GetDocumentStates(); AssertEx.Equal(new[] { "(A, MatchesBuildOutput)" }, matchingDocuments.Select(e => (solution.GetDocument(e.id).Name, e.state)).OrderBy(e => e.Name).Select(e => e.ToString())); // Valid update: solution = solution.WithDocumentText(documentIdA, SourceText.From(source2, Encoding.UTF8)); var result = await hotReload.EmitSolutionUpdateAsync(solution, CancellationToken.None); Assert.Empty(result.diagnostics); Assert.Equal(1, result.updates.Length); AssertEx.Equal(new[] { 0x02000002 }, result.updates[0].UpdatedTypes); // Rude edit: solution = solution.WithDocumentText(documentIdA, SourceText.From(source3, Encoding.UTF8)); result = await hotReload.EmitSolutionUpdateAsync(solution, CancellationToken.None); AssertEx.Equal( new[] { "ENC0020: " + string.Format(FeaturesResources.Renaming_0_requires_restarting_the_application, FeaturesResources.method) }, result.diagnostics.Select(d => $"{d.Id}: {d.GetMessage()}")); Assert.Empty(result.updates); // Syntax error (not reported in diagnostics): solution = solution.WithDocumentText(documentIdA, SourceText.From(source4, Encoding.UTF8)); result = await hotReload.EmitSolutionUpdateAsync(solution, CancellationToken.None); Assert.Empty(result.diagnostics); Assert.Empty(result.updates); hotReload.EndSession(); } [Fact] public async Task UnitTestingHotReloadServiceTest() { var source1 = "class C { void M() { System.Console.WriteLine(1); } }"; var source2 = "class C { void M() { System.Console.WriteLine(2); } }"; var source3 = "class C { void X() { System.Console.WriteLine(2); } }"; var source4 = "class C { void M() { System.Console.WriteLine(2)/* missing semicolon */ }"; var dir = Temp.CreateDirectory(); var sourceFileA = dir.CreateFile("A.cs").WriteAllText(source1); var moduleId = EmitLibrary(source1, sourceFileA.Path, Encoding.UTF8, "Proj"); using var workspace = CreateWorkspace(out var solution, out var encService); var projectP = solution. AddProject("P", "P", LanguageNames.CSharp). WithMetadataReferences(TargetFrameworkUtil.GetReferences(DefaultTargetFramework)); solution = projectP.Solution; var documentIdA = DocumentId.CreateNewId(projectP.Id, debugName: "A"); solution = solution.AddDocument(DocumentInfo.Create( id: documentIdA, name: "A", loader: new FileTextLoader(sourceFileA.Path, Encoding.UTF8), filePath: sourceFileA.Path)); var hotReload = new UnitTestingHotReloadService(workspace.Services); await hotReload.StartSessionAsync(solution, ImmutableArray.Create("Baseline", "AddDefinitionToExistingType", "NewTypeDefinition"), CancellationToken.None); var sessionId = hotReload.GetTestAccessor().SessionId; var session = encService.GetTestAccessor().GetDebuggingSession(sessionId); var matchingDocuments = session.LastCommittedSolution.Test_GetDocumentStates(); AssertEx.Equal(new[] { "(A, MatchesBuildOutput)" }, matchingDocuments.Select(e => (solution.GetDocument(e.id).Name, e.state)).OrderBy(e => e.Name).Select(e => e.ToString())); // Valid change solution = solution.WithDocumentText(documentIdA, SourceText.From(source2, Encoding.UTF8)); var result = await hotReload.EmitSolutionUpdateAsync(solution, commitUpdates: true, CancellationToken.None); Assert.Empty(result.diagnostics); Assert.Equal(1, result.updates.Length); solution = solution.WithDocumentText(documentIdA, SourceText.From(source3, Encoding.UTF8)); // Rude edit result = await hotReload.EmitSolutionUpdateAsync(solution, commitUpdates: true, CancellationToken.None); AssertEx.Equal( new[] { "ENC0020: " + string.Format(FeaturesResources.Renaming_0_requires_restarting_the_application, FeaturesResources.method) }, result.diagnostics.Select(d => $"{d.Id}: {d.GetMessage()}")); Assert.Empty(result.updates); // Syntax error is reported in the diagnostics: solution = solution.WithDocumentText(documentIdA, SourceText.From(source4, Encoding.UTF8)); result = await hotReload.EmitSolutionUpdateAsync(solution, commitUpdates: true, CancellationToken.None); Assert.Equal(1, result.diagnostics.Length); Assert.Empty(result.updates); hotReload.EndSession(); } } }
// Licensed to the .NET Foundation under one or more 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.IO; using System.Linq; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using System.Reflection.PortableExecutable; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Debugging; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.ExternalAccess.UnitTesting.Api; using Microsoft.CodeAnalysis.ExternalAccess.Watch.Api; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.UnitTests; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; using Roslyn.Test.Utilities; using Roslyn.Test.Utilities.TestGenerators; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.EditAndContinue.UnitTests { using static ActiveStatementTestHelpers; [UseExportProvider] public sealed partial class EditAndContinueWorkspaceServiceTests : TestBase { private static readonly TestComposition s_composition = FeaturesTestCompositions.Features; private static readonly ActiveStatementSpanProvider s_noActiveSpans = (_, _, _) => new(ImmutableArray<ActiveStatementSpan>.Empty); private const TargetFramework DefaultTargetFramework = TargetFramework.NetStandard20; private Func<Project, CompilationOutputs> _mockCompilationOutputsProvider; private readonly List<string> _telemetryLog; private int _telemetryId; private readonly MockManagedEditAndContinueDebuggerService _debuggerService; public EditAndContinueWorkspaceServiceTests() { _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(Guid.NewGuid()); _telemetryLog = new List<string>(); _debuggerService = new MockManagedEditAndContinueDebuggerService() { LoadedModules = new Dictionary<Guid, ManagedEditAndContinueAvailability>() }; } private TestWorkspace CreateWorkspace(out Solution solution, out EditAndContinueWorkspaceService service, Type[] additionalParts = null) { var workspace = new TestWorkspace(composition: s_composition.AddParts(additionalParts)); solution = workspace.CurrentSolution; service = GetEditAndContinueService(workspace); return workspace; } private static SourceText GetAnalyzerConfigText((string key, string value)[] analyzerConfig) => SourceText.From("[*.*]" + Environment.NewLine + string.Join(Environment.NewLine, analyzerConfig.Select(c => $"{c.key} = {c.value}"))); private static (Solution, Document) AddDefaultTestProject( Solution solution, string source, ISourceGenerator generator = null, string additionalFileText = null, (string key, string value)[] analyzerConfig = null) { solution = AddDefaultTestProject(solution, new[] { source }, generator, additionalFileText, analyzerConfig); return (solution, solution.Projects.Single().Documents.Single()); } private static Solution AddDefaultTestProject( Solution solution, string[] sources, ISourceGenerator generator = null, string additionalFileText = null, (string key, string value)[] analyzerConfig = null) { var project = solution. AddProject("proj", "proj", LanguageNames.CSharp). WithMetadataReferences(TargetFrameworkUtil.GetReferences(DefaultTargetFramework)); solution = project.Solution; if (generator != null) { solution = solution.AddAnalyzerReference(project.Id, new TestGeneratorReference(generator)); } if (additionalFileText != null) { solution = solution.AddAdditionalDocument(DocumentId.CreateNewId(project.Id), "additional", SourceText.From(additionalFileText)); } if (analyzerConfig != null) { solution = solution.AddAnalyzerConfigDocument( DocumentId.CreateNewId(project.Id), name: "config", GetAnalyzerConfigText(analyzerConfig), filePath: Path.Combine(TempRoot.Root, "config")); } Document document = null; var i = 1; foreach (var source in sources) { var fileName = $"test{i++}.cs"; document = solution.GetProject(project.Id). AddDocument(fileName, SourceText.From(source, Encoding.UTF8), filePath: Path.Combine(TempRoot.Root, fileName)); solution = document.Project.Solution; } return document.Project.Solution; } private EditAndContinueWorkspaceService GetEditAndContinueService(Workspace workspace) { var service = (EditAndContinueWorkspaceService)workspace.Services.GetRequiredService<IEditAndContinueWorkspaceService>(); var accessor = service.GetTestAccessor(); accessor.SetOutputProvider(project => _mockCompilationOutputsProvider(project)); return service; } private async Task<DebuggingSession> StartDebuggingSessionAsync( EditAndContinueWorkspaceService service, Solution solution, CommittedSolution.DocumentState initialState = CommittedSolution.DocumentState.MatchesBuildOutput) { var sessionId = await service.StartDebuggingSessionAsync( solution, _debuggerService, captureMatchingDocuments: ImmutableArray<DocumentId>.Empty, captureAllMatchingDocuments: false, reportDiagnostics: true, CancellationToken.None); var session = service.GetTestAccessor().GetDebuggingSession(sessionId); if (initialState != CommittedSolution.DocumentState.None) { SetDocumentsState(session, solution, initialState); } session.GetTestAccessor().SetTelemetryLogger((id, message) => _telemetryLog.Add($"{id}: {message.GetMessage()}"), () => ++_telemetryId); return session; } private void EnterBreakState( DebuggingSession session, ImmutableArray<ManagedActiveStatementDebugInfo> activeStatements = default, ImmutableArray<DocumentId> documentsWithRudeEdits = default) { _debuggerService.GetActiveStatementsImpl = () => activeStatements.NullToEmpty(); session.BreakStateChanged(inBreakState: true, out var documentsToReanalyze); AssertEx.Equal(documentsWithRudeEdits.NullToEmpty(), documentsToReanalyze); } private void ExitBreakState( DebuggingSession session, ImmutableArray<DocumentId> documentsWithRudeEdits = default) { _debuggerService.GetActiveStatementsImpl = () => ImmutableArray<ManagedActiveStatementDebugInfo>.Empty; session.BreakStateChanged(inBreakState: false, out var documentsToReanalyze); AssertEx.Equal(documentsWithRudeEdits.NullToEmpty(), documentsToReanalyze); } private static void CommitSolutionUpdate(DebuggingSession session, ImmutableArray<DocumentId> documentsWithRudeEdits = default) { session.CommitSolutionUpdate(out var documentsToReanalyze); AssertEx.Equal(documentsWithRudeEdits.NullToEmpty(), documentsToReanalyze); } private static void EndDebuggingSession(DebuggingSession session, ImmutableArray<DocumentId> documentsWithRudeEdits = default) { session.EndSession(out var documentsToReanalyze, out _); AssertEx.Equal(documentsWithRudeEdits.NullToEmpty(), documentsToReanalyze); } private static async Task<(ManagedModuleUpdates updates, ImmutableArray<DiagnosticData> diagnostics)> EmitSolutionUpdateAsync( DebuggingSession session, Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider = null) { var result = await session.EmitSolutionUpdateAsync(solution, activeStatementSpanProvider ?? s_noActiveSpans, CancellationToken.None); return (result.ModuleUpdates, result.GetDiagnosticData(solution)); } internal static void SetDocumentsState(DebuggingSession session, Solution solution, CommittedSolution.DocumentState state) { foreach (var project in solution.Projects) { foreach (var document in project.Documents) { session.LastCommittedSolution.Test_SetDocumentState(document.Id, state); } } } private static IEnumerable<string> InspectDiagnostics(ImmutableArray<DiagnosticData> actual) => actual.Select(d => $"{d.ProjectId} {InspectDiagnostic(d)}"); private static string InspectDiagnostic(DiagnosticData diagnostic) => $"{diagnostic.Severity} {diagnostic.Id}: {diagnostic.Message}"; internal static Guid ReadModuleVersionId(Stream stream) { using var peReader = new PEReader(stream); var metadataReader = peReader.GetMetadataReader(); var mvidHandle = metadataReader.GetModuleDefinition().Mvid; return metadataReader.GetGuid(mvidHandle); } private Guid EmitAndLoadLibraryToDebuggee(string source, string sourceFilePath = null, Encoding encoding = null, string assemblyName = "") { var moduleId = EmitLibrary(source, sourceFilePath, encoding, assemblyName); LoadLibraryToDebuggee(moduleId); return moduleId; } private void LoadLibraryToDebuggee(Guid moduleId, ManagedEditAndContinueAvailability availability = default) { _debuggerService.LoadedModules.Add(moduleId, availability); } private Guid EmitLibrary( string source, string sourceFilePath = null, Encoding encoding = null, string assemblyName = "", DebugInformationFormat pdbFormat = DebugInformationFormat.PortablePdb, ISourceGenerator generator = null, string additionalFileText = null, IEnumerable<(string, string)> analyzerOptions = null) { return EmitLibrary(new[] { (source, sourceFilePath ?? Path.Combine(TempRoot.Root, "test1.cs")) }, encoding, assemblyName, pdbFormat, generator, additionalFileText, analyzerOptions); } private Guid EmitLibrary( (string content, string filePath)[] sources, Encoding encoding = null, string assemblyName = "", DebugInformationFormat pdbFormat = DebugInformationFormat.PortablePdb, ISourceGenerator generator = null, string additionalFileText = null, IEnumerable<(string, string)> analyzerOptions = null) { encoding ??= Encoding.UTF8; var parseOptions = TestOptions.RegularPreview; var trees = sources.Select(source => { var sourceText = SourceText.From(new MemoryStream(encoding.GetBytes(source.content)), encoding, checksumAlgorithm: SourceHashAlgorithm.Sha256); return SyntaxFactory.ParseSyntaxTree(sourceText, parseOptions, source.filePath); }); Compilation compilation = CSharpTestBase.CreateCompilation(trees.ToArray(), options: TestOptions.DebugDll, targetFramework: DefaultTargetFramework, assemblyName: assemblyName); if (generator != null) { var optionsProvider = (analyzerOptions != null) ? new EditAndContinueTestAnalyzerConfigOptionsProvider(analyzerOptions) : null; var additionalTexts = (additionalFileText != null) ? new[] { new InMemoryAdditionalText("additional_file", additionalFileText) } : null; var generatorDriver = CSharpGeneratorDriver.Create(new[] { generator }, additionalTexts, parseOptions, optionsProvider); generatorDriver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics); generatorDiagnostics.Verify(); compilation = outputCompilation; } return EmitLibrary(compilation, pdbFormat); } private Guid EmitLibrary(Compilation compilation, DebugInformationFormat pdbFormat = DebugInformationFormat.PortablePdb) { var (peImage, pdbImage) = compilation.EmitToArrays(new EmitOptions(debugInformationFormat: pdbFormat)); var symReader = SymReaderTestHelpers.OpenDummySymReader(pdbImage); var moduleMetadata = ModuleMetadata.CreateFromImage(peImage); var moduleId = moduleMetadata.GetModuleVersionId(); // associate the binaries with the project (assumes a single project) _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(moduleId) { OpenAssemblyStreamImpl = () => { var stream = new MemoryStream(); peImage.WriteToStream(stream); stream.Position = 0; return stream; }, OpenPdbStreamImpl = () => { var stream = new MemoryStream(); pdbImage.WriteToStream(stream); stream.Position = 0; return stream; } }; return moduleId; } private static SourceText CreateSourceTextFromFile(string path) { using var stream = File.OpenRead(path); return SourceText.From(stream, Encoding.UTF8, SourceHashAlgorithm.Sha256); } private static TextSpan GetSpan(string str, string substr) => new TextSpan(str.IndexOf(substr), substr.Length); private static void VerifyReadersDisposed(IEnumerable<IDisposable> readers) { foreach (var reader in readers) { Assert.Throws<ObjectDisposedException>(() => { if (reader is MetadataReaderProvider md) { md.GetMetadataReader(); } else { ((DebugInformationReaderProvider)reader).CreateEditAndContinueMethodDebugInfoReader(); } }); } } private static DocumentInfo CreateDesignTimeOnlyDocument(ProjectId projectId, string name = "design-time-only.cs", string path = "design-time-only.cs") => DocumentInfo.Create( DocumentId.CreateNewId(projectId, name), name: name, folders: Array.Empty<string>(), sourceCodeKind: SourceCodeKind.Regular, loader: TextLoader.From(TextAndVersion.Create(SourceText.From("class DTO {}"), VersionStamp.Create(), path)), filePath: path, isGenerated: false, designTimeOnly: true, documentServiceProvider: null); internal sealed class FailingTextLoader : TextLoader { public override Task<TextAndVersion> LoadTextAndVersionAsync(Workspace workspace, DocumentId documentId, CancellationToken cancellationToken) { Assert.True(false, $"Content of document {documentId} should never be loaded"); throw ExceptionUtilities.Unreachable; } } private static EditAndContinueLogEntry Row(int rowNumber, TableIndex table, EditAndContinueOperation operation) => new(MetadataTokens.Handle(table, rowNumber), operation); private static unsafe void VerifyEncLogMetadata(ImmutableArray<byte> delta, params EditAndContinueLogEntry[] expectedRows) { fixed (byte* ptr = delta.ToArray()) { var reader = new MetadataReader(ptr, delta.Length); AssertEx.Equal(expectedRows, reader.GetEditAndContinueLogEntries(), itemInspector: EncLogRowToString); } static string EncLogRowToString(EditAndContinueLogEntry row) { TableIndex tableIndex; MetadataTokens.TryGetTableIndex(row.Handle.Kind, out tableIndex); return string.Format( "Row({0}, TableIndex.{1}, EditAndContinueOperation.{2})", MetadataTokens.GetRowNumber(row.Handle), tableIndex, row.Operation); } } private static void GenerateSource(GeneratorExecutionContext context) { foreach (var syntaxTree in context.Compilation.SyntaxTrees) { var fileName = PathUtilities.GetFileName(syntaxTree.FilePath); Generate(syntaxTree.GetText().ToString(), fileName); if (context.AnalyzerConfigOptions.GetOptions(syntaxTree).TryGetValue("enc_generator_output", out var optionValue)) { context.AddSource("GeneratedFromOptions_" + fileName, $"class G {{ int X => {optionValue}; }}"); } } foreach (var additionalFile in context.AdditionalFiles) { Generate(additionalFile.GetText()!.ToString(), PathUtilities.GetFileName(additionalFile.Path)); } void Generate(string source, string fileName) { var generatedSource = GetGeneratedCodeFromMarkedSource(source); if (generatedSource != null) { context.AddSource($"Generated_{fileName}", generatedSource); } } } private static string GetGeneratedCodeFromMarkedSource(string markedSource) { const string OpeningMarker = "/* GENERATE:"; const string ClosingMarker = "*/"; var index = markedSource.IndexOf(OpeningMarker); if (index > 0) { index += OpeningMarker.Length; var closing = markedSource.IndexOf(ClosingMarker, index); return markedSource[index..closing].Trim(); } return null; } [Theory] [CombinatorialData] public async Task StartDebuggingSession_CapturingDocuments(bool captureAllDocuments) { var encodingA = Encoding.BigEndianUnicode; var encodingB = Encoding.Unicode; var encodingC = Encoding.GetEncoding("SJIS"); var encodingE = Encoding.UTF8; var sourceA1 = "class A {}"; var sourceB1 = "class B { int F() => 1; }"; var sourceB2 = "class B { int F() => 2; }"; var sourceB3 = "class B { int F() => 3; }"; var sourceC1 = "class C { const char L = 'ワ'; }"; var sourceD1 = "dummy code"; var sourceE1 = "class E { }"; var sourceBytesA1 = encodingA.GetBytes(sourceA1); var sourceBytesB1 = encodingB.GetBytes(sourceB1); var sourceBytesC1 = encodingC.GetBytes(sourceC1); var sourceBytesE1 = encodingE.GetBytes(sourceE1); var dir = Temp.CreateDirectory(); var sourceFileA = dir.CreateFile("A.cs").WriteAllBytes(sourceBytesA1); var sourceFileB = dir.CreateFile("B.cs").WriteAllBytes(sourceBytesB1); var sourceFileC = dir.CreateFile("C.cs").WriteAllBytes(sourceBytesC1); var sourceFileD = dir.CreateFile("dummy").WriteAllText(sourceD1); var sourceFileE = dir.CreateFile("E.cs").WriteAllBytes(sourceBytesE1); var sourceTreeA1 = SyntaxFactory.ParseSyntaxTree(SourceText.From(sourceBytesA1, sourceBytesA1.Length, encodingA, SourceHashAlgorithm.Sha256), TestOptions.Regular, sourceFileA.Path); var sourceTreeB1 = SyntaxFactory.ParseSyntaxTree(SourceText.From(sourceBytesB1, sourceBytesB1.Length, encodingB, SourceHashAlgorithm.Sha256), TestOptions.Regular, sourceFileB.Path); var sourceTreeC1 = SyntaxFactory.ParseSyntaxTree(SourceText.From(sourceBytesC1, sourceBytesC1.Length, encodingC, SourceHashAlgorithm.Sha1), TestOptions.Regular, sourceFileC.Path); // E is not included in the compilation: var compilation = CSharpTestBase.CreateCompilation(new[] { sourceTreeA1, sourceTreeB1, sourceTreeC1 }, options: TestOptions.DebugDll, targetFramework: DefaultTargetFramework, assemblyName: "P"); EmitLibrary(compilation); // change content of B on disk: sourceFileB.WriteAllText(sourceB2, encodingB); // prepare workspace as if it was loaded from project files: using var _ = CreateWorkspace(out var solution, out var service, new[] { typeof(DummyLanguageService) }); var projectP = solution.AddProject("P", "P", LanguageNames.CSharp); solution = projectP.Solution; var documentIdA = DocumentId.CreateNewId(projectP.Id, debugName: "A"); solution = solution.AddDocument(DocumentInfo.Create( id: documentIdA, name: "A", loader: new FileTextLoader(sourceFileA.Path, encodingA), filePath: sourceFileA.Path)); var documentIdB = DocumentId.CreateNewId(projectP.Id, debugName: "B"); solution = solution.AddDocument(DocumentInfo.Create( id: documentIdB, name: "B", loader: new FileTextLoader(sourceFileB.Path, encodingB), filePath: sourceFileB.Path)); var documentIdC = DocumentId.CreateNewId(projectP.Id, debugName: "C"); solution = solution.AddDocument(DocumentInfo.Create( id: documentIdC, name: "C", loader: new FileTextLoader(sourceFileC.Path, encodingC), filePath: sourceFileC.Path)); var documentIdE = DocumentId.CreateNewId(projectP.Id, debugName: "E"); solution = solution.AddDocument(DocumentInfo.Create( id: documentIdE, name: "E", loader: new FileTextLoader(sourceFileE.Path, encodingE), filePath: sourceFileE.Path)); // check that are testing documents whose hash algorithm does not match the PDB (but the hash itself does): Assert.Equal(SourceHashAlgorithm.Sha1, solution.GetDocument(documentIdA).GetTextSynchronously(default).ChecksumAlgorithm); Assert.Equal(SourceHashAlgorithm.Sha1, solution.GetDocument(documentIdB).GetTextSynchronously(default).ChecksumAlgorithm); Assert.Equal(SourceHashAlgorithm.Sha1, solution.GetDocument(documentIdC).GetTextSynchronously(default).ChecksumAlgorithm); Assert.Equal(SourceHashAlgorithm.Sha1, solution.GetDocument(documentIdE).GetTextSynchronously(default).ChecksumAlgorithm); // design-time-only document with and without absolute path: solution = solution. AddDocument(CreateDesignTimeOnlyDocument(projectP.Id, name: "dt1.cs", path: Path.Combine(dir.Path, "dt1.cs"))). AddDocument(CreateDesignTimeOnlyDocument(projectP.Id, name: "dt2.cs", path: "dt2.cs")); // project that does not support EnC - the contents of documents in this project shouldn't be loaded: var projectQ = solution.AddProject("Q", "Q", DummyLanguageService.LanguageName); solution = projectQ.Solution; solution = solution.AddDocument(DocumentInfo.Create( id: DocumentId.CreateNewId(projectQ.Id, debugName: "D"), name: "D", loader: new FailingTextLoader(), filePath: sourceFileD.Path)); var captureMatchingDocuments = captureAllDocuments ? ImmutableArray<DocumentId>.Empty : (from project in solution.Projects from documentId in project.DocumentIds select documentId).ToImmutableArray(); var sessionId = await service.StartDebuggingSessionAsync(solution, _debuggerService, captureMatchingDocuments, captureAllDocuments, reportDiagnostics: true, CancellationToken.None); var debuggingSession = service.GetTestAccessor().GetDebuggingSession(sessionId); var matchingDocuments = debuggingSession.LastCommittedSolution.Test_GetDocumentStates(); AssertEx.Equal(new[] { "(A, MatchesBuildOutput)", "(C, MatchesBuildOutput)" }, matchingDocuments.Select(e => (solution.GetDocument(e.id).Name, e.state)).OrderBy(e => e.Name).Select(e => e.ToString())); // change content of B on disk again: sourceFileB.WriteAllText(sourceB3, encodingB); solution = solution.WithDocumentTextLoader(documentIdB, new FileTextLoader(sourceFileB.Path, encodingB), PreservationMode.PreserveValue); EnterBreakState(debuggingSession); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(updates.Updates); AssertEx.Equal(new[] { $"{projectP.Id} Warning ENC1005: {string.Format(FeaturesResources.DocumentIsOutOfSyncWithDebuggee, sourceFileB.Path)}" }, InspectDiagnostics(emitDiagnostics)); EndDebuggingSession(debuggingSession); } [Fact] public async Task ProjectNotBuilt() { using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, "class C1 { void M() { System.Console.WriteLine(1); } }"); _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(Guid.Empty); await StartDebuggingSessionAsync(service, solution); // no changes: var diagnostics = await service.GetDocumentDiagnosticsAsync(document1, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); // change the source: solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { System.Console.WriteLine(2); } }")); var document2 = solution.GetDocument(document1.Id); diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); } [Fact] public async Task DifferentDocumentWithSameContent() { var source = "class C1 { void M1() { System.Console.WriteLine(1); } }"; var moduleFile = Temp.CreateFile().WriteAllBytes(TestResources.Basic.Members); using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, source); solution = solution.WithProjectOutputFilePath(document.Project.Id, moduleFile.Path); _mockCompilationOutputsProvider = _ => new CompilationOutputFiles(moduleFile.Path); var debuggingSession = await StartDebuggingSessionAsync(service, solution); // update the document var document1 = solution.GetDocument(document.Id); solution = solution.WithDocumentText(document.Id, SourceText.From(source)); var document2 = solution.GetDocument(document.Id); Assert.Equal(document1.Id, document2.Id); Assert.NotSame(document1, document2); var diagnostics2 = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics2); // validate solution update status and emit - changes made during run mode are ignored: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); EndDebuggingSession(debuggingSession); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=0|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=1" }, _telemetryLog); } [Theory] [CombinatorialData] public async Task ProjectThatDoesNotSupportEnC(bool breakMode) { using var _ = CreateWorkspace(out var solution, out var service, new[] { typeof(DummyLanguageService) }); var project = solution.AddProject("dummy_proj", "dummy_proj", DummyLanguageService.LanguageName); var document = project.AddDocument("test", SourceText.From("dummy1")); solution = document.Project.Solution; var debuggingSession = await StartDebuggingSessionAsync(service, solution); if (breakMode) { EnterBreakState(debuggingSession); } // no changes: var document1 = solution.Projects.Single().Documents.Single(); var diagnostics = await service.GetDocumentDiagnosticsAsync(document1, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); // change the source: solution = solution.WithDocumentText(document1.Id, SourceText.From("dummy2")); // validate solution update status and emit: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); var document2 = solution.GetDocument(document1.Id); diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); } [Fact] public async Task DesignTimeOnlyDocument() { var moduleFile = Temp.CreateFile().WriteAllBytes(TestResources.Basic.Members); using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, "class C1 { void M() { System.Console.WriteLine(1); } }"); var documentInfo = CreateDesignTimeOnlyDocument(document1.Project.Id); solution = solution.WithProjectOutputFilePath(document1.Project.Id, moduleFile.Path).AddDocument(documentInfo); _mockCompilationOutputsProvider = _ => new CompilationOutputFiles(moduleFile.Path); var debuggingSession = await StartDebuggingSessionAsync(service, solution); // update a design-time-only source file: solution = solution.WithDocumentText(documentInfo.Id, SourceText.From("class UpdatedC2 {}")); var document2 = solution.GetDocument(documentInfo.Id); // no updates: var diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); // validate solution update status and emit - changes made in design-time-only documents are ignored: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); EndDebuggingSession(debuggingSession); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=0|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=1" }, _telemetryLog); } [Fact] public async Task DesignTimeOnlyDocument_Dynamic() { using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, "class C {}"); var documentInfo = DocumentInfo.Create( DocumentId.CreateNewId(document.Project.Id), name: "design-time-only.cs", folders: Array.Empty<string>(), sourceCodeKind: SourceCodeKind.Regular, loader: TextLoader.From(TextAndVersion.Create(SourceText.From("class D {}"), VersionStamp.Create(), "design-time-only.cs")), filePath: "design-time-only.cs", isGenerated: false, designTimeOnly: true, documentServiceProvider: null); solution = solution.AddDocument(documentInfo); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source: var document1 = solution.GetDocument(documentInfo.Id); solution = solution.WithDocumentText(document1.Id, SourceText.From("class E {}")); // validate solution update status and emit: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); } [Theory] [InlineData(true)] [InlineData(false)] public async Task DesignTimeOnlyDocument_Wpf(bool delayLoad) { var sourceA = "class A { public void M() { } }"; var sourceB = "class B { public void M() { } }"; var sourceC = "class C { public void M() { } }"; var dir = Temp.CreateDirectory(); var sourceFileA = dir.CreateFile("a.cs").WriteAllText(sourceA); using var _ = CreateWorkspace(out var solution, out var service); // the workspace starts with a version of the source that's not updated with the output of single file generator (or design-time build): var documentA = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)). AddDocument("a.cs", SourceText.From(sourceA, Encoding.UTF8), filePath: sourceFileA.Path); var documentB = documentA.Project. AddDocument("b.g.i.cs", SourceText.From(sourceB, Encoding.UTF8), filePath: "b.g.i.cs"); var documentC = documentB.Project. AddDocument("c.g.i.vb", SourceText.From(sourceC, Encoding.UTF8), filePath: "c.g.i.vb"); solution = documentC.Project.Solution; // only compile A; B and C are design-time-only: var moduleId = EmitLibrary(sourceA, sourceFilePath: sourceFileA.Path); if (!delayLoad) { LoadLibraryToDebuggee(moduleId); } var sessionId = await service.StartDebuggingSessionAsync(solution, _debuggerService, captureMatchingDocuments: ImmutableArray<DocumentId>.Empty, captureAllMatchingDocuments: false, reportDiagnostics: true, CancellationToken.None); var debuggingSession = service.GetTestAccessor().GetDebuggingSession(sessionId); EnterBreakState(debuggingSession); // change the source (rude edit): solution = solution.WithDocumentText(documentB.Id, SourceText.From("class B { public void RenamedMethod() { } }")); solution = solution.WithDocumentText(documentC.Id, SourceText.From("class C { public void RenamedMethod() { } }")); var documentB2 = solution.GetDocument(documentB.Id); var documentC2 = solution.GetDocument(documentC.Id); // no Rude Edits reported: Assert.Empty(await service.GetDocumentDiagnosticsAsync(documentB2, s_noActiveSpans, CancellationToken.None)); Assert.Empty(await service.GetDocumentDiagnosticsAsync(documentC2, s_noActiveSpans, CancellationToken.None)); // validate solution update status and emit: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(emitDiagnostics); if (delayLoad) { LoadLibraryToDebuggee(moduleId); // validate solution update status and emit: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(emitDiagnostics); } EndDebuggingSession(debuggingSession); } [Theory] [CombinatorialData] public async Task ErrorReadingModuleFile(bool breakMode) { // module file is empty, which will cause a read error: var moduleFile = Temp.CreateFile(); string expectedErrorMessage = null; try { using var stream = File.OpenRead(moduleFile.Path); using var peReader = new PEReader(stream); _ = peReader.GetMetadataReader(); } catch (Exception e) { expectedErrorMessage = e.Message; } using var _w = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, "class C1 { void M() { System.Console.WriteLine(1); } }"); _mockCompilationOutputsProvider = _ => new CompilationOutputFiles(moduleFile.Path); var debuggingSession = await StartDebuggingSessionAsync(service, solution); if (breakMode) { EnterBreakState(debuggingSession); } // change the source: solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { System.Console.WriteLine(2); } }")); var document2 = solution.GetDocument(document1.Id); // error not reported here since it might be intermittent and will be reported if the issue persist when applying the update: var diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); AssertEx.Equal(new[] { $"{document2.Project.Id} Error ENC1001: {string.Format(FeaturesResources.ErrorReadingFile, moduleFile.Path, expectedErrorMessage)}" }, InspectDiagnostics(emitDiagnostics)); if (breakMode) { ExitBreakState(debuggingSession); } EndDebuggingSession(debuggingSession); if (breakMode) { AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=2", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=1|InBreakState=True|Capabilities=31", "Debugging_EncSession_EditSession_EmitDeltaErrorId: SessionId=1|EditSessionId=2|ErrorId=ENC1001" }, _telemetryLog); } else { AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=0|EmptySessionCount=0|HotReloadSessionCount=1|EmptyHotReloadSessionCount=0", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=1|InBreakState=False|Capabilities=31", "Debugging_EncSession_EditSession_EmitDeltaErrorId: SessionId=1|EditSessionId=2|ErrorId=ENC1001" }, _telemetryLog); } } [Fact] public async Task ErrorReadingPdbFile() { var source1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("a.cs").WriteAllText(source1); using var _ = CreateWorkspace(out var solution, out var service); var document1 = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)). AddDocument("a.cs", SourceText.From(source1, Encoding.UTF8), filePath: sourceFile.Path); var project = document1.Project; solution = project.Solution; var moduleId = EmitAndLoadLibraryToDebuggee(source1, sourceFilePath: sourceFile.Path); _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(moduleId) { OpenPdbStreamImpl = () => { throw new IOException("Error"); } }; var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); EnterBreakState(debuggingSession); // change the source: solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { System.Console.WriteLine(2); } }", Encoding.UTF8)); var document2 = solution.GetDocument(document1.Id); // error not reported here since it might be intermittent and will be reported if the issue persist when applying the update: var diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); // an error occurred so we need to call update to determine whether we have changes to apply or not: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(updates.Updates); AssertEx.Equal(new[] { $"{project.Id} Warning ENC1006: {string.Format(FeaturesResources.UnableToReadSourceFileOrPdb, sourceFile.Path)}" }, InspectDiagnostics(emitDiagnostics)); EndDebuggingSession(debuggingSession); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=0|EmptySessionCount=1|HotReloadSessionCount=0|EmptyHotReloadSessionCount=1" }, _telemetryLog); } [Fact] public async Task ErrorReadingSourceFile() { var source1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("a.cs").WriteAllText(source1); using var _ = CreateWorkspace(out var solution, out var service); var document1 = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(DefaultTargetFramework)). AddDocument("a.cs", SourceText.From(source1, Encoding.UTF8), filePath: sourceFile.Path); var project = document1.Project; solution = project.Solution; var moduleId = EmitAndLoadLibraryToDebuggee(source1, sourceFilePath: sourceFile.Path); var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); EnterBreakState(debuggingSession); // change the source: solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { System.Console.WriteLine(2); } }", Encoding.UTF8)); var document2 = solution.GetDocument(document1.Id); using var fileLock = File.Open(sourceFile.Path, FileMode.Open, FileAccess.Read, FileShare.None); // error not reported here since it might be intermittent and will be reported if the issue persist when applying the update: var diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); // an error occurred so we need to call update to determine whether we have changes to apply or not: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); // try apply changes: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(updates.Updates); AssertEx.Equal(new[] { $"{project.Id} Warning ENC1006: {string.Format(FeaturesResources.UnableToReadSourceFileOrPdb, sourceFile.Path)}" }, InspectDiagnostics(emitDiagnostics)); fileLock.Dispose(); // try apply changes again: (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); Assert.NotEmpty(updates.Updates); Assert.Empty(emitDiagnostics); EndDebuggingSession(debuggingSession); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=1", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=0|InBreakState=True|Capabilities=31" }, _telemetryLog); } [Theory] [CombinatorialData] public async Task FileAdded(bool breakMode) { var sourceA = "class C1 { void M() { System.Console.WriteLine(1); } }"; var sourceB = "class C2 {}"; var sourceFileA = Temp.CreateFile().WriteAllText(sourceA); var sourceFileB = Temp.CreateFile().WriteAllText(sourceB); using var _ = CreateWorkspace(out var solution, out var service); var documentA = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)). AddDocument("test.cs", SourceText.From(sourceA, Encoding.UTF8), filePath: sourceFileA.Path); solution = documentA.Project.Solution; // Source B will be added while debugging. EmitAndLoadLibraryToDebuggee(sourceA, sourceFilePath: sourceFileA.Path); var project = documentA.Project; var debuggingSession = await StartDebuggingSessionAsync(service, solution); if (breakMode) { EnterBreakState(debuggingSession); } // add a source file: var documentB = project.AddDocument("file2.cs", SourceText.From(sourceB, Encoding.UTF8), filePath: sourceFileB.Path); solution = documentB.Project.Solution; documentB = solution.GetDocument(documentB.Id); var diagnostics2 = await service.GetDocumentDiagnosticsAsync(documentB, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics2); Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); if (breakMode) { ExitBreakState(debuggingSession); } EndDebuggingSession(debuggingSession); if (breakMode) { AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=2", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=0|InBreakState=True|Capabilities=31" }, _telemetryLog); } else { AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=0|EmptySessionCount=0|HotReloadSessionCount=1|EmptyHotReloadSessionCount=0", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=0|InBreakState=False|Capabilities=31" }, _telemetryLog); } } [Fact] public async Task ModuleDisallowsEditAndContinue() { var moduleId = Guid.NewGuid(); var source1 = @" class C1 { void M() { System.Console.WriteLine(1); System.Console.WriteLine(2); System.Console.WriteLine(3); } }"; var source2 = @" class C1 { void M() { System.Console.WriteLine(9); System.Console.WriteLine(); System.Console.WriteLine(30); } }"; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, source1); _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(moduleId); LoadLibraryToDebuggee(moduleId, new ManagedEditAndContinueAvailability(ManagedEditAndContinueAvailabilityStatus.NotAllowedForRuntime, "*message*")); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source: var document1 = solution.Projects.Single().Documents.Single(); solution = solution.WithDocumentText(document1.Id, SourceText.From(source2)); var document2 = solution.GetDocument(document1.Id); // We do not report module diagnostics until emit. // This is to make the analysis deterministic (not dependent on the current state of the debuggee). var diagnostics1 = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Empty(diagnostics1); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); AssertEx.Equal(new[] { $"{document2.Project.Id} Error ENC2016: {string.Format(FeaturesResources.EditAndContinueDisallowedByProject, document2.Project.Name, "*message*")}" }, InspectDiagnostics(emitDiagnostics)); EndDebuggingSession(debuggingSession); AssertEx.SetEqual(new[] { moduleId }, debuggingSession.GetTestAccessor().GetModulesPreparedForUpdate()); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=1", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=1|InBreakState=True|Capabilities=31", "Debugging_EncSession_EditSession_EmitDeltaErrorId: SessionId=1|EditSessionId=2|ErrorId=ENC2016" }, _telemetryLog); } [Fact] public async Task Encodings() { var source1 = "class C1 { void M() { System.Console.WriteLine(\"ã\"); } }"; var encoding = Encoding.GetEncoding(1252); var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("test.cs").WriteAllText(source1, encoding); using var _ = CreateWorkspace(out var solution, out var service); var document1 = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)). AddDocument("test.cs", SourceText.From(source1, encoding), filePath: sourceFile.Path); var documentId = document1.Id; var project = document1.Project; solution = project.Solution; var moduleId = EmitAndLoadLibraryToDebuggee(source1, sourceFilePath: sourceFile.Path, encoding: encoding); var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); EnterBreakState(debuggingSession); // Emulate opening the file, which will trigger "out-of-sync" check. // Since we find content matching the PDB checksum we update the committed solution with this source text. // If we used wrong encoding this would lead to a false change detected below. var currentDocument = solution.GetDocument(documentId); await debuggingSession.OnSourceFileUpdatedAsync(currentDocument); // EnC service queries for a document, which triggers read of the source file from disk. Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); EndDebuggingSession(debuggingSession); } [Theory] [CombinatorialData] public async Task RudeEdits(bool breakMode) { var source1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var source2 = "class C1 { void M1() { System.Console.WriteLine(1); } }"; var moduleId = Guid.NewGuid(); using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, source1); _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); if (breakMode) { EnterBreakState(debuggingSession); } // change the source (rude edit): var document1 = solution.Projects.Single().Documents.Single(); solution = solution.WithDocumentText(document1.Id, SourceText.From(source2, Encoding.UTF8)); var document2 = solution.GetDocument(document1.Id); var diagnostics1 = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Equal(new[] { "ENC0020: " + string.Format(FeaturesResources.Renaming_0_requires_restarting_the_application, FeaturesResources.method) }, diagnostics1.Select(d => $"{d.Id}: {d.GetMessage()}")); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); if (breakMode) { ExitBreakState(debuggingSession, documentsWithRudeEdits: ImmutableArray.Create(document2.Id)); EndDebuggingSession(debuggingSession); } else { EndDebuggingSession(debuggingSession, documentsWithRudeEdits: ImmutableArray.Create(document2.Id)); } AssertEx.SetEqual(new[] { moduleId }, debuggingSession.GetTestAccessor().GetModulesPreparedForUpdate()); if (breakMode) { AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=2", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=True|HadValidChanges=False|HadValidInsignificantChanges=False|RudeEditsCount=1|EmitDeltaErrorIdCount=0|InBreakState=True|Capabilities=31", "Debugging_EncSession_EditSession_RudeEdit: SessionId=1|EditSessionId=2|RudeEditKind=20|RudeEditSyntaxKind=8875|RudeEditBlocking=True" }, _telemetryLog); } else { AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=0|EmptySessionCount=0|HotReloadSessionCount=1|EmptyHotReloadSessionCount=0", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=True|HadValidChanges=False|HadValidInsignificantChanges=False|RudeEditsCount=1|EmitDeltaErrorIdCount=0|InBreakState=False|Capabilities=31", "Debugging_EncSession_EditSession_RudeEdit: SessionId=1|EditSessionId=2|RudeEditKind=20|RudeEditSyntaxKind=8875|RudeEditBlocking=True" }, _telemetryLog); } } [Fact] public async Task RudeEdits_SourceGenerators() { var sourceV1 = @" /* GENERATE: class G { int X1 => 1; } */ class C { int Y => 1; } "; var sourceV2 = @" /* GENERATE: class G { int X2 => 1; } */ class C { int Y => 2; } "; var generator = new TestSourceGenerator() { ExecuteImpl = GenerateSource }; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, sourceV1, generator: generator); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source: var document1 = solution.Projects.Single().Documents.Single(); solution = solution.WithDocumentText(document1.Id, SourceText.From(sourceV2, Encoding.UTF8)); var generatedDocument = (await solution.Projects.Single().GetSourceGeneratedDocumentsAsync()).Single(); var diagnostics1 = await service.GetDocumentDiagnosticsAsync(generatedDocument, s_noActiveSpans, CancellationToken.None); AssertEx.Equal(new[] { "ENC0020: " + string.Format(FeaturesResources.Renaming_0_requires_restarting_the_application, FeaturesResources.property_) }, diagnostics1.Select(d => $"{d.Id}: {d.GetMessage()}")); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); EndDebuggingSession(debuggingSession, documentsWithRudeEdits: ImmutableArray.Create(generatedDocument.Id)); } [Theory] [CombinatorialData] public async Task RudeEdits_DocumentOutOfSync(bool breakMode) { var source0 = "class C1 { void M() { System.Console.WriteLine(0); } }"; var source1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var source2 = "class C1 { void RenamedMethod() { System.Console.WriteLine(1); } }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("a.cs"); using var _ = CreateWorkspace(out var solution, out var service); var project = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)); solution = project.Solution; // compile with source0: var moduleId = EmitAndLoadLibraryToDebuggee(source0, sourceFilePath: sourceFile.Path); // update the file with source1 before session starts: sourceFile.WriteAllText(source1); // source1 is reflected in workspace before session starts: var document1 = project.AddDocument("a.cs", SourceText.From(source1, Encoding.UTF8), filePath: sourceFile.Path); solution = document1.Project.Solution; var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); if (breakMode) { EnterBreakState(debuggingSession); } // change the source (rude edit): solution = solution.WithDocumentText(document1.Id, SourceText.From(source2)); var document2 = solution.GetDocument(document1.Id); // no Rude Edits, since the document is out-of-sync var diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); // since the document is out-of-sync we need to call update to determine whether we have changes to apply or not: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(updates.Updates); AssertEx.Equal(new[] { $"{project.Id} Warning ENC1005: {string.Format(FeaturesResources.DocumentIsOutOfSyncWithDebuggee, sourceFile.Path)}" }, InspectDiagnostics(emitDiagnostics)); // update the file to match the build: sourceFile.WriteAllText(source0); // we do not reload the content of out-of-sync file for analyzer query: diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); // debugger query will trigger reload of out-of-sync file content: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); // now we see the rude edit: diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Equal(new[] { "ENC0020: " + string.Format(FeaturesResources.Renaming_0_requires_restarting_the_application, FeaturesResources.method) }, diagnostics.Select(d => $"{d.Id}: {d.GetMessage()}")); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); if (breakMode) { ExitBreakState(debuggingSession, documentsWithRudeEdits: ImmutableArray.Create(document2.Id)); EndDebuggingSession(debuggingSession); } else { EndDebuggingSession(debuggingSession, documentsWithRudeEdits: ImmutableArray.Create(document2.Id)); } AssertEx.SetEqual(new[] { moduleId }, debuggingSession.GetTestAccessor().GetModulesPreparedForUpdate()); if (breakMode) { AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=2", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=True|HadValidChanges=False|HadValidInsignificantChanges=False|RudeEditsCount=1|EmitDeltaErrorIdCount=0|InBreakState=True|Capabilities=31", "Debugging_EncSession_EditSession_RudeEdit: SessionId=1|EditSessionId=2|RudeEditKind=20|RudeEditSyntaxKind=8875|RudeEditBlocking=True" }, _telemetryLog); } else { AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=0|EmptySessionCount=0|HotReloadSessionCount=1|EmptyHotReloadSessionCount=0", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=True|HadValidChanges=False|HadValidInsignificantChanges=False|RudeEditsCount=1|EmitDeltaErrorIdCount=0|InBreakState=False|Capabilities=31", "Debugging_EncSession_EditSession_RudeEdit: SessionId=1|EditSessionId=2|RudeEditKind=20|RudeEditSyntaxKind=8875|RudeEditBlocking=True" }, _telemetryLog); } } [Fact] public async Task RudeEdits_DocumentWithoutSequencePoints() { var source1 = "abstract class C { public abstract void M(); }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("a.cs").WriteAllText(source1); using var _ = CreateWorkspace(out var solution, out var service); // the workspace starts with a version of the source that's not updated with the output of single file generator (or design-time build): var document1 = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)). AddDocument("test.cs", SourceText.From(source1, Encoding.UTF8), filePath: sourceFile.Path); var project = document1.Project; solution = project.Solution; var moduleId = EmitAndLoadLibraryToDebuggee(source1, sourceFilePath: sourceFile.Path); // do not initialize the document state - we will detect the state based on the PDB content. var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); EnterBreakState(debuggingSession); // change the source (rude edit since the base document content matches the PDB checksum, so the document is not out-of-sync): solution = solution.WithDocumentText(document1.Id, SourceText.From("abstract class C { public abstract void M(); public abstract void N(); }")); var document2 = solution.Projects.Single().Documents.Single(); // Rude Edits reported: var diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Equal( new[] { "ENC0023: " + string.Format(FeaturesResources.Adding_an_abstract_0_or_overriding_an_inherited_0_requires_restarting_the_application, FeaturesResources.method) }, diagnostics.Select(d => $"{d.Id}: {d.GetMessage()}")); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); EndDebuggingSession(debuggingSession, documentsWithRudeEdits: ImmutableArray.Create(document2.Id)); } [Fact] public async Task RudeEdits_DelayLoadedModule() { var source1 = "class C { public void M() { } }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("a.cs").WriteAllText(source1); using var _ = CreateWorkspace(out var solution, out var service); // the workspace starts with a version of the source that's not updated with the output of single file generator (or design-time build): var document1 = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)). AddDocument("test.cs", SourceText.From(source1, Encoding.UTF8), filePath: sourceFile.Path); var project = document1.Project; solution = project.Solution; var moduleId = EmitLibrary(source1, sourceFilePath: sourceFile.Path); // do not initialize the document state - we will detect the state based on the PDB content. var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); EnterBreakState(debuggingSession); // change the source (rude edit) before the library is loaded: solution = solution.WithDocumentText(document1.Id, SourceText.From("class C { public void Renamed() { } }")); var document2 = solution.Projects.Single().Documents.Single(); // Rude Edits reported: var diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Equal( new[] { "ENC0020: " + string.Format(FeaturesResources.Renaming_0_requires_restarting_the_application, FeaturesResources.method) }, diagnostics.Select(d => $"{d.Id}: {d.GetMessage()}")); Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); // load library to the debuggee: LoadLibraryToDebuggee(moduleId); // Rude Edits still reported: diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Equal( new[] { "ENC0020: " + string.Format(FeaturesResources.Renaming_0_requires_restarting_the_application, FeaturesResources.method) }, diagnostics.Select(d => $"{d.Id}: {d.GetMessage()}")); Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); EndDebuggingSession(debuggingSession, documentsWithRudeEdits: ImmutableArray.Create(document2.Id)); } [Fact] public async Task SyntaxError() { var moduleId = Guid.NewGuid(); using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, "class C1 { void M() { System.Console.WriteLine(1); } }"); _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source (compilation error): var document1 = solution.Projects.Single().Documents.Single(); solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { ")); var document2 = solution.Projects.Single().Documents.Single(); // compilation errors are not reported via EnC diagnostic analyzer: var diagnostics1 = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Empty(diagnostics1); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); EndDebuggingSession(debuggingSession); AssertEx.SetEqual(new[] { moduleId }, debuggingSession.GetTestAccessor().GetModulesPreparedForUpdate()); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=1", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=True|HadRudeEdits=False|HadValidChanges=False|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=0|InBreakState=True|Capabilities=31" }, _telemetryLog); } [Fact] public async Task SemanticError() { var sourceV1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, sourceV1); var moduleId = EmitAndLoadLibraryToDebuggee(sourceV1); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source (compilation error): var document1 = solution.Projects.Single().Documents.Single(); solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { int i = 0L; System.Console.WriteLine(i); } }", Encoding.UTF8)); var document2 = solution.Projects.Single().Documents.Single(); // compilation errors are not reported via EnC diagnostic analyzer: var diagnostics1 = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Empty(diagnostics1); // The EnC analyzer does not check for and block on all semantic errors as they are already reported by diagnostic analyzer. // Blocking update on semantic errors would be possible, but the status check is only an optimization to avoid emitting. Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); // TODO: https://github.com/dotnet/roslyn/issues/36061 // Semantic errors should not be reported in emit diagnostics. AssertEx.Equal(new[] { $"{document2.Project.Id} Error CS0266: {string.Format(CSharpResources.ERR_NoImplicitConvCast, "long", "int")}" }, InspectDiagnostics(emitDiagnostics)); EndDebuggingSession(debuggingSession); AssertEx.SetEqual(new[] { moduleId }, debuggingSession.GetTestAccessor().GetModulesPreparedForUpdate()); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=1", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=1|InBreakState=True|Capabilities=31", "Debugging_EncSession_EditSession_EmitDeltaErrorId: SessionId=1|EditSessionId=2|ErrorId=CS0266" }, _telemetryLog); } [Fact] public async Task FileStatus_CompilationError() { using var _ = CreateWorkspace(out var solution, out var service); solution = solution. AddProject("A", "A", "C#"). AddDocument("A.cs", "class Program { void Main() { System.Console.WriteLine(1); } }", filePath: "A.cs").Project.Solution. AddProject("B", "B", "C#"). AddDocument("Common.cs", "class Common {}", filePath: "Common.cs").Project. AddDocument("B.cs", "class B {}", filePath: "B.cs").Project.Solution. AddProject("C", "C", "C#"). AddDocument("Common.cs", "class Common {}", filePath: "Common.cs").Project. AddDocument("C.cs", "class C {}", filePath: "C.cs").Project.Solution; var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change C.cs to have a compilation error: var projectC = solution.GetProjectsByName("C").Single(); var documentC = projectC.Documents.Single(d => d.Name == "C.cs"); solution = solution.WithDocumentText(documentC.Id, SourceText.From("class C { void M() { ")); // Common.cs is included in projects B and C. Both of these projects must have no errors, otherwise update is blocked. Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: "Common.cs", CancellationToken.None)); // No changes in project containing file B.cs. Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: "B.cs", CancellationToken.None)); // All projects must have no errors. Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); EndDebuggingSession(debuggingSession); } [Fact] [WorkItem(1204, "https://github.com/dotnet/roslyn/issues/1204")] [WorkItem(1371694, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371694")] public async Task Project_Add() { var sourceA1 = "class A { void M() { System.Console.WriteLine(1); } }"; var sourceB1 = "class B { int F() => 1; }"; var sourceB2 = "class B { int G() => 1; }"; var sourceB3 = "class B { int F() => 2; }"; var dir = Temp.CreateDirectory(); var sourceFileA = dir.CreateFile("a.cs").WriteAllText(sourceA1); var sourceFileB = dir.CreateFile("b.cs").WriteAllText(sourceB1); using var _ = CreateWorkspace(out var solution, out var service); solution = AddDefaultTestProject(solution, new[] { sourceA1 }); var documentA1 = solution.Projects.Single().Documents.Single(); var mvidA = EmitAndLoadLibraryToDebuggee(sourceA1, sourceFilePath: sourceFileA.Path, assemblyName: "A"); var mvidB = EmitAndLoadLibraryToDebuggee(sourceB1, sourceFilePath: sourceFileB.Path, assemblyName: "B"); var debuggingSession = await StartDebuggingSessionAsync(service, solution); // An active statement may be present in the added file since the file exists in the PDB: var activeLineSpanA1 = SourceText.From(sourceA1, Encoding.UTF8).Lines.GetLinePositionSpan(GetSpan(sourceA1, "System.Console.WriteLine(1);")); var activeLineSpanB1 = SourceText.From(sourceB1, Encoding.UTF8).Lines.GetLinePositionSpan(GetSpan(sourceB1, "1")); var activeStatements = ImmutableArray.Create( new ManagedActiveStatementDebugInfo( new ManagedInstructionId(new ManagedMethodId(mvidA, token: 0x06000001, version: 1), ilOffset: 1), sourceFileA.Path, activeLineSpanA1.ToSourceSpan(), ActiveStatementFlags.IsLeafFrame | ActiveStatementFlags.MethodUpToDate), new ManagedActiveStatementDebugInfo( new ManagedInstructionId(new ManagedMethodId(mvidB, token: 0x06000001, version: 1), ilOffset: 1), sourceFileB.Path, activeLineSpanB1.ToSourceSpan(), ActiveStatementFlags.IsLeafFrame | ActiveStatementFlags.MethodUpToDate)); EnterBreakState(debuggingSession, activeStatements); // add project that matches assembly B and update the document: var documentB2 = solution. AddProject("B", "B", LanguageNames.CSharp). AddDocument("b.cs", SourceText.From(sourceB2, Encoding.UTF8, SourceHashAlgorithm.Sha256), filePath: sourceFileB.Path); solution = documentB2.Project.Solution; // TODO: https://github.com/dotnet/roslyn/issues/1204 // Should return span in document B since the document content matches the PDB. var baseSpans = await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(documentA1.Id, documentB2.Id), CancellationToken.None); AssertEx.Equal(new[] { "<empty>", "(0,21)-(0,22)" }, baseSpans.Select(spans => spans.IsEmpty ? "<empty>" : string.Join(",", spans.Select(s => s.LineSpan.ToString())))); var trackedActiveSpans = ImmutableArray.Create( new ActiveStatementSpan(1, activeLineSpanB1, ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame, unmappedDocumentId: null)); var currentSpans = await debuggingSession.GetAdjustedActiveStatementSpansAsync(documentB2, (_, _, _) => new(trackedActiveSpans), CancellationToken.None); // TODO: https://github.com/dotnet/roslyn/issues/1204 // AssertEx.Equal(trackedActiveSpans, currentSpans); Assert.Empty(currentSpans); Assert.Equal(activeLineSpanB1, await debuggingSession.GetCurrentActiveStatementPositionAsync(documentB2.Project.Solution, (_, _, _) => new(trackedActiveSpans), activeStatements[1].ActiveInstruction, CancellationToken.None)); var diagnostics = await service.GetDocumentDiagnosticsAsync(documentB2, s_noActiveSpans, CancellationToken.None); // TODO: https://github.com/dotnet/roslyn/issues/1204 //AssertEx.Equal( // new[] { "ENC0020: " + string.Format(FeaturesResources.Renaming_0_requires_restarting_the_application, FeaturesResources.method) }, // diagnostics.Select(d => $"{d.Id}: {d.GetMessage()}")); Assert.Empty(diagnostics); // update document with a valid change: solution = solution.WithDocumentText(documentB2.Id, SourceText.From(sourceB3, Encoding.UTF8, SourceHashAlgorithm.Sha256)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); // TODO: https://github.com/dotnet/roslyn/issues/1204 // verify valid update Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); ExitBreakState(debuggingSession); EndDebuggingSession(debuggingSession); } [Fact] public async Task Capabilities() { var source1 = "class C { void M() { } }"; var source2 = "[System.Obsolete]class C { void M() { } }"; using var _ = CreateWorkspace(out var solution, out var service); solution = AddDefaultTestProject(solution, new[] { source1 }); var documentId = solution.Projects.Single().Documents.Single().Id; EmitAndLoadLibraryToDebuggee(source1); // attached to processes that allow updating custom attributes: _debuggerService.GetCapabilitiesImpl = () => ImmutableArray.Create("Baseline", "ChangeCustomAttributes"); // F5 var debuggingSession = await StartDebuggingSessionAsync(service, solution); // update document: solution = solution.WithDocumentText(documentId, SourceText.From(source2, Encoding.UTF8)); var diagnostics = await service.GetDocumentDiagnosticsAsync(solution.GetDocument(documentId), s_noActiveSpans, CancellationToken.None); AssertEx.Empty(diagnostics); EnterBreakState(debuggingSession); diagnostics = await service.GetDocumentDiagnosticsAsync(solution.GetDocument(documentId), s_noActiveSpans, CancellationToken.None); AssertEx.Empty(diagnostics); // attach to additional processes - at least one process that does not allow updating custom attributes: ExitBreakState(debuggingSession); _debuggerService.GetCapabilitiesImpl = () => ImmutableArray.Create("Baseline"); EnterBreakState(debuggingSession); diagnostics = await service.GetDocumentDiagnosticsAsync(solution.GetDocument(documentId), s_noActiveSpans, CancellationToken.None); AssertEx.Equal(new[] { "ENC0101: " + string.Format(FeaturesResources.Updating_the_attributes_of_0_requires_restarting_the_application_because_it_is_not_supported_by_the_runtime, FeaturesResources.class_) }, diagnostics.Select(d => $"{d.Id}: {d.GetMessage()}")); ExitBreakState(debuggingSession, documentsWithRudeEdits: ImmutableArray.Create(documentId)); diagnostics = await service.GetDocumentDiagnosticsAsync(solution.GetDocument(documentId), s_noActiveSpans, CancellationToken.None); AssertEx.Equal(new[] { "ENC0101: " + string.Format(FeaturesResources.Updating_the_attributes_of_0_requires_restarting_the_application_because_it_is_not_supported_by_the_runtime, FeaturesResources.class_) }, diagnostics.Select(d => $"{d.Id}: {d.GetMessage()}")); // detach from processes that do not allow updating custom attributes: _debuggerService.GetCapabilitiesImpl = () => ImmutableArray.Create("Baseline", "ChangeCustomAttributes"); EnterBreakState(debuggingSession, documentsWithRudeEdits: ImmutableArray.Create(documentId)); diagnostics = await service.GetDocumentDiagnosticsAsync(solution.GetDocument(documentId), s_noActiveSpans, CancellationToken.None); AssertEx.Empty(diagnostics); ExitBreakState(debuggingSession); EndDebuggingSession(debuggingSession); } [Fact] public async Task Capabilities_SynthesizedNewType() { var source1 = "class C { void M() { } }"; var source2 = "class C { void M() { var x = new { Goo = 1 }; } }"; using var _ = CreateWorkspace(out var solution, out var service); solution = AddDefaultTestProject(solution, new[] { source1 }); var project = solution.Projects.Single(); solution = solution.WithProjectParseOptions(project.Id, new CSharpParseOptions(LanguageVersion.CSharp10)); var documentId = solution.Projects.Single().Documents.Single().Id; EmitAndLoadLibraryToDebuggee(source1); // attached to processes that doesn't allow creating new types _debuggerService.GetCapabilitiesImpl = () => ImmutableArray.Create("Baseline"); // F5 var debuggingSession = await StartDebuggingSessionAsync(service, solution); // update document: solution = solution.WithDocumentText(documentId, SourceText.From(source2, Encoding.UTF8)); var document2 = solution.Projects.Single().Documents.Single(); // These errors aren't reported as document diagnostics var diagnostics = await service.GetDocumentDiagnosticsAsync(solution.GetDocument(documentId), s_noActiveSpans, CancellationToken.None); AssertEx.Empty(diagnostics); // They are reported as emit diagnostics var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); AssertEx.Equal(new[] { $"{document2.Project.Id} Error ENC1007: {FeaturesResources.ChangesRequiredSynthesizedType}" }, InspectDiagnostics(emitDiagnostics)); // no emitted delta: Assert.Empty(updates.Updates); EndDebuggingSession(debuggingSession); } [Fact] public async Task ValidSignificantChange_EmitError() { var sourceV1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, sourceV1); EmitAndLoadLibraryToDebuggee(sourceV1); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source (valid edit but passing no encoding to emulate emit error): var document1 = solution.Projects.Single().Documents.Single(); solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { System.Console.WriteLine(2); } }", encoding: null)); var document2 = solution.Projects.Single().Documents.Single(); var diagnostics1 = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Empty(diagnostics1); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); AssertEx.Equal(new[] { $"{document2.Project.Id} Error CS8055: {string.Format(CSharpResources.ERR_EncodinglessSyntaxTree)}" }, InspectDiagnostics(emitDiagnostics)); // no emitted delta: Assert.Empty(updates.Updates); // no pending update: Assert.Null(debuggingSession.GetTestAccessor().GetPendingSolutionUpdate()); Assert.Throws<InvalidOperationException>(() => debuggingSession.CommitSolutionUpdate(out var _)); Assert.Throws<InvalidOperationException>(() => debuggingSession.DiscardSolutionUpdate()); // no change in non-remappable regions since we didn't have any active statements: Assert.Empty(debuggingSession.EditSession.NonRemappableRegions); // solution update status after discarding an update (still has update ready): Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); EndDebuggingSession(debuggingSession); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=1", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=1|InBreakState=True|Capabilities=31", "Debugging_EncSession_EditSession_EmitDeltaErrorId: SessionId=1|EditSessionId=2|ErrorId=CS8055" }, _telemetryLog); } [Theory] [InlineData(true)] [InlineData(false)] public async Task ValidSignificantChange_ApplyBeforeFileWatcherEvent(bool saveDocument) { // Scenarios tested: // // SaveDocument=true // workspace: --V0-------------|--V2--------|------------| // file system: --V0---------V1--|-----V2-----|------------| // \--build--/ F5 ^ F10 ^ F10 // save file watcher: no-op // SaveDocument=false // workspace: --V0-------------|--V2--------|----V1------| // file system: --V0---------V1--|------------|------------| // \--build--/ F5 F10 ^ F10 // file watcher: workspace update var source1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("test.cs").WriteAllText(source1); using var _ = CreateWorkspace(out var solution, out var service); // the workspace starts with a version of the source that's not updated with the output of single file generator (or design-time build): var document1 = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(DefaultTargetFramework)). AddDocument("test.cs", SourceText.From("class C1 { void M() { System.Console.WriteLine(0); } }", Encoding.UTF8), filePath: sourceFile.Path); var documentId = document1.Id; solution = document1.Project.Solution; var moduleId = EmitAndLoadLibraryToDebuggee(source1, sourceFilePath: sourceFile.Path); var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); EnterBreakState(debuggingSession); // The user opens the source file and changes the source before Roslyn receives file watcher event. var source2 = "class C1 { void M() { System.Console.WriteLine(2); } }"; solution = solution.WithDocumentText(documentId, SourceText.From(source2, Encoding.UTF8)); var document2 = solution.GetDocument(documentId); // Save the document: if (saveDocument) { await debuggingSession.OnSourceFileUpdatedAsync(document2); sourceFile.WriteAllText(source2); } // EnC service queries for a document, which triggers read of the source file from disk. Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); CommitSolutionUpdate(debuggingSession); ExitBreakState(debuggingSession); EnterBreakState(debuggingSession); // file watcher updates the workspace: solution = solution.WithDocumentText(documentId, CreateSourceTextFromFile(sourceFile.Path)); var document3 = solution.Projects.Single().Documents.Single(); var hasChanges = await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); if (saveDocument) { Assert.False(hasChanges); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); } else { Assert.True(hasChanges); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); } ExitBreakState(debuggingSession); EndDebuggingSession(debuggingSession); } [Fact] public async Task ValidSignificantChange_FileUpdateNotObservedBeforeDebuggingSessionStart() { // workspace: --V0--------------V2-------|--------V3------------------V1--------------| // file system: --V0---------V1-----V2-----|------------------------------V1------------| // \--build--/ ^save F5 ^ ^F10 (no change) ^save F10 (ok) // file watcher: no-op // build updates file from V0 -> V1 var source1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var source2 = "class C1 { void M() { System.Console.WriteLine(2); } }"; var source3 = "class C1 { void M() { System.Console.WriteLine(3); } }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("test.cs").WriteAllText(source2); using var _ = CreateWorkspace(out var solution, out var service); // the workspace starts with a version of the source that's not updated with the output of single file generator (or design-time build): var document2 = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)). AddDocument("test.cs", SourceText.From(source2, Encoding.UTF8), filePath: sourceFile.Path); var documentId = document2.Id; var project = document2.Project; solution = project.Solution; var moduleId = EmitAndLoadLibraryToDebuggee(source1, sourceFilePath: sourceFile.Path); var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); EnterBreakState(debuggingSession); // user edits the file: solution = solution.WithDocumentText(documentId, SourceText.From(source3, Encoding.UTF8)); var document3 = solution.Projects.Single().Documents.Single(); // EnC service queries for a document, but the source file on disk doesn't match the PDB // We don't report rude edits for out-of-sync documents: var diagnostics = await service.GetDocumentDiagnosticsAsync(document3, s_noActiveSpans, CancellationToken.None); AssertEx.Empty(diagnostics); // since the document is out-of-sync we need to call update to determine whether we have changes to apply or not: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); AssertEx.Equal(new[] { $"{project.Id} Warning ENC1005: {string.Format(FeaturesResources.DocumentIsOutOfSyncWithDebuggee, sourceFile.Path)}" }, InspectDiagnostics(emitDiagnostics)); // undo: solution = solution.WithDocumentText(documentId, SourceText.From(source1, Encoding.UTF8)); var currentDocument = solution.GetDocument(documentId); // save (note that this call will fail to match the content with the PDB since it uses the content prior to the actual file write) await debuggingSession.OnSourceFileUpdatedAsync(currentDocument); var (doc, state) = await debuggingSession.LastCommittedSolution.GetDocumentAndStateAsync(documentId, currentDocument, CancellationToken.None); Assert.Null(doc); Assert.Equal(CommittedSolution.DocumentState.OutOfSync, state); sourceFile.WriteAllText(source1); Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); // the content actually hasn't changed: Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); EndDebuggingSession(debuggingSession); } [Fact] public async Task ValidSignificantChange_AddedFileNotObservedBeforeDebuggingSessionStart() { // workspace: ------|----V0---------------|---------- // file system: --V0--|---------------------|---------- // F5 ^ ^F10 (no change) // file watcher observes the file var source1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("test.cs").WriteAllText(source1); using var _ = CreateWorkspace(out var solution, out var service); // the workspace starts with no file var project = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)); solution = project.Solution; var moduleId = EmitAndLoadLibraryToDebuggee(source1, sourceFilePath: sourceFile.Path); _debuggerService.IsEditAndContinueAvailable = _ => new ManagedEditAndContinueAvailability(ManagedEditAndContinueAvailabilityStatus.Attach, localizedMessage: "*attached*"); var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); // An active statement may be present in the added file since the file exists in the PDB: var activeInstruction1 = new ManagedInstructionId(new ManagedMethodId(moduleId, token: 0x06000001, version: 1), ilOffset: 1); var activeSpan1 = GetSpan(source1, "System.Console.WriteLine(1);"); var sourceText1 = SourceText.From(source1, Encoding.UTF8); var activeLineSpan1 = sourceText1.Lines.GetLinePositionSpan(activeSpan1); var activeStatements = ImmutableArray.Create( new ManagedActiveStatementDebugInfo( activeInstruction1, "test.cs", activeLineSpan1.ToSourceSpan(), ActiveStatementFlags.IsLeafFrame)); // disallow any edits (attach scenario) EnterBreakState(debuggingSession, activeStatements); // File watcher observes the document and adds it to the workspace: var document1 = project.AddDocument("test.cs", sourceText1, filePath: sourceFile.Path); solution = document1.Project.Solution; // We don't report rude edits for the added document: var diagnostics = await service.GetDocumentDiagnosticsAsync(document1, s_noActiveSpans, CancellationToken.None); AssertEx.Empty(diagnostics); // TODO: https://github.com/dotnet/roslyn/issues/49938 // We currently create the AS map against the committed solution, which may not contain all documents. // var spans = await service.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(document1.Id), CancellationToken.None); // AssertEx.Equal(new[] { $"({activeLineSpan1}, IsLeafFrame)" }, spans.Single().Select(s => s.ToString())); // No changes. Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); AssertEx.Empty(emitDiagnostics); EndDebuggingSession(debuggingSession); } [Theory] [CombinatorialData] public async Task ValidSignificantChange_DocumentOutOfSync(bool delayLoad) { var sourceOnDisk = "class C1 { void M() { System.Console.WriteLine(1); } }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("test.cs").WriteAllText(sourceOnDisk); using var _ = CreateWorkspace(out var solution, out var service); // the workspace starts with a version of the source that's not updated with the output of single file generator (or design-time build): var document1 = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)). AddDocument("test.cs", SourceText.From("class C1 { void M() { System.Console.WriteLine(0); } }", Encoding.UTF8), filePath: sourceFile.Path); var project = document1.Project; solution = project.Solution; var moduleId = EmitLibrary(sourceOnDisk, sourceFilePath: sourceFile.Path); if (!delayLoad) { LoadLibraryToDebuggee(moduleId); } var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); EnterBreakState(debuggingSession); // no changes have been made to the project Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); // a file watcher observed a change and updated the document, so it now reflects the content on disk (the code that we compiled): solution = solution.WithDocumentText(document1.Id, SourceText.From(sourceOnDisk, Encoding.UTF8)); var document3 = solution.Projects.Single().Documents.Single(); var diagnostics = await service.GetDocumentDiagnosticsAsync(document3, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); // the content of the file is now exactly the same as the compiled document, so there is no change to be applied: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(emitDiagnostics); EndDebuggingSession(debuggingSession); Assert.Empty(debuggingSession.GetTestAccessor().GetModulesPreparedForUpdate()); } [Theory] [CombinatorialData] public async Task ValidSignificantChange_EmitSuccessful(bool breakMode, bool commitUpdate) { var sourceV1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var sourceV2 = "class C1 { void M() { System.Console.WriteLine(2); } }"; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, sourceV1); var moduleId = EmitAndLoadLibraryToDebuggee(sourceV1); var debuggingSession = await StartDebuggingSessionAsync(service, solution); if (breakMode) { EnterBreakState(debuggingSession); } // change the source (valid edit): solution = solution.WithDocumentText(document1.Id, SourceText.From(sourceV2, Encoding.UTF8)); var document2 = solution.GetDocument(document1.Id); var diagnostics1 = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Empty(diagnostics1); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); ValidateDelta(updates.Updates.Single()); void ValidateDelta(ManagedModuleUpdate delta) { // check emitted delta: Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Equal(0x06000001, delta.UpdatedMethods.Single()); Assert.Equal(0x02000002, delta.UpdatedTypes.Single()); Assert.Equal(moduleId, delta.Module); Assert.Empty(delta.ExceptionRegions); Assert.Empty(delta.SequencePoints); } // the update should be stored on the service: var pendingUpdate = debuggingSession.GetTestAccessor().GetPendingSolutionUpdate(); var (baselineProjectId, newBaseline) = pendingUpdate.EmitBaselines.Single(); AssertEx.Equal(updates.Updates, pendingUpdate.Deltas); Assert.Equal(document2.Project.Id, baselineProjectId); Assert.Equal(moduleId, newBaseline.OriginalMetadata.GetModuleVersionId()); var readers = debuggingSession.GetTestAccessor().GetBaselineModuleReaders(); Assert.Equal(2, readers.Length); Assert.NotNull(readers[0]); Assert.NotNull(readers[1]); if (commitUpdate) { // all update providers either provided updates or had no change to apply: CommitSolutionUpdate(debuggingSession); Assert.Null(debuggingSession.GetTestAccessor().GetPendingSolutionUpdate()); // no change in non-remappable regions since we didn't have any active statements: Assert.Empty(debuggingSession.EditSession.NonRemappableRegions); var baselineReaders = debuggingSession.GetTestAccessor().GetBaselineModuleReaders(); Assert.Equal(2, baselineReaders.Length); Assert.Same(readers[0], baselineReaders[0]); Assert.Same(readers[1], baselineReaders[1]); // verify that baseline is added: Assert.Same(newBaseline, debuggingSession.GetTestAccessor().GetProjectEmitBaseline(document2.Project.Id)); // solution update status after committing an update: var commitedUpdateSolutionStatus = await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None); Assert.False(commitedUpdateSolutionStatus); } else { // another update provider blocked the update: debuggingSession.DiscardSolutionUpdate(); Assert.Null(debuggingSession.GetTestAccessor().GetPendingSolutionUpdate()); // solution update status after committing an update: var discardedUpdateSolutionStatus = await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None); Assert.True(discardedUpdateSolutionStatus); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); ValidateDelta(updates.Updates.Single()); } if (breakMode) { ExitBreakState(debuggingSession); } EndDebuggingSession(debuggingSession); // open module readers should be disposed when the debugging session ends: VerifyReadersDisposed(readers); AssertEx.SetEqual(new[] { moduleId }, debuggingSession.GetTestAccessor().GetModulesPreparedForUpdate()); if (breakMode) { AssertEx.Equal(new[] { $"Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount={(commitUpdate ? 3 : 2)}", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=0|InBreakState=True|Capabilities=31", }, _telemetryLog); } else { AssertEx.Equal(new[] { $"Debugging_EncSession: SessionId=1|SessionCount=0|EmptySessionCount=0|HotReloadSessionCount=1|EmptyHotReloadSessionCount={(commitUpdate ? 1 : 0)}", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=0|InBreakState=False|Capabilities=31" }, _telemetryLog); } } [Theory] [InlineData(true)] [InlineData(false)] public async Task ValidSignificantChange_EmitSuccessful_UpdateDeferred(bool commitUpdate) { var dir = Temp.CreateDirectory(); var sourceV1 = "class C1 { void M1() { int a = 1; System.Console.WriteLine(a); } void M2() { System.Console.WriteLine(1); } }"; var compilationV1 = CSharpTestBase.CreateCompilation(sourceV1, options: TestOptions.DebugDll, targetFramework: DefaultTargetFramework, assemblyName: "lib"); var (peImage, pdbImage) = compilationV1.EmitToArrays(new EmitOptions(debugInformationFormat: DebugInformationFormat.PortablePdb)); var moduleMetadata = ModuleMetadata.CreateFromImage(peImage); var moduleFile = dir.CreateFile("lib.dll").WriteAllBytes(peImage); var pdbFile = dir.CreateFile("lib.pdb").WriteAllBytes(pdbImage); var moduleId = moduleMetadata.GetModuleVersionId(); using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, sourceV1); _mockCompilationOutputsProvider = _ => new CompilationOutputFiles(moduleFile.Path, pdbFile.Path); // set up an active statement in the first method, so that we can test preservation of local signature. var activeStatements = ImmutableArray.Create(new ManagedActiveStatementDebugInfo( new ManagedInstructionId(new ManagedMethodId(moduleId, token: 0x06000001, version: 1), ilOffset: 0), documentName: document1.Name, sourceSpan: new SourceSpan(0, 15, 0, 16), ActiveStatementFlags.IsLeafFrame)); var debuggingSession = await StartDebuggingSessionAsync(service, solution); // module is not loaded: EnterBreakState(debuggingSession, activeStatements); // change the source (valid edit): solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M1() { int a = 1; System.Console.WriteLine(a); } void M2() { System.Console.WriteLine(2); } }", Encoding.UTF8)); var document2 = solution.GetDocument(document1.Id); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); Assert.Empty(emitDiagnostics); // delta to apply: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Equal(0x06000002, delta.UpdatedMethods.Single()); Assert.Equal(0x02000002, delta.UpdatedTypes.Single()); Assert.Equal(moduleId, delta.Module); Assert.Empty(delta.ExceptionRegions); Assert.Empty(delta.SequencePoints); // the update should be stored on the service: var pendingUpdate = debuggingSession.GetTestAccessor().GetPendingSolutionUpdate(); var (baselineProjectId, newBaseline) = pendingUpdate.EmitBaselines.Single(); var readers = debuggingSession.GetTestAccessor().GetBaselineModuleReaders(); Assert.Equal(2, readers.Length); Assert.NotNull(readers[0]); Assert.NotNull(readers[1]); Assert.Equal(document2.Project.Id, baselineProjectId); Assert.Equal(moduleId, newBaseline.OriginalMetadata.GetModuleVersionId()); if (commitUpdate) { CommitSolutionUpdate(debuggingSession); Assert.Null(debuggingSession.GetTestAccessor().GetPendingSolutionUpdate()); // no change in non-remappable regions since we didn't have any active statements: Assert.Empty(debuggingSession.EditSession.NonRemappableRegions); // verify that baseline is added: Assert.Same(newBaseline, debuggingSession.GetTestAccessor().GetProjectEmitBaseline(document2.Project.Id)); // solution update status after committing an update: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); ExitBreakState(debuggingSession); // make another update: EnterBreakState(debuggingSession); // Update M1 - this method has an active statement, so we will attempt to preserve the local signature. // Since the method hasn't been edited before we'll read the baseline PDB to get the signature token. // This validates that the Portable PDB reader can be used (and is not disposed) for a second generation edit. var document3 = solution.GetDocument(document1.Id); solution = solution.WithDocumentText(document3.Id, SourceText.From("class C1 { void M1() { int a = 3; System.Console.WriteLine(a); } void M2() { System.Console.WriteLine(2); } }", Encoding.UTF8)); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); Assert.Empty(emitDiagnostics); } else { debuggingSession.DiscardSolutionUpdate(); Assert.Null(debuggingSession.GetTestAccessor().GetPendingSolutionUpdate()); } ExitBreakState(debuggingSession); EndDebuggingSession(debuggingSession); // open module readers should be disposed when the debugging session ends: VerifyReadersDisposed(readers); } [Fact] public async Task ValidSignificantChange_PartialTypes() { var sourceA1 = @" partial class C { int X = 1; void F() { X = 1; } } partial class D { int U = 1; public D() { } } partial class D { int W = 1; } partial class E { int A; public E(int a) { A = a; } } "; var sourceB1 = @" partial class C { int Y = 1; } partial class E { int B; public E(int a, int b) { A = a; B = new System.Func<int>(() => b)(); } } "; var sourceA2 = @" partial class C { int X = 2; void F() { X = 2; } } partial class D { int U = 2; } partial class D { int W = 2; public D() { } } partial class E { int A = 1; public E(int a) { A = a; } } "; var sourceB2 = @" partial class C { int Y = 2; } partial class E { int B = 2; public E(int a, int b) { A = a; B = new System.Func<int>(() => b)(); } } "; using var _ = CreateWorkspace(out var solution, out var service); solution = AddDefaultTestProject(solution, new[] { sourceA1, sourceB1 }); var project = solution.Projects.Single(); LoadLibraryToDebuggee(EmitLibrary(new[] { (sourceA1, "test1.cs"), (sourceB1, "test2.cs") })); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source (valid edit): var documentA = project.Documents.First(); var documentB = project.Documents.Skip(1).First(); solution = solution.WithDocumentText(documentA.Id, SourceText.From(sourceA2, Encoding.UTF8)); solution = solution.WithDocumentText(documentB.Id, SourceText.From(sourceB2, Encoding.UTF8)); // validate solution update status and emit: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); // check emitted delta: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Equal(6, delta.UpdatedMethods.Length); // F, C.C(), D.D(), E.E(int), E.E(int, int), lambda AssertEx.SetEqual(new[] { 0x02000002, 0x02000003, 0x02000004, 0x02000005 }, delta.UpdatedTypes, itemInspector: t => "0x" + t.ToString("X")); EndDebuggingSession(debuggingSession); } [Fact] public async Task ValidSignificantChange_SourceGenerators_DocumentUpdate_GeneratedDocumentUpdate() { var sourceV1 = @" /* GENERATE: class G { int X => 1; } */ class C { int Y => 1; } "; var sourceV2 = @" /* GENERATE: class G { int X => 2; } */ class C { int Y => 2; } "; var generator = new TestSourceGenerator() { ExecuteImpl = GenerateSource }; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, sourceV1, generator); var moduleId = EmitLibrary(sourceV1, generator: generator); LoadLibraryToDebuggee(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source (valid edit) solution = solution.WithDocumentText(document1.Id, SourceText.From(sourceV2, Encoding.UTF8)); // validate solution update status and emit: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); // check emitted delta: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Equal(2, delta.UpdatedMethods.Length); AssertEx.Equal(new[] { 0x02000002, 0x02000003 }, delta.UpdatedTypes, itemInspector: t => "0x" + t.ToString("X")); EndDebuggingSession(debuggingSession); } [Fact] public async Task ValidSignificantChange_SourceGenerators_DocumentUpdate_GeneratedDocumentUpdate_LineChanges() { var sourceV1 = @" /* GENERATE: class G { int M() { return 1; } } */ "; var sourceV2 = @" /* GENERATE: class G { int M() { return 1; } } */ "; var generator = new TestSourceGenerator() { ExecuteImpl = GenerateSource }; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, sourceV1, generator); var moduleId = EmitLibrary(sourceV1, generator: generator); LoadLibraryToDebuggee(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source (valid edit): solution = solution.WithDocumentText(document1.Id, SourceText.From(sourceV2, Encoding.UTF8)); // validate solution update status and emit: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); // check emitted delta: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); var lineUpdate = delta.SequencePoints.Single(); AssertEx.Equal(new[] { "3 -> 4" }, lineUpdate.LineUpdates.Select(edit => $"{edit.OldLine} -> {edit.NewLine}")); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Empty(delta.UpdatedMethods); Assert.Empty(delta.UpdatedTypes); EndDebuggingSession(debuggingSession); } [Fact] public async Task ValidSignificantChange_SourceGenerators_DocumentUpdate_GeneratedDocumentInsert() { var sourceV1 = @" partial class C { int X = 1; } "; var sourceV2 = @" /* GENERATE: partial class C { int Y = 2; } */ partial class C { int X = 1; } "; var generator = new TestSourceGenerator() { ExecuteImpl = GenerateSource }; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, sourceV1, generator); var moduleId = EmitLibrary(sourceV1, generator: generator); LoadLibraryToDebuggee(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source (valid edit): solution = solution.WithDocumentText(document1.Id, SourceText.From(sourceV2, Encoding.UTF8)); // validate solution update status and emit: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); // check emitted delta: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Equal(1, delta.UpdatedMethods.Length); // constructor update Assert.Equal(0x02000002, delta.UpdatedTypes.Single()); EndDebuggingSession(debuggingSession); } [Fact] public async Task ValidSignificantChange_SourceGenerators_AdditionalDocumentUpdate() { var source = @" class C { int Y => 1; } "; var additionalSourceV1 = @" /* GENERATE: class G { int X => 1; } */ "; var additionalSourceV2 = @" /* GENERATE: class G { int X => 2; } */ "; var generator = new TestSourceGenerator() { ExecuteImpl = GenerateSource }; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, source, generator, additionalFileText: additionalSourceV1); var moduleId = EmitLibrary(source, generator: generator, additionalFileText: additionalSourceV1); LoadLibraryToDebuggee(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the additional source (valid edit): var additionalDocument1 = solution.Projects.Single().AdditionalDocuments.Single(); solution = solution.WithAdditionalDocumentText(additionalDocument1.Id, SourceText.From(additionalSourceV2, Encoding.UTF8)); // validate solution update status and emit: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); // check emitted delta: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Equal(1, delta.UpdatedMethods.Length); Assert.Equal(0x02000003, delta.UpdatedTypes.Single()); EndDebuggingSession(debuggingSession); } [Fact] public async Task ValidSignificantChange_SourceGenerators_AnalyzerConfigUpdate() { var source = @" class C { int Y => 1; } "; var configV1 = new[] { ("enc_generator_output", "1") }; var configV2 = new[] { ("enc_generator_output", "2") }; var generator = new TestSourceGenerator() { ExecuteImpl = GenerateSource }; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, source, generator, analyzerConfig: configV1); var moduleId = EmitLibrary(source, generator: generator, analyzerOptions: configV1); LoadLibraryToDebuggee(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the additional source (valid edit): var configDocument1 = solution.Projects.Single().AnalyzerConfigDocuments.Single(); solution = solution.WithAnalyzerConfigDocumentText(configDocument1.Id, GetAnalyzerConfigText(configV2)); // validate solution update status and emit: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); // check emitted delta: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Equal(1, delta.UpdatedMethods.Length); Assert.Equal(0x02000003, delta.UpdatedTypes.Single()); EndDebuggingSession(debuggingSession); } [Fact] public async Task ValidSignificantChange_SourceGenerators_DocumentRemove() { var source1 = ""; var generator = new TestSourceGenerator() { ExecuteImpl = context => context.AddSource("generated", $"class G {{ int X => {context.Compilation.SyntaxTrees.Count()}; }}") }; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, source1, generator); var moduleId = EmitLibrary(source1, generator: generator); LoadLibraryToDebuggee(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // remove the source document (valid edit): solution = document1.Project.Solution.RemoveDocument(document1.Id); // validate solution update status and emit: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); // check emitted delta: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Equal(1, delta.UpdatedMethods.Length); Assert.Equal(0x02000002, delta.UpdatedTypes.Single()); EndDebuggingSession(debuggingSession); } /// <summary> /// Emulates two updates to Multi-TFM project. /// </summary> [Fact] public async Task TwoUpdatesWithLoadedAndUnloadedModule() { var dir = Temp.CreateDirectory(); var source1 = "class A { void M() { System.Console.WriteLine(1); } }"; var source2 = "class A { void M() { System.Console.WriteLine(2); } }"; var source3 = "class A { void M() { System.Console.WriteLine(3); } }"; var compilationA = CSharpTestBase.CreateCompilation(source1, options: TestOptions.DebugDll, targetFramework: DefaultTargetFramework, assemblyName: "A"); var compilationB = CSharpTestBase.CreateCompilation(source1, options: TestOptions.DebugDll, targetFramework: DefaultTargetFramework, assemblyName: "B"); var (peImageA, pdbImageA) = compilationA.EmitToArrays(new EmitOptions(debugInformationFormat: DebugInformationFormat.PortablePdb)); var moduleMetadataA = ModuleMetadata.CreateFromImage(peImageA); var moduleFileA = Temp.CreateFile("A.dll").WriteAllBytes(peImageA); var pdbFileA = dir.CreateFile("A.pdb").WriteAllBytes(pdbImageA); var moduleIdA = moduleMetadataA.GetModuleVersionId(); var (peImageB, pdbImageB) = compilationB.EmitToArrays(new EmitOptions(debugInformationFormat: DebugInformationFormat.PortablePdb)); var moduleMetadataB = ModuleMetadata.CreateFromImage(peImageB); var moduleFileB = dir.CreateFile("B.dll").WriteAllBytes(peImageB); var pdbFileB = dir.CreateFile("B.pdb").WriteAllBytes(pdbImageB); var moduleIdB = moduleMetadataB.GetModuleVersionId(); using var _ = CreateWorkspace(out var solution, out var service); (solution, var documentA) = AddDefaultTestProject(solution, source1); var projectA = documentA.Project; var projectB = solution.AddProject("B", "A", "C#").AddMetadataReferences(projectA.MetadataReferences).AddDocument("DocB", source1, filePath: "DocB.cs").Project; solution = projectB.Solution; _mockCompilationOutputsProvider = project => (project.Id == projectA.Id) ? new CompilationOutputFiles(moduleFileA.Path, pdbFileA.Path) : (project.Id == projectB.Id) ? new CompilationOutputFiles(moduleFileB.Path, pdbFileB.Path) : throw ExceptionUtilities.UnexpectedValue(project); // only module A is loaded LoadLibraryToDebuggee(moduleIdA); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // // First update. // solution = solution.WithDocumentText(projectA.Documents.Single().Id, SourceText.From(source2, Encoding.UTF8)); solution = solution.WithDocumentText(projectB.Documents.Single().Id, SourceText.From(source2, Encoding.UTF8)); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); Assert.Empty(emitDiagnostics); var deltaA = updates.Updates.Single(d => d.Module == moduleIdA); var deltaB = updates.Updates.Single(d => d.Module == moduleIdB); Assert.Equal(2, updates.Updates.Length); // the update should be stored on the service: var pendingUpdate = debuggingSession.GetTestAccessor().GetPendingSolutionUpdate(); var (_, newBaselineA1) = pendingUpdate.EmitBaselines.Single(b => b.ProjectId == projectA.Id); var (_, newBaselineB1) = pendingUpdate.EmitBaselines.Single(b => b.ProjectId == projectB.Id); var baselineA0 = newBaselineA1.GetInitialEmitBaseline(); var baselineB0 = newBaselineB1.GetInitialEmitBaseline(); var readers = debuggingSession.GetTestAccessor().GetBaselineModuleReaders(); Assert.Equal(4, readers.Length); Assert.False(readers.Any(r => r is null)); Assert.Equal(moduleIdA, newBaselineA1.OriginalMetadata.GetModuleVersionId()); Assert.Equal(moduleIdB, newBaselineB1.OriginalMetadata.GetModuleVersionId()); CommitSolutionUpdate(debuggingSession); Assert.Null(debuggingSession.GetTestAccessor().GetPendingSolutionUpdate()); // no change in non-remappable regions since we didn't have any active statements: Assert.Empty(debuggingSession.EditSession.NonRemappableRegions); // verify that baseline is added for both modules: Assert.Same(newBaselineA1, debuggingSession.GetTestAccessor().GetProjectEmitBaseline(projectA.Id)); Assert.Same(newBaselineB1, debuggingSession.GetTestAccessor().GetProjectEmitBaseline(projectB.Id)); // solution update status after committing an update: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); ExitBreakState(debuggingSession); EnterBreakState(debuggingSession); // // Second update. // solution = solution.WithDocumentText(projectA.Documents.Single().Id, SourceText.From(source3, Encoding.UTF8)); solution = solution.WithDocumentText(projectB.Documents.Single().Id, SourceText.From(source3, Encoding.UTF8)); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); Assert.Empty(emitDiagnostics); deltaA = updates.Updates.Single(d => d.Module == moduleIdA); deltaB = updates.Updates.Single(d => d.Module == moduleIdB); Assert.Equal(2, updates.Updates.Length); // the update should be stored on the service: pendingUpdate = debuggingSession.GetTestAccessor().GetPendingSolutionUpdate(); var (_, newBaselineA2) = pendingUpdate.EmitBaselines.Single(b => b.ProjectId == projectA.Id); var (_, newBaselineB2) = pendingUpdate.EmitBaselines.Single(b => b.ProjectId == projectB.Id); Assert.NotSame(newBaselineA1, newBaselineA2); Assert.NotSame(newBaselineB1, newBaselineB2); Assert.Same(baselineA0, newBaselineA2.GetInitialEmitBaseline()); Assert.Same(baselineB0, newBaselineB2.GetInitialEmitBaseline()); Assert.Same(baselineA0.OriginalMetadata, newBaselineA2.OriginalMetadata); Assert.Same(baselineB0.OriginalMetadata, newBaselineB2.OriginalMetadata); // no new module readers: var baselineReaders = debuggingSession.GetTestAccessor().GetBaselineModuleReaders(); AssertEx.Equal(readers, baselineReaders); CommitSolutionUpdate(debuggingSession); Assert.Null(debuggingSession.GetTestAccessor().GetPendingSolutionUpdate()); // no change in non-remappable regions since we didn't have any active statements: Assert.Empty(debuggingSession.EditSession.NonRemappableRegions); // module readers tracked: baselineReaders = debuggingSession.GetTestAccessor().GetBaselineModuleReaders(); AssertEx.Equal(readers, baselineReaders); // verify that baseline is updated for both modules: Assert.Same(newBaselineA2, debuggingSession.GetTestAccessor().GetProjectEmitBaseline(projectA.Id)); Assert.Same(newBaselineB2, debuggingSession.GetTestAccessor().GetProjectEmitBaseline(projectB.Id)); // solution update status after committing an update: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); ExitBreakState(debuggingSession); EndDebuggingSession(debuggingSession); // open deferred module readers should be dispose when the debugging session ends: VerifyReadersDisposed(readers); } [Fact] public async Task ValidSignificantChange_BaselineCreationFailed_NoStream() { using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, "class C1 { void M() { System.Console.WriteLine(1); } }"); _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(Guid.NewGuid()) { OpenPdbStreamImpl = () => null, OpenAssemblyStreamImpl = () => null, }; var debuggingSession = await StartDebuggingSessionAsync(service, solution); // module not loaded EnterBreakState(debuggingSession); // change the source (valid edit): solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { System.Console.WriteLine(2); } }", Encoding.UTF8)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); AssertEx.Equal(new[] { $"{document1.Project.Id} Error ENC1001: {string.Format(FeaturesResources.ErrorReadingFile, "test-pdb", new FileNotFoundException().Message)}" }, InspectDiagnostics(emitDiagnostics)); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); } [Fact] public async Task ValidSignificantChange_BaselineCreationFailed_AssemblyReadError() { var sourceV1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var compilationV1 = CSharpTestBase.CreateCompilationWithMscorlib40(sourceV1, options: TestOptions.DebugDll, assemblyName: "lib"); var pdbStream = new MemoryStream(); var peImage = compilationV1.EmitToArray(new EmitOptions(debugInformationFormat: DebugInformationFormat.PortablePdb), pdbStream: pdbStream); pdbStream.Position = 0; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, sourceV1); _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(Guid.NewGuid()) { OpenPdbStreamImpl = () => pdbStream, OpenAssemblyStreamImpl = () => throw new IOException("*message*"), }; var debuggingSession = await StartDebuggingSessionAsync(service, solution); // module not loaded EnterBreakState(debuggingSession); // change the source (valid edit): var document1 = solution.Projects.Single().Documents.Single(); solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { System.Console.WriteLine(2); } }", Encoding.UTF8)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); AssertEx.Equal(new[] { $"{document.Project.Id} Error ENC1001: {string.Format(FeaturesResources.ErrorReadingFile, "test-assembly", "*message*")}" }, InspectDiagnostics(emitDiagnostics)); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); EndDebuggingSession(debuggingSession); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=1", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=1|InBreakState=True|Capabilities=31", "Debugging_EncSession_EditSession_EmitDeltaErrorId: SessionId=1|EditSessionId=2|ErrorId=ENC1001" }, _telemetryLog); } [Fact] public async Task ActiveStatements() { var sourceV1 = "class C { void F() { G(1); } void G(int a) => System.Console.WriteLine(1); }"; var sourceV2 = "class C { int x; void F() { G(2); G(1); } void G(int a) => System.Console.WriteLine(2); }"; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, sourceV1); var activeSpan11 = GetSpan(sourceV1, "G(1);"); var activeSpan12 = GetSpan(sourceV1, "System.Console.WriteLine(1)"); var activeSpan21 = GetSpan(sourceV2, "G(2); G(1);"); var activeSpan22 = GetSpan(sourceV2, "System.Console.WriteLine(2)"); var adjustedActiveSpan1 = GetSpan(sourceV2, "G(2);"); var adjustedActiveSpan2 = GetSpan(sourceV2, "System.Console.WriteLine(2)"); var documentId = document1.Id; var documentPath = document1.FilePath; var sourceTextV1 = document1.GetTextSynchronously(CancellationToken.None); var sourceTextV2 = SourceText.From(sourceV2, Encoding.UTF8); var activeLineSpan11 = sourceTextV1.Lines.GetLinePositionSpan(activeSpan11); var activeLineSpan12 = sourceTextV1.Lines.GetLinePositionSpan(activeSpan12); var activeLineSpan21 = sourceTextV2.Lines.GetLinePositionSpan(activeSpan21); var activeLineSpan22 = sourceTextV2.Lines.GetLinePositionSpan(activeSpan22); var adjustedActiveLineSpan1 = sourceTextV2.Lines.GetLinePositionSpan(adjustedActiveSpan1); var adjustedActiveLineSpan2 = sourceTextV2.Lines.GetLinePositionSpan(adjustedActiveSpan2); var debuggingSession = await StartDebuggingSessionAsync(service, solution); // default if not called in a break state Assert.True((await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(document1.Id), CancellationToken.None)).IsDefault); var moduleId = Guid.NewGuid(); var activeInstruction1 = new ManagedInstructionId(new ManagedMethodId(moduleId, token: 0x06000001, version: 1), ilOffset: 1); var activeInstruction2 = new ManagedInstructionId(new ManagedMethodId(moduleId, token: 0x06000002, version: 1), ilOffset: 1); var activeStatements = ImmutableArray.Create( new ManagedActiveStatementDebugInfo( activeInstruction1, documentPath, activeLineSpan11.ToSourceSpan(), ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsNonLeafFrame), new ManagedActiveStatementDebugInfo( activeInstruction2, documentPath, activeLineSpan12.ToSourceSpan(), ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame)); EnterBreakState(debuggingSession, activeStatements); var activeStatementSpan11 = new ActiveStatementSpan(0, activeLineSpan11, ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsNonLeafFrame, unmappedDocumentId: null); var activeStatementSpan12 = new ActiveStatementSpan(1, activeLineSpan12, ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame, unmappedDocumentId: null); var baseSpans = await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(document1.Id), CancellationToken.None); AssertEx.Equal(new[] { activeStatementSpan11, activeStatementSpan12 }, baseSpans.Single()); var trackedActiveSpans1 = ImmutableArray.Create(activeStatementSpan11, activeStatementSpan12); var currentSpans = await debuggingSession.GetAdjustedActiveStatementSpansAsync(document1, (_, _, _) => new(trackedActiveSpans1), CancellationToken.None); AssertEx.Equal(trackedActiveSpans1, currentSpans); Assert.Equal(activeLineSpan11, await debuggingSession.GetCurrentActiveStatementPositionAsync(document1.Project.Solution, (_, _, _) => new(trackedActiveSpans1), activeInstruction1, CancellationToken.None)); Assert.Equal(activeLineSpan12, await debuggingSession.GetCurrentActiveStatementPositionAsync(document1.Project.Solution, (_, _, _) => new(trackedActiveSpans1), activeInstruction2, CancellationToken.None)); // change the source (valid edit): solution = solution.WithDocumentText(documentId, sourceTextV2); var document2 = solution.GetDocument(documentId); // tracking span update triggered by the edit: var activeStatementSpan21 = new ActiveStatementSpan(0, activeLineSpan21, ActiveStatementFlags.IsNonLeafFrame, unmappedDocumentId: null); var activeStatementSpan22 = new ActiveStatementSpan(1, activeLineSpan22, ActiveStatementFlags.IsLeafFrame, unmappedDocumentId: null); var trackedActiveSpans2 = ImmutableArray.Create(activeStatementSpan21, activeStatementSpan22); currentSpans = await debuggingSession.GetAdjustedActiveStatementSpansAsync(document2, (_, _, _) => new(trackedActiveSpans2), CancellationToken.None); AssertEx.Equal(new[] { adjustedActiveLineSpan1, adjustedActiveLineSpan2 }, currentSpans.Select(s => s.LineSpan)); Assert.Equal(adjustedActiveLineSpan1, await debuggingSession.GetCurrentActiveStatementPositionAsync(solution, (_, _, _) => new(trackedActiveSpans2), activeInstruction1, CancellationToken.None)); Assert.Equal(adjustedActiveLineSpan2, await debuggingSession.GetCurrentActiveStatementPositionAsync(solution, (_, _, _) => new(trackedActiveSpans2), activeInstruction2, CancellationToken.None)); } [Theory] [CombinatorialData] public async Task ActiveStatements_SyntaxErrorOrOutOfSyncDocument(bool isOutOfSync) { var sourceV1 = "class C { void F() => G(1); void G(int a) => System.Console.WriteLine(1); }"; // syntax error (missing ';') unless testing out-of-sync document var sourceV2 = isOutOfSync ? "class C { int x; void F() => G(1); void G(int a) => System.Console.WriteLine(2); }" : "class C { int x void F() => G(1); void G(int a) => System.Console.WriteLine(2); }"; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, sourceV1); var activeSpan11 = GetSpan(sourceV1, "G(1)"); var activeSpan12 = GetSpan(sourceV1, "System.Console.WriteLine(1)"); var documentId = document1.Id; var documentFilePath = document1.FilePath; var sourceTextV1 = await document1.GetTextAsync(CancellationToken.None); var sourceTextV2 = SourceText.From(sourceV2, Encoding.UTF8); var activeLineSpan11 = sourceTextV1.Lines.GetLinePositionSpan(activeSpan11); var activeLineSpan12 = sourceTextV1.Lines.GetLinePositionSpan(activeSpan12); var debuggingSession = await StartDebuggingSessionAsync( service, solution, isOutOfSync ? CommittedSolution.DocumentState.OutOfSync : CommittedSolution.DocumentState.MatchesBuildOutput); var moduleId = Guid.NewGuid(); var activeInstruction1 = new ManagedInstructionId(new ManagedMethodId(moduleId, token: 0x06000001, version: 1), ilOffset: 1); var activeInstruction2 = new ManagedInstructionId(new ManagedMethodId(moduleId, token: 0x06000002, version: 1), ilOffset: 1); var activeStatements = ImmutableArray.Create( new ManagedActiveStatementDebugInfo( activeInstruction1, documentFilePath, activeLineSpan11.ToSourceSpan(), ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsNonLeafFrame), new ManagedActiveStatementDebugInfo( activeInstruction2, documentFilePath, activeLineSpan12.ToSourceSpan(), ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame)); EnterBreakState(debuggingSession, activeStatements); var baseSpans = (await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(documentId), CancellationToken.None)).Single(); AssertEx.Equal(new[] { new ActiveStatementSpan(0, activeLineSpan11, ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsNonLeafFrame, unmappedDocumentId: null), new ActiveStatementSpan(1, activeLineSpan12, ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame, unmappedDocumentId: null) }, baseSpans); // change the source (valid edit): solution = solution.WithDocumentText(documentId, sourceTextV2); var document2 = solution.GetDocument(documentId); // no adjustments made due to syntax error or out-of-sync document: var currentSpans = await debuggingSession.GetAdjustedActiveStatementSpansAsync(document2, (_, _, _) => ValueTaskFactory.FromResult(baseSpans), CancellationToken.None); AssertEx.Equal(new[] { activeLineSpan11, activeLineSpan12 }, currentSpans.Select(s => s.LineSpan)); var currentSpan1 = await debuggingSession.GetCurrentActiveStatementPositionAsync(solution, (_, _, _) => ValueTaskFactory.FromResult(baseSpans), activeInstruction1, CancellationToken.None); var currentSpan2 = await debuggingSession.GetCurrentActiveStatementPositionAsync(solution, (_, _, _) => ValueTaskFactory.FromResult(baseSpans), activeInstruction2, CancellationToken.None); if (isOutOfSync) { Assert.Equal(baseSpans[0].LineSpan, currentSpan1.Value); Assert.Equal(baseSpans[1].LineSpan, currentSpan2.Value); } else { Assert.Null(currentSpan1); Assert.Null(currentSpan2); } } [Fact] public async Task ActiveStatements_ForeignDocument() { var composition = FeaturesTestCompositions.Features.AddParts(typeof(DummyLanguageService)); using var _ = CreateWorkspace(out var solution, out var service, new[] { typeof(DummyLanguageService) }); var project = solution.AddProject("dummy_proj", "dummy_proj", DummyLanguageService.LanguageName); var document = project.AddDocument("test", SourceText.From("dummy1")); solution = document.Project.Solution; var debuggingSession = await StartDebuggingSessionAsync(service, solution); var activeStatements = ImmutableArray.Create( new ManagedActiveStatementDebugInfo( new ManagedInstructionId(new ManagedMethodId(Guid.Empty, token: 0x06000001, version: 1), ilOffset: 0), documentName: document.Name, sourceSpan: new SourceSpan(0, 1, 0, 2), ActiveStatementFlags.IsNonLeafFrame)); EnterBreakState(debuggingSession, activeStatements); // active statements are not tracked in non-Roslyn projects: var currentSpans = await debuggingSession.GetAdjustedActiveStatementSpansAsync(document, s_noActiveSpans, CancellationToken.None); Assert.Empty(currentSpans); var baseSpans = await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(document.Id), CancellationToken.None); Assert.Empty(baseSpans.Single()); } [Fact, WorkItem(24320, "https://github.com/dotnet/roslyn/issues/24320")] public async Task ActiveStatements_LinkedDocuments() { var markedSources = new[] { @"class Test1 { static void Main() => <AS:2>Project2::Test1.F();</AS:2> static void F() => <AS:1>Project4::Test2.M();</AS:1> }", @"class Test2 { static void M() => <AS:0>Console.WriteLine();</AS:0> }" }; var module1 = Guid.NewGuid(); var module2 = Guid.NewGuid(); var module4 = Guid.NewGuid(); var debugInfos = GetActiveStatementDebugInfosCSharp( markedSources, methodRowIds: new[] { 1, 2, 1 }, modules: new[] { module4, module2, module1 }); // Project1: Test1.cs, Test2.cs // Project2: Test1.cs (link from P1) // Project3: Test1.cs (link from P1) // Project4: Test2.cs (link from P1) using var _ = CreateWorkspace(out var solution, out var service); solution = AddDefaultTestProject(solution, ActiveStatementsDescription.ClearTags(markedSources)); var documents = solution.Projects.Single().Documents; var doc1 = documents.First(); var doc2 = documents.Skip(1).First(); var text1 = await doc1.GetTextAsync(); var text2 = await doc2.GetTextAsync(); DocumentId AddProjectAndLinkDocument(string projectName, Document doc, SourceText text) { var p = solution.AddProject(projectName, projectName, "C#"); var linkedDocId = DocumentId.CreateNewId(p.Id, projectName + "->" + doc.Name); solution = p.Solution.AddDocument(linkedDocId, doc.Name, text, filePath: doc.FilePath); return linkedDocId; } var docId3 = AddProjectAndLinkDocument("Project2", doc1, text1); var docId4 = AddProjectAndLinkDocument("Project3", doc1, text1); var docId5 = AddProjectAndLinkDocument("Project4", doc2, text2); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession, debugInfos); // Base Active Statements var baseActiveStatementsMap = await debuggingSession.EditSession.BaseActiveStatements.GetValueAsync(CancellationToken.None).ConfigureAwait(false); var documentMap = baseActiveStatementsMap.DocumentPathMap; Assert.Equal(2, documentMap.Count); AssertEx.Equal(new[] { $"2: {doc1.FilePath}: (2,32)-(2,52) flags=[MethodUpToDate, IsNonLeafFrame]", $"1: {doc1.FilePath}: (3,29)-(3,49) flags=[MethodUpToDate, IsNonLeafFrame]" }, documentMap[doc1.FilePath].Select(InspectActiveStatement)); AssertEx.Equal(new[] { $"0: {doc2.FilePath}: (0,39)-(0,59) flags=[IsLeafFrame, MethodUpToDate]", }, documentMap[doc2.FilePath].Select(InspectActiveStatement)); Assert.Equal(3, baseActiveStatementsMap.InstructionMap.Count); var statements = baseActiveStatementsMap.InstructionMap.Values.OrderBy(v => v.Ordinal).ToArray(); var s = statements[0]; Assert.Equal(0x06000001, s.InstructionId.Method.Token); Assert.Equal(module4, s.InstructionId.Method.Module); s = statements[1]; Assert.Equal(0x06000002, s.InstructionId.Method.Token); Assert.Equal(module2, s.InstructionId.Method.Module); s = statements[2]; Assert.Equal(0x06000001, s.InstructionId.Method.Token); Assert.Equal(module1, s.InstructionId.Method.Module); var spans = await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(doc1.Id, doc2.Id, docId3, docId4, docId5), CancellationToken.None); AssertEx.Equal(new[] { "(2,32)-(2,52), (3,29)-(3,49)", // test1.cs "(0,39)-(0,59)", // test2.cs "(2,32)-(2,52), (3,29)-(3,49)", // link test1.cs "(2,32)-(2,52), (3,29)-(3,49)", // link test1.cs "(0,39)-(0,59)" // link test2.cs }, spans.Select(docSpans => string.Join(", ", docSpans.Select(span => span.LineSpan)))); } [Fact] public async Task ActiveStatements_OutOfSyncDocuments() { var markedSource1 = @"class C { static void M() { try { } catch (Exception e) { <AS:0>M();</AS:0> } } }"; var source2 = @"class C { static void M() { try { } catch (Exception e) { M(); } } }"; var markedSources = new[] { markedSource1 }; var thread1 = Guid.NewGuid(); // Thread1 stack trace: F (AS:0 leaf) var debugInfos = GetActiveStatementDebugInfosCSharp( markedSources, methodRowIds: new[] { 1 }, ilOffsets: new[] { 1 }, flags: new[] { ActiveStatementFlags.IsLeafFrame | ActiveStatementFlags.MethodUpToDate }); using var _ = CreateWorkspace(out var solution, out var service); solution = AddDefaultTestProject(solution, ActiveStatementsDescription.ClearTags(markedSources)); var project = solution.Projects.Single(); var document = project.Documents.Single(); var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.OutOfSync); EnterBreakState(debuggingSession, debugInfos); // update document to test a changed solution solution = solution.WithDocumentText(document.Id, SourceText.From(source2, Encoding.UTF8)); document = solution.GetDocument(document.Id); var baseActiveStatementMap = await debuggingSession.EditSession.BaseActiveStatements.GetValueAsync(CancellationToken.None).ConfigureAwait(false); // Active Statements - available in out-of-sync documents, as they reflect the state of the debuggee and not the base document content Assert.Single(baseActiveStatementMap.DocumentPathMap); AssertEx.Equal(new[] { $"0: {document.FilePath}: (9,18)-(9,22) flags=[IsLeafFrame, MethodUpToDate]", }, baseActiveStatementMap.DocumentPathMap[document.FilePath].Select(InspectActiveStatement)); Assert.Equal(1, baseActiveStatementMap.InstructionMap.Count); var activeStatement1 = baseActiveStatementMap.InstructionMap.Values.OrderBy(v => v.InstructionId.Method.Token).Single(); Assert.Equal(0x06000001, activeStatement1.InstructionId.Method.Token); Assert.Equal(document.FilePath, activeStatement1.FilePath); Assert.True(activeStatement1.IsLeaf); // Active statement reported as unchanged as the containing document is out-of-sync: var baseSpans = await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(document.Id), CancellationToken.None); AssertEx.Equal(new[] { $"(9,18)-(9,22)" }, baseSpans.Single().Select(s => s.LineSpan.ToString())); // Whether or not an active statement is in an exception region is unknown if the document is out-of-sync: Assert.Null(await debuggingSession.IsActiveStatementInExceptionRegionAsync(solution, activeStatement1.InstructionId, CancellationToken.None)); // Document got synchronized: debuggingSession.LastCommittedSolution.Test_SetDocumentState(document.Id, CommittedSolution.DocumentState.MatchesBuildOutput); // New location of the active statement reported: baseSpans = await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(document.Id), CancellationToken.None); AssertEx.Equal(new[] { $"(10,12)-(10,16)" }, baseSpans.Single().Select(s => s.LineSpan.ToString())); Assert.True(await debuggingSession.IsActiveStatementInExceptionRegionAsync(solution, activeStatement1.InstructionId, CancellationToken.None)); } [Fact] public async Task ActiveStatements_SourceGeneratedDocuments_LineDirectives() { var markedSource1 = @" /* GENERATE: class C { void F() { #line 1 ""a.razor"" <AS:0>F();</AS:0> #line default } } */ "; var markedSource2 = @" /* GENERATE: class C { void F() { #line 2 ""a.razor"" <AS:0>F();</AS:0> #line default } } */ "; var source1 = ActiveStatementsDescription.ClearTags(markedSource1); var source2 = ActiveStatementsDescription.ClearTags(markedSource2); var additionalFileSourceV1 = @" xxxxxxxxxxxxxxxxx "; var generator = new TestSourceGenerator() { ExecuteImpl = GenerateSource }; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, source1, generator, additionalFileText: additionalFileSourceV1); var generatedDocument1 = (await solution.Projects.Single().GetSourceGeneratedDocumentsAsync().ConfigureAwait(false)).Single(); var moduleId = EmitLibrary(source1, generator: generator, additionalFileText: additionalFileSourceV1); LoadLibraryToDebuggee(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession, GetActiveStatementDebugInfosCSharp( new[] { GetGeneratedCodeFromMarkedSource(markedSource1) }, filePaths: new[] { generatedDocument1.FilePath }, modules: new[] { moduleId }, methodRowIds: new[] { 1 }, methodVersions: new[] { 1 }, flags: new[] { ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame })); // change the source (valid edit) solution = solution.WithDocumentText(document1.Id, SourceText.From(source2, Encoding.UTF8)); // validate solution update status and emit: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); // check emitted delta: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Empty(delta.UpdatedMethods); Assert.Empty(delta.UpdatedTypes); AssertEx.Equal(new[] { "a.razor: [0 -> 1]" }, delta.SequencePoints.Inspect()); EndDebuggingSession(debuggingSession); } [Fact] [WorkItem(54347, "https://github.com/dotnet/roslyn/issues/54347")] public async Task ActiveStatements_EncSessionFollowedByHotReload() { var markedSource1 = @" class C { int F() { try { return 0; } catch { <AS:0>return 1;</AS:0> } } } "; var markedSource2 = @" class C { int F() { try { return 0; } catch { <AS:0>return 2;</AS:0> } } } "; var source1 = ActiveStatementsDescription.ClearTags(markedSource1); var source2 = ActiveStatementsDescription.ClearTags(markedSource2); using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, source1); var moduleId = EmitLibrary(source1); LoadLibraryToDebuggee(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession, GetActiveStatementDebugInfosCSharp( new[] { markedSource1 }, modules: new[] { moduleId }, methodRowIds: new[] { 1 }, methodVersions: new[] { 1 }, flags: new[] { ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame })); // change the source (rude edit) solution = solution.WithDocumentText(document.Id, SourceText.From(source2, Encoding.UTF8)); document = solution.GetDocument(document.Id); var diagnostics = await service.GetDocumentDiagnosticsAsync(document, s_noActiveSpans, CancellationToken.None); AssertEx.Equal(new[] { "ENC0063: " + string.Format(FeaturesResources.Updating_a_0_around_an_active_statement_requires_restarting_the_application, CSharpFeaturesResources.catch_clause) }, diagnostics.Select(d => $"{d.Id}: {d.GetMessage()}")); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); // undo the change solution = solution.WithDocumentText(document.Id, SourceText.From(source1, Encoding.UTF8)); document = solution.GetDocument(document.Id); ExitBreakState(debuggingSession, ImmutableArray.Create(document.Id)); // change the source (now a valid edit since there is no active statement) solution = solution.WithDocumentText(document.Id, SourceText.From(source2, Encoding.UTF8)); diagnostics = await service.GetDocumentDiagnosticsAsync(document, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); // validate solution update status and emit (Hot Reload change): (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); EndDebuggingSession(debuggingSession); } /// <summary> /// Scenario: /// F5 a program that has function F that calls G. G has a long-running loop, which starts executing. /// The user makes following operations: /// 1) Break, edit F from version 1 to version 2, continue (change is applied), G is still running in its loop /// Function remapping is produced for F v1 -> F v2. /// 2) Hot-reload edit F (without breaking) to version 3. /// Function remapping is not produced for F v2 -> F v3. If G ever returned to F it will be remapped from F v1 -> F v2, /// where F v2 is considered stale code. This is consistent with the semantic of Hot Reload: Hot Reloaded changes do not have /// an effect until the method is called again. In this case the method is not called, it it returned into hence the stale /// version executes. /// 3) Break and apply EnC edit. This edit is to F v3 (Hot Reload) of the method. We will produce remapping F v3 -> v4. /// </summary> [Fact, WorkItem(52100, "https://github.com/dotnet/roslyn/issues/52100")] public async Task BreakStateRemappingFollowedUpByRunStateUpdate() { var markedSourceV1 = @"class Test { static bool B() => true; static void G() { while (B()); <AS:0>}</AS:0> static void F() { /*insert1[1]*/B();/*insert2[5]*/B();/*insert3[10]*/B(); <AS:1>G();</AS:1> } }"; var markedSourceV2 = Update(markedSourceV1, marker: "1"); var markedSourceV3 = Update(markedSourceV2, marker: "2"); var markedSourceV4 = Update(markedSourceV3, marker: "3"); var moduleId = EmitAndLoadLibraryToDebuggee(ActiveStatementsDescription.ClearTags(markedSourceV1)); using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, ActiveStatementsDescription.ClearTags(markedSourceV1)); var documentId = document.Id; var debuggingSession = await StartDebuggingSessionAsync(service, solution); // EnC update F v1 -> v2 EnterBreakState(debuggingSession, GetActiveStatementDebugInfosCSharp( new[] { markedSourceV1 }, modules: new[] { moduleId, moduleId }, methodRowIds: new[] { 2, 3 }, methodVersions: new[] { 1, 1 }, flags: new[] { ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame, // G ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsNonLeafFrame, // F })); solution = solution.WithDocumentText(documentId, SourceText.From(ActiveStatementsDescription.ClearTags(markedSourceV2), Encoding.UTF8)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(0x06000003, updates.Updates.Single().UpdatedMethods.Single()); Assert.Equal(0x02000002, updates.Updates.Single().UpdatedTypes.Single()); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); CommitSolutionUpdate(debuggingSession); AssertEx.Equal(new[] { $"0x06000002 v1 | AS {document.FilePath}: (4,41)-(4,42) δ=0", $"0x06000003 v1 | AS {document.FilePath}: (9,14)-(9,18) δ=1", }, InspectNonRemappableRegions(debuggingSession.EditSession.NonRemappableRegions)); ExitBreakState(debuggingSession); // Hot Reload update F v2 -> v3 solution = solution.WithDocumentText(documentId, SourceText.From(ActiveStatementsDescription.ClearTags(markedSourceV3), Encoding.UTF8)); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(0x06000003, updates.Updates.Single().UpdatedMethods.Single()); Assert.Equal(0x02000002, updates.Updates.Single().UpdatedTypes.Single()); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); CommitSolutionUpdate(debuggingSession); // the regions remain unchanged AssertEx.Equal(new[] { $"0x06000002 v1 | AS {document.FilePath}: (4,41)-(4,42) δ=0", $"0x06000003 v1 | AS {document.FilePath}: (9,14)-(9,18) δ=1", }, InspectNonRemappableRegions(debuggingSession.EditSession.NonRemappableRegions)); // EnC update F v3 -> v4 EnterBreakState(debuggingSession, GetActiveStatementDebugInfosCSharp( new[] { markedSourceV1 }, // matches F v1 modules: new[] { moduleId, moduleId }, methodRowIds: new[] { 2, 3 }, methodVersions: new[] { 1, 1 }, // frame F v1 is still executing (G has not returned) flags: new[] { ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame, // G ActiveStatementFlags.IsStale | ActiveStatementFlags.IsNonLeafFrame, // F - not up-to-date anymore and since F v1 is followed by F v3 (hot-reload) it is now stale })); var spans = (await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(documentId), CancellationToken.None)).Single(); AssertEx.Equal(new[] { new ActiveStatementSpan(0, new LinePositionSpan(new(4,41), new(4,42)), ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame, unmappedDocumentId: null), }, spans); solution = solution.WithDocumentText(documentId, SourceText.From(ActiveStatementsDescription.ClearTags(markedSourceV4), Encoding.UTF8)); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(0x06000003, updates.Updates.Single().UpdatedMethods.Single()); Assert.Equal(0x02000002, updates.Updates.Single().UpdatedTypes.Single()); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); CommitSolutionUpdate(debuggingSession); // Stale active statement region is gone. AssertEx.Equal(new[] { $"0x06000002 v1 | AS {document.FilePath}: (4,41)-(4,42) δ=0", }, InspectNonRemappableRegions(debuggingSession.EditSession.NonRemappableRegions)); ExitBreakState(debuggingSession); } /// <summary> /// Scenario: /// - F5 /// - edit, but not apply the edits /// - break /// </summary> [Fact] public async Task BreakInPresenceOfUnappliedChanges() { var markedSource1 = @"class Test { static bool B() => true; static void G() { while (B()); <AS:0>}</AS:0> static void F() { <AS:1>G();</AS:1> } }"; var markedSource2 = @"class Test { static bool B() => true; static void G() { while (B()); <AS:0>}</AS:0> static void F() { B(); <AS:1>G();</AS:1> } }"; var markedSource3 = @"class Test { static bool B() => true; static void G() { while (B()); <AS:0>}</AS:0> static void F() { B(); B(); <AS:1>G();</AS:1> } }"; var moduleId = EmitAndLoadLibraryToDebuggee(ActiveStatementsDescription.ClearTags(markedSource1)); using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, ActiveStatementsDescription.ClearTags(markedSource1)); var documentId = document.Id; var debuggingSession = await StartDebuggingSessionAsync(service, solution); // Update to snapshot 2, but don't apply solution = solution.WithDocumentText(documentId, SourceText.From(ActiveStatementsDescription.ClearTags(markedSource2), Encoding.UTF8)); // EnC update F v2 -> v3 EnterBreakState(debuggingSession, GetActiveStatementDebugInfosCSharp( new[] { markedSource1 }, modules: new[] { moduleId, moduleId }, methodRowIds: new[] { 2, 3 }, methodVersions: new[] { 1, 1 }, flags: new[] { ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame, // G ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsNonLeafFrame, // F })); // check that the active statement is mapped correctly to snapshot v2: var expectedSpanG1 = new LinePositionSpan(new LinePosition(3, 41), new LinePosition(3, 42)); var expectedSpanF1 = new LinePositionSpan(new LinePosition(8, 14), new LinePosition(8, 18)); var activeInstructionF1 = new ManagedInstructionId(new ManagedMethodId(moduleId, 0x06000003, version: 1), ilOffset: 0); var span = await debuggingSession.GetCurrentActiveStatementPositionAsync(solution, s_noActiveSpans, activeInstructionF1, CancellationToken.None); Assert.Equal(expectedSpanF1, span.Value); var spans = (await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(documentId), CancellationToken.None)).Single(); AssertEx.Equal(new[] { new ActiveStatementSpan(0, expectedSpanG1, ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame, documentId), new ActiveStatementSpan(1, expectedSpanF1, ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsNonLeafFrame, documentId) }, spans); solution = solution.WithDocumentText(documentId, SourceText.From(ActiveStatementsDescription.ClearTags(markedSource3), Encoding.UTF8)); // check that the active statement is mapped correctly to snapshot v3: var expectedSpanG2 = new LinePositionSpan(new LinePosition(3, 41), new LinePosition(3, 42)); var expectedSpanF2 = new LinePositionSpan(new LinePosition(9, 14), new LinePosition(9, 18)); span = await debuggingSession.GetCurrentActiveStatementPositionAsync(solution, s_noActiveSpans, activeInstructionF1, CancellationToken.None); Assert.Equal(expectedSpanF2, span); spans = (await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(documentId), CancellationToken.None)).Single(); AssertEx.Equal(new[] { new ActiveStatementSpan(0, expectedSpanG2, ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame, documentId), new ActiveStatementSpan(1, expectedSpanF2, ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsNonLeafFrame, documentId) }, spans); // no rude edits: var document1 = solution.GetDocument(documentId); var diagnostics = await service.GetDocumentDiagnosticsAsync(document1, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(0x06000003, updates.Updates.Single().UpdatedMethods.Single()); Assert.Equal(0x02000002, updates.Updates.Single().UpdatedTypes.Single()); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); CommitSolutionUpdate(debuggingSession); AssertEx.Equal(new[] { $"0x06000002 v1 | AS {document.FilePath}: (3,41)-(3,42) δ=0", $"0x06000003 v1 | AS {document.FilePath}: (7,14)-(7,18) δ=2", }, InspectNonRemappableRegions(debuggingSession.EditSession.NonRemappableRegions)); ExitBreakState(debuggingSession); } /// <summary> /// Scenario: /// - F5 /// - edit and apply edit that deletes non-leaf active statement /// - break /// </summary> [Fact, WorkItem(52100, "https://github.com/dotnet/roslyn/issues/52100")] public async Task BreakAfterRunModeChangeDeletesNonLeafActiveStatement() { var markedSource1 = @"class Test { static bool B() => true; static void G() { while (B()); <AS:0>}</AS:0> static void F() { <AS:1>G();</AS:1> } }"; var markedSource2 = @"class Test { static bool B() => true; static void G() { while (B()); <AS:0>}</AS:0> static void F() { } }"; var moduleId = EmitAndLoadLibraryToDebuggee(ActiveStatementsDescription.ClearTags(markedSource1)); using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, ActiveStatementsDescription.ClearTags(markedSource1)); var documentId = document.Id; var debuggingSession = await StartDebuggingSessionAsync(service, solution); // Apply update: F v1 -> v2. solution = solution.WithDocumentText(documentId, SourceText.From(ActiveStatementsDescription.ClearTags(markedSource2), Encoding.UTF8)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(0x06000003, updates.Updates.Single().UpdatedMethods.Single()); Assert.Equal(0x02000002, updates.Updates.Single().UpdatedTypes.Single()); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); CommitSolutionUpdate(debuggingSession); // Break EnterBreakState(debuggingSession, GetActiveStatementDebugInfosCSharp( new[] { markedSource1 }, modules: new[] { moduleId, moduleId }, methodRowIds: new[] { 2, 3 }, methodVersions: new[] { 1, 1 }, // frame F v1 is still executing (G has not returned) flags: new[] { ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame, // G ActiveStatementFlags.IsNonLeafFrame, // F })); // check that the active statement is mapped correctly to snapshot v2: var expectedSpanF1 = new LinePositionSpan(new LinePosition(7, 14), new LinePosition(7, 18)); var expectedSpanG1 = new LinePositionSpan(new LinePosition(3, 41), new LinePosition(3, 42)); var activeInstructionG1 = new ManagedInstructionId(new ManagedMethodId(moduleId, 0x06000002, version: 1), ilOffset: 0); var span = await debuggingSession.GetCurrentActiveStatementPositionAsync(solution, s_noActiveSpans, activeInstructionG1, CancellationToken.None); Assert.Equal(expectedSpanG1, span); // Active statement in F has been deleted: var activeInstructionF1 = new ManagedInstructionId(new ManagedMethodId(moduleId, 0x06000003, version: 1), ilOffset: 0); span = await debuggingSession.GetCurrentActiveStatementPositionAsync(solution, s_noActiveSpans, activeInstructionF1, CancellationToken.None); Assert.Null(span); var spans = (await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(documentId), CancellationToken.None)).Single(); AssertEx.Equal(new[] { new ActiveStatementSpan(0, expectedSpanG1, ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame, unmappedDocumentId: null) // active statement in F has been deleted }, spans); ExitBreakState(debuggingSession); } [Fact] public async Task MultiSession() { var source1 = "class C { void M() { System.Console.WriteLine(); } }"; var source3 = "class C { void M() { WriteLine(2); } }"; var dir = Temp.CreateDirectory(); var sourceFileA = dir.CreateFile("A.cs").WriteAllText(source1); var moduleId = EmitLibrary(source1, sourceFileA.Path, Encoding.UTF8, "Proj"); using var workspace = CreateWorkspace(out var solution, out var encService); var projectP = solution. AddProject("P", "P", LanguageNames.CSharp). WithMetadataReferences(TargetFrameworkUtil.GetReferences(DefaultTargetFramework)); solution = projectP.Solution; var documentIdA = DocumentId.CreateNewId(projectP.Id, debugName: "A"); solution = solution.AddDocument(DocumentInfo.Create( id: documentIdA, name: "A", loader: new FileTextLoader(sourceFileA.Path, Encoding.UTF8), filePath: sourceFileA.Path)); var tasks = Enumerable.Range(0, 10).Select(async i => { var sessionId = await encService.StartDebuggingSessionAsync( solution, _debuggerService, captureMatchingDocuments: ImmutableArray<DocumentId>.Empty, captureAllMatchingDocuments: true, reportDiagnostics: true, CancellationToken.None); var solution1 = solution.WithDocumentText(documentIdA, SourceText.From("class C { void M() { System.Console.WriteLine(" + i + "); } }", Encoding.UTF8)); var result1 = await encService.EmitSolutionUpdateAsync(sessionId, solution1, s_noActiveSpans, CancellationToken.None); Assert.Empty(result1.Diagnostics); Assert.Equal(1, result1.ModuleUpdates.Updates.Length); var solution2 = solution1.WithDocumentText(documentIdA, SourceText.From(source3, Encoding.UTF8)); var result2 = await encService.EmitSolutionUpdateAsync(sessionId, solution2, s_noActiveSpans, CancellationToken.None); Assert.Equal("CS0103", result2.Diagnostics.Single().Diagnostics.Single().Id); Assert.Empty(result2.ModuleUpdates.Updates); encService.EndDebuggingSession(sessionId, out var _); }); await Task.WhenAll(tasks); Assert.Empty(encService.GetTestAccessor().GetActiveDebuggingSessions()); } [Fact] public async Task Disposal() { using var _1 = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, "class C { }"); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EndDebuggingSession(debuggingSession); // The folling methods shall not be called after the debugging session ended. await Assert.ThrowsAsync<ObjectDisposedException>(async () => await debuggingSession.EmitSolutionUpdateAsync(solution, s_noActiveSpans, CancellationToken.None)); await Assert.ThrowsAsync<ObjectDisposedException>(async () => await debuggingSession.GetCurrentActiveStatementPositionAsync(solution, s_noActiveSpans, instructionId: default, CancellationToken.None)); await Assert.ThrowsAsync<ObjectDisposedException>(async () => await debuggingSession.IsActiveStatementInExceptionRegionAsync(solution, instructionId: default, CancellationToken.None)); Assert.Throws<ObjectDisposedException>(() => debuggingSession.BreakStateChanged(inBreakState: true, out _)); Assert.Throws<ObjectDisposedException>(() => debuggingSession.DiscardSolutionUpdate()); Assert.Throws<ObjectDisposedException>(() => debuggingSession.CommitSolutionUpdate(out _)); Assert.Throws<ObjectDisposedException>(() => debuggingSession.EndSession(out _, out _)); // The following methods can be called at any point in time, so we must handle race with dispose gracefully. Assert.Empty(await debuggingSession.GetDocumentDiagnosticsAsync(document, s_noActiveSpans, CancellationToken.None)); Assert.Empty(await debuggingSession.GetAdjustedActiveStatementSpansAsync(document, s_noActiveSpans, CancellationToken.None)); Assert.True((await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray<DocumentId>.Empty, CancellationToken.None)).IsDefault); } [Fact] public async Task WatchHotReloadServiceTest() { // See https://github.com/dotnet/sdk/blob/main/src/BuiltInTools/dotnet-watch/HotReload/CompilationHandler.cs#L125 var source1 = "class C { void M() { System.Console.WriteLine(1); } }"; var source2 = "class C { void M() { System.Console.WriteLine(2); } }"; var source3 = "class C { void X() { System.Console.WriteLine(2); } }"; var source4 = "class C { void M() { System.Console.WriteLine(2)/* missing semicolon */ }"; var dir = Temp.CreateDirectory(); var sourceFileA = dir.CreateFile("A.cs").WriteAllText(source1); var moduleId = EmitLibrary(source1, sourceFileA.Path, Encoding.UTF8, "Proj"); using var workspace = CreateWorkspace(out var solution, out var encService); var projectP = solution. AddProject("P", "P", LanguageNames.CSharp). WithMetadataReferences(TargetFrameworkUtil.GetReferences(DefaultTargetFramework)); solution = projectP.Solution; var documentIdA = DocumentId.CreateNewId(projectP.Id, debugName: "A"); solution = solution.AddDocument(DocumentInfo.Create( id: documentIdA, name: "A", loader: new FileTextLoader(sourceFileA.Path, Encoding.UTF8), filePath: sourceFileA.Path)); var hotReload = new WatchHotReloadService(workspace.Services, ImmutableArray.Create("Baseline", "AddDefinitionToExistingType", "NewTypeDefinition")); await hotReload.StartSessionAsync(solution, CancellationToken.None); var sessionId = hotReload.GetTestAccessor().SessionId; var session = encService.GetTestAccessor().GetDebuggingSession(sessionId); var matchingDocuments = session.LastCommittedSolution.Test_GetDocumentStates(); AssertEx.Equal(new[] { "(A, MatchesBuildOutput)" }, matchingDocuments.Select(e => (solution.GetDocument(e.id).Name, e.state)).OrderBy(e => e.Name).Select(e => e.ToString())); // Valid update: solution = solution.WithDocumentText(documentIdA, SourceText.From(source2, Encoding.UTF8)); var result = await hotReload.EmitSolutionUpdateAsync(solution, CancellationToken.None); Assert.Empty(result.diagnostics); Assert.Equal(1, result.updates.Length); AssertEx.Equal(new[] { 0x02000002 }, result.updates[0].UpdatedTypes); // Rude edit: solution = solution.WithDocumentText(documentIdA, SourceText.From(source3, Encoding.UTF8)); result = await hotReload.EmitSolutionUpdateAsync(solution, CancellationToken.None); AssertEx.Equal( new[] { "ENC0020: " + string.Format(FeaturesResources.Renaming_0_requires_restarting_the_application, FeaturesResources.method) }, result.diagnostics.Select(d => $"{d.Id}: {d.GetMessage()}")); Assert.Empty(result.updates); // Syntax error (not reported in diagnostics): solution = solution.WithDocumentText(documentIdA, SourceText.From(source4, Encoding.UTF8)); result = await hotReload.EmitSolutionUpdateAsync(solution, CancellationToken.None); Assert.Empty(result.diagnostics); Assert.Empty(result.updates); hotReload.EndSession(); } [Fact] public async Task UnitTestingHotReloadServiceTest() { var source1 = "class C { void M() { System.Console.WriteLine(1); } }"; var source2 = "class C { void M() { System.Console.WriteLine(2); } }"; var source3 = "class C { void X() { System.Console.WriteLine(2); } }"; var source4 = "class C { void M() { System.Console.WriteLine(2)/* missing semicolon */ }"; var dir = Temp.CreateDirectory(); var sourceFileA = dir.CreateFile("A.cs").WriteAllText(source1); var moduleId = EmitLibrary(source1, sourceFileA.Path, Encoding.UTF8, "Proj"); using var workspace = CreateWorkspace(out var solution, out var encService); var projectP = solution. AddProject("P", "P", LanguageNames.CSharp). WithMetadataReferences(TargetFrameworkUtil.GetReferences(DefaultTargetFramework)); solution = projectP.Solution; var documentIdA = DocumentId.CreateNewId(projectP.Id, debugName: "A"); solution = solution.AddDocument(DocumentInfo.Create( id: documentIdA, name: "A", loader: new FileTextLoader(sourceFileA.Path, Encoding.UTF8), filePath: sourceFileA.Path)); var hotReload = new UnitTestingHotReloadService(workspace.Services); await hotReload.StartSessionAsync(solution, ImmutableArray.Create("Baseline", "AddDefinitionToExistingType", "NewTypeDefinition"), CancellationToken.None); var sessionId = hotReload.GetTestAccessor().SessionId; var session = encService.GetTestAccessor().GetDebuggingSession(sessionId); var matchingDocuments = session.LastCommittedSolution.Test_GetDocumentStates(); AssertEx.Equal(new[] { "(A, MatchesBuildOutput)" }, matchingDocuments.Select(e => (solution.GetDocument(e.id).Name, e.state)).OrderBy(e => e.Name).Select(e => e.ToString())); // Valid change solution = solution.WithDocumentText(documentIdA, SourceText.From(source2, Encoding.UTF8)); var result = await hotReload.EmitSolutionUpdateAsync(solution, commitUpdates: true, CancellationToken.None); Assert.Empty(result.diagnostics); Assert.Equal(1, result.updates.Length); solution = solution.WithDocumentText(documentIdA, SourceText.From(source3, Encoding.UTF8)); // Rude edit result = await hotReload.EmitSolutionUpdateAsync(solution, commitUpdates: true, CancellationToken.None); AssertEx.Equal( new[] { "ENC0020: " + string.Format(FeaturesResources.Renaming_0_requires_restarting_the_application, FeaturesResources.method) }, result.diagnostics.Select(d => $"{d.Id}: {d.GetMessage()}")); Assert.Empty(result.updates); // Syntax error is reported in the diagnostics: solution = solution.WithDocumentText(documentIdA, SourceText.From(source4, Encoding.UTF8)); result = await hotReload.EmitSolutionUpdateAsync(solution, commitUpdates: true, CancellationToken.None); Assert.Equal(1, result.diagnostics.Length); Assert.Empty(result.updates); hotReload.EndSession(); } } }
-1
dotnet/roslyn
56,450
Implement INamespaceTypeReference.GetUnit for RootModuleType
Fixes #56412.
AlekseyTs
"2021-09-16T16:44:04Z"
"2021-09-17T18:21:59Z"
4b06ee428bafa0141c9eb3250003a19109dcfc86
d695369176aa109f0e0fb8b0019294aaa0823a54
Implement INamespaceTypeReference.GetUnit for RootModuleType. Fixes #56412.
./src/Compilers/VisualBasic/Portable/Emit/FieldSymbolAdapter.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.Cci Imports Microsoft.CodeAnalysis.CodeGen Imports Microsoft.CodeAnalysis.Emit Imports Microsoft.CodeAnalysis.VisualBasic.Emit Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols #If DEBUG Then Partial Friend Class FieldSymbolAdapter Inherits SymbolAdapter #Else Partial Friend Class FieldSymbol #End If Implements IFieldReference Implements IFieldDefinition Implements ITypeMemberReference Implements ITypeDefinitionMember Implements ISpecializedFieldReference Private Function IFieldReferenceGetType(context As EmitContext) As ITypeReference Implements IFieldReference.GetType Dim moduleBeingBuilt As PEModuleBuilder = DirectCast(context.Module, PEModuleBuilder) Dim customModifiers = AdaptedFieldSymbol.CustomModifiers Dim type = moduleBeingBuilt.Translate(AdaptedFieldSymbol.Type, syntaxNodeOpt:=DirectCast(context.SyntaxNode, VisualBasicSyntaxNode), diagnostics:=context.Diagnostics) If customModifiers.Length = 0 Then Return type Else Return New ModifiedTypeReference(type, customModifiers.As(Of Cci.ICustomModifier)) End If End Function Private Function IFieldReferenceGetResolvedField(context As EmitContext) As IFieldDefinition Implements IFieldReference.GetResolvedField Return ResolvedFieldImpl(DirectCast(context.Module, PEModuleBuilder)) End Function Private Function ResolvedFieldImpl(moduleBeingBuilt As PEModuleBuilder) As IFieldDefinition Debug.Assert(Me.IsDefinitionOrDistinct()) If AdaptedFieldSymbol.IsDefinition AndAlso AdaptedFieldSymbol.ContainingModule = moduleBeingBuilt.SourceModule Then Return Me End If Return Nothing End Function Private ReadOnly Property IFieldReferenceAsSpecializedFieldReference As ISpecializedFieldReference Implements IFieldReference.AsSpecializedFieldReference Get Debug.Assert(Me.IsDefinitionOrDistinct()) If Not AdaptedFieldSymbol.IsDefinition Then Return Me End If Return Nothing End Get End Property Private Function ITypeMemberReferenceGetContainingType(context As EmitContext) As ITypeReference Implements ITypeMemberReference.GetContainingType Dim moduleBeingBuilt As PEModuleBuilder = DirectCast(context.Module, PEModuleBuilder) Debug.Assert(Me.IsDefinitionOrDistinct()) Return moduleBeingBuilt.Translate(AdaptedFieldSymbol.ContainingType, syntaxNodeOpt:=DirectCast(context.SyntaxNode, VisualBasicSyntaxNode), diagnostics:=context.Diagnostics, needDeclaration:=AdaptedFieldSymbol.IsDefinition) End Function Friend NotOverridable Overrides Sub IReferenceDispatch(visitor As MetadataVisitor) ' Implements IReference.Dispatch Debug.Assert(Me.IsDefinitionOrDistinct()) If Not AdaptedFieldSymbol.IsDefinition Then visitor.Visit(DirectCast(Me, ISpecializedFieldReference)) Else If AdaptedFieldSymbol.ContainingModule = (DirectCast(visitor.Context.Module, PEModuleBuilder)).SourceModule Then visitor.Visit(DirectCast(Me, IFieldDefinition)) Else visitor.Visit(DirectCast(Me, IFieldReference)) End If End If End Sub Friend NotOverridable Overrides Function IReferenceAsDefinition(context As EmitContext) As IDefinition ' Implements IReference.AsDefinition Dim moduleBeingBuilt As PEModuleBuilder = DirectCast(context.Module, PEModuleBuilder) Return ResolvedFieldImpl(moduleBeingBuilt) End Function Private ReadOnly Property INamedEntityName As String Implements INamedEntity.Name Get Return AdaptedFieldSymbol.MetadataName End Get End Property Private ReadOnly Property IFieldReference_IsContextualNamedEntity As Boolean Implements IFieldReference.IsContextualNamedEntity Get Return AdaptedFieldSymbol.IsContextualNamedEntity End Get End Property Private Function IFieldDefinition_GetCompileTimeValue(context As EmitContext) As MetadataConstant Implements IFieldDefinition.GetCompileTimeValue CheckDefinitionInvariant() Return GetMetadataConstantValue(context) End Function Friend Function GetMetadataConstantValue(context As EmitContext) As MetadataConstant ' do not return a compile time value for const fields of types DateTime or Decimal because they ' are only const from a VB point of view If AdaptedFieldSymbol.IsMetadataConstant Then Return DirectCast(context.Module, PEModuleBuilder).CreateConstant(AdaptedFieldSymbol.Type, AdaptedFieldSymbol.ConstantValue, syntaxNodeOpt:=DirectCast(context.SyntaxNode, VisualBasicSyntaxNode), diagnostics:=context.Diagnostics) End If Return Nothing End Function Private ReadOnly Property IFieldDefinitionFieldMapping As ImmutableArray(Of Byte) Implements IFieldDefinition.MappedData Get Return Nothing End Get End Property Private ReadOnly Property IFieldDefinitionIsCompileTimeConstant As Boolean Implements IFieldDefinition.IsCompileTimeConstant Get CheckDefinitionInvariant() ' const fields of types DateTime or Decimal are not compile time constant, because they are only const ' from a VB point of view If AdaptedFieldSymbol.IsMetadataConstant Then Return True End If Return False End Get End Property Private ReadOnly Property IFieldDefinitionIsNotSerialized As Boolean Implements IFieldDefinition.IsNotSerialized Get CheckDefinitionInvariant() Return AdaptedFieldSymbol.IsNotSerialized End Get End Property Private ReadOnly Property IFieldDefinitionIsReadOnly As Boolean Implements IFieldDefinition.IsReadOnly Get CheckDefinitionInvariant() ' a const field of type DateTime or Decimal is ReadOnly in IL. Return AdaptedFieldSymbol.IsReadOnly OrElse AdaptedFieldSymbol.IsConstButNotMetadataConstant End Get End Property Private ReadOnly Property IFieldDefinitionIsRuntimeSpecial As Boolean Implements IFieldDefinition.IsRuntimeSpecial Get CheckDefinitionInvariant() Return AdaptedFieldSymbol.HasRuntimeSpecialName End Get End Property Private ReadOnly Property IFieldDefinitionIsSpecialName As Boolean Implements IFieldDefinition.IsSpecialName Get CheckDefinitionInvariant() Return AdaptedFieldSymbol.HasSpecialName End Get End Property Private ReadOnly Property IFieldDefinitionIsStatic As Boolean Implements IFieldDefinition.IsStatic Get CheckDefinitionInvariant() Return AdaptedFieldSymbol.IsShared End Get End Property Private ReadOnly Property IFieldDefinitionIsMarshalledExplicitly As Boolean Implements IFieldDefinition.IsMarshalledExplicitly Get CheckDefinitionInvariant() Return AdaptedFieldSymbol.IsMarshalledExplicitly End Get End Property Private ReadOnly Property IFieldDefinitionMarshallingInformation As IMarshallingInformation Implements IFieldDefinition.MarshallingInformation Get CheckDefinitionInvariant() Return AdaptedFieldSymbol.MarshallingInformation End Get End Property Private ReadOnly Property IFieldDefinitionMarshallingDescriptor As ImmutableArray(Of Byte) Implements IFieldDefinition.MarshallingDescriptor Get CheckDefinitionInvariant() Return AdaptedFieldSymbol.MarshallingDescriptor End Get End Property Private ReadOnly Property IFieldDefinitionOffset As Integer Implements IFieldDefinition.Offset Get CheckDefinitionInvariant() Return If(AdaptedFieldSymbol.TypeLayoutOffset, 0) End Get End Property Private ReadOnly Property ITypeDefinitionMemberContainingTypeDefinition As ITypeDefinition Implements ITypeDefinitionMember.ContainingTypeDefinition Get CheckDefinitionInvariant() Return AdaptedFieldSymbol.ContainingType.GetCciAdapter() End Get End Property Private ReadOnly Property ITypeDefinitionMemberVisibility As TypeMemberVisibility Implements ITypeDefinitionMember.Visibility Get CheckDefinitionInvariant() Return PEModuleBuilder.MemberVisibility(AdaptedFieldSymbol) End Get End Property Private ReadOnly Property ISpecializedFieldReferenceUnspecializedVersion As IFieldReference Implements ISpecializedFieldReference.UnspecializedVersion Get Debug.Assert(Not AdaptedFieldSymbol.IsDefinition) Return AdaptedFieldSymbol.OriginalDefinition.GetCciAdapter() End Get End Property End Class Partial Friend Class FieldSymbol #If DEBUG Then Private _lazyAdapter As FieldSymbolAdapter Protected Overrides Function GetCciAdapterImpl() As SymbolAdapter Return GetCciAdapter() End Function Friend Shadows Function GetCciAdapter() As FieldSymbolAdapter If _lazyAdapter Is Nothing Then Return InterlockedOperations.Initialize(_lazyAdapter, FieldSymbolAdapter.Create(Me)) End If Return _lazyAdapter End Function #Else Friend ReadOnly Property AdaptedFieldSymbol As FieldSymbol Get Return Me End Get End Property Friend Shadows Function GetCciAdapter() As FieldSymbol Return Me End Function #End If Friend Overridable ReadOnly Property IsContextualNamedEntity As Boolean Get Return False End Get End Property Friend Overridable ReadOnly Property IsMarshalledExplicitly As Boolean Get CheckDefinitionInvariant() Return Me.MarshallingInformation IsNot Nothing End Get End Property Friend Overridable ReadOnly Property MarshallingDescriptor As ImmutableArray(Of Byte) Get CheckDefinitionInvariant() Return Nothing End Get End Property End Class #If DEBUG Then Partial Friend Class FieldSymbolAdapter Friend ReadOnly Property AdaptedFieldSymbol As FieldSymbol Protected Sub New(underlyingFieldSymbol As FieldSymbol) AdaptedFieldSymbol = underlyingFieldSymbol End Sub Friend Shared Function Create(underlyingFieldSymbol As FieldSymbol) As FieldSymbolAdapter Dim synthesizedStaticLocalBackingField = TryCast(underlyingFieldSymbol, SynthesizedStaticLocalBackingField) If synthesizedStaticLocalBackingField IsNot Nothing Then Return New SynthesizedStaticLocalBackingFieldAdapter(synthesizedStaticLocalBackingField) End If Return New FieldSymbolAdapter(underlyingFieldSymbol) End Function Friend Overrides ReadOnly Property AdaptedSymbol As Symbol Get Return AdaptedFieldSymbol End Get End Property End Class #End If 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.Cci Imports Microsoft.CodeAnalysis.CodeGen Imports Microsoft.CodeAnalysis.Emit Imports Microsoft.CodeAnalysis.VisualBasic.Emit Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols #If DEBUG Then Partial Friend Class FieldSymbolAdapter Inherits SymbolAdapter #Else Partial Friend Class FieldSymbol #End If Implements IFieldReference Implements IFieldDefinition Implements ITypeMemberReference Implements ITypeDefinitionMember Implements ISpecializedFieldReference Private Function IFieldReferenceGetType(context As EmitContext) As ITypeReference Implements IFieldReference.GetType Dim moduleBeingBuilt As PEModuleBuilder = DirectCast(context.Module, PEModuleBuilder) Dim customModifiers = AdaptedFieldSymbol.CustomModifiers Dim type = moduleBeingBuilt.Translate(AdaptedFieldSymbol.Type, syntaxNodeOpt:=DirectCast(context.SyntaxNode, VisualBasicSyntaxNode), diagnostics:=context.Diagnostics) If customModifiers.Length = 0 Then Return type Else Return New ModifiedTypeReference(type, customModifiers.As(Of Cci.ICustomModifier)) End If End Function Private Function IFieldReferenceGetResolvedField(context As EmitContext) As IFieldDefinition Implements IFieldReference.GetResolvedField Return ResolvedFieldImpl(DirectCast(context.Module, PEModuleBuilder)) End Function Private Function ResolvedFieldImpl(moduleBeingBuilt As PEModuleBuilder) As IFieldDefinition Debug.Assert(Me.IsDefinitionOrDistinct()) If AdaptedFieldSymbol.IsDefinition AndAlso AdaptedFieldSymbol.ContainingModule = moduleBeingBuilt.SourceModule Then Return Me End If Return Nothing End Function Private ReadOnly Property IFieldReferenceAsSpecializedFieldReference As ISpecializedFieldReference Implements IFieldReference.AsSpecializedFieldReference Get Debug.Assert(Me.IsDefinitionOrDistinct()) If Not AdaptedFieldSymbol.IsDefinition Then Return Me End If Return Nothing End Get End Property Private Function ITypeMemberReferenceGetContainingType(context As EmitContext) As ITypeReference Implements ITypeMemberReference.GetContainingType Dim moduleBeingBuilt As PEModuleBuilder = DirectCast(context.Module, PEModuleBuilder) Debug.Assert(Me.IsDefinitionOrDistinct()) Return moduleBeingBuilt.Translate(AdaptedFieldSymbol.ContainingType, syntaxNodeOpt:=DirectCast(context.SyntaxNode, VisualBasicSyntaxNode), diagnostics:=context.Diagnostics, needDeclaration:=AdaptedFieldSymbol.IsDefinition) End Function Friend NotOverridable Overrides Sub IReferenceDispatch(visitor As MetadataVisitor) ' Implements IReference.Dispatch Debug.Assert(Me.IsDefinitionOrDistinct()) If Not AdaptedFieldSymbol.IsDefinition Then visitor.Visit(DirectCast(Me, ISpecializedFieldReference)) Else If AdaptedFieldSymbol.ContainingModule = (DirectCast(visitor.Context.Module, PEModuleBuilder)).SourceModule Then visitor.Visit(DirectCast(Me, IFieldDefinition)) Else visitor.Visit(DirectCast(Me, IFieldReference)) End If End If End Sub Friend NotOverridable Overrides Function IReferenceAsDefinition(context As EmitContext) As IDefinition ' Implements IReference.AsDefinition Dim moduleBeingBuilt As PEModuleBuilder = DirectCast(context.Module, PEModuleBuilder) Return ResolvedFieldImpl(moduleBeingBuilt) End Function Private ReadOnly Property INamedEntityName As String Implements INamedEntity.Name Get Return AdaptedFieldSymbol.MetadataName End Get End Property Private ReadOnly Property IFieldReference_IsContextualNamedEntity As Boolean Implements IFieldReference.IsContextualNamedEntity Get Return AdaptedFieldSymbol.IsContextualNamedEntity End Get End Property Private Function IFieldDefinition_GetCompileTimeValue(context As EmitContext) As MetadataConstant Implements IFieldDefinition.GetCompileTimeValue CheckDefinitionInvariant() Return GetMetadataConstantValue(context) End Function Friend Function GetMetadataConstantValue(context As EmitContext) As MetadataConstant ' do not return a compile time value for const fields of types DateTime or Decimal because they ' are only const from a VB point of view If AdaptedFieldSymbol.IsMetadataConstant Then Return DirectCast(context.Module, PEModuleBuilder).CreateConstant(AdaptedFieldSymbol.Type, AdaptedFieldSymbol.ConstantValue, syntaxNodeOpt:=DirectCast(context.SyntaxNode, VisualBasicSyntaxNode), diagnostics:=context.Diagnostics) End If Return Nothing End Function Private ReadOnly Property IFieldDefinitionFieldMapping As ImmutableArray(Of Byte) Implements IFieldDefinition.MappedData Get Return Nothing End Get End Property Private ReadOnly Property IFieldDefinitionIsCompileTimeConstant As Boolean Implements IFieldDefinition.IsCompileTimeConstant Get CheckDefinitionInvariant() ' const fields of types DateTime or Decimal are not compile time constant, because they are only const ' from a VB point of view If AdaptedFieldSymbol.IsMetadataConstant Then Return True End If Return False End Get End Property Private ReadOnly Property IFieldDefinitionIsNotSerialized As Boolean Implements IFieldDefinition.IsNotSerialized Get CheckDefinitionInvariant() Return AdaptedFieldSymbol.IsNotSerialized End Get End Property Private ReadOnly Property IFieldDefinitionIsReadOnly As Boolean Implements IFieldDefinition.IsReadOnly Get CheckDefinitionInvariant() ' a const field of type DateTime or Decimal is ReadOnly in IL. Return AdaptedFieldSymbol.IsReadOnly OrElse AdaptedFieldSymbol.IsConstButNotMetadataConstant End Get End Property Private ReadOnly Property IFieldDefinitionIsRuntimeSpecial As Boolean Implements IFieldDefinition.IsRuntimeSpecial Get CheckDefinitionInvariant() Return AdaptedFieldSymbol.HasRuntimeSpecialName End Get End Property Private ReadOnly Property IFieldDefinitionIsSpecialName As Boolean Implements IFieldDefinition.IsSpecialName Get CheckDefinitionInvariant() Return AdaptedFieldSymbol.HasSpecialName End Get End Property Private ReadOnly Property IFieldDefinitionIsStatic As Boolean Implements IFieldDefinition.IsStatic Get CheckDefinitionInvariant() Return AdaptedFieldSymbol.IsShared End Get End Property Private ReadOnly Property IFieldDefinitionIsMarshalledExplicitly As Boolean Implements IFieldDefinition.IsMarshalledExplicitly Get CheckDefinitionInvariant() Return AdaptedFieldSymbol.IsMarshalledExplicitly End Get End Property Private ReadOnly Property IFieldDefinitionMarshallingInformation As IMarshallingInformation Implements IFieldDefinition.MarshallingInformation Get CheckDefinitionInvariant() Return AdaptedFieldSymbol.MarshallingInformation End Get End Property Private ReadOnly Property IFieldDefinitionMarshallingDescriptor As ImmutableArray(Of Byte) Implements IFieldDefinition.MarshallingDescriptor Get CheckDefinitionInvariant() Return AdaptedFieldSymbol.MarshallingDescriptor End Get End Property Private ReadOnly Property IFieldDefinitionOffset As Integer Implements IFieldDefinition.Offset Get CheckDefinitionInvariant() Return If(AdaptedFieldSymbol.TypeLayoutOffset, 0) End Get End Property Private ReadOnly Property ITypeDefinitionMemberContainingTypeDefinition As ITypeDefinition Implements ITypeDefinitionMember.ContainingTypeDefinition Get CheckDefinitionInvariant() Return AdaptedFieldSymbol.ContainingType.GetCciAdapter() End Get End Property Private ReadOnly Property ITypeDefinitionMemberVisibility As TypeMemberVisibility Implements ITypeDefinitionMember.Visibility Get CheckDefinitionInvariant() Return PEModuleBuilder.MemberVisibility(AdaptedFieldSymbol) End Get End Property Private ReadOnly Property ISpecializedFieldReferenceUnspecializedVersion As IFieldReference Implements ISpecializedFieldReference.UnspecializedVersion Get Debug.Assert(Not AdaptedFieldSymbol.IsDefinition) Return AdaptedFieldSymbol.OriginalDefinition.GetCciAdapter() End Get End Property End Class Partial Friend Class FieldSymbol #If DEBUG Then Private _lazyAdapter As FieldSymbolAdapter Protected Overrides Function GetCciAdapterImpl() As SymbolAdapter Return GetCciAdapter() End Function Friend Shadows Function GetCciAdapter() As FieldSymbolAdapter If _lazyAdapter Is Nothing Then Return InterlockedOperations.Initialize(_lazyAdapter, FieldSymbolAdapter.Create(Me)) End If Return _lazyAdapter End Function #Else Friend ReadOnly Property AdaptedFieldSymbol As FieldSymbol Get Return Me End Get End Property Friend Shadows Function GetCciAdapter() As FieldSymbol Return Me End Function #End If Friend Overridable ReadOnly Property IsContextualNamedEntity As Boolean Get Return False End Get End Property Friend Overridable ReadOnly Property IsMarshalledExplicitly As Boolean Get CheckDefinitionInvariant() Return Me.MarshallingInformation IsNot Nothing End Get End Property Friend Overridable ReadOnly Property MarshallingDescriptor As ImmutableArray(Of Byte) Get CheckDefinitionInvariant() Return Nothing End Get End Property End Class #If DEBUG Then Partial Friend Class FieldSymbolAdapter Friend ReadOnly Property AdaptedFieldSymbol As FieldSymbol Protected Sub New(underlyingFieldSymbol As FieldSymbol) AdaptedFieldSymbol = underlyingFieldSymbol End Sub Friend Shared Function Create(underlyingFieldSymbol As FieldSymbol) As FieldSymbolAdapter Dim synthesizedStaticLocalBackingField = TryCast(underlyingFieldSymbol, SynthesizedStaticLocalBackingField) If synthesizedStaticLocalBackingField IsNot Nothing Then Return New SynthesizedStaticLocalBackingFieldAdapter(synthesizedStaticLocalBackingField) End If Return New FieldSymbolAdapter(underlyingFieldSymbol) End Function Friend Overrides ReadOnly Property AdaptedSymbol As Symbol Get Return AdaptedFieldSymbol End Get End Property End Class #End If End Namespace
-1
dotnet/roslyn
56,450
Implement INamespaceTypeReference.GetUnit for RootModuleType
Fixes #56412.
AlekseyTs
"2021-09-16T16:44:04Z"
"2021-09-17T18:21:59Z"
4b06ee428bafa0141c9eb3250003a19109dcfc86
d695369176aa109f0e0fb8b0019294aaa0823a54
Implement INamespaceTypeReference.GetUnit for RootModuleType. Fixes #56412.
./src/Compilers/VisualBasic/Test/Emit/ExpressionTrees/Results/CheckedConcatenate.txt
-=-=-=-=-=-=-=-=- SByte & String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.SByte ) Parameter( y type: System.String ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Convert( ConvertChecked( Parameter( x type: System.SByte ) type: System.Int32 ) method: System.String ToString(Int32) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) Parameter( y type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.SByte,System.String,System.String] ) -=-=-=-=-=-=-=-=- SByte + String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.SByte ) Parameter( y type: System.String ) body { Convert( Add( Convert( Parameter( x type: System.SByte ) type: System.Double ) Convert( Parameter( y type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.SByte,System.String,System.String] ) -=-=-=-=-=-=-=-=- String & SByte => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.SByte ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Parameter( x type: System.String ) Convert( ConvertChecked( Parameter( y type: System.SByte ) type: System.Int32 ) method: System.String ToString(Int32) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.String,System.SByte,System.String] ) -=-=-=-=-=-=-=-=- String + SByte => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.SByte ) body { Convert( Add( Convert( Parameter( x type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) Convert( Parameter( y type: System.SByte ) type: System.Double ) type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.String,System.SByte,System.String] ) -=-=-=-=-=-=-=-=- SByte? & String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.SByte] ) Parameter( y type: System.String ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Coalesce( Parameter( x type: System.Nullable`1[System.SByte] ) Constant( null type: System.String ) conversion: Lambda( Parameter( CoalesceLHS type: System.Nullable`1[System.SByte] ) body { Convert( ConvertChecked( ConvertChecked( Parameter( CoalesceLHS type: System.Nullable`1[System.SByte] ) method: SByte op_Explicit(System.Nullable`1[System.SByte]) in System.Nullable`1[System.SByte] type: System.SByte ) type: System.Int32 ) method: System.String ToString(Int32) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Nullable`1[System.SByte],System.String] ) type: System.String ) Parameter( y type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.Nullable`1[System.SByte],System.String,System.String] ) -=-=-=-=-=-=-=-=- SByte? + String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.SByte] ) Parameter( y type: System.String ) body { Convert( Convert( Add( Convert( Parameter( x type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) Convert( Convert( Parameter( y type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) method: System.Nullable`1[System.Double] op_Implicit(Double) in System.Nullable`1[System.Double] type: System.Nullable`1[System.Double] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) method: Double op_Explicit(System.Nullable`1[System.Double]) in System.Nullable`1[System.Double] type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.Nullable`1[System.SByte],System.String,System.String] ) -=-=-=-=-=-=-=-=- String & SByte? => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.Nullable`1[System.SByte] ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Parameter( x type: System.String ) Coalesce( Parameter( y type: System.Nullable`1[System.SByte] ) Constant( null type: System.String ) conversion: Lambda( Parameter( CoalesceLHS type: System.Nullable`1[System.SByte] ) body { Convert( ConvertChecked( ConvertChecked( Parameter( CoalesceLHS type: System.Nullable`1[System.SByte] ) method: SByte op_Explicit(System.Nullable`1[System.SByte]) in System.Nullable`1[System.SByte] type: System.SByte ) type: System.Int32 ) method: System.String ToString(Int32) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Nullable`1[System.SByte],System.String] ) type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.String,System.Nullable`1[System.SByte],System.String] ) -=-=-=-=-=-=-=-=- String + SByte? => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.Nullable`1[System.SByte] ) body { Convert( Convert( Add( Convert( Convert( Parameter( x type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) method: System.Nullable`1[System.Double] op_Implicit(Double) in System.Nullable`1[System.Double] type: System.Nullable`1[System.Double] ) Convert( Parameter( y type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) method: Double op_Explicit(System.Nullable`1[System.Double]) in System.Nullable`1[System.Double] type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.String,System.Nullable`1[System.SByte],System.String] ) -=-=-=-=-=-=-=-=- E_SByte & String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_SByte ) Parameter( y type: System.String ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Convert( ConvertChecked( Parameter( x type: E_SByte ) type: System.Int32 ) method: System.String ToString(Int32) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) Parameter( y type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[E_SByte,System.String,System.String] ) -=-=-=-=-=-=-=-=- E_SByte + String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_SByte ) Parameter( y type: System.String ) body { Convert( Add( Convert( Parameter( x type: E_SByte ) type: System.Double ) Convert( Parameter( y type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[E_SByte,System.String,System.String] ) -=-=-=-=-=-=-=-=- String & E_SByte => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: E_SByte ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Parameter( x type: System.String ) Convert( ConvertChecked( Parameter( y type: E_SByte ) type: System.Int32 ) method: System.String ToString(Int32) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.String,E_SByte,System.String] ) -=-=-=-=-=-=-=-=- String + E_SByte => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: E_SByte ) body { Convert( Add( Convert( Parameter( x type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) Convert( Parameter( y type: E_SByte ) type: System.Double ) type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.String,E_SByte,System.String] ) -=-=-=-=-=-=-=-=- E_SByte? & String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_SByte] ) Parameter( y type: System.String ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Coalesce( Parameter( x type: System.Nullable`1[E_SByte] ) Constant( null type: System.String ) conversion: Lambda( Parameter( CoalesceLHS type: System.Nullable`1[E_SByte] ) body { Convert( ConvertChecked( ConvertChecked( Parameter( CoalesceLHS type: System.Nullable`1[E_SByte] ) method: E_SByte op_Explicit(System.Nullable`1[E_SByte]) in System.Nullable`1[E_SByte] type: E_SByte ) type: System.Int32 ) method: System.String ToString(Int32) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Nullable`1[E_SByte],System.String] ) type: System.String ) Parameter( y type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.Nullable`1[E_SByte],System.String,System.String] ) -=-=-=-=-=-=-=-=- E_SByte? + String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_SByte] ) Parameter( y type: System.String ) body { Convert( Convert( Add( Convert( Parameter( x type: System.Nullable`1[E_SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) Convert( Convert( Parameter( y type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) method: System.Nullable`1[System.Double] op_Implicit(Double) in System.Nullable`1[System.Double] type: System.Nullable`1[System.Double] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) method: Double op_Explicit(System.Nullable`1[System.Double]) in System.Nullable`1[System.Double] type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.Nullable`1[E_SByte],System.String,System.String] ) -=-=-=-=-=-=-=-=- String & E_SByte? => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.Nullable`1[E_SByte] ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Parameter( x type: System.String ) Coalesce( Parameter( y type: System.Nullable`1[E_SByte] ) Constant( null type: System.String ) conversion: Lambda( Parameter( CoalesceLHS type: System.Nullable`1[E_SByte] ) body { Convert( ConvertChecked( ConvertChecked( Parameter( CoalesceLHS type: System.Nullable`1[E_SByte] ) method: E_SByte op_Explicit(System.Nullable`1[E_SByte]) in System.Nullable`1[E_SByte] type: E_SByte ) type: System.Int32 ) method: System.String ToString(Int32) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Nullable`1[E_SByte],System.String] ) type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.String,System.Nullable`1[E_SByte],System.String] ) -=-=-=-=-=-=-=-=- String + E_SByte? => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.Nullable`1[E_SByte] ) body { Convert( Convert( Add( Convert( Convert( Parameter( x type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) method: System.Nullable`1[System.Double] op_Implicit(Double) in System.Nullable`1[System.Double] type: System.Nullable`1[System.Double] ) Convert( Parameter( y type: System.Nullable`1[E_SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) method: Double op_Explicit(System.Nullable`1[System.Double]) in System.Nullable`1[System.Double] type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.String,System.Nullable`1[E_SByte],System.String] ) -=-=-=-=-=-=-=-=- Byte & String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Byte ) Parameter( y type: System.String ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Convert( Parameter( x type: System.Byte ) method: System.String ToString(Byte) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) Parameter( y type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.Byte,System.String,System.String] ) -=-=-=-=-=-=-=-=- Byte + String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Byte ) Parameter( y type: System.String ) body { Convert( Add( Convert( Parameter( x type: System.Byte ) type: System.Double ) Convert( Parameter( y type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.Byte,System.String,System.String] ) -=-=-=-=-=-=-=-=- String & Byte => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.Byte ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Parameter( x type: System.String ) Convert( Parameter( y type: System.Byte ) method: System.String ToString(Byte) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.String,System.Byte,System.String] ) -=-=-=-=-=-=-=-=- String + Byte => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.Byte ) body { Convert( Add( Convert( Parameter( x type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) Convert( Parameter( y type: System.Byte ) type: System.Double ) type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.String,System.Byte,System.String] ) -=-=-=-=-=-=-=-=- Byte? & String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Byte] ) Parameter( y type: System.String ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Coalesce( Parameter( x type: System.Nullable`1[System.Byte] ) Constant( null type: System.String ) conversion: Lambda( Parameter( CoalesceLHS type: System.Nullable`1[System.Byte] ) body { Convert( ConvertChecked( Parameter( CoalesceLHS type: System.Nullable`1[System.Byte] ) method: Byte op_Explicit(System.Nullable`1[System.Byte]) in System.Nullable`1[System.Byte] type: System.Byte ) method: System.String ToString(Byte) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Nullable`1[System.Byte],System.String] ) type: System.String ) Parameter( y type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.Nullable`1[System.Byte],System.String,System.String] ) -=-=-=-=-=-=-=-=- Byte? + String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Byte] ) Parameter( y type: System.String ) body { Convert( Convert( Add( Convert( Parameter( x type: System.Nullable`1[System.Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) Convert( Convert( Parameter( y type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) method: System.Nullable`1[System.Double] op_Implicit(Double) in System.Nullable`1[System.Double] type: System.Nullable`1[System.Double] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) method: Double op_Explicit(System.Nullable`1[System.Double]) in System.Nullable`1[System.Double] type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.Nullable`1[System.Byte],System.String,System.String] ) -=-=-=-=-=-=-=-=- String & Byte? => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.Nullable`1[System.Byte] ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Parameter( x type: System.String ) Coalesce( Parameter( y type: System.Nullable`1[System.Byte] ) Constant( null type: System.String ) conversion: Lambda( Parameter( CoalesceLHS type: System.Nullable`1[System.Byte] ) body { Convert( ConvertChecked( Parameter( CoalesceLHS type: System.Nullable`1[System.Byte] ) method: Byte op_Explicit(System.Nullable`1[System.Byte]) in System.Nullable`1[System.Byte] type: System.Byte ) method: System.String ToString(Byte) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Nullable`1[System.Byte],System.String] ) type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.String,System.Nullable`1[System.Byte],System.String] ) -=-=-=-=-=-=-=-=- String + Byte? => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.Nullable`1[System.Byte] ) body { Convert( Convert( Add( Convert( Convert( Parameter( x type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) method: System.Nullable`1[System.Double] op_Implicit(Double) in System.Nullable`1[System.Double] type: System.Nullable`1[System.Double] ) Convert( Parameter( y type: System.Nullable`1[System.Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) method: Double op_Explicit(System.Nullable`1[System.Double]) in System.Nullable`1[System.Double] type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.String,System.Nullable`1[System.Byte],System.String] ) -=-=-=-=-=-=-=-=- E_Byte & String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Byte ) Parameter( y type: System.String ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Convert( ConvertChecked( Parameter( x type: E_Byte ) type: System.Byte ) method: System.String ToString(Byte) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) Parameter( y type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[E_Byte,System.String,System.String] ) -=-=-=-=-=-=-=-=- E_Byte + String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Byte ) Parameter( y type: System.String ) body { Convert( Add( Convert( Parameter( x type: E_Byte ) type: System.Double ) Convert( Parameter( y type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[E_Byte,System.String,System.String] ) -=-=-=-=-=-=-=-=- String & E_Byte => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: E_Byte ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Parameter( x type: System.String ) Convert( ConvertChecked( Parameter( y type: E_Byte ) type: System.Byte ) method: System.String ToString(Byte) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.String,E_Byte,System.String] ) -=-=-=-=-=-=-=-=- String + E_Byte => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: E_Byte ) body { Convert( Add( Convert( Parameter( x type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) Convert( Parameter( y type: E_Byte ) type: System.Double ) type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.String,E_Byte,System.String] ) -=-=-=-=-=-=-=-=- E_Byte? & String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Byte] ) Parameter( y type: System.String ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Coalesce( Parameter( x type: System.Nullable`1[E_Byte] ) Constant( null type: System.String ) conversion: Lambda( Parameter( CoalesceLHS type: System.Nullable`1[E_Byte] ) body { Convert( ConvertChecked( ConvertChecked( Parameter( CoalesceLHS type: System.Nullable`1[E_Byte] ) method: E_Byte op_Explicit(System.Nullable`1[E_Byte]) in System.Nullable`1[E_Byte] type: E_Byte ) type: System.Byte ) method: System.String ToString(Byte) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Nullable`1[E_Byte],System.String] ) type: System.String ) Parameter( y type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.Nullable`1[E_Byte],System.String,System.String] ) -=-=-=-=-=-=-=-=- E_Byte? + String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Byte] ) Parameter( y type: System.String ) body { Convert( Convert( Add( Convert( Parameter( x type: System.Nullable`1[E_Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) Convert( Convert( Parameter( y type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) method: System.Nullable`1[System.Double] op_Implicit(Double) in System.Nullable`1[System.Double] type: System.Nullable`1[System.Double] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) method: Double op_Explicit(System.Nullable`1[System.Double]) in System.Nullable`1[System.Double] type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.Nullable`1[E_Byte],System.String,System.String] ) -=-=-=-=-=-=-=-=- String & E_Byte? => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.Nullable`1[E_Byte] ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Parameter( x type: System.String ) Coalesce( Parameter( y type: System.Nullable`1[E_Byte] ) Constant( null type: System.String ) conversion: Lambda( Parameter( CoalesceLHS type: System.Nullable`1[E_Byte] ) body { Convert( ConvertChecked( ConvertChecked( Parameter( CoalesceLHS type: System.Nullable`1[E_Byte] ) method: E_Byte op_Explicit(System.Nullable`1[E_Byte]) in System.Nullable`1[E_Byte] type: E_Byte ) type: System.Byte ) method: System.String ToString(Byte) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Nullable`1[E_Byte],System.String] ) type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.String,System.Nullable`1[E_Byte],System.String] ) -=-=-=-=-=-=-=-=- String + E_Byte? => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.Nullable`1[E_Byte] ) body { Convert( Convert( Add( Convert( Convert( Parameter( x type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) method: System.Nullable`1[System.Double] op_Implicit(Double) in System.Nullable`1[System.Double] type: System.Nullable`1[System.Double] ) Convert( Parameter( y type: System.Nullable`1[E_Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) method: Double op_Explicit(System.Nullable`1[System.Double]) in System.Nullable`1[System.Double] type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.String,System.Nullable`1[E_Byte],System.String] ) -=-=-=-=-=-=-=-=- Short & String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int16 ) Parameter( y type: System.String ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Convert( ConvertChecked( Parameter( x type: System.Int16 ) type: System.Int32 ) method: System.String ToString(Int32) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) Parameter( y type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.Int16,System.String,System.String] ) -=-=-=-=-=-=-=-=- Short + String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int16 ) Parameter( y type: System.String ) body { Convert( Add( Convert( Parameter( x type: System.Int16 ) type: System.Double ) Convert( Parameter( y type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.Int16,System.String,System.String] ) -=-=-=-=-=-=-=-=- String & Short => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.Int16 ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Parameter( x type: System.String ) Convert( ConvertChecked( Parameter( y type: System.Int16 ) type: System.Int32 ) method: System.String ToString(Int32) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.String,System.Int16,System.String] ) -=-=-=-=-=-=-=-=- String + Short => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.Int16 ) body { Convert( Add( Convert( Parameter( x type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) Convert( Parameter( y type: System.Int16 ) type: System.Double ) type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.String,System.Int16,System.String] ) -=-=-=-=-=-=-=-=- Short? & String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int16] ) Parameter( y type: System.String ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Coalesce( Parameter( x type: System.Nullable`1[System.Int16] ) Constant( null type: System.String ) conversion: Lambda( Parameter( CoalesceLHS type: System.Nullable`1[System.Int16] ) body { Convert( ConvertChecked( ConvertChecked( Parameter( CoalesceLHS type: System.Nullable`1[System.Int16] ) method: Int16 op_Explicit(System.Nullable`1[System.Int16]) in System.Nullable`1[System.Int16] type: System.Int16 ) type: System.Int32 ) method: System.String ToString(Int32) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Nullable`1[System.Int16],System.String] ) type: System.String ) Parameter( y type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.Nullable`1[System.Int16],System.String,System.String] ) -=-=-=-=-=-=-=-=- Short? + String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int16] ) Parameter( y type: System.String ) body { Convert( Convert( Add( Convert( Parameter( x type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) Convert( Convert( Parameter( y type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) method: System.Nullable`1[System.Double] op_Implicit(Double) in System.Nullable`1[System.Double] type: System.Nullable`1[System.Double] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) method: Double op_Explicit(System.Nullable`1[System.Double]) in System.Nullable`1[System.Double] type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.Nullable`1[System.Int16],System.String,System.String] ) -=-=-=-=-=-=-=-=- String & Short? => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.Nullable`1[System.Int16] ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Parameter( x type: System.String ) Coalesce( Parameter( y type: System.Nullable`1[System.Int16] ) Constant( null type: System.String ) conversion: Lambda( Parameter( CoalesceLHS type: System.Nullable`1[System.Int16] ) body { Convert( ConvertChecked( ConvertChecked( Parameter( CoalesceLHS type: System.Nullable`1[System.Int16] ) method: Int16 op_Explicit(System.Nullable`1[System.Int16]) in System.Nullable`1[System.Int16] type: System.Int16 ) type: System.Int32 ) method: System.String ToString(Int32) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Nullable`1[System.Int16],System.String] ) type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.String,System.Nullable`1[System.Int16],System.String] ) -=-=-=-=-=-=-=-=- String + Short? => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.Nullable`1[System.Int16] ) body { Convert( Convert( Add( Convert( Convert( Parameter( x type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) method: System.Nullable`1[System.Double] op_Implicit(Double) in System.Nullable`1[System.Double] type: System.Nullable`1[System.Double] ) Convert( Parameter( y type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) method: Double op_Explicit(System.Nullable`1[System.Double]) in System.Nullable`1[System.Double] type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.String,System.Nullable`1[System.Int16],System.String] ) -=-=-=-=-=-=-=-=- E_Short & String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Short ) Parameter( y type: System.String ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Convert( ConvertChecked( Parameter( x type: E_Short ) type: System.Int32 ) method: System.String ToString(Int32) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) Parameter( y type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[E_Short,System.String,System.String] ) -=-=-=-=-=-=-=-=- E_Short + String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Short ) Parameter( y type: System.String ) body { Convert( Add( Convert( Parameter( x type: E_Short ) type: System.Double ) Convert( Parameter( y type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[E_Short,System.String,System.String] ) -=-=-=-=-=-=-=-=- String & E_Short => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: E_Short ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Parameter( x type: System.String ) Convert( ConvertChecked( Parameter( y type: E_Short ) type: System.Int32 ) method: System.String ToString(Int32) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.String,E_Short,System.String] ) -=-=-=-=-=-=-=-=- String + E_Short => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: E_Short ) body { Convert( Add( Convert( Parameter( x type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) Convert( Parameter( y type: E_Short ) type: System.Double ) type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.String,E_Short,System.String] ) -=-=-=-=-=-=-=-=- E_Short? & String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Short] ) Parameter( y type: System.String ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Coalesce( Parameter( x type: System.Nullable`1[E_Short] ) Constant( null type: System.String ) conversion: Lambda( Parameter( CoalesceLHS type: System.Nullable`1[E_Short] ) body { Convert( ConvertChecked( ConvertChecked( Parameter( CoalesceLHS type: System.Nullable`1[E_Short] ) method: E_Short op_Explicit(System.Nullable`1[E_Short]) in System.Nullable`1[E_Short] type: E_Short ) type: System.Int32 ) method: System.String ToString(Int32) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Nullable`1[E_Short],System.String] ) type: System.String ) Parameter( y type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.Nullable`1[E_Short],System.String,System.String] ) -=-=-=-=-=-=-=-=- E_Short? + String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Short] ) Parameter( y type: System.String ) body { Convert( Convert( Add( Convert( Parameter( x type: System.Nullable`1[E_Short] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) Convert( Convert( Parameter( y type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) method: System.Nullable`1[System.Double] op_Implicit(Double) in System.Nullable`1[System.Double] type: System.Nullable`1[System.Double] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) method: Double op_Explicit(System.Nullable`1[System.Double]) in System.Nullable`1[System.Double] type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.Nullable`1[E_Short],System.String,System.String] ) -=-=-=-=-=-=-=-=- String & E_Short? => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.Nullable`1[E_Short] ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Parameter( x type: System.String ) Coalesce( Parameter( y type: System.Nullable`1[E_Short] ) Constant( null type: System.String ) conversion: Lambda( Parameter( CoalesceLHS type: System.Nullable`1[E_Short] ) body { Convert( ConvertChecked( ConvertChecked( Parameter( CoalesceLHS type: System.Nullable`1[E_Short] ) method: E_Short op_Explicit(System.Nullable`1[E_Short]) in System.Nullable`1[E_Short] type: E_Short ) type: System.Int32 ) method: System.String ToString(Int32) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Nullable`1[E_Short],System.String] ) type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.String,System.Nullable`1[E_Short],System.String] ) -=-=-=-=-=-=-=-=- String + E_Short? => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.Nullable`1[E_Short] ) body { Convert( Convert( Add( Convert( Convert( Parameter( x type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) method: System.Nullable`1[System.Double] op_Implicit(Double) in System.Nullable`1[System.Double] type: System.Nullable`1[System.Double] ) Convert( Parameter( y type: System.Nullable`1[E_Short] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) method: Double op_Explicit(System.Nullable`1[System.Double]) in System.Nullable`1[System.Double] type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.String,System.Nullable`1[E_Short],System.String] ) -=-=-=-=-=-=-=-=- UShort & String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt16 ) Parameter( y type: System.String ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Convert( ConvertChecked( Parameter( x type: System.UInt16 ) type: System.UInt32 ) method: System.String ToString(UInt32) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) Parameter( y type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.UInt16,System.String,System.String] ) -=-=-=-=-=-=-=-=- UShort + String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt16 ) Parameter( y type: System.String ) body { Convert( Add( Convert( Parameter( x type: System.UInt16 ) type: System.Double ) Convert( Parameter( y type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.UInt16,System.String,System.String] ) -=-=-=-=-=-=-=-=- String & UShort => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.UInt16 ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Parameter( x type: System.String ) Convert( ConvertChecked( Parameter( y type: System.UInt16 ) type: System.UInt32 ) method: System.String ToString(UInt32) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.String,System.UInt16,System.String] ) -=-=-=-=-=-=-=-=- String + UShort => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.UInt16 ) body { Convert( Add( Convert( Parameter( x type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) Convert( Parameter( y type: System.UInt16 ) type: System.Double ) type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.String,System.UInt16,System.String] ) -=-=-=-=-=-=-=-=- UShort? & String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt16] ) Parameter( y type: System.String ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Coalesce( Parameter( x type: System.Nullable`1[System.UInt16] ) Constant( null type: System.String ) conversion: Lambda( Parameter( CoalesceLHS type: System.Nullable`1[System.UInt16] ) body { Convert( ConvertChecked( ConvertChecked( Parameter( CoalesceLHS type: System.Nullable`1[System.UInt16] ) method: UInt16 op_Explicit(System.Nullable`1[System.UInt16]) in System.Nullable`1[System.UInt16] type: System.UInt16 ) type: System.UInt32 ) method: System.String ToString(UInt32) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Nullable`1[System.UInt16],System.String] ) type: System.String ) Parameter( y type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.Nullable`1[System.UInt16],System.String,System.String] ) -=-=-=-=-=-=-=-=- UShort? + String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt16] ) Parameter( y type: System.String ) body { Convert( Convert( Add( Convert( Parameter( x type: System.Nullable`1[System.UInt16] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) Convert( Convert( Parameter( y type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) method: System.Nullable`1[System.Double] op_Implicit(Double) in System.Nullable`1[System.Double] type: System.Nullable`1[System.Double] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) method: Double op_Explicit(System.Nullable`1[System.Double]) in System.Nullable`1[System.Double] type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.Nullable`1[System.UInt16],System.String,System.String] ) -=-=-=-=-=-=-=-=- String & UShort? => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.Nullable`1[System.UInt16] ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Parameter( x type: System.String ) Coalesce( Parameter( y type: System.Nullable`1[System.UInt16] ) Constant( null type: System.String ) conversion: Lambda( Parameter( CoalesceLHS type: System.Nullable`1[System.UInt16] ) body { Convert( ConvertChecked( ConvertChecked( Parameter( CoalesceLHS type: System.Nullable`1[System.UInt16] ) method: UInt16 op_Explicit(System.Nullable`1[System.UInt16]) in System.Nullable`1[System.UInt16] type: System.UInt16 ) type: System.UInt32 ) method: System.String ToString(UInt32) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Nullable`1[System.UInt16],System.String] ) type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.String,System.Nullable`1[System.UInt16],System.String] ) -=-=-=-=-=-=-=-=- String + UShort? => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.Nullable`1[System.UInt16] ) body { Convert( Convert( Add( Convert( Convert( Parameter( x type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) method: System.Nullable`1[System.Double] op_Implicit(Double) in System.Nullable`1[System.Double] type: System.Nullable`1[System.Double] ) Convert( Parameter( y type: System.Nullable`1[System.UInt16] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) method: Double op_Explicit(System.Nullable`1[System.Double]) in System.Nullable`1[System.Double] type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.String,System.Nullable`1[System.UInt16],System.String] ) -=-=-=-=-=-=-=-=- E_UShort & String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UShort ) Parameter( y type: System.String ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Convert( ConvertChecked( Parameter( x type: E_UShort ) type: System.UInt32 ) method: System.String ToString(UInt32) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) Parameter( y type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[E_UShort,System.String,System.String] ) -=-=-=-=-=-=-=-=- E_UShort + String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UShort ) Parameter( y type: System.String ) body { Convert( Add( Convert( Parameter( x type: E_UShort ) type: System.Double ) Convert( Parameter( y type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[E_UShort,System.String,System.String] ) -=-=-=-=-=-=-=-=- String & E_UShort => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: E_UShort ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Parameter( x type: System.String ) Convert( ConvertChecked( Parameter( y type: E_UShort ) type: System.UInt32 ) method: System.String ToString(UInt32) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.String,E_UShort,System.String] ) -=-=-=-=-=-=-=-=- String + E_UShort => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: E_UShort ) body { Convert( Add( Convert( Parameter( x type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) Convert( Parameter( y type: E_UShort ) type: System.Double ) type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.String,E_UShort,System.String] ) -=-=-=-=-=-=-=-=- E_UShort? & String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_UShort] ) Parameter( y type: System.String ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Coalesce( Parameter( x type: System.Nullable`1[E_UShort] ) Constant( null type: System.String ) conversion: Lambda( Parameter( CoalesceLHS type: System.Nullable`1[E_UShort] ) body { Convert( ConvertChecked( ConvertChecked( Parameter( CoalesceLHS type: System.Nullable`1[E_UShort] ) method: E_UShort op_Explicit(System.Nullable`1[E_UShort]) in System.Nullable`1[E_UShort] type: E_UShort ) type: System.UInt32 ) method: System.String ToString(UInt32) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Nullable`1[E_UShort],System.String] ) type: System.String ) Parameter( y type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.Nullable`1[E_UShort],System.String,System.String] ) -=-=-=-=-=-=-=-=- E_UShort? + String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_UShort] ) Parameter( y type: System.String ) body { Convert( Convert( Add( Convert( Parameter( x type: System.Nullable`1[E_UShort] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) Convert( Convert( Parameter( y type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) method: System.Nullable`1[System.Double] op_Implicit(Double) in System.Nullable`1[System.Double] type: System.Nullable`1[System.Double] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) method: Double op_Explicit(System.Nullable`1[System.Double]) in System.Nullable`1[System.Double] type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.Nullable`1[E_UShort],System.String,System.String] ) -=-=-=-=-=-=-=-=- String & E_UShort? => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.Nullable`1[E_UShort] ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Parameter( x type: System.String ) Coalesce( Parameter( y type: System.Nullable`1[E_UShort] ) Constant( null type: System.String ) conversion: Lambda( Parameter( CoalesceLHS type: System.Nullable`1[E_UShort] ) body { Convert( ConvertChecked( ConvertChecked( Parameter( CoalesceLHS type: System.Nullable`1[E_UShort] ) method: E_UShort op_Explicit(System.Nullable`1[E_UShort]) in System.Nullable`1[E_UShort] type: E_UShort ) type: System.UInt32 ) method: System.String ToString(UInt32) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Nullable`1[E_UShort],System.String] ) type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.String,System.Nullable`1[E_UShort],System.String] ) -=-=-=-=-=-=-=-=- String + E_UShort? => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.Nullable`1[E_UShort] ) body { Convert( Convert( Add( Convert( Convert( Parameter( x type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) method: System.Nullable`1[System.Double] op_Implicit(Double) in System.Nullable`1[System.Double] type: System.Nullable`1[System.Double] ) Convert( Parameter( y type: System.Nullable`1[E_UShort] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) method: Double op_Explicit(System.Nullable`1[System.Double]) in System.Nullable`1[System.Double] type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.String,System.Nullable`1[E_UShort],System.String] ) -=-=-=-=-=-=-=-=- Integer & String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int32 ) Parameter( y type: System.String ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Convert( Parameter( x type: System.Int32 ) method: System.String ToString(Int32) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) Parameter( y type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.Int32,System.String,System.String] ) -=-=-=-=-=-=-=-=- Integer + String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int32 ) Parameter( y type: System.String ) body { Convert( Add( Convert( Parameter( x type: System.Int32 ) type: System.Double ) Convert( Parameter( y type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.Int32,System.String,System.String] ) -=-=-=-=-=-=-=-=- String & Integer => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.Int32 ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Parameter( x type: System.String ) Convert( Parameter( y type: System.Int32 ) method: System.String ToString(Int32) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.String,System.Int32,System.String] ) -=-=-=-=-=-=-=-=- String + Integer => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.Int32 ) body { Convert( Add( Convert( Parameter( x type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) Convert( Parameter( y type: System.Int32 ) type: System.Double ) type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.String,System.Int32,System.String] ) -=-=-=-=-=-=-=-=- Integer? & String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int32] ) Parameter( y type: System.String ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Coalesce( Parameter( x type: System.Nullable`1[System.Int32] ) Constant( null type: System.String ) conversion: Lambda( Parameter( CoalesceLHS type: System.Nullable`1[System.Int32] ) body { Convert( ConvertChecked( Parameter( CoalesceLHS type: System.Nullable`1[System.Int32] ) method: Int32 op_Explicit(System.Nullable`1[System.Int32]) in System.Nullable`1[System.Int32] type: System.Int32 ) method: System.String ToString(Int32) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Nullable`1[System.Int32],System.String] ) type: System.String ) Parameter( y type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.Nullable`1[System.Int32],System.String,System.String] ) -=-=-=-=-=-=-=-=- Integer? + String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int32] ) Parameter( y type: System.String ) body { Convert( Convert( Add( Convert( Parameter( x type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) Convert( Convert( Parameter( y type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) method: System.Nullable`1[System.Double] op_Implicit(Double) in System.Nullable`1[System.Double] type: System.Nullable`1[System.Double] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) method: Double op_Explicit(System.Nullable`1[System.Double]) in System.Nullable`1[System.Double] type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.Nullable`1[System.Int32],System.String,System.String] ) -=-=-=-=-=-=-=-=- String & Integer? => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.Nullable`1[System.Int32] ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Parameter( x type: System.String ) Coalesce( Parameter( y type: System.Nullable`1[System.Int32] ) Constant( null type: System.String ) conversion: Lambda( Parameter( CoalesceLHS type: System.Nullable`1[System.Int32] ) body { Convert( ConvertChecked( Parameter( CoalesceLHS type: System.Nullable`1[System.Int32] ) method: Int32 op_Explicit(System.Nullable`1[System.Int32]) in System.Nullable`1[System.Int32] type: System.Int32 ) method: System.String ToString(Int32) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Nullable`1[System.Int32],System.String] ) type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.String,System.Nullable`1[System.Int32],System.String] ) -=-=-=-=-=-=-=-=- String + Integer? => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.Nullable`1[System.Int32] ) body { Convert( Convert( Add( Convert( Convert( Parameter( x type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) method: System.Nullable`1[System.Double] op_Implicit(Double) in System.Nullable`1[System.Double] type: System.Nullable`1[System.Double] ) Convert( Parameter( y type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) method: Double op_Explicit(System.Nullable`1[System.Double]) in System.Nullable`1[System.Double] type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.String,System.Nullable`1[System.Int32],System.String] ) -=-=-=-=-=-=-=-=- E_Integer & String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Integer ) Parameter( y type: System.String ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Convert( ConvertChecked( Parameter( x type: E_Integer ) type: System.Int32 ) method: System.String ToString(Int32) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) Parameter( y type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[E_Integer,System.String,System.String] ) -=-=-=-=-=-=-=-=- E_Integer + String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Integer ) Parameter( y type: System.String ) body { Convert( Add( Convert( Parameter( x type: E_Integer ) type: System.Double ) Convert( Parameter( y type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[E_Integer,System.String,System.String] ) -=-=-=-=-=-=-=-=- String & E_Integer => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: E_Integer ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Parameter( x type: System.String ) Convert( ConvertChecked( Parameter( y type: E_Integer ) type: System.Int32 ) method: System.String ToString(Int32) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.String,E_Integer,System.String] ) -=-=-=-=-=-=-=-=- String + E_Integer => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: E_Integer ) body { Convert( Add( Convert( Parameter( x type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) Convert( Parameter( y type: E_Integer ) type: System.Double ) type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.String,E_Integer,System.String] ) -=-=-=-=-=-=-=-=- E_Integer? & String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Integer] ) Parameter( y type: System.String ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Coalesce( Parameter( x type: System.Nullable`1[E_Integer] ) Constant( null type: System.String ) conversion: Lambda( Parameter( CoalesceLHS type: System.Nullable`1[E_Integer] ) body { Convert( ConvertChecked( ConvertChecked( Parameter( CoalesceLHS type: System.Nullable`1[E_Integer] ) method: E_Integer op_Explicit(System.Nullable`1[E_Integer]) in System.Nullable`1[E_Integer] type: E_Integer ) type: System.Int32 ) method: System.String ToString(Int32) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Nullable`1[E_Integer],System.String] ) type: System.String ) Parameter( y type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.Nullable`1[E_Integer],System.String,System.String] ) -=-=-=-=-=-=-=-=- E_Integer? + String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Integer] ) Parameter( y type: System.String ) body { Convert( Convert( Add( Convert( Parameter( x type: System.Nullable`1[E_Integer] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) Convert( Convert( Parameter( y type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) method: System.Nullable`1[System.Double] op_Implicit(Double) in System.Nullable`1[System.Double] type: System.Nullable`1[System.Double] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) method: Double op_Explicit(System.Nullable`1[System.Double]) in System.Nullable`1[System.Double] type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.Nullable`1[E_Integer],System.String,System.String] ) -=-=-=-=-=-=-=-=- String & E_Integer? => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.Nullable`1[E_Integer] ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Parameter( x type: System.String ) Coalesce( Parameter( y type: System.Nullable`1[E_Integer] ) Constant( null type: System.String ) conversion: Lambda( Parameter( CoalesceLHS type: System.Nullable`1[E_Integer] ) body { Convert( ConvertChecked( ConvertChecked( Parameter( CoalesceLHS type: System.Nullable`1[E_Integer] ) method: E_Integer op_Explicit(System.Nullable`1[E_Integer]) in System.Nullable`1[E_Integer] type: E_Integer ) type: System.Int32 ) method: System.String ToString(Int32) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Nullable`1[E_Integer],System.String] ) type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.String,System.Nullable`1[E_Integer],System.String] ) -=-=-=-=-=-=-=-=- String + E_Integer? => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.Nullable`1[E_Integer] ) body { Convert( Convert( Add( Convert( Convert( Parameter( x type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) method: System.Nullable`1[System.Double] op_Implicit(Double) in System.Nullable`1[System.Double] type: System.Nullable`1[System.Double] ) Convert( Parameter( y type: System.Nullable`1[E_Integer] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) method: Double op_Explicit(System.Nullable`1[System.Double]) in System.Nullable`1[System.Double] type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.String,System.Nullable`1[E_Integer],System.String] ) -=-=-=-=-=-=-=-=- UInteger & String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt32 ) Parameter( y type: System.String ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Convert( Parameter( x type: System.UInt32 ) method: System.String ToString(UInt32) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) Parameter( y type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.UInt32,System.String,System.String] ) -=-=-=-=-=-=-=-=- UInteger + String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt32 ) Parameter( y type: System.String ) body { Convert( Add( Convert( Parameter( x type: System.UInt32 ) type: System.Double ) Convert( Parameter( y type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.UInt32,System.String,System.String] ) -=-=-=-=-=-=-=-=- String & UInteger => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.UInt32 ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Parameter( x type: System.String ) Convert( Parameter( y type: System.UInt32 ) method: System.String ToString(UInt32) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.String,System.UInt32,System.String] ) -=-=-=-=-=-=-=-=- String + UInteger => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.UInt32 ) body { Convert( Add( Convert( Parameter( x type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) Convert( Parameter( y type: System.UInt32 ) type: System.Double ) type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.String,System.UInt32,System.String] ) -=-=-=-=-=-=-=-=- UInteger? & String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt32] ) Parameter( y type: System.String ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Coalesce( Parameter( x type: System.Nullable`1[System.UInt32] ) Constant( null type: System.String ) conversion: Lambda( Parameter( CoalesceLHS type: System.Nullable`1[System.UInt32] ) body { Convert( ConvertChecked( Parameter( CoalesceLHS type: System.Nullable`1[System.UInt32] ) method: UInt32 op_Explicit(System.Nullable`1[System.UInt32]) in System.Nullable`1[System.UInt32] type: System.UInt32 ) method: System.String ToString(UInt32) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Nullable`1[System.UInt32],System.String] ) type: System.String ) Parameter( y type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.Nullable`1[System.UInt32],System.String,System.String] ) -=-=-=-=-=-=-=-=- UInteger? + String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt32] ) Parameter( y type: System.String ) body { Convert( Convert( Add( Convert( Parameter( x type: System.Nullable`1[System.UInt32] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) Convert( Convert( Parameter( y type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) method: System.Nullable`1[System.Double] op_Implicit(Double) in System.Nullable`1[System.Double] type: System.Nullable`1[System.Double] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) method: Double op_Explicit(System.Nullable`1[System.Double]) in System.Nullable`1[System.Double] type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.Nullable`1[System.UInt32],System.String,System.String] ) -=-=-=-=-=-=-=-=- String & UInteger? => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.Nullable`1[System.UInt32] ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Parameter( x type: System.String ) Coalesce( Parameter( y type: System.Nullable`1[System.UInt32] ) Constant( null type: System.String ) conversion: Lambda( Parameter( CoalesceLHS type: System.Nullable`1[System.UInt32] ) body { Convert( ConvertChecked( Parameter( CoalesceLHS type: System.Nullable`1[System.UInt32] ) method: UInt32 op_Explicit(System.Nullable`1[System.UInt32]) in System.Nullable`1[System.UInt32] type: System.UInt32 ) method: System.String ToString(UInt32) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Nullable`1[System.UInt32],System.String] ) type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.String,System.Nullable`1[System.UInt32],System.String] ) -=-=-=-=-=-=-=-=- String + UInteger? => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.Nullable`1[System.UInt32] ) body { Convert( Convert( Add( Convert( Convert( Parameter( x type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) method: System.Nullable`1[System.Double] op_Implicit(Double) in System.Nullable`1[System.Double] type: System.Nullable`1[System.Double] ) Convert( Parameter( y type: System.Nullable`1[System.UInt32] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) method: Double op_Explicit(System.Nullable`1[System.Double]) in System.Nullable`1[System.Double] type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.String,System.Nullable`1[System.UInt32],System.String] ) -=-=-=-=-=-=-=-=- E_UInteger & String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UInteger ) Parameter( y type: System.String ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Convert( ConvertChecked( Parameter( x type: E_UInteger ) type: System.UInt32 ) method: System.String ToString(UInt32) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) Parameter( y type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[E_UInteger,System.String,System.String] ) -=-=-=-=-=-=-=-=- E_UInteger + String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UInteger ) Parameter( y type: System.String ) body { Convert( Add( Convert( Parameter( x type: E_UInteger ) type: System.Double ) Convert( Parameter( y type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[E_UInteger,System.String,System.String] ) -=-=-=-=-=-=-=-=- String & E_UInteger => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: E_UInteger ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Parameter( x type: System.String ) Convert( ConvertChecked( Parameter( y type: E_UInteger ) type: System.UInt32 ) method: System.String ToString(UInt32) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.String,E_UInteger,System.String] ) -=-=-=-=-=-=-=-=- String + E_UInteger => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: E_UInteger ) body { Convert( Add( Convert( Parameter( x type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) Convert( Parameter( y type: E_UInteger ) type: System.Double ) type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.String,E_UInteger,System.String] ) -=-=-=-=-=-=-=-=- E_UInteger? & String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_UInteger] ) Parameter( y type: System.String ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Coalesce( Parameter( x type: System.Nullable`1[E_UInteger] ) Constant( null type: System.String ) conversion: Lambda( Parameter( CoalesceLHS type: System.Nullable`1[E_UInteger] ) body { Convert( ConvertChecked( ConvertChecked( Parameter( CoalesceLHS type: System.Nullable`1[E_UInteger] ) method: E_UInteger op_Explicit(System.Nullable`1[E_UInteger]) in System.Nullable`1[E_UInteger] type: E_UInteger ) type: System.UInt32 ) method: System.String ToString(UInt32) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Nullable`1[E_UInteger],System.String] ) type: System.String ) Parameter( y type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.Nullable`1[E_UInteger],System.String,System.String] ) -=-=-=-=-=-=-=-=- E_UInteger? + String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_UInteger] ) Parameter( y type: System.String ) body { Convert( Convert( Add( Convert( Parameter( x type: System.Nullable`1[E_UInteger] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) Convert( Convert( Parameter( y type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) method: System.Nullable`1[System.Double] op_Implicit(Double) in System.Nullable`1[System.Double] type: System.Nullable`1[System.Double] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) method: Double op_Explicit(System.Nullable`1[System.Double]) in System.Nullable`1[System.Double] type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.Nullable`1[E_UInteger],System.String,System.String] ) -=-=-=-=-=-=-=-=- String & E_UInteger? => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.Nullable`1[E_UInteger] ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Parameter( x type: System.String ) Coalesce( Parameter( y type: System.Nullable`1[E_UInteger] ) Constant( null type: System.String ) conversion: Lambda( Parameter( CoalesceLHS type: System.Nullable`1[E_UInteger] ) body { Convert( ConvertChecked( ConvertChecked( Parameter( CoalesceLHS type: System.Nullable`1[E_UInteger] ) method: E_UInteger op_Explicit(System.Nullable`1[E_UInteger]) in System.Nullable`1[E_UInteger] type: E_UInteger ) type: System.UInt32 ) method: System.String ToString(UInt32) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Nullable`1[E_UInteger],System.String] ) type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.String,System.Nullable`1[E_UInteger],System.String] ) -=-=-=-=-=-=-=-=- String + E_UInteger? => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.Nullable`1[E_UInteger] ) body { Convert( Convert( Add( Convert( Convert( Parameter( x type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) method: System.Nullable`1[System.Double] op_Implicit(Double) in System.Nullable`1[System.Double] type: System.Nullable`1[System.Double] ) Convert( Parameter( y type: System.Nullable`1[E_UInteger] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) method: Double op_Explicit(System.Nullable`1[System.Double]) in System.Nullable`1[System.Double] type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.String,System.Nullable`1[E_UInteger],System.String] ) -=-=-=-=-=-=-=-=- Long & String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int64 ) Parameter( y type: System.String ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Convert( Parameter( x type: System.Int64 ) method: System.String ToString(Int64) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) Parameter( y type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.Int64,System.String,System.String] ) -=-=-=-=-=-=-=-=- Long + String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int64 ) Parameter( y type: System.String ) body { Convert( Add( Convert( Parameter( x type: System.Int64 ) type: System.Double ) Convert( Parameter( y type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.Int64,System.String,System.String] ) -=-=-=-=-=-=-=-=- String & Long => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.Int64 ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Parameter( x type: System.String ) Convert( Parameter( y type: System.Int64 ) method: System.String ToString(Int64) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.String,System.Int64,System.String] ) -=-=-=-=-=-=-=-=- String + Long => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.Int64 ) body { Convert( Add( Convert( Parameter( x type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) Convert( Parameter( y type: System.Int64 ) type: System.Double ) type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.String,System.Int64,System.String] ) -=-=-=-=-=-=-=-=- Long? & String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int64] ) Parameter( y type: System.String ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Coalesce( Parameter( x type: System.Nullable`1[System.Int64] ) Constant( null type: System.String ) conversion: Lambda( Parameter( CoalesceLHS type: System.Nullable`1[System.Int64] ) body { Convert( ConvertChecked( Parameter( CoalesceLHS type: System.Nullable`1[System.Int64] ) method: Int64 op_Explicit(System.Nullable`1[System.Int64]) in System.Nullable`1[System.Int64] type: System.Int64 ) method: System.String ToString(Int64) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Nullable`1[System.Int64],System.String] ) type: System.String ) Parameter( y type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.Nullable`1[System.Int64],System.String,System.String] ) -=-=-=-=-=-=-=-=- Long? + String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int64] ) Parameter( y type: System.String ) body { Convert( Convert( Add( Convert( Parameter( x type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) Convert( Convert( Parameter( y type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) method: System.Nullable`1[System.Double] op_Implicit(Double) in System.Nullable`1[System.Double] type: System.Nullable`1[System.Double] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) method: Double op_Explicit(System.Nullable`1[System.Double]) in System.Nullable`1[System.Double] type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.Nullable`1[System.Int64],System.String,System.String] ) -=-=-=-=-=-=-=-=- String & Long? => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.Nullable`1[System.Int64] ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Parameter( x type: System.String ) Coalesce( Parameter( y type: System.Nullable`1[System.Int64] ) Constant( null type: System.String ) conversion: Lambda( Parameter( CoalesceLHS type: System.Nullable`1[System.Int64] ) body { Convert( ConvertChecked( Parameter( CoalesceLHS type: System.Nullable`1[System.Int64] ) method: Int64 op_Explicit(System.Nullable`1[System.Int64]) in System.Nullable`1[System.Int64] type: System.Int64 ) method: System.String ToString(Int64) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Nullable`1[System.Int64],System.String] ) type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.String,System.Nullable`1[System.Int64],System.String] ) -=-=-=-=-=-=-=-=- String + Long? => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.Nullable`1[System.Int64] ) body { Convert( Convert( Add( Convert( Convert( Parameter( x type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) method: System.Nullable`1[System.Double] op_Implicit(Double) in System.Nullable`1[System.Double] type: System.Nullable`1[System.Double] ) Convert( Parameter( y type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) method: Double op_Explicit(System.Nullable`1[System.Double]) in System.Nullable`1[System.Double] type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.String,System.Nullable`1[System.Int64],System.String] ) -=-=-=-=-=-=-=-=- E_Long & String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Long ) Parameter( y type: System.String ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Convert( ConvertChecked( Parameter( x type: E_Long ) type: System.Int64 ) method: System.String ToString(Int64) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) Parameter( y type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[E_Long,System.String,System.String] ) -=-=-=-=-=-=-=-=- E_Long + String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Long ) Parameter( y type: System.String ) body { Convert( Add( Convert( Parameter( x type: E_Long ) type: System.Double ) Convert( Parameter( y type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[E_Long,System.String,System.String] ) -=-=-=-=-=-=-=-=- String & E_Long => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: E_Long ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Parameter( x type: System.String ) Convert( ConvertChecked( Parameter( y type: E_Long ) type: System.Int64 ) method: System.String ToString(Int64) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.String,E_Long,System.String] ) -=-=-=-=-=-=-=-=- String + E_Long => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: E_Long ) body { Convert( Add( Convert( Parameter( x type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) Convert( Parameter( y type: E_Long ) type: System.Double ) type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.String,E_Long,System.String] ) -=-=-=-=-=-=-=-=- E_Long? & String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Long] ) Parameter( y type: System.String ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Coalesce( Parameter( x type: System.Nullable`1[E_Long] ) Constant( null type: System.String ) conversion: Lambda( Parameter( CoalesceLHS type: System.Nullable`1[E_Long] ) body { Convert( ConvertChecked( ConvertChecked( Parameter( CoalesceLHS type: System.Nullable`1[E_Long] ) method: E_Long op_Explicit(System.Nullable`1[E_Long]) in System.Nullable`1[E_Long] type: E_Long ) type: System.Int64 ) method: System.String ToString(Int64) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Nullable`1[E_Long],System.String] ) type: System.String ) Parameter( y type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.Nullable`1[E_Long],System.String,System.String] ) -=-=-=-=-=-=-=-=- E_Long? + String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Long] ) Parameter( y type: System.String ) body { Convert( Convert( Add( Convert( Parameter( x type: System.Nullable`1[E_Long] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) Convert( Convert( Parameter( y type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) method: System.Nullable`1[System.Double] op_Implicit(Double) in System.Nullable`1[System.Double] type: System.Nullable`1[System.Double] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) method: Double op_Explicit(System.Nullable`1[System.Double]) in System.Nullable`1[System.Double] type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.Nullable`1[E_Long],System.String,System.String] ) -=-=-=-=-=-=-=-=- String & E_Long? => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.Nullable`1[E_Long] ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Parameter( x type: System.String ) Coalesce( Parameter( y type: System.Nullable`1[E_Long] ) Constant( null type: System.String ) conversion: Lambda( Parameter( CoalesceLHS type: System.Nullable`1[E_Long] ) body { Convert( ConvertChecked( ConvertChecked( Parameter( CoalesceLHS type: System.Nullable`1[E_Long] ) method: E_Long op_Explicit(System.Nullable`1[E_Long]) in System.Nullable`1[E_Long] type: E_Long ) type: System.Int64 ) method: System.String ToString(Int64) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Nullable`1[E_Long],System.String] ) type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.String,System.Nullable`1[E_Long],System.String] ) -=-=-=-=-=-=-=-=- String + E_Long? => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.Nullable`1[E_Long] ) body { Convert( Convert( Add( Convert( Convert( Parameter( x type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) method: System.Nullable`1[System.Double] op_Implicit(Double) in System.Nullable`1[System.Double] type: System.Nullable`1[System.Double] ) Convert( Parameter( y type: System.Nullable`1[E_Long] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) method: Double op_Explicit(System.Nullable`1[System.Double]) in System.Nullable`1[System.Double] type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.String,System.Nullable`1[E_Long],System.String] ) -=-=-=-=-=-=-=-=- Boolean & String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Boolean ) Parameter( y type: System.String ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Convert( Parameter( x type: System.Boolean ) method: System.String ToString(Boolean) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) Parameter( y type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.Boolean,System.String,System.String] ) -=-=-=-=-=-=-=-=- Boolean + String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Boolean ) Parameter( y type: System.String ) body { Convert( Add( Negate( Convert( Parameter( x type: System.Boolean ) type: System.Double ) type: System.Double ) Convert( Parameter( y type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.Boolean,System.String,System.String] ) -=-=-=-=-=-=-=-=- String & Boolean => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.Boolean ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Parameter( x type: System.String ) Convert( Parameter( y type: System.Boolean ) method: System.String ToString(Boolean) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.String,System.Boolean,System.String] ) -=-=-=-=-=-=-=-=- String + Boolean => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.Boolean ) body { Convert( Add( Convert( Parameter( x type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) Negate( Convert( Parameter( y type: System.Boolean ) type: System.Double ) type: System.Double ) type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.String,System.Boolean,System.String] ) -=-=-=-=-=-=-=-=- Boolean? & String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Boolean] ) Parameter( y type: System.String ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Coalesce( Parameter( x type: System.Nullable`1[System.Boolean] ) Constant( null type: System.String ) conversion: Lambda( Parameter( CoalesceLHS type: System.Nullable`1[System.Boolean] ) body { Convert( Convert( Parameter( CoalesceLHS type: System.Nullable`1[System.Boolean] ) method: Boolean op_Explicit(System.Nullable`1[System.Boolean]) in System.Nullable`1[System.Boolean] type: System.Boolean ) method: System.String ToString(Boolean) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Nullable`1[System.Boolean],System.String] ) type: System.String ) Parameter( y type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.Nullable`1[System.Boolean],System.String,System.String] ) -=-=-=-=-=-=-=-=- Boolean? + String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Boolean] ) Parameter( y type: System.String ) body { Convert( Convert( Add( Negate( Convert( Parameter( x type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) Convert( Convert( Parameter( y type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) method: System.Nullable`1[System.Double] op_Implicit(Double) in System.Nullable`1[System.Double] type: System.Nullable`1[System.Double] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) method: Double op_Explicit(System.Nullable`1[System.Double]) in System.Nullable`1[System.Double] type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.Nullable`1[System.Boolean],System.String,System.String] ) -=-=-=-=-=-=-=-=- String & Boolean? => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.Nullable`1[System.Boolean] ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Parameter( x type: System.String ) Coalesce( Parameter( y type: System.Nullable`1[System.Boolean] ) Constant( null type: System.String ) conversion: Lambda( Parameter( CoalesceLHS type: System.Nullable`1[System.Boolean] ) body { Convert( Convert( Parameter( CoalesceLHS type: System.Nullable`1[System.Boolean] ) method: Boolean op_Explicit(System.Nullable`1[System.Boolean]) in System.Nullable`1[System.Boolean] type: System.Boolean ) method: System.String ToString(Boolean) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Nullable`1[System.Boolean],System.String] ) type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.String,System.Nullable`1[System.Boolean],System.String] ) -=-=-=-=-=-=-=-=- String + Boolean? => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.Nullable`1[System.Boolean] ) body { Convert( Convert( Add( Convert( Convert( Parameter( x type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) method: System.Nullable`1[System.Double] op_Implicit(Double) in System.Nullable`1[System.Double] type: System.Nullable`1[System.Double] ) Negate( Convert( Parameter( y type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) method: Double op_Explicit(System.Nullable`1[System.Double]) in System.Nullable`1[System.Double] type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.String,System.Nullable`1[System.Boolean],System.String] ) -=-=-=-=-=-=-=-=- Single & String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Single ) Parameter( y type: System.String ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Convert( Parameter( x type: System.Single ) method: System.String ToString(Single) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) Parameter( y type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.Single,System.String,System.String] ) -=-=-=-=-=-=-=-=- Single + String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Single ) Parameter( y type: System.String ) body { Convert( Add( Convert( Parameter( x type: System.Single ) type: System.Double ) Convert( Parameter( y type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.Single,System.String,System.String] ) -=-=-=-=-=-=-=-=- String & Single => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.Single ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Parameter( x type: System.String ) Convert( Parameter( y type: System.Single ) method: System.String ToString(Single) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.String,System.Single,System.String] ) -=-=-=-=-=-=-=-=- String + Single => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.Single ) body { Convert( Add( Convert( Parameter( x type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) Convert( Parameter( y type: System.Single ) type: System.Double ) type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.String,System.Single,System.String] ) -=-=-=-=-=-=-=-=- Single? & String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Single] ) Parameter( y type: System.String ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Coalesce( Parameter( x type: System.Nullable`1[System.Single] ) Constant( null type: System.String ) conversion: Lambda( Parameter( CoalesceLHS type: System.Nullable`1[System.Single] ) body { Convert( Convert( Parameter( CoalesceLHS type: System.Nullable`1[System.Single] ) method: Single op_Explicit(System.Nullable`1[System.Single]) in System.Nullable`1[System.Single] type: System.Single ) method: System.String ToString(Single) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Nullable`1[System.Single],System.String] ) type: System.String ) Parameter( y type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.Nullable`1[System.Single],System.String,System.String] ) -=-=-=-=-=-=-=-=- Single? + String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Single] ) Parameter( y type: System.String ) body { Convert( Convert( Add( Convert( Parameter( x type: System.Nullable`1[System.Single] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) Convert( Convert( Parameter( y type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) method: System.Nullable`1[System.Double] op_Implicit(Double) in System.Nullable`1[System.Double] type: System.Nullable`1[System.Double] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) method: Double op_Explicit(System.Nullable`1[System.Double]) in System.Nullable`1[System.Double] type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.Nullable`1[System.Single],System.String,System.String] ) -=-=-=-=-=-=-=-=- String & Single? => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.Nullable`1[System.Single] ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Parameter( x type: System.String ) Coalesce( Parameter( y type: System.Nullable`1[System.Single] ) Constant( null type: System.String ) conversion: Lambda( Parameter( CoalesceLHS type: System.Nullable`1[System.Single] ) body { Convert( Convert( Parameter( CoalesceLHS type: System.Nullable`1[System.Single] ) method: Single op_Explicit(System.Nullable`1[System.Single]) in System.Nullable`1[System.Single] type: System.Single ) method: System.String ToString(Single) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Nullable`1[System.Single],System.String] ) type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.String,System.Nullable`1[System.Single],System.String] ) -=-=-=-=-=-=-=-=- String + Single? => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.Nullable`1[System.Single] ) body { Convert( Convert( Add( Convert( Convert( Parameter( x type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) method: System.Nullable`1[System.Double] op_Implicit(Double) in System.Nullable`1[System.Double] type: System.Nullable`1[System.Double] ) Convert( Parameter( y type: System.Nullable`1[System.Single] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) method: Double op_Explicit(System.Nullable`1[System.Double]) in System.Nullable`1[System.Double] type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.String,System.Nullable`1[System.Single],System.String] ) -=-=-=-=-=-=-=-=- Double & String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Double ) Parameter( y type: System.String ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Convert( Parameter( x type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) Parameter( y type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.Double,System.String,System.String] ) -=-=-=-=-=-=-=-=- Double + String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Double ) Parameter( y type: System.String ) body { Convert( Add( Parameter( x type: System.Double ) Convert( Parameter( y type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.Double,System.String,System.String] ) -=-=-=-=-=-=-=-=- String & Double => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.Double ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Parameter( x type: System.String ) Convert( Parameter( y type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.String,System.Double,System.String] ) -=-=-=-=-=-=-=-=- String + Double => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.Double ) body { Convert( Add( Convert( Parameter( x type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) Parameter( y type: System.Double ) type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.String,System.Double,System.String] ) -=-=-=-=-=-=-=-=- Double? & String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Double] ) Parameter( y type: System.String ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Coalesce( Parameter( x type: System.Nullable`1[System.Double] ) Constant( null type: System.String ) conversion: Lambda( Parameter( CoalesceLHS type: System.Nullable`1[System.Double] ) body { Convert( Convert( Parameter( CoalesceLHS type: System.Nullable`1[System.Double] ) method: Double op_Explicit(System.Nullable`1[System.Double]) in System.Nullable`1[System.Double] type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Nullable`1[System.Double],System.String] ) type: System.String ) Parameter( y type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.Nullable`1[System.Double],System.String,System.String] ) -=-=-=-=-=-=-=-=- Double? + String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Double] ) Parameter( y type: System.String ) body { Convert( Convert( Add( Parameter( x type: System.Nullable`1[System.Double] ) Convert( Convert( Parameter( y type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) method: System.Nullable`1[System.Double] op_Implicit(Double) in System.Nullable`1[System.Double] type: System.Nullable`1[System.Double] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) method: Double op_Explicit(System.Nullable`1[System.Double]) in System.Nullable`1[System.Double] type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.Nullable`1[System.Double],System.String,System.String] ) -=-=-=-=-=-=-=-=- String & Double? => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.Nullable`1[System.Double] ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Parameter( x type: System.String ) Coalesce( Parameter( y type: System.Nullable`1[System.Double] ) Constant( null type: System.String ) conversion: Lambda( Parameter( CoalesceLHS type: System.Nullable`1[System.Double] ) body { Convert( Convert( Parameter( CoalesceLHS type: System.Nullable`1[System.Double] ) method: Double op_Explicit(System.Nullable`1[System.Double]) in System.Nullable`1[System.Double] type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Nullable`1[System.Double],System.String] ) type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.String,System.Nullable`1[System.Double],System.String] ) -=-=-=-=-=-=-=-=- String + Double? => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.Nullable`1[System.Double] ) body { Convert( Convert( Add( Convert( Convert( Parameter( x type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) method: System.Nullable`1[System.Double] op_Implicit(Double) in System.Nullable`1[System.Double] type: System.Nullable`1[System.Double] ) Parameter( y type: System.Nullable`1[System.Double] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) method: Double op_Explicit(System.Nullable`1[System.Double]) in System.Nullable`1[System.Double] type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.String,System.Nullable`1[System.Double],System.String] ) -=-=-=-=-=-=-=-=- Decimal & String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Decimal ) Parameter( y type: System.String ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Convert( Parameter( x type: System.Decimal ) method: System.String ToString(System.Decimal) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) Parameter( y type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.Decimal,System.String,System.String] ) -=-=-=-=-=-=-=-=- Decimal + String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Decimal ) Parameter( y type: System.String ) body { Convert( Add( Convert( Parameter( x type: System.Decimal ) method: Double op_Explicit(System.Decimal) in System.Decimal type: System.Double ) Convert( Parameter( y type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.Decimal,System.String,System.String] ) -=-=-=-=-=-=-=-=- String & Decimal => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.Decimal ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Parameter( x type: System.String ) Convert( Parameter( y type: System.Decimal ) method: System.String ToString(System.Decimal) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.String,System.Decimal,System.String] ) -=-=-=-=-=-=-=-=- String + Decimal => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.Decimal ) body { Convert( Add( Convert( Parameter( x type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) Convert( Parameter( y type: System.Decimal ) method: Double op_Explicit(System.Decimal) in System.Decimal type: System.Double ) type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.String,System.Decimal,System.String] ) -=-=-=-=-=-=-=-=- Decimal? & String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Decimal] ) Parameter( y type: System.String ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Coalesce( Parameter( x type: System.Nullable`1[System.Decimal] ) Constant( null type: System.String ) conversion: Lambda( Parameter( CoalesceLHS type: System.Nullable`1[System.Decimal] ) body { Convert( Convert( Parameter( CoalesceLHS type: System.Nullable`1[System.Decimal] ) method: System.Decimal op_Explicit(System.Nullable`1[System.Decimal]) in System.Nullable`1[System.Decimal] type: System.Decimal ) method: System.String ToString(System.Decimal) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Nullable`1[System.Decimal],System.String] ) type: System.String ) Parameter( y type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.Nullable`1[System.Decimal],System.String,System.String] ) -=-=-=-=-=-=-=-=- Decimal? + String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Decimal] ) Parameter( y type: System.String ) body { Convert( Convert( Add( Convert( Parameter( x type: System.Nullable`1[System.Decimal] ) Lifted LiftedToNull method: Double op_Explicit(System.Decimal) in System.Decimal type: System.Nullable`1[System.Double] ) Convert( Convert( Parameter( y type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) method: System.Nullable`1[System.Double] op_Implicit(Double) in System.Nullable`1[System.Double] type: System.Nullable`1[System.Double] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) method: Double op_Explicit(System.Nullable`1[System.Double]) in System.Nullable`1[System.Double] type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.Nullable`1[System.Decimal],System.String,System.String] ) -=-=-=-=-=-=-=-=- String & Decimal? => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.Nullable`1[System.Decimal] ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Parameter( x type: System.String ) Coalesce( Parameter( y type: System.Nullable`1[System.Decimal] ) Constant( null type: System.String ) conversion: Lambda( Parameter( CoalesceLHS type: System.Nullable`1[System.Decimal] ) body { Convert( Convert( Parameter( CoalesceLHS type: System.Nullable`1[System.Decimal] ) method: System.Decimal op_Explicit(System.Nullable`1[System.Decimal]) in System.Nullable`1[System.Decimal] type: System.Decimal ) method: System.String ToString(System.Decimal) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Nullable`1[System.Decimal],System.String] ) type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.String,System.Nullable`1[System.Decimal],System.String] ) -=-=-=-=-=-=-=-=- String + Decimal? => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.Nullable`1[System.Decimal] ) body { Convert( Convert( Add( Convert( Convert( Parameter( x type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) method: System.Nullable`1[System.Double] op_Implicit(Double) in System.Nullable`1[System.Double] type: System.Nullable`1[System.Double] ) Convert( Parameter( y type: System.Nullable`1[System.Decimal] ) Lifted LiftedToNull method: Double op_Explicit(System.Decimal) in System.Decimal type: System.Nullable`1[System.Double] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) method: Double op_Explicit(System.Nullable`1[System.Double]) in System.Nullable`1[System.Double] type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.String,System.Nullable`1[System.Decimal],System.String] ) -=-=-=-=-=-=-=-=- Date & String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.DateTime ) Parameter( y type: System.String ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Convert( Parameter( x type: System.DateTime ) method: System.String ToString(System.DateTime) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) Parameter( y type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.DateTime,System.String,System.String] ) -=-=-=-=-=-=-=-=- Date + String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.DateTime ) Parameter( y type: System.String ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Convert( Parameter( x type: System.DateTime ) method: System.String ToString(System.DateTime) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) Parameter( y type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.DateTime,System.String,System.String] ) -=-=-=-=-=-=-=-=- String & Date => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.DateTime ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Parameter( x type: System.String ) Convert( Parameter( y type: System.DateTime ) method: System.String ToString(System.DateTime) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.String,System.DateTime,System.String] ) -=-=-=-=-=-=-=-=- String + Date => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.DateTime ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Parameter( x type: System.String ) Convert( Parameter( y type: System.DateTime ) method: System.String ToString(System.DateTime) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.String,System.DateTime,System.String] ) -=-=-=-=-=-=-=-=- Date? & String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.DateTime] ) Parameter( y type: System.String ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Coalesce( Parameter( x type: System.Nullable`1[System.DateTime] ) Constant( null type: System.String ) conversion: Lambda( Parameter( CoalesceLHS type: System.Nullable`1[System.DateTime] ) body { Convert( Convert( Parameter( CoalesceLHS type: System.Nullable`1[System.DateTime] ) method: System.DateTime op_Explicit(System.Nullable`1[System.DateTime]) in System.Nullable`1[System.DateTime] type: System.DateTime ) method: System.String ToString(System.DateTime) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Nullable`1[System.DateTime],System.String] ) type: System.String ) Parameter( y type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.Nullable`1[System.DateTime],System.String,System.String] ) -=-=-=-=-=-=-=-=- Date? + String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.DateTime] ) Parameter( y type: System.String ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Convert( Convert( Parameter( x type: System.Nullable`1[System.DateTime] ) method: System.DateTime op_Explicit(System.Nullable`1[System.DateTime]) in System.Nullable`1[System.DateTime] type: System.DateTime ) method: System.String ToString(System.DateTime) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) Parameter( y type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.Nullable`1[System.DateTime],System.String,System.String] ) -=-=-=-=-=-=-=-=- String & Date? => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.Nullable`1[System.DateTime] ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Parameter( x type: System.String ) Coalesce( Parameter( y type: System.Nullable`1[System.DateTime] ) Constant( null type: System.String ) conversion: Lambda( Parameter( CoalesceLHS type: System.Nullable`1[System.DateTime] ) body { Convert( Convert( Parameter( CoalesceLHS type: System.Nullable`1[System.DateTime] ) method: System.DateTime op_Explicit(System.Nullable`1[System.DateTime]) in System.Nullable`1[System.DateTime] type: System.DateTime ) method: System.String ToString(System.DateTime) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Nullable`1[System.DateTime],System.String] ) type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.String,System.Nullable`1[System.DateTime],System.String] ) -=-=-=-=-=-=-=-=- String + Date? => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.Nullable`1[System.DateTime] ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Parameter( x type: System.String ) Convert( Convert( Parameter( y type: System.Nullable`1[System.DateTime] ) method: System.DateTime op_Explicit(System.Nullable`1[System.DateTime]) in System.Nullable`1[System.DateTime] type: System.DateTime ) method: System.String ToString(System.DateTime) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.String,System.Nullable`1[System.DateTime],System.String] ) -=-=-=-=-=-=-=-=- String & String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.String ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Parameter( x type: System.String ) Parameter( y type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.String,System.String,System.String] ) -=-=-=-=-=-=-=-=- String + String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.String ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Parameter( x type: System.String ) Parameter( y type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.String,System.String,System.String] ) -=-=-=-=-=-=-=-=- String & String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.String ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Parameter( x type: System.String ) Parameter( y type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.String,System.String,System.String] ) -=-=-=-=-=-=-=-=- String + String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.String ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Parameter( x type: System.String ) Parameter( y type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.String,System.String,System.String] ) -=-=-=-=-=-=-=-=- Object & String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) Parameter( y type: System.String ) body { Convert( Call( <NULL> method: System.Object ConcatenateObject(System.Object, System.Object) in Microsoft.VisualBasic.CompilerServices.Operators ( Parameter( x type: System.Object ) Convert( Parameter( y type: System.String ) type: System.Object ) ) type: System.Object ) method: System.String ToString(System.Object) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.Object,System.String,System.String] ) -=-=-=-=-=-=-=-=- Object + String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) Parameter( y type: System.String ) body { Convert( Add( Parameter( x type: System.Object ) Convert( Parameter( y type: System.String ) type: System.Object ) method: System.Object AddObject(System.Object, System.Object) in Microsoft.VisualBasic.CompilerServices.Operators type: System.Object ) method: System.String ToString(System.Object) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.Object,System.String,System.String] ) -=-=-=-=-=-=-=-=- String & Object => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.Object ) body { Convert( Call( <NULL> method: System.Object ConcatenateObject(System.Object, System.Object) in Microsoft.VisualBasic.CompilerServices.Operators ( Convert( Parameter( x type: System.String ) type: System.Object ) Parameter( y type: System.Object ) ) type: System.Object ) method: System.String ToString(System.Object) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.String,System.Object,System.String] ) -=-=-=-=-=-=-=-=- String + Object => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.Object ) body { Convert( Add( Convert( Parameter( x type: System.String ) type: System.Object ) Parameter( y type: System.Object ) method: System.Object AddObject(System.Object, System.Object) in Microsoft.VisualBasic.CompilerServices.Operators type: System.Object ) method: System.String ToString(System.Object) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.String,System.Object,System.String] ) -=-=-=-=-=-=-=-=- Object & Object => Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) Parameter( y type: System.Object ) body { Call( <NULL> method: System.Object ConcatenateObject(System.Object, System.Object) in Microsoft.VisualBasic.CompilerServices.Operators ( Parameter( x type: System.Object ) Parameter( y type: System.Object ) ) type: System.Object ) } return type: System.Object type: System.Func`3[System.Object,System.Object,System.Object] )
-=-=-=-=-=-=-=-=- SByte & String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.SByte ) Parameter( y type: System.String ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Convert( ConvertChecked( Parameter( x type: System.SByte ) type: System.Int32 ) method: System.String ToString(Int32) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) Parameter( y type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.SByte,System.String,System.String] ) -=-=-=-=-=-=-=-=- SByte + String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.SByte ) Parameter( y type: System.String ) body { Convert( Add( Convert( Parameter( x type: System.SByte ) type: System.Double ) Convert( Parameter( y type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.SByte,System.String,System.String] ) -=-=-=-=-=-=-=-=- String & SByte => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.SByte ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Parameter( x type: System.String ) Convert( ConvertChecked( Parameter( y type: System.SByte ) type: System.Int32 ) method: System.String ToString(Int32) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.String,System.SByte,System.String] ) -=-=-=-=-=-=-=-=- String + SByte => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.SByte ) body { Convert( Add( Convert( Parameter( x type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) Convert( Parameter( y type: System.SByte ) type: System.Double ) type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.String,System.SByte,System.String] ) -=-=-=-=-=-=-=-=- SByte? & String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.SByte] ) Parameter( y type: System.String ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Coalesce( Parameter( x type: System.Nullable`1[System.SByte] ) Constant( null type: System.String ) conversion: Lambda( Parameter( CoalesceLHS type: System.Nullable`1[System.SByte] ) body { Convert( ConvertChecked( ConvertChecked( Parameter( CoalesceLHS type: System.Nullable`1[System.SByte] ) method: SByte op_Explicit(System.Nullable`1[System.SByte]) in System.Nullable`1[System.SByte] type: System.SByte ) type: System.Int32 ) method: System.String ToString(Int32) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Nullable`1[System.SByte],System.String] ) type: System.String ) Parameter( y type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.Nullable`1[System.SByte],System.String,System.String] ) -=-=-=-=-=-=-=-=- SByte? + String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.SByte] ) Parameter( y type: System.String ) body { Convert( Convert( Add( Convert( Parameter( x type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) Convert( Convert( Parameter( y type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) method: System.Nullable`1[System.Double] op_Implicit(Double) in System.Nullable`1[System.Double] type: System.Nullable`1[System.Double] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) method: Double op_Explicit(System.Nullable`1[System.Double]) in System.Nullable`1[System.Double] type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.Nullable`1[System.SByte],System.String,System.String] ) -=-=-=-=-=-=-=-=- String & SByte? => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.Nullable`1[System.SByte] ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Parameter( x type: System.String ) Coalesce( Parameter( y type: System.Nullable`1[System.SByte] ) Constant( null type: System.String ) conversion: Lambda( Parameter( CoalesceLHS type: System.Nullable`1[System.SByte] ) body { Convert( ConvertChecked( ConvertChecked( Parameter( CoalesceLHS type: System.Nullable`1[System.SByte] ) method: SByte op_Explicit(System.Nullable`1[System.SByte]) in System.Nullable`1[System.SByte] type: System.SByte ) type: System.Int32 ) method: System.String ToString(Int32) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Nullable`1[System.SByte],System.String] ) type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.String,System.Nullable`1[System.SByte],System.String] ) -=-=-=-=-=-=-=-=- String + SByte? => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.Nullable`1[System.SByte] ) body { Convert( Convert( Add( Convert( Convert( Parameter( x type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) method: System.Nullable`1[System.Double] op_Implicit(Double) in System.Nullable`1[System.Double] type: System.Nullable`1[System.Double] ) Convert( Parameter( y type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) method: Double op_Explicit(System.Nullable`1[System.Double]) in System.Nullable`1[System.Double] type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.String,System.Nullable`1[System.SByte],System.String] ) -=-=-=-=-=-=-=-=- E_SByte & String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_SByte ) Parameter( y type: System.String ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Convert( ConvertChecked( Parameter( x type: E_SByte ) type: System.Int32 ) method: System.String ToString(Int32) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) Parameter( y type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[E_SByte,System.String,System.String] ) -=-=-=-=-=-=-=-=- E_SByte + String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_SByte ) Parameter( y type: System.String ) body { Convert( Add( Convert( Parameter( x type: E_SByte ) type: System.Double ) Convert( Parameter( y type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[E_SByte,System.String,System.String] ) -=-=-=-=-=-=-=-=- String & E_SByte => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: E_SByte ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Parameter( x type: System.String ) Convert( ConvertChecked( Parameter( y type: E_SByte ) type: System.Int32 ) method: System.String ToString(Int32) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.String,E_SByte,System.String] ) -=-=-=-=-=-=-=-=- String + E_SByte => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: E_SByte ) body { Convert( Add( Convert( Parameter( x type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) Convert( Parameter( y type: E_SByte ) type: System.Double ) type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.String,E_SByte,System.String] ) -=-=-=-=-=-=-=-=- E_SByte? & String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_SByte] ) Parameter( y type: System.String ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Coalesce( Parameter( x type: System.Nullable`1[E_SByte] ) Constant( null type: System.String ) conversion: Lambda( Parameter( CoalesceLHS type: System.Nullable`1[E_SByte] ) body { Convert( ConvertChecked( ConvertChecked( Parameter( CoalesceLHS type: System.Nullable`1[E_SByte] ) method: E_SByte op_Explicit(System.Nullable`1[E_SByte]) in System.Nullable`1[E_SByte] type: E_SByte ) type: System.Int32 ) method: System.String ToString(Int32) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Nullable`1[E_SByte],System.String] ) type: System.String ) Parameter( y type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.Nullable`1[E_SByte],System.String,System.String] ) -=-=-=-=-=-=-=-=- E_SByte? + String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_SByte] ) Parameter( y type: System.String ) body { Convert( Convert( Add( Convert( Parameter( x type: System.Nullable`1[E_SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) Convert( Convert( Parameter( y type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) method: System.Nullable`1[System.Double] op_Implicit(Double) in System.Nullable`1[System.Double] type: System.Nullable`1[System.Double] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) method: Double op_Explicit(System.Nullable`1[System.Double]) in System.Nullable`1[System.Double] type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.Nullable`1[E_SByte],System.String,System.String] ) -=-=-=-=-=-=-=-=- String & E_SByte? => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.Nullable`1[E_SByte] ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Parameter( x type: System.String ) Coalesce( Parameter( y type: System.Nullable`1[E_SByte] ) Constant( null type: System.String ) conversion: Lambda( Parameter( CoalesceLHS type: System.Nullable`1[E_SByte] ) body { Convert( ConvertChecked( ConvertChecked( Parameter( CoalesceLHS type: System.Nullable`1[E_SByte] ) method: E_SByte op_Explicit(System.Nullable`1[E_SByte]) in System.Nullable`1[E_SByte] type: E_SByte ) type: System.Int32 ) method: System.String ToString(Int32) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Nullable`1[E_SByte],System.String] ) type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.String,System.Nullable`1[E_SByte],System.String] ) -=-=-=-=-=-=-=-=- String + E_SByte? => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.Nullable`1[E_SByte] ) body { Convert( Convert( Add( Convert( Convert( Parameter( x type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) method: System.Nullable`1[System.Double] op_Implicit(Double) in System.Nullable`1[System.Double] type: System.Nullable`1[System.Double] ) Convert( Parameter( y type: System.Nullable`1[E_SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) method: Double op_Explicit(System.Nullable`1[System.Double]) in System.Nullable`1[System.Double] type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.String,System.Nullable`1[E_SByte],System.String] ) -=-=-=-=-=-=-=-=- Byte & String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Byte ) Parameter( y type: System.String ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Convert( Parameter( x type: System.Byte ) method: System.String ToString(Byte) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) Parameter( y type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.Byte,System.String,System.String] ) -=-=-=-=-=-=-=-=- Byte + String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Byte ) Parameter( y type: System.String ) body { Convert( Add( Convert( Parameter( x type: System.Byte ) type: System.Double ) Convert( Parameter( y type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.Byte,System.String,System.String] ) -=-=-=-=-=-=-=-=- String & Byte => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.Byte ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Parameter( x type: System.String ) Convert( Parameter( y type: System.Byte ) method: System.String ToString(Byte) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.String,System.Byte,System.String] ) -=-=-=-=-=-=-=-=- String + Byte => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.Byte ) body { Convert( Add( Convert( Parameter( x type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) Convert( Parameter( y type: System.Byte ) type: System.Double ) type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.String,System.Byte,System.String] ) -=-=-=-=-=-=-=-=- Byte? & String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Byte] ) Parameter( y type: System.String ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Coalesce( Parameter( x type: System.Nullable`1[System.Byte] ) Constant( null type: System.String ) conversion: Lambda( Parameter( CoalesceLHS type: System.Nullable`1[System.Byte] ) body { Convert( ConvertChecked( Parameter( CoalesceLHS type: System.Nullable`1[System.Byte] ) method: Byte op_Explicit(System.Nullable`1[System.Byte]) in System.Nullable`1[System.Byte] type: System.Byte ) method: System.String ToString(Byte) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Nullable`1[System.Byte],System.String] ) type: System.String ) Parameter( y type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.Nullable`1[System.Byte],System.String,System.String] ) -=-=-=-=-=-=-=-=- Byte? + String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Byte] ) Parameter( y type: System.String ) body { Convert( Convert( Add( Convert( Parameter( x type: System.Nullable`1[System.Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) Convert( Convert( Parameter( y type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) method: System.Nullable`1[System.Double] op_Implicit(Double) in System.Nullable`1[System.Double] type: System.Nullable`1[System.Double] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) method: Double op_Explicit(System.Nullable`1[System.Double]) in System.Nullable`1[System.Double] type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.Nullable`1[System.Byte],System.String,System.String] ) -=-=-=-=-=-=-=-=- String & Byte? => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.Nullable`1[System.Byte] ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Parameter( x type: System.String ) Coalesce( Parameter( y type: System.Nullable`1[System.Byte] ) Constant( null type: System.String ) conversion: Lambda( Parameter( CoalesceLHS type: System.Nullable`1[System.Byte] ) body { Convert( ConvertChecked( Parameter( CoalesceLHS type: System.Nullable`1[System.Byte] ) method: Byte op_Explicit(System.Nullable`1[System.Byte]) in System.Nullable`1[System.Byte] type: System.Byte ) method: System.String ToString(Byte) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Nullable`1[System.Byte],System.String] ) type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.String,System.Nullable`1[System.Byte],System.String] ) -=-=-=-=-=-=-=-=- String + Byte? => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.Nullable`1[System.Byte] ) body { Convert( Convert( Add( Convert( Convert( Parameter( x type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) method: System.Nullable`1[System.Double] op_Implicit(Double) in System.Nullable`1[System.Double] type: System.Nullable`1[System.Double] ) Convert( Parameter( y type: System.Nullable`1[System.Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) method: Double op_Explicit(System.Nullable`1[System.Double]) in System.Nullable`1[System.Double] type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.String,System.Nullable`1[System.Byte],System.String] ) -=-=-=-=-=-=-=-=- E_Byte & String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Byte ) Parameter( y type: System.String ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Convert( ConvertChecked( Parameter( x type: E_Byte ) type: System.Byte ) method: System.String ToString(Byte) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) Parameter( y type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[E_Byte,System.String,System.String] ) -=-=-=-=-=-=-=-=- E_Byte + String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Byte ) Parameter( y type: System.String ) body { Convert( Add( Convert( Parameter( x type: E_Byte ) type: System.Double ) Convert( Parameter( y type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[E_Byte,System.String,System.String] ) -=-=-=-=-=-=-=-=- String & E_Byte => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: E_Byte ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Parameter( x type: System.String ) Convert( ConvertChecked( Parameter( y type: E_Byte ) type: System.Byte ) method: System.String ToString(Byte) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.String,E_Byte,System.String] ) -=-=-=-=-=-=-=-=- String + E_Byte => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: E_Byte ) body { Convert( Add( Convert( Parameter( x type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) Convert( Parameter( y type: E_Byte ) type: System.Double ) type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.String,E_Byte,System.String] ) -=-=-=-=-=-=-=-=- E_Byte? & String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Byte] ) Parameter( y type: System.String ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Coalesce( Parameter( x type: System.Nullable`1[E_Byte] ) Constant( null type: System.String ) conversion: Lambda( Parameter( CoalesceLHS type: System.Nullable`1[E_Byte] ) body { Convert( ConvertChecked( ConvertChecked( Parameter( CoalesceLHS type: System.Nullable`1[E_Byte] ) method: E_Byte op_Explicit(System.Nullable`1[E_Byte]) in System.Nullable`1[E_Byte] type: E_Byte ) type: System.Byte ) method: System.String ToString(Byte) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Nullable`1[E_Byte],System.String] ) type: System.String ) Parameter( y type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.Nullable`1[E_Byte],System.String,System.String] ) -=-=-=-=-=-=-=-=- E_Byte? + String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Byte] ) Parameter( y type: System.String ) body { Convert( Convert( Add( Convert( Parameter( x type: System.Nullable`1[E_Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) Convert( Convert( Parameter( y type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) method: System.Nullable`1[System.Double] op_Implicit(Double) in System.Nullable`1[System.Double] type: System.Nullable`1[System.Double] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) method: Double op_Explicit(System.Nullable`1[System.Double]) in System.Nullable`1[System.Double] type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.Nullable`1[E_Byte],System.String,System.String] ) -=-=-=-=-=-=-=-=- String & E_Byte? => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.Nullable`1[E_Byte] ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Parameter( x type: System.String ) Coalesce( Parameter( y type: System.Nullable`1[E_Byte] ) Constant( null type: System.String ) conversion: Lambda( Parameter( CoalesceLHS type: System.Nullable`1[E_Byte] ) body { Convert( ConvertChecked( ConvertChecked( Parameter( CoalesceLHS type: System.Nullable`1[E_Byte] ) method: E_Byte op_Explicit(System.Nullable`1[E_Byte]) in System.Nullable`1[E_Byte] type: E_Byte ) type: System.Byte ) method: System.String ToString(Byte) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Nullable`1[E_Byte],System.String] ) type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.String,System.Nullable`1[E_Byte],System.String] ) -=-=-=-=-=-=-=-=- String + E_Byte? => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.Nullable`1[E_Byte] ) body { Convert( Convert( Add( Convert( Convert( Parameter( x type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) method: System.Nullable`1[System.Double] op_Implicit(Double) in System.Nullable`1[System.Double] type: System.Nullable`1[System.Double] ) Convert( Parameter( y type: System.Nullable`1[E_Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) method: Double op_Explicit(System.Nullable`1[System.Double]) in System.Nullable`1[System.Double] type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.String,System.Nullable`1[E_Byte],System.String] ) -=-=-=-=-=-=-=-=- Short & String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int16 ) Parameter( y type: System.String ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Convert( ConvertChecked( Parameter( x type: System.Int16 ) type: System.Int32 ) method: System.String ToString(Int32) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) Parameter( y type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.Int16,System.String,System.String] ) -=-=-=-=-=-=-=-=- Short + String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int16 ) Parameter( y type: System.String ) body { Convert( Add( Convert( Parameter( x type: System.Int16 ) type: System.Double ) Convert( Parameter( y type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.Int16,System.String,System.String] ) -=-=-=-=-=-=-=-=- String & Short => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.Int16 ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Parameter( x type: System.String ) Convert( ConvertChecked( Parameter( y type: System.Int16 ) type: System.Int32 ) method: System.String ToString(Int32) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.String,System.Int16,System.String] ) -=-=-=-=-=-=-=-=- String + Short => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.Int16 ) body { Convert( Add( Convert( Parameter( x type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) Convert( Parameter( y type: System.Int16 ) type: System.Double ) type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.String,System.Int16,System.String] ) -=-=-=-=-=-=-=-=- Short? & String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int16] ) Parameter( y type: System.String ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Coalesce( Parameter( x type: System.Nullable`1[System.Int16] ) Constant( null type: System.String ) conversion: Lambda( Parameter( CoalesceLHS type: System.Nullable`1[System.Int16] ) body { Convert( ConvertChecked( ConvertChecked( Parameter( CoalesceLHS type: System.Nullable`1[System.Int16] ) method: Int16 op_Explicit(System.Nullable`1[System.Int16]) in System.Nullable`1[System.Int16] type: System.Int16 ) type: System.Int32 ) method: System.String ToString(Int32) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Nullable`1[System.Int16],System.String] ) type: System.String ) Parameter( y type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.Nullable`1[System.Int16],System.String,System.String] ) -=-=-=-=-=-=-=-=- Short? + String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int16] ) Parameter( y type: System.String ) body { Convert( Convert( Add( Convert( Parameter( x type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) Convert( Convert( Parameter( y type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) method: System.Nullable`1[System.Double] op_Implicit(Double) in System.Nullable`1[System.Double] type: System.Nullable`1[System.Double] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) method: Double op_Explicit(System.Nullable`1[System.Double]) in System.Nullable`1[System.Double] type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.Nullable`1[System.Int16],System.String,System.String] ) -=-=-=-=-=-=-=-=- String & Short? => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.Nullable`1[System.Int16] ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Parameter( x type: System.String ) Coalesce( Parameter( y type: System.Nullable`1[System.Int16] ) Constant( null type: System.String ) conversion: Lambda( Parameter( CoalesceLHS type: System.Nullable`1[System.Int16] ) body { Convert( ConvertChecked( ConvertChecked( Parameter( CoalesceLHS type: System.Nullable`1[System.Int16] ) method: Int16 op_Explicit(System.Nullable`1[System.Int16]) in System.Nullable`1[System.Int16] type: System.Int16 ) type: System.Int32 ) method: System.String ToString(Int32) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Nullable`1[System.Int16],System.String] ) type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.String,System.Nullable`1[System.Int16],System.String] ) -=-=-=-=-=-=-=-=- String + Short? => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.Nullable`1[System.Int16] ) body { Convert( Convert( Add( Convert( Convert( Parameter( x type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) method: System.Nullable`1[System.Double] op_Implicit(Double) in System.Nullable`1[System.Double] type: System.Nullable`1[System.Double] ) Convert( Parameter( y type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) method: Double op_Explicit(System.Nullable`1[System.Double]) in System.Nullable`1[System.Double] type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.String,System.Nullable`1[System.Int16],System.String] ) -=-=-=-=-=-=-=-=- E_Short & String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Short ) Parameter( y type: System.String ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Convert( ConvertChecked( Parameter( x type: E_Short ) type: System.Int32 ) method: System.String ToString(Int32) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) Parameter( y type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[E_Short,System.String,System.String] ) -=-=-=-=-=-=-=-=- E_Short + String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Short ) Parameter( y type: System.String ) body { Convert( Add( Convert( Parameter( x type: E_Short ) type: System.Double ) Convert( Parameter( y type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[E_Short,System.String,System.String] ) -=-=-=-=-=-=-=-=- String & E_Short => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: E_Short ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Parameter( x type: System.String ) Convert( ConvertChecked( Parameter( y type: E_Short ) type: System.Int32 ) method: System.String ToString(Int32) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.String,E_Short,System.String] ) -=-=-=-=-=-=-=-=- String + E_Short => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: E_Short ) body { Convert( Add( Convert( Parameter( x type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) Convert( Parameter( y type: E_Short ) type: System.Double ) type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.String,E_Short,System.String] ) -=-=-=-=-=-=-=-=- E_Short? & String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Short] ) Parameter( y type: System.String ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Coalesce( Parameter( x type: System.Nullable`1[E_Short] ) Constant( null type: System.String ) conversion: Lambda( Parameter( CoalesceLHS type: System.Nullable`1[E_Short] ) body { Convert( ConvertChecked( ConvertChecked( Parameter( CoalesceLHS type: System.Nullable`1[E_Short] ) method: E_Short op_Explicit(System.Nullable`1[E_Short]) in System.Nullable`1[E_Short] type: E_Short ) type: System.Int32 ) method: System.String ToString(Int32) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Nullable`1[E_Short],System.String] ) type: System.String ) Parameter( y type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.Nullable`1[E_Short],System.String,System.String] ) -=-=-=-=-=-=-=-=- E_Short? + String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Short] ) Parameter( y type: System.String ) body { Convert( Convert( Add( Convert( Parameter( x type: System.Nullable`1[E_Short] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) Convert( Convert( Parameter( y type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) method: System.Nullable`1[System.Double] op_Implicit(Double) in System.Nullable`1[System.Double] type: System.Nullable`1[System.Double] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) method: Double op_Explicit(System.Nullable`1[System.Double]) in System.Nullable`1[System.Double] type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.Nullable`1[E_Short],System.String,System.String] ) -=-=-=-=-=-=-=-=- String & E_Short? => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.Nullable`1[E_Short] ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Parameter( x type: System.String ) Coalesce( Parameter( y type: System.Nullable`1[E_Short] ) Constant( null type: System.String ) conversion: Lambda( Parameter( CoalesceLHS type: System.Nullable`1[E_Short] ) body { Convert( ConvertChecked( ConvertChecked( Parameter( CoalesceLHS type: System.Nullable`1[E_Short] ) method: E_Short op_Explicit(System.Nullable`1[E_Short]) in System.Nullable`1[E_Short] type: E_Short ) type: System.Int32 ) method: System.String ToString(Int32) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Nullable`1[E_Short],System.String] ) type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.String,System.Nullable`1[E_Short],System.String] ) -=-=-=-=-=-=-=-=- String + E_Short? => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.Nullable`1[E_Short] ) body { Convert( Convert( Add( Convert( Convert( Parameter( x type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) method: System.Nullable`1[System.Double] op_Implicit(Double) in System.Nullable`1[System.Double] type: System.Nullable`1[System.Double] ) Convert( Parameter( y type: System.Nullable`1[E_Short] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) method: Double op_Explicit(System.Nullable`1[System.Double]) in System.Nullable`1[System.Double] type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.String,System.Nullable`1[E_Short],System.String] ) -=-=-=-=-=-=-=-=- UShort & String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt16 ) Parameter( y type: System.String ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Convert( ConvertChecked( Parameter( x type: System.UInt16 ) type: System.UInt32 ) method: System.String ToString(UInt32) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) Parameter( y type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.UInt16,System.String,System.String] ) -=-=-=-=-=-=-=-=- UShort + String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt16 ) Parameter( y type: System.String ) body { Convert( Add( Convert( Parameter( x type: System.UInt16 ) type: System.Double ) Convert( Parameter( y type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.UInt16,System.String,System.String] ) -=-=-=-=-=-=-=-=- String & UShort => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.UInt16 ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Parameter( x type: System.String ) Convert( ConvertChecked( Parameter( y type: System.UInt16 ) type: System.UInt32 ) method: System.String ToString(UInt32) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.String,System.UInt16,System.String] ) -=-=-=-=-=-=-=-=- String + UShort => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.UInt16 ) body { Convert( Add( Convert( Parameter( x type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) Convert( Parameter( y type: System.UInt16 ) type: System.Double ) type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.String,System.UInt16,System.String] ) -=-=-=-=-=-=-=-=- UShort? & String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt16] ) Parameter( y type: System.String ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Coalesce( Parameter( x type: System.Nullable`1[System.UInt16] ) Constant( null type: System.String ) conversion: Lambda( Parameter( CoalesceLHS type: System.Nullable`1[System.UInt16] ) body { Convert( ConvertChecked( ConvertChecked( Parameter( CoalesceLHS type: System.Nullable`1[System.UInt16] ) method: UInt16 op_Explicit(System.Nullable`1[System.UInt16]) in System.Nullable`1[System.UInt16] type: System.UInt16 ) type: System.UInt32 ) method: System.String ToString(UInt32) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Nullable`1[System.UInt16],System.String] ) type: System.String ) Parameter( y type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.Nullable`1[System.UInt16],System.String,System.String] ) -=-=-=-=-=-=-=-=- UShort? + String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt16] ) Parameter( y type: System.String ) body { Convert( Convert( Add( Convert( Parameter( x type: System.Nullable`1[System.UInt16] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) Convert( Convert( Parameter( y type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) method: System.Nullable`1[System.Double] op_Implicit(Double) in System.Nullable`1[System.Double] type: System.Nullable`1[System.Double] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) method: Double op_Explicit(System.Nullable`1[System.Double]) in System.Nullable`1[System.Double] type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.Nullable`1[System.UInt16],System.String,System.String] ) -=-=-=-=-=-=-=-=- String & UShort? => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.Nullable`1[System.UInt16] ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Parameter( x type: System.String ) Coalesce( Parameter( y type: System.Nullable`1[System.UInt16] ) Constant( null type: System.String ) conversion: Lambda( Parameter( CoalesceLHS type: System.Nullable`1[System.UInt16] ) body { Convert( ConvertChecked( ConvertChecked( Parameter( CoalesceLHS type: System.Nullable`1[System.UInt16] ) method: UInt16 op_Explicit(System.Nullable`1[System.UInt16]) in System.Nullable`1[System.UInt16] type: System.UInt16 ) type: System.UInt32 ) method: System.String ToString(UInt32) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Nullable`1[System.UInt16],System.String] ) type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.String,System.Nullable`1[System.UInt16],System.String] ) -=-=-=-=-=-=-=-=- String + UShort? => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.Nullable`1[System.UInt16] ) body { Convert( Convert( Add( Convert( Convert( Parameter( x type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) method: System.Nullable`1[System.Double] op_Implicit(Double) in System.Nullable`1[System.Double] type: System.Nullable`1[System.Double] ) Convert( Parameter( y type: System.Nullable`1[System.UInt16] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) method: Double op_Explicit(System.Nullable`1[System.Double]) in System.Nullable`1[System.Double] type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.String,System.Nullable`1[System.UInt16],System.String] ) -=-=-=-=-=-=-=-=- E_UShort & String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UShort ) Parameter( y type: System.String ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Convert( ConvertChecked( Parameter( x type: E_UShort ) type: System.UInt32 ) method: System.String ToString(UInt32) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) Parameter( y type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[E_UShort,System.String,System.String] ) -=-=-=-=-=-=-=-=- E_UShort + String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UShort ) Parameter( y type: System.String ) body { Convert( Add( Convert( Parameter( x type: E_UShort ) type: System.Double ) Convert( Parameter( y type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[E_UShort,System.String,System.String] ) -=-=-=-=-=-=-=-=- String & E_UShort => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: E_UShort ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Parameter( x type: System.String ) Convert( ConvertChecked( Parameter( y type: E_UShort ) type: System.UInt32 ) method: System.String ToString(UInt32) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.String,E_UShort,System.String] ) -=-=-=-=-=-=-=-=- String + E_UShort => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: E_UShort ) body { Convert( Add( Convert( Parameter( x type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) Convert( Parameter( y type: E_UShort ) type: System.Double ) type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.String,E_UShort,System.String] ) -=-=-=-=-=-=-=-=- E_UShort? & String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_UShort] ) Parameter( y type: System.String ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Coalesce( Parameter( x type: System.Nullable`1[E_UShort] ) Constant( null type: System.String ) conversion: Lambda( Parameter( CoalesceLHS type: System.Nullable`1[E_UShort] ) body { Convert( ConvertChecked( ConvertChecked( Parameter( CoalesceLHS type: System.Nullable`1[E_UShort] ) method: E_UShort op_Explicit(System.Nullable`1[E_UShort]) in System.Nullable`1[E_UShort] type: E_UShort ) type: System.UInt32 ) method: System.String ToString(UInt32) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Nullable`1[E_UShort],System.String] ) type: System.String ) Parameter( y type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.Nullable`1[E_UShort],System.String,System.String] ) -=-=-=-=-=-=-=-=- E_UShort? + String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_UShort] ) Parameter( y type: System.String ) body { Convert( Convert( Add( Convert( Parameter( x type: System.Nullable`1[E_UShort] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) Convert( Convert( Parameter( y type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) method: System.Nullable`1[System.Double] op_Implicit(Double) in System.Nullable`1[System.Double] type: System.Nullable`1[System.Double] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) method: Double op_Explicit(System.Nullable`1[System.Double]) in System.Nullable`1[System.Double] type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.Nullable`1[E_UShort],System.String,System.String] ) -=-=-=-=-=-=-=-=- String & E_UShort? => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.Nullable`1[E_UShort] ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Parameter( x type: System.String ) Coalesce( Parameter( y type: System.Nullable`1[E_UShort] ) Constant( null type: System.String ) conversion: Lambda( Parameter( CoalesceLHS type: System.Nullable`1[E_UShort] ) body { Convert( ConvertChecked( ConvertChecked( Parameter( CoalesceLHS type: System.Nullable`1[E_UShort] ) method: E_UShort op_Explicit(System.Nullable`1[E_UShort]) in System.Nullable`1[E_UShort] type: E_UShort ) type: System.UInt32 ) method: System.String ToString(UInt32) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Nullable`1[E_UShort],System.String] ) type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.String,System.Nullable`1[E_UShort],System.String] ) -=-=-=-=-=-=-=-=- String + E_UShort? => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.Nullable`1[E_UShort] ) body { Convert( Convert( Add( Convert( Convert( Parameter( x type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) method: System.Nullable`1[System.Double] op_Implicit(Double) in System.Nullable`1[System.Double] type: System.Nullable`1[System.Double] ) Convert( Parameter( y type: System.Nullable`1[E_UShort] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) method: Double op_Explicit(System.Nullable`1[System.Double]) in System.Nullable`1[System.Double] type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.String,System.Nullable`1[E_UShort],System.String] ) -=-=-=-=-=-=-=-=- Integer & String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int32 ) Parameter( y type: System.String ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Convert( Parameter( x type: System.Int32 ) method: System.String ToString(Int32) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) Parameter( y type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.Int32,System.String,System.String] ) -=-=-=-=-=-=-=-=- Integer + String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int32 ) Parameter( y type: System.String ) body { Convert( Add( Convert( Parameter( x type: System.Int32 ) type: System.Double ) Convert( Parameter( y type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.Int32,System.String,System.String] ) -=-=-=-=-=-=-=-=- String & Integer => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.Int32 ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Parameter( x type: System.String ) Convert( Parameter( y type: System.Int32 ) method: System.String ToString(Int32) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.String,System.Int32,System.String] ) -=-=-=-=-=-=-=-=- String + Integer => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.Int32 ) body { Convert( Add( Convert( Parameter( x type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) Convert( Parameter( y type: System.Int32 ) type: System.Double ) type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.String,System.Int32,System.String] ) -=-=-=-=-=-=-=-=- Integer? & String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int32] ) Parameter( y type: System.String ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Coalesce( Parameter( x type: System.Nullable`1[System.Int32] ) Constant( null type: System.String ) conversion: Lambda( Parameter( CoalesceLHS type: System.Nullable`1[System.Int32] ) body { Convert( ConvertChecked( Parameter( CoalesceLHS type: System.Nullable`1[System.Int32] ) method: Int32 op_Explicit(System.Nullable`1[System.Int32]) in System.Nullable`1[System.Int32] type: System.Int32 ) method: System.String ToString(Int32) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Nullable`1[System.Int32],System.String] ) type: System.String ) Parameter( y type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.Nullable`1[System.Int32],System.String,System.String] ) -=-=-=-=-=-=-=-=- Integer? + String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int32] ) Parameter( y type: System.String ) body { Convert( Convert( Add( Convert( Parameter( x type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) Convert( Convert( Parameter( y type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) method: System.Nullable`1[System.Double] op_Implicit(Double) in System.Nullable`1[System.Double] type: System.Nullable`1[System.Double] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) method: Double op_Explicit(System.Nullable`1[System.Double]) in System.Nullable`1[System.Double] type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.Nullable`1[System.Int32],System.String,System.String] ) -=-=-=-=-=-=-=-=- String & Integer? => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.Nullable`1[System.Int32] ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Parameter( x type: System.String ) Coalesce( Parameter( y type: System.Nullable`1[System.Int32] ) Constant( null type: System.String ) conversion: Lambda( Parameter( CoalesceLHS type: System.Nullable`1[System.Int32] ) body { Convert( ConvertChecked( Parameter( CoalesceLHS type: System.Nullable`1[System.Int32] ) method: Int32 op_Explicit(System.Nullable`1[System.Int32]) in System.Nullable`1[System.Int32] type: System.Int32 ) method: System.String ToString(Int32) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Nullable`1[System.Int32],System.String] ) type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.String,System.Nullable`1[System.Int32],System.String] ) -=-=-=-=-=-=-=-=- String + Integer? => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.Nullable`1[System.Int32] ) body { Convert( Convert( Add( Convert( Convert( Parameter( x type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) method: System.Nullable`1[System.Double] op_Implicit(Double) in System.Nullable`1[System.Double] type: System.Nullable`1[System.Double] ) Convert( Parameter( y type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) method: Double op_Explicit(System.Nullable`1[System.Double]) in System.Nullable`1[System.Double] type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.String,System.Nullable`1[System.Int32],System.String] ) -=-=-=-=-=-=-=-=- E_Integer & String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Integer ) Parameter( y type: System.String ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Convert( ConvertChecked( Parameter( x type: E_Integer ) type: System.Int32 ) method: System.String ToString(Int32) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) Parameter( y type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[E_Integer,System.String,System.String] ) -=-=-=-=-=-=-=-=- E_Integer + String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Integer ) Parameter( y type: System.String ) body { Convert( Add( Convert( Parameter( x type: E_Integer ) type: System.Double ) Convert( Parameter( y type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[E_Integer,System.String,System.String] ) -=-=-=-=-=-=-=-=- String & E_Integer => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: E_Integer ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Parameter( x type: System.String ) Convert( ConvertChecked( Parameter( y type: E_Integer ) type: System.Int32 ) method: System.String ToString(Int32) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.String,E_Integer,System.String] ) -=-=-=-=-=-=-=-=- String + E_Integer => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: E_Integer ) body { Convert( Add( Convert( Parameter( x type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) Convert( Parameter( y type: E_Integer ) type: System.Double ) type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.String,E_Integer,System.String] ) -=-=-=-=-=-=-=-=- E_Integer? & String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Integer] ) Parameter( y type: System.String ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Coalesce( Parameter( x type: System.Nullable`1[E_Integer] ) Constant( null type: System.String ) conversion: Lambda( Parameter( CoalesceLHS type: System.Nullable`1[E_Integer] ) body { Convert( ConvertChecked( ConvertChecked( Parameter( CoalesceLHS type: System.Nullable`1[E_Integer] ) method: E_Integer op_Explicit(System.Nullable`1[E_Integer]) in System.Nullable`1[E_Integer] type: E_Integer ) type: System.Int32 ) method: System.String ToString(Int32) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Nullable`1[E_Integer],System.String] ) type: System.String ) Parameter( y type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.Nullable`1[E_Integer],System.String,System.String] ) -=-=-=-=-=-=-=-=- E_Integer? + String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Integer] ) Parameter( y type: System.String ) body { Convert( Convert( Add( Convert( Parameter( x type: System.Nullable`1[E_Integer] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) Convert( Convert( Parameter( y type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) method: System.Nullable`1[System.Double] op_Implicit(Double) in System.Nullable`1[System.Double] type: System.Nullable`1[System.Double] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) method: Double op_Explicit(System.Nullable`1[System.Double]) in System.Nullable`1[System.Double] type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.Nullable`1[E_Integer],System.String,System.String] ) -=-=-=-=-=-=-=-=- String & E_Integer? => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.Nullable`1[E_Integer] ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Parameter( x type: System.String ) Coalesce( Parameter( y type: System.Nullable`1[E_Integer] ) Constant( null type: System.String ) conversion: Lambda( Parameter( CoalesceLHS type: System.Nullable`1[E_Integer] ) body { Convert( ConvertChecked( ConvertChecked( Parameter( CoalesceLHS type: System.Nullable`1[E_Integer] ) method: E_Integer op_Explicit(System.Nullable`1[E_Integer]) in System.Nullable`1[E_Integer] type: E_Integer ) type: System.Int32 ) method: System.String ToString(Int32) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Nullable`1[E_Integer],System.String] ) type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.String,System.Nullable`1[E_Integer],System.String] ) -=-=-=-=-=-=-=-=- String + E_Integer? => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.Nullable`1[E_Integer] ) body { Convert( Convert( Add( Convert( Convert( Parameter( x type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) method: System.Nullable`1[System.Double] op_Implicit(Double) in System.Nullable`1[System.Double] type: System.Nullable`1[System.Double] ) Convert( Parameter( y type: System.Nullable`1[E_Integer] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) method: Double op_Explicit(System.Nullable`1[System.Double]) in System.Nullable`1[System.Double] type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.String,System.Nullable`1[E_Integer],System.String] ) -=-=-=-=-=-=-=-=- UInteger & String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt32 ) Parameter( y type: System.String ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Convert( Parameter( x type: System.UInt32 ) method: System.String ToString(UInt32) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) Parameter( y type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.UInt32,System.String,System.String] ) -=-=-=-=-=-=-=-=- UInteger + String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt32 ) Parameter( y type: System.String ) body { Convert( Add( Convert( Parameter( x type: System.UInt32 ) type: System.Double ) Convert( Parameter( y type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.UInt32,System.String,System.String] ) -=-=-=-=-=-=-=-=- String & UInteger => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.UInt32 ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Parameter( x type: System.String ) Convert( Parameter( y type: System.UInt32 ) method: System.String ToString(UInt32) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.String,System.UInt32,System.String] ) -=-=-=-=-=-=-=-=- String + UInteger => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.UInt32 ) body { Convert( Add( Convert( Parameter( x type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) Convert( Parameter( y type: System.UInt32 ) type: System.Double ) type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.String,System.UInt32,System.String] ) -=-=-=-=-=-=-=-=- UInteger? & String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt32] ) Parameter( y type: System.String ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Coalesce( Parameter( x type: System.Nullable`1[System.UInt32] ) Constant( null type: System.String ) conversion: Lambda( Parameter( CoalesceLHS type: System.Nullable`1[System.UInt32] ) body { Convert( ConvertChecked( Parameter( CoalesceLHS type: System.Nullable`1[System.UInt32] ) method: UInt32 op_Explicit(System.Nullable`1[System.UInt32]) in System.Nullable`1[System.UInt32] type: System.UInt32 ) method: System.String ToString(UInt32) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Nullable`1[System.UInt32],System.String] ) type: System.String ) Parameter( y type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.Nullable`1[System.UInt32],System.String,System.String] ) -=-=-=-=-=-=-=-=- UInteger? + String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt32] ) Parameter( y type: System.String ) body { Convert( Convert( Add( Convert( Parameter( x type: System.Nullable`1[System.UInt32] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) Convert( Convert( Parameter( y type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) method: System.Nullable`1[System.Double] op_Implicit(Double) in System.Nullable`1[System.Double] type: System.Nullable`1[System.Double] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) method: Double op_Explicit(System.Nullable`1[System.Double]) in System.Nullable`1[System.Double] type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.Nullable`1[System.UInt32],System.String,System.String] ) -=-=-=-=-=-=-=-=- String & UInteger? => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.Nullable`1[System.UInt32] ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Parameter( x type: System.String ) Coalesce( Parameter( y type: System.Nullable`1[System.UInt32] ) Constant( null type: System.String ) conversion: Lambda( Parameter( CoalesceLHS type: System.Nullable`1[System.UInt32] ) body { Convert( ConvertChecked( Parameter( CoalesceLHS type: System.Nullable`1[System.UInt32] ) method: UInt32 op_Explicit(System.Nullable`1[System.UInt32]) in System.Nullable`1[System.UInt32] type: System.UInt32 ) method: System.String ToString(UInt32) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Nullable`1[System.UInt32],System.String] ) type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.String,System.Nullable`1[System.UInt32],System.String] ) -=-=-=-=-=-=-=-=- String + UInteger? => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.Nullable`1[System.UInt32] ) body { Convert( Convert( Add( Convert( Convert( Parameter( x type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) method: System.Nullable`1[System.Double] op_Implicit(Double) in System.Nullable`1[System.Double] type: System.Nullable`1[System.Double] ) Convert( Parameter( y type: System.Nullable`1[System.UInt32] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) method: Double op_Explicit(System.Nullable`1[System.Double]) in System.Nullable`1[System.Double] type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.String,System.Nullable`1[System.UInt32],System.String] ) -=-=-=-=-=-=-=-=- E_UInteger & String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UInteger ) Parameter( y type: System.String ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Convert( ConvertChecked( Parameter( x type: E_UInteger ) type: System.UInt32 ) method: System.String ToString(UInt32) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) Parameter( y type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[E_UInteger,System.String,System.String] ) -=-=-=-=-=-=-=-=- E_UInteger + String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UInteger ) Parameter( y type: System.String ) body { Convert( Add( Convert( Parameter( x type: E_UInteger ) type: System.Double ) Convert( Parameter( y type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[E_UInteger,System.String,System.String] ) -=-=-=-=-=-=-=-=- String & E_UInteger => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: E_UInteger ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Parameter( x type: System.String ) Convert( ConvertChecked( Parameter( y type: E_UInteger ) type: System.UInt32 ) method: System.String ToString(UInt32) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.String,E_UInteger,System.String] ) -=-=-=-=-=-=-=-=- String + E_UInteger => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: E_UInteger ) body { Convert( Add( Convert( Parameter( x type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) Convert( Parameter( y type: E_UInteger ) type: System.Double ) type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.String,E_UInteger,System.String] ) -=-=-=-=-=-=-=-=- E_UInteger? & String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_UInteger] ) Parameter( y type: System.String ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Coalesce( Parameter( x type: System.Nullable`1[E_UInteger] ) Constant( null type: System.String ) conversion: Lambda( Parameter( CoalesceLHS type: System.Nullable`1[E_UInteger] ) body { Convert( ConvertChecked( ConvertChecked( Parameter( CoalesceLHS type: System.Nullable`1[E_UInteger] ) method: E_UInteger op_Explicit(System.Nullable`1[E_UInteger]) in System.Nullable`1[E_UInteger] type: E_UInteger ) type: System.UInt32 ) method: System.String ToString(UInt32) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Nullable`1[E_UInteger],System.String] ) type: System.String ) Parameter( y type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.Nullable`1[E_UInteger],System.String,System.String] ) -=-=-=-=-=-=-=-=- E_UInteger? + String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_UInteger] ) Parameter( y type: System.String ) body { Convert( Convert( Add( Convert( Parameter( x type: System.Nullable`1[E_UInteger] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) Convert( Convert( Parameter( y type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) method: System.Nullable`1[System.Double] op_Implicit(Double) in System.Nullable`1[System.Double] type: System.Nullable`1[System.Double] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) method: Double op_Explicit(System.Nullable`1[System.Double]) in System.Nullable`1[System.Double] type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.Nullable`1[E_UInteger],System.String,System.String] ) -=-=-=-=-=-=-=-=- String & E_UInteger? => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.Nullable`1[E_UInteger] ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Parameter( x type: System.String ) Coalesce( Parameter( y type: System.Nullable`1[E_UInteger] ) Constant( null type: System.String ) conversion: Lambda( Parameter( CoalesceLHS type: System.Nullable`1[E_UInteger] ) body { Convert( ConvertChecked( ConvertChecked( Parameter( CoalesceLHS type: System.Nullable`1[E_UInteger] ) method: E_UInteger op_Explicit(System.Nullable`1[E_UInteger]) in System.Nullable`1[E_UInteger] type: E_UInteger ) type: System.UInt32 ) method: System.String ToString(UInt32) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Nullable`1[E_UInteger],System.String] ) type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.String,System.Nullable`1[E_UInteger],System.String] ) -=-=-=-=-=-=-=-=- String + E_UInteger? => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.Nullable`1[E_UInteger] ) body { Convert( Convert( Add( Convert( Convert( Parameter( x type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) method: System.Nullable`1[System.Double] op_Implicit(Double) in System.Nullable`1[System.Double] type: System.Nullable`1[System.Double] ) Convert( Parameter( y type: System.Nullable`1[E_UInteger] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) method: Double op_Explicit(System.Nullable`1[System.Double]) in System.Nullable`1[System.Double] type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.String,System.Nullable`1[E_UInteger],System.String] ) -=-=-=-=-=-=-=-=- Long & String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int64 ) Parameter( y type: System.String ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Convert( Parameter( x type: System.Int64 ) method: System.String ToString(Int64) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) Parameter( y type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.Int64,System.String,System.String] ) -=-=-=-=-=-=-=-=- Long + String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int64 ) Parameter( y type: System.String ) body { Convert( Add( Convert( Parameter( x type: System.Int64 ) type: System.Double ) Convert( Parameter( y type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.Int64,System.String,System.String] ) -=-=-=-=-=-=-=-=- String & Long => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.Int64 ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Parameter( x type: System.String ) Convert( Parameter( y type: System.Int64 ) method: System.String ToString(Int64) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.String,System.Int64,System.String] ) -=-=-=-=-=-=-=-=- String + Long => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.Int64 ) body { Convert( Add( Convert( Parameter( x type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) Convert( Parameter( y type: System.Int64 ) type: System.Double ) type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.String,System.Int64,System.String] ) -=-=-=-=-=-=-=-=- Long? & String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int64] ) Parameter( y type: System.String ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Coalesce( Parameter( x type: System.Nullable`1[System.Int64] ) Constant( null type: System.String ) conversion: Lambda( Parameter( CoalesceLHS type: System.Nullable`1[System.Int64] ) body { Convert( ConvertChecked( Parameter( CoalesceLHS type: System.Nullable`1[System.Int64] ) method: Int64 op_Explicit(System.Nullable`1[System.Int64]) in System.Nullable`1[System.Int64] type: System.Int64 ) method: System.String ToString(Int64) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Nullable`1[System.Int64],System.String] ) type: System.String ) Parameter( y type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.Nullable`1[System.Int64],System.String,System.String] ) -=-=-=-=-=-=-=-=- Long? + String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int64] ) Parameter( y type: System.String ) body { Convert( Convert( Add( Convert( Parameter( x type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) Convert( Convert( Parameter( y type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) method: System.Nullable`1[System.Double] op_Implicit(Double) in System.Nullable`1[System.Double] type: System.Nullable`1[System.Double] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) method: Double op_Explicit(System.Nullable`1[System.Double]) in System.Nullable`1[System.Double] type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.Nullable`1[System.Int64],System.String,System.String] ) -=-=-=-=-=-=-=-=- String & Long? => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.Nullable`1[System.Int64] ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Parameter( x type: System.String ) Coalesce( Parameter( y type: System.Nullable`1[System.Int64] ) Constant( null type: System.String ) conversion: Lambda( Parameter( CoalesceLHS type: System.Nullable`1[System.Int64] ) body { Convert( ConvertChecked( Parameter( CoalesceLHS type: System.Nullable`1[System.Int64] ) method: Int64 op_Explicit(System.Nullable`1[System.Int64]) in System.Nullable`1[System.Int64] type: System.Int64 ) method: System.String ToString(Int64) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Nullable`1[System.Int64],System.String] ) type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.String,System.Nullable`1[System.Int64],System.String] ) -=-=-=-=-=-=-=-=- String + Long? => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.Nullable`1[System.Int64] ) body { Convert( Convert( Add( Convert( Convert( Parameter( x type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) method: System.Nullable`1[System.Double] op_Implicit(Double) in System.Nullable`1[System.Double] type: System.Nullable`1[System.Double] ) Convert( Parameter( y type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) method: Double op_Explicit(System.Nullable`1[System.Double]) in System.Nullable`1[System.Double] type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.String,System.Nullable`1[System.Int64],System.String] ) -=-=-=-=-=-=-=-=- E_Long & String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Long ) Parameter( y type: System.String ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Convert( ConvertChecked( Parameter( x type: E_Long ) type: System.Int64 ) method: System.String ToString(Int64) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) Parameter( y type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[E_Long,System.String,System.String] ) -=-=-=-=-=-=-=-=- E_Long + String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Long ) Parameter( y type: System.String ) body { Convert( Add( Convert( Parameter( x type: E_Long ) type: System.Double ) Convert( Parameter( y type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[E_Long,System.String,System.String] ) -=-=-=-=-=-=-=-=- String & E_Long => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: E_Long ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Parameter( x type: System.String ) Convert( ConvertChecked( Parameter( y type: E_Long ) type: System.Int64 ) method: System.String ToString(Int64) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.String,E_Long,System.String] ) -=-=-=-=-=-=-=-=- String + E_Long => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: E_Long ) body { Convert( Add( Convert( Parameter( x type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) Convert( Parameter( y type: E_Long ) type: System.Double ) type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.String,E_Long,System.String] ) -=-=-=-=-=-=-=-=- E_Long? & String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Long] ) Parameter( y type: System.String ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Coalesce( Parameter( x type: System.Nullable`1[E_Long] ) Constant( null type: System.String ) conversion: Lambda( Parameter( CoalesceLHS type: System.Nullable`1[E_Long] ) body { Convert( ConvertChecked( ConvertChecked( Parameter( CoalesceLHS type: System.Nullable`1[E_Long] ) method: E_Long op_Explicit(System.Nullable`1[E_Long]) in System.Nullable`1[E_Long] type: E_Long ) type: System.Int64 ) method: System.String ToString(Int64) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Nullable`1[E_Long],System.String] ) type: System.String ) Parameter( y type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.Nullable`1[E_Long],System.String,System.String] ) -=-=-=-=-=-=-=-=- E_Long? + String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Long] ) Parameter( y type: System.String ) body { Convert( Convert( Add( Convert( Parameter( x type: System.Nullable`1[E_Long] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) Convert( Convert( Parameter( y type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) method: System.Nullable`1[System.Double] op_Implicit(Double) in System.Nullable`1[System.Double] type: System.Nullable`1[System.Double] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) method: Double op_Explicit(System.Nullable`1[System.Double]) in System.Nullable`1[System.Double] type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.Nullable`1[E_Long],System.String,System.String] ) -=-=-=-=-=-=-=-=- String & E_Long? => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.Nullable`1[E_Long] ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Parameter( x type: System.String ) Coalesce( Parameter( y type: System.Nullable`1[E_Long] ) Constant( null type: System.String ) conversion: Lambda( Parameter( CoalesceLHS type: System.Nullable`1[E_Long] ) body { Convert( ConvertChecked( ConvertChecked( Parameter( CoalesceLHS type: System.Nullable`1[E_Long] ) method: E_Long op_Explicit(System.Nullable`1[E_Long]) in System.Nullable`1[E_Long] type: E_Long ) type: System.Int64 ) method: System.String ToString(Int64) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Nullable`1[E_Long],System.String] ) type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.String,System.Nullable`1[E_Long],System.String] ) -=-=-=-=-=-=-=-=- String + E_Long? => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.Nullable`1[E_Long] ) body { Convert( Convert( Add( Convert( Convert( Parameter( x type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) method: System.Nullable`1[System.Double] op_Implicit(Double) in System.Nullable`1[System.Double] type: System.Nullable`1[System.Double] ) Convert( Parameter( y type: System.Nullable`1[E_Long] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) method: Double op_Explicit(System.Nullable`1[System.Double]) in System.Nullable`1[System.Double] type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.String,System.Nullable`1[E_Long],System.String] ) -=-=-=-=-=-=-=-=- Boolean & String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Boolean ) Parameter( y type: System.String ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Convert( Parameter( x type: System.Boolean ) method: System.String ToString(Boolean) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) Parameter( y type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.Boolean,System.String,System.String] ) -=-=-=-=-=-=-=-=- Boolean + String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Boolean ) Parameter( y type: System.String ) body { Convert( Add( Negate( Convert( Parameter( x type: System.Boolean ) type: System.Double ) type: System.Double ) Convert( Parameter( y type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.Boolean,System.String,System.String] ) -=-=-=-=-=-=-=-=- String & Boolean => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.Boolean ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Parameter( x type: System.String ) Convert( Parameter( y type: System.Boolean ) method: System.String ToString(Boolean) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.String,System.Boolean,System.String] ) -=-=-=-=-=-=-=-=- String + Boolean => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.Boolean ) body { Convert( Add( Convert( Parameter( x type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) Negate( Convert( Parameter( y type: System.Boolean ) type: System.Double ) type: System.Double ) type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.String,System.Boolean,System.String] ) -=-=-=-=-=-=-=-=- Boolean? & String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Boolean] ) Parameter( y type: System.String ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Coalesce( Parameter( x type: System.Nullable`1[System.Boolean] ) Constant( null type: System.String ) conversion: Lambda( Parameter( CoalesceLHS type: System.Nullable`1[System.Boolean] ) body { Convert( Convert( Parameter( CoalesceLHS type: System.Nullable`1[System.Boolean] ) method: Boolean op_Explicit(System.Nullable`1[System.Boolean]) in System.Nullable`1[System.Boolean] type: System.Boolean ) method: System.String ToString(Boolean) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Nullable`1[System.Boolean],System.String] ) type: System.String ) Parameter( y type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.Nullable`1[System.Boolean],System.String,System.String] ) -=-=-=-=-=-=-=-=- Boolean? + String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Boolean] ) Parameter( y type: System.String ) body { Convert( Convert( Add( Negate( Convert( Parameter( x type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) Convert( Convert( Parameter( y type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) method: System.Nullable`1[System.Double] op_Implicit(Double) in System.Nullable`1[System.Double] type: System.Nullable`1[System.Double] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) method: Double op_Explicit(System.Nullable`1[System.Double]) in System.Nullable`1[System.Double] type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.Nullable`1[System.Boolean],System.String,System.String] ) -=-=-=-=-=-=-=-=- String & Boolean? => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.Nullable`1[System.Boolean] ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Parameter( x type: System.String ) Coalesce( Parameter( y type: System.Nullable`1[System.Boolean] ) Constant( null type: System.String ) conversion: Lambda( Parameter( CoalesceLHS type: System.Nullable`1[System.Boolean] ) body { Convert( Convert( Parameter( CoalesceLHS type: System.Nullable`1[System.Boolean] ) method: Boolean op_Explicit(System.Nullable`1[System.Boolean]) in System.Nullable`1[System.Boolean] type: System.Boolean ) method: System.String ToString(Boolean) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Nullable`1[System.Boolean],System.String] ) type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.String,System.Nullable`1[System.Boolean],System.String] ) -=-=-=-=-=-=-=-=- String + Boolean? => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.Nullable`1[System.Boolean] ) body { Convert( Convert( Add( Convert( Convert( Parameter( x type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) method: System.Nullable`1[System.Double] op_Implicit(Double) in System.Nullable`1[System.Double] type: System.Nullable`1[System.Double] ) Negate( Convert( Parameter( y type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) method: Double op_Explicit(System.Nullable`1[System.Double]) in System.Nullable`1[System.Double] type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.String,System.Nullable`1[System.Boolean],System.String] ) -=-=-=-=-=-=-=-=- Single & String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Single ) Parameter( y type: System.String ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Convert( Parameter( x type: System.Single ) method: System.String ToString(Single) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) Parameter( y type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.Single,System.String,System.String] ) -=-=-=-=-=-=-=-=- Single + String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Single ) Parameter( y type: System.String ) body { Convert( Add( Convert( Parameter( x type: System.Single ) type: System.Double ) Convert( Parameter( y type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.Single,System.String,System.String] ) -=-=-=-=-=-=-=-=- String & Single => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.Single ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Parameter( x type: System.String ) Convert( Parameter( y type: System.Single ) method: System.String ToString(Single) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.String,System.Single,System.String] ) -=-=-=-=-=-=-=-=- String + Single => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.Single ) body { Convert( Add( Convert( Parameter( x type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) Convert( Parameter( y type: System.Single ) type: System.Double ) type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.String,System.Single,System.String] ) -=-=-=-=-=-=-=-=- Single? & String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Single] ) Parameter( y type: System.String ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Coalesce( Parameter( x type: System.Nullable`1[System.Single] ) Constant( null type: System.String ) conversion: Lambda( Parameter( CoalesceLHS type: System.Nullable`1[System.Single] ) body { Convert( Convert( Parameter( CoalesceLHS type: System.Nullable`1[System.Single] ) method: Single op_Explicit(System.Nullable`1[System.Single]) in System.Nullable`1[System.Single] type: System.Single ) method: System.String ToString(Single) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Nullable`1[System.Single],System.String] ) type: System.String ) Parameter( y type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.Nullable`1[System.Single],System.String,System.String] ) -=-=-=-=-=-=-=-=- Single? + String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Single] ) Parameter( y type: System.String ) body { Convert( Convert( Add( Convert( Parameter( x type: System.Nullable`1[System.Single] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) Convert( Convert( Parameter( y type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) method: System.Nullable`1[System.Double] op_Implicit(Double) in System.Nullable`1[System.Double] type: System.Nullable`1[System.Double] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) method: Double op_Explicit(System.Nullable`1[System.Double]) in System.Nullable`1[System.Double] type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.Nullable`1[System.Single],System.String,System.String] ) -=-=-=-=-=-=-=-=- String & Single? => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.Nullable`1[System.Single] ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Parameter( x type: System.String ) Coalesce( Parameter( y type: System.Nullable`1[System.Single] ) Constant( null type: System.String ) conversion: Lambda( Parameter( CoalesceLHS type: System.Nullable`1[System.Single] ) body { Convert( Convert( Parameter( CoalesceLHS type: System.Nullable`1[System.Single] ) method: Single op_Explicit(System.Nullable`1[System.Single]) in System.Nullable`1[System.Single] type: System.Single ) method: System.String ToString(Single) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Nullable`1[System.Single],System.String] ) type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.String,System.Nullable`1[System.Single],System.String] ) -=-=-=-=-=-=-=-=- String + Single? => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.Nullable`1[System.Single] ) body { Convert( Convert( Add( Convert( Convert( Parameter( x type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) method: System.Nullable`1[System.Double] op_Implicit(Double) in System.Nullable`1[System.Double] type: System.Nullable`1[System.Double] ) Convert( Parameter( y type: System.Nullable`1[System.Single] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) method: Double op_Explicit(System.Nullable`1[System.Double]) in System.Nullable`1[System.Double] type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.String,System.Nullable`1[System.Single],System.String] ) -=-=-=-=-=-=-=-=- Double & String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Double ) Parameter( y type: System.String ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Convert( Parameter( x type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) Parameter( y type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.Double,System.String,System.String] ) -=-=-=-=-=-=-=-=- Double + String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Double ) Parameter( y type: System.String ) body { Convert( Add( Parameter( x type: System.Double ) Convert( Parameter( y type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.Double,System.String,System.String] ) -=-=-=-=-=-=-=-=- String & Double => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.Double ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Parameter( x type: System.String ) Convert( Parameter( y type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.String,System.Double,System.String] ) -=-=-=-=-=-=-=-=- String + Double => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.Double ) body { Convert( Add( Convert( Parameter( x type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) Parameter( y type: System.Double ) type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.String,System.Double,System.String] ) -=-=-=-=-=-=-=-=- Double? & String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Double] ) Parameter( y type: System.String ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Coalesce( Parameter( x type: System.Nullable`1[System.Double] ) Constant( null type: System.String ) conversion: Lambda( Parameter( CoalesceLHS type: System.Nullable`1[System.Double] ) body { Convert( Convert( Parameter( CoalesceLHS type: System.Nullable`1[System.Double] ) method: Double op_Explicit(System.Nullable`1[System.Double]) in System.Nullable`1[System.Double] type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Nullable`1[System.Double],System.String] ) type: System.String ) Parameter( y type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.Nullable`1[System.Double],System.String,System.String] ) -=-=-=-=-=-=-=-=- Double? + String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Double] ) Parameter( y type: System.String ) body { Convert( Convert( Add( Parameter( x type: System.Nullable`1[System.Double] ) Convert( Convert( Parameter( y type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) method: System.Nullable`1[System.Double] op_Implicit(Double) in System.Nullable`1[System.Double] type: System.Nullable`1[System.Double] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) method: Double op_Explicit(System.Nullable`1[System.Double]) in System.Nullable`1[System.Double] type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.Nullable`1[System.Double],System.String,System.String] ) -=-=-=-=-=-=-=-=- String & Double? => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.Nullable`1[System.Double] ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Parameter( x type: System.String ) Coalesce( Parameter( y type: System.Nullable`1[System.Double] ) Constant( null type: System.String ) conversion: Lambda( Parameter( CoalesceLHS type: System.Nullable`1[System.Double] ) body { Convert( Convert( Parameter( CoalesceLHS type: System.Nullable`1[System.Double] ) method: Double op_Explicit(System.Nullable`1[System.Double]) in System.Nullable`1[System.Double] type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Nullable`1[System.Double],System.String] ) type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.String,System.Nullable`1[System.Double],System.String] ) -=-=-=-=-=-=-=-=- String + Double? => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.Nullable`1[System.Double] ) body { Convert( Convert( Add( Convert( Convert( Parameter( x type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) method: System.Nullable`1[System.Double] op_Implicit(Double) in System.Nullable`1[System.Double] type: System.Nullable`1[System.Double] ) Parameter( y type: System.Nullable`1[System.Double] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) method: Double op_Explicit(System.Nullable`1[System.Double]) in System.Nullable`1[System.Double] type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.String,System.Nullable`1[System.Double],System.String] ) -=-=-=-=-=-=-=-=- Decimal & String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Decimal ) Parameter( y type: System.String ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Convert( Parameter( x type: System.Decimal ) method: System.String ToString(System.Decimal) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) Parameter( y type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.Decimal,System.String,System.String] ) -=-=-=-=-=-=-=-=- Decimal + String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Decimal ) Parameter( y type: System.String ) body { Convert( Add( Convert( Parameter( x type: System.Decimal ) method: Double op_Explicit(System.Decimal) in System.Decimal type: System.Double ) Convert( Parameter( y type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.Decimal,System.String,System.String] ) -=-=-=-=-=-=-=-=- String & Decimal => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.Decimal ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Parameter( x type: System.String ) Convert( Parameter( y type: System.Decimal ) method: System.String ToString(System.Decimal) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.String,System.Decimal,System.String] ) -=-=-=-=-=-=-=-=- String + Decimal => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.Decimal ) body { Convert( Add( Convert( Parameter( x type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) Convert( Parameter( y type: System.Decimal ) method: Double op_Explicit(System.Decimal) in System.Decimal type: System.Double ) type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.String,System.Decimal,System.String] ) -=-=-=-=-=-=-=-=- Decimal? & String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Decimal] ) Parameter( y type: System.String ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Coalesce( Parameter( x type: System.Nullable`1[System.Decimal] ) Constant( null type: System.String ) conversion: Lambda( Parameter( CoalesceLHS type: System.Nullable`1[System.Decimal] ) body { Convert( Convert( Parameter( CoalesceLHS type: System.Nullable`1[System.Decimal] ) method: System.Decimal op_Explicit(System.Nullable`1[System.Decimal]) in System.Nullable`1[System.Decimal] type: System.Decimal ) method: System.String ToString(System.Decimal) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Nullable`1[System.Decimal],System.String] ) type: System.String ) Parameter( y type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.Nullable`1[System.Decimal],System.String,System.String] ) -=-=-=-=-=-=-=-=- Decimal? + String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Decimal] ) Parameter( y type: System.String ) body { Convert( Convert( Add( Convert( Parameter( x type: System.Nullable`1[System.Decimal] ) Lifted LiftedToNull method: Double op_Explicit(System.Decimal) in System.Decimal type: System.Nullable`1[System.Double] ) Convert( Convert( Parameter( y type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) method: System.Nullable`1[System.Double] op_Implicit(Double) in System.Nullable`1[System.Double] type: System.Nullable`1[System.Double] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) method: Double op_Explicit(System.Nullable`1[System.Double]) in System.Nullable`1[System.Double] type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.Nullable`1[System.Decimal],System.String,System.String] ) -=-=-=-=-=-=-=-=- String & Decimal? => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.Nullable`1[System.Decimal] ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Parameter( x type: System.String ) Coalesce( Parameter( y type: System.Nullable`1[System.Decimal] ) Constant( null type: System.String ) conversion: Lambda( Parameter( CoalesceLHS type: System.Nullable`1[System.Decimal] ) body { Convert( Convert( Parameter( CoalesceLHS type: System.Nullable`1[System.Decimal] ) method: System.Decimal op_Explicit(System.Nullable`1[System.Decimal]) in System.Nullable`1[System.Decimal] type: System.Decimal ) method: System.String ToString(System.Decimal) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Nullable`1[System.Decimal],System.String] ) type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.String,System.Nullable`1[System.Decimal],System.String] ) -=-=-=-=-=-=-=-=- String + Decimal? => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.Nullable`1[System.Decimal] ) body { Convert( Convert( Add( Convert( Convert( Parameter( x type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) method: System.Nullable`1[System.Double] op_Implicit(Double) in System.Nullable`1[System.Double] type: System.Nullable`1[System.Double] ) Convert( Parameter( y type: System.Nullable`1[System.Decimal] ) Lifted LiftedToNull method: Double op_Explicit(System.Decimal) in System.Decimal type: System.Nullable`1[System.Double] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) method: Double op_Explicit(System.Nullable`1[System.Double]) in System.Nullable`1[System.Double] type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.String,System.Nullable`1[System.Decimal],System.String] ) -=-=-=-=-=-=-=-=- Date & String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.DateTime ) Parameter( y type: System.String ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Convert( Parameter( x type: System.DateTime ) method: System.String ToString(System.DateTime) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) Parameter( y type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.DateTime,System.String,System.String] ) -=-=-=-=-=-=-=-=- Date + String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.DateTime ) Parameter( y type: System.String ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Convert( Parameter( x type: System.DateTime ) method: System.String ToString(System.DateTime) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) Parameter( y type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.DateTime,System.String,System.String] ) -=-=-=-=-=-=-=-=- String & Date => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.DateTime ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Parameter( x type: System.String ) Convert( Parameter( y type: System.DateTime ) method: System.String ToString(System.DateTime) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.String,System.DateTime,System.String] ) -=-=-=-=-=-=-=-=- String + Date => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.DateTime ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Parameter( x type: System.String ) Convert( Parameter( y type: System.DateTime ) method: System.String ToString(System.DateTime) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.String,System.DateTime,System.String] ) -=-=-=-=-=-=-=-=- Date? & String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.DateTime] ) Parameter( y type: System.String ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Coalesce( Parameter( x type: System.Nullable`1[System.DateTime] ) Constant( null type: System.String ) conversion: Lambda( Parameter( CoalesceLHS type: System.Nullable`1[System.DateTime] ) body { Convert( Convert( Parameter( CoalesceLHS type: System.Nullable`1[System.DateTime] ) method: System.DateTime op_Explicit(System.Nullable`1[System.DateTime]) in System.Nullable`1[System.DateTime] type: System.DateTime ) method: System.String ToString(System.DateTime) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Nullable`1[System.DateTime],System.String] ) type: System.String ) Parameter( y type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.Nullable`1[System.DateTime],System.String,System.String] ) -=-=-=-=-=-=-=-=- Date? + String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.DateTime] ) Parameter( y type: System.String ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Convert( Convert( Parameter( x type: System.Nullable`1[System.DateTime] ) method: System.DateTime op_Explicit(System.Nullable`1[System.DateTime]) in System.Nullable`1[System.DateTime] type: System.DateTime ) method: System.String ToString(System.DateTime) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) Parameter( y type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.Nullable`1[System.DateTime],System.String,System.String] ) -=-=-=-=-=-=-=-=- String & Date? => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.Nullable`1[System.DateTime] ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Parameter( x type: System.String ) Coalesce( Parameter( y type: System.Nullable`1[System.DateTime] ) Constant( null type: System.String ) conversion: Lambda( Parameter( CoalesceLHS type: System.Nullable`1[System.DateTime] ) body { Convert( Convert( Parameter( CoalesceLHS type: System.Nullable`1[System.DateTime] ) method: System.DateTime op_Explicit(System.Nullable`1[System.DateTime]) in System.Nullable`1[System.DateTime] type: System.DateTime ) method: System.String ToString(System.DateTime) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Nullable`1[System.DateTime],System.String] ) type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.String,System.Nullable`1[System.DateTime],System.String] ) -=-=-=-=-=-=-=-=- String + Date? => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.Nullable`1[System.DateTime] ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Parameter( x type: System.String ) Convert( Convert( Parameter( y type: System.Nullable`1[System.DateTime] ) method: System.DateTime op_Explicit(System.Nullable`1[System.DateTime]) in System.Nullable`1[System.DateTime] type: System.DateTime ) method: System.String ToString(System.DateTime) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.String,System.Nullable`1[System.DateTime],System.String] ) -=-=-=-=-=-=-=-=- String & String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.String ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Parameter( x type: System.String ) Parameter( y type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.String,System.String,System.String] ) -=-=-=-=-=-=-=-=- String + String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.String ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Parameter( x type: System.String ) Parameter( y type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.String,System.String,System.String] ) -=-=-=-=-=-=-=-=- String & String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.String ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Parameter( x type: System.String ) Parameter( y type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.String,System.String,System.String] ) -=-=-=-=-=-=-=-=- String + String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.String ) body { Call( <NULL> method: System.String Concat(System.String, System.String) in System.String ( Parameter( x type: System.String ) Parameter( y type: System.String ) ) type: System.String ) } return type: System.String type: System.Func`3[System.String,System.String,System.String] ) -=-=-=-=-=-=-=-=- Object & String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) Parameter( y type: System.String ) body { Convert( Call( <NULL> method: System.Object ConcatenateObject(System.Object, System.Object) in Microsoft.VisualBasic.CompilerServices.Operators ( Parameter( x type: System.Object ) Convert( Parameter( y type: System.String ) type: System.Object ) ) type: System.Object ) method: System.String ToString(System.Object) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.Object,System.String,System.String] ) -=-=-=-=-=-=-=-=- Object + String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) Parameter( y type: System.String ) body { Convert( Add( Parameter( x type: System.Object ) Convert( Parameter( y type: System.String ) type: System.Object ) method: System.Object AddObject(System.Object, System.Object) in Microsoft.VisualBasic.CompilerServices.Operators type: System.Object ) method: System.String ToString(System.Object) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.Object,System.String,System.String] ) -=-=-=-=-=-=-=-=- String & Object => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.Object ) body { Convert( Call( <NULL> method: System.Object ConcatenateObject(System.Object, System.Object) in Microsoft.VisualBasic.CompilerServices.Operators ( Convert( Parameter( x type: System.String ) type: System.Object ) Parameter( y type: System.Object ) ) type: System.Object ) method: System.String ToString(System.Object) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.String,System.Object,System.String] ) -=-=-=-=-=-=-=-=- String + Object => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) Parameter( y type: System.Object ) body { Convert( Add( Convert( Parameter( x type: System.String ) type: System.Object ) Parameter( y type: System.Object ) method: System.Object AddObject(System.Object, System.Object) in Microsoft.VisualBasic.CompilerServices.Operators type: System.Object ) method: System.String ToString(System.Object) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`3[System.String,System.Object,System.String] ) -=-=-=-=-=-=-=-=- Object & Object => Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) Parameter( y type: System.Object ) body { Call( <NULL> method: System.Object ConcatenateObject(System.Object, System.Object) in Microsoft.VisualBasic.CompilerServices.Operators ( Parameter( x type: System.Object ) Parameter( y type: System.Object ) ) type: System.Object ) } return type: System.Object type: System.Func`3[System.Object,System.Object,System.Object] )
-1
dotnet/roslyn
56,450
Implement INamespaceTypeReference.GetUnit for RootModuleType
Fixes #56412.
AlekseyTs
"2021-09-16T16:44:04Z"
"2021-09-17T18:21:59Z"
4b06ee428bafa0141c9eb3250003a19109dcfc86
d695369176aa109f0e0fb8b0019294aaa0823a54
Implement INamespaceTypeReference.GetUnit for RootModuleType. Fixes #56412.
./src/EditorFeatures/VisualBasic/AutomaticEndConstructCorrection/ViewCreationListener.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.ObjectModel Imports System.ComponentModel.Composition Imports Microsoft.CodeAnalysis.Editor.Host Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.VisualStudio.Text Imports Microsoft.VisualStudio.Text.Editor Imports Microsoft.VisualStudio.Utilities Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.AutomaticEndConstructCorrection ''' <summary> ''' Tracks user's interaction with editor ''' </summary> <Export(GetType(ITextViewConnectionListener))> <ContentType(ContentTypeNames.VisualBasicContentType)> <TextViewRole(PredefinedTextViewRoles.Interactive)> Friend Class ViewCreationListener Implements ITextViewConnectionListener Private ReadOnly _uiThreadOperationExecutor As IUIThreadOperationExecutor <ImportingConstructor()> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New(uiThreadOperationExecutor As IUIThreadOperationExecutor) _uiThreadOperationExecutor = uiThreadOperationExecutor End Sub Public Sub SubjectBuffersConnected( textView As ITextView, reason As ConnectionReason, subjectBuffers As IReadOnlyCollection(Of ITextBuffer)) Implements ITextViewConnectionListener.SubjectBuffersConnected If Not subjectBuffers(0).GetFeatureOnOffOption(FeatureOnOffOptions.EndConstruct) Then Return End If Dim vbBuffers = subjectBuffers.Where(Function(b) b.ContentType.IsOfType(ContentTypeNames.VisualBasicContentType)) AddConstructPairTo(vbBuffers) End Sub Public Sub SubjectBuffersDisconnected(textView As ITextView, reason As ConnectionReason, subjectBuffers As IReadOnlyCollection(Of ITextBuffer)) Implements ITextViewConnectionListener.SubjectBuffersDisconnected Dim vbBuffers = subjectBuffers.Where(Function(b) b.ContentType.IsOfType(ContentTypeNames.VisualBasicContentType)) RemoveConstructPairFrom(vbBuffers) End Sub Private Sub AddConstructPairTo(buffers As IEnumerable(Of ITextBuffer)) buffers.Do(Sub(b) b.Properties.GetOrCreateSingletonProperty(Function() New AutomaticEndConstructCorrector(b, _uiThreadOperationExecutor)).Connect()) End Sub Private Sub RemoveConstructPairFrom(buffers As IEnumerable(Of ITextBuffer)) buffers.Do(Sub(b) b.Properties.GetOrCreateSingletonProperty(Function() New AutomaticEndConstructCorrector(b, _uiThreadOperationExecutor)).Disconnect()) buffers.Where( Function(b) b.Properties.GetProperty(Of AutomaticEndConstructCorrector)(GetType(AutomaticEndConstructCorrector)).IsDisconnected).Do( Function(b) b.Properties.RemoveProperty(GetType(AutomaticEndConstructCorrector))) End Sub 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.ObjectModel Imports System.ComponentModel.Composition Imports Microsoft.CodeAnalysis.Editor.Host Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.VisualStudio.Text Imports Microsoft.VisualStudio.Text.Editor Imports Microsoft.VisualStudio.Utilities Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.AutomaticEndConstructCorrection ''' <summary> ''' Tracks user's interaction with editor ''' </summary> <Export(GetType(ITextViewConnectionListener))> <ContentType(ContentTypeNames.VisualBasicContentType)> <TextViewRole(PredefinedTextViewRoles.Interactive)> Friend Class ViewCreationListener Implements ITextViewConnectionListener Private ReadOnly _uiThreadOperationExecutor As IUIThreadOperationExecutor <ImportingConstructor()> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New(uiThreadOperationExecutor As IUIThreadOperationExecutor) _uiThreadOperationExecutor = uiThreadOperationExecutor End Sub Public Sub SubjectBuffersConnected( textView As ITextView, reason As ConnectionReason, subjectBuffers As IReadOnlyCollection(Of ITextBuffer)) Implements ITextViewConnectionListener.SubjectBuffersConnected If Not subjectBuffers(0).GetFeatureOnOffOption(FeatureOnOffOptions.EndConstruct) Then Return End If Dim vbBuffers = subjectBuffers.Where(Function(b) b.ContentType.IsOfType(ContentTypeNames.VisualBasicContentType)) AddConstructPairTo(vbBuffers) End Sub Public Sub SubjectBuffersDisconnected(textView As ITextView, reason As ConnectionReason, subjectBuffers As IReadOnlyCollection(Of ITextBuffer)) Implements ITextViewConnectionListener.SubjectBuffersDisconnected Dim vbBuffers = subjectBuffers.Where(Function(b) b.ContentType.IsOfType(ContentTypeNames.VisualBasicContentType)) RemoveConstructPairFrom(vbBuffers) End Sub Private Sub AddConstructPairTo(buffers As IEnumerable(Of ITextBuffer)) buffers.Do(Sub(b) b.Properties.GetOrCreateSingletonProperty(Function() New AutomaticEndConstructCorrector(b, _uiThreadOperationExecutor)).Connect()) End Sub Private Sub RemoveConstructPairFrom(buffers As IEnumerable(Of ITextBuffer)) buffers.Do(Sub(b) b.Properties.GetOrCreateSingletonProperty(Function() New AutomaticEndConstructCorrector(b, _uiThreadOperationExecutor)).Disconnect()) buffers.Where( Function(b) b.Properties.GetProperty(Of AutomaticEndConstructCorrector)(GetType(AutomaticEndConstructCorrector)).IsDisconnected).Do( Function(b) b.Properties.RemoveProperty(GetType(AutomaticEndConstructCorrector))) End Sub End Class End Namespace
-1
dotnet/roslyn
56,450
Implement INamespaceTypeReference.GetUnit for RootModuleType
Fixes #56412.
AlekseyTs
"2021-09-16T16:44:04Z"
"2021-09-17T18:21:59Z"
4b06ee428bafa0141c9eb3250003a19109dcfc86
d695369176aa109f0e0fb8b0019294aaa0823a54
Implement INamespaceTypeReference.GetUnit for RootModuleType. Fixes #56412.
./src/Analyzers/Core/Analyzers/SimplifyBooleanExpression/SimplifyBooleanExpressionConstants.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.SimplifyBooleanExpression { internal static class SimplifyBooleanExpressionConstants { public const string Negate = nameof(Negate); public const string Or = nameof(Or); public const string And = nameof(And); public const string WhenTrue = nameof(WhenTrue); public const string WhenFalse = nameof(WhenFalse); } }
// Licensed to the .NET Foundation under one or more 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.SimplifyBooleanExpression { internal static class SimplifyBooleanExpressionConstants { public const string Negate = nameof(Negate); public const string Or = nameof(Or); public const string And = nameof(And); public const string WhenTrue = nameof(WhenTrue); public const string WhenFalse = nameof(WhenFalse); } }
-1
dotnet/roslyn
56,450
Implement INamespaceTypeReference.GetUnit for RootModuleType
Fixes #56412.
AlekseyTs
"2021-09-16T16:44:04Z"
"2021-09-17T18:21:59Z"
4b06ee428bafa0141c9eb3250003a19109dcfc86
d695369176aa109f0e0fb8b0019294aaa0823a54
Implement INamespaceTypeReference.GetUnit for RootModuleType. Fixes #56412.
./src/Compilers/Core/Portable/Syntax/AbstractWarningStateMap.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.Diagnostics; using System.Diagnostics.CodeAnalysis; namespace Microsoft.CodeAnalysis.Syntax { internal abstract class AbstractWarningStateMap<TWarningState> where TWarningState : struct { /// <summary> /// List of entries sorted in source order, each of which captures a /// position in the supplied syntax tree and the set of diagnostics (warnings) /// whose reporting should either be suppressed or enabled at this position. /// </summary> private readonly WarningStateMapEntry[] _warningStateMapEntries; protected AbstractWarningStateMap(SyntaxTree syntaxTree) { _warningStateMapEntries = CreateWarningStateMapEntries(syntaxTree); } /// <summary> /// Returns list of entries sorted in source order, each of which captures a /// position in the supplied syntax tree and the set of diagnostics (warnings) /// whose reporting should either be suppressed or enabled at this position. /// </summary> protected abstract WarningStateMapEntry[] CreateWarningStateMapEntries(SyntaxTree syntaxTree); /// <summary> /// Returns the reporting state for the supplied diagnostic id at the supplied position /// in the associated syntax tree. /// </summary> public TWarningState GetWarningState(string id, int position) { var entry = GetEntryAtOrBeforePosition(position); TWarningState state; if (entry.SpecificWarningOption.TryGetValue(id, out state)) { return state; } return entry.GeneralWarningOption; } /// <summary> /// Gets the entry with the largest position less than or equal to supplied position. /// </summary> private WarningStateMapEntry GetEntryAtOrBeforePosition(int position) { Debug.Assert(_warningStateMapEntries != null && _warningStateMapEntries.Length > 0); int r = Array.BinarySearch(_warningStateMapEntries, new WarningStateMapEntry(position)); return _warningStateMapEntries[r >= 0 ? r : ((~r) - 1)]; } /// <summary> /// Struct that represents an entry in the warning state map. Sorts by position in the associated syntax tree. /// </summary> protected readonly struct WarningStateMapEntry : IComparable<WarningStateMapEntry> { // 0-based position in the associated syntax tree public readonly int Position; // the general option applicable to all warnings, accumulated of all #pragma up to the current Line. public readonly TWarningState GeneralWarningOption; // the mapping of the specific warning to the option, accumulated of all #pragma up to the current Line. public readonly ImmutableDictionary<string, TWarningState> SpecificWarningOption; public WarningStateMapEntry(int position) { this.Position = position; this.GeneralWarningOption = default; this.SpecificWarningOption = ImmutableDictionary.Create<string, TWarningState>(); } public WarningStateMapEntry(int position, TWarningState general, ImmutableDictionary<string, TWarningState> specific) { this.Position = position; this.GeneralWarningOption = general; this.SpecificWarningOption = specific ?? ImmutableDictionary.Create<string, TWarningState>(); } public int CompareTo(WarningStateMapEntry other) { return this.Position - other.Position; } } } }
// Licensed to the .NET Foundation under one or more 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.Diagnostics; using System.Diagnostics.CodeAnalysis; namespace Microsoft.CodeAnalysis.Syntax { internal abstract class AbstractWarningStateMap<TWarningState> where TWarningState : struct { /// <summary> /// List of entries sorted in source order, each of which captures a /// position in the supplied syntax tree and the set of diagnostics (warnings) /// whose reporting should either be suppressed or enabled at this position. /// </summary> private readonly WarningStateMapEntry[] _warningStateMapEntries; protected AbstractWarningStateMap(SyntaxTree syntaxTree) { _warningStateMapEntries = CreateWarningStateMapEntries(syntaxTree); } /// <summary> /// Returns list of entries sorted in source order, each of which captures a /// position in the supplied syntax tree and the set of diagnostics (warnings) /// whose reporting should either be suppressed or enabled at this position. /// </summary> protected abstract WarningStateMapEntry[] CreateWarningStateMapEntries(SyntaxTree syntaxTree); /// <summary> /// Returns the reporting state for the supplied diagnostic id at the supplied position /// in the associated syntax tree. /// </summary> public TWarningState GetWarningState(string id, int position) { var entry = GetEntryAtOrBeforePosition(position); TWarningState state; if (entry.SpecificWarningOption.TryGetValue(id, out state)) { return state; } return entry.GeneralWarningOption; } /// <summary> /// Gets the entry with the largest position less than or equal to supplied position. /// </summary> private WarningStateMapEntry GetEntryAtOrBeforePosition(int position) { Debug.Assert(_warningStateMapEntries != null && _warningStateMapEntries.Length > 0); int r = Array.BinarySearch(_warningStateMapEntries, new WarningStateMapEntry(position)); return _warningStateMapEntries[r >= 0 ? r : ((~r) - 1)]; } /// <summary> /// Struct that represents an entry in the warning state map. Sorts by position in the associated syntax tree. /// </summary> protected readonly struct WarningStateMapEntry : IComparable<WarningStateMapEntry> { // 0-based position in the associated syntax tree public readonly int Position; // the general option applicable to all warnings, accumulated of all #pragma up to the current Line. public readonly TWarningState GeneralWarningOption; // the mapping of the specific warning to the option, accumulated of all #pragma up to the current Line. public readonly ImmutableDictionary<string, TWarningState> SpecificWarningOption; public WarningStateMapEntry(int position) { this.Position = position; this.GeneralWarningOption = default; this.SpecificWarningOption = ImmutableDictionary.Create<string, TWarningState>(); } public WarningStateMapEntry(int position, TWarningState general, ImmutableDictionary<string, TWarningState> specific) { this.Position = position; this.GeneralWarningOption = general; this.SpecificWarningOption = specific ?? ImmutableDictionary.Create<string, TWarningState>(); } public int CompareTo(WarningStateMapEntry other) { return this.Position - other.Position; } } } }
-1
dotnet/roslyn
56,450
Implement INamespaceTypeReference.GetUnit for RootModuleType
Fixes #56412.
AlekseyTs
"2021-09-16T16:44:04Z"
"2021-09-17T18:21:59Z"
4b06ee428bafa0141c9eb3250003a19109dcfc86
d695369176aa109f0e0fb8b0019294aaa0823a54
Implement INamespaceTypeReference.GetUnit for RootModuleType. Fixes #56412.
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/CodeStyle/CodeStyleOptions2.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.Diagnostics; using Microsoft.CodeAnalysis.Options; using Roslyn.Utilities; using static Microsoft.CodeAnalysis.CodeStyle.CodeStyleHelpers; namespace Microsoft.CodeAnalysis.CodeStyle { internal static class CodeStyleOptions2 { private static readonly ImmutableArray<IOption2>.Builder s_allOptionsBuilder = ImmutableArray.CreateBuilder<IOption2>(); internal static ImmutableArray<IOption2> AllOptions { get; } private static PerLanguageOption2<T> CreateOption<T>( OptionGroup group, string name, T defaultValue, OptionStorageLocation2 storageLocation) { var option = new PerLanguageOption2<T>( "CodeStyleOptions", group, name, defaultValue, ImmutableArray.Create(storageLocation)); s_allOptionsBuilder.Add(option); return option; } private static PerLanguageOption2<T> CreateOption<T>( OptionGroup group, string name, T defaultValue, OptionStorageLocation2 storageLocation1, OptionStorageLocation2 storageLocation2) { var option = new PerLanguageOption2<T>( "CodeStyleOptions", group, name, defaultValue, ImmutableArray.Create(storageLocation1, storageLocation2)); s_allOptionsBuilder.Add(option); return option; } private static Option2<T> CreateCommonOption<T>(OptionGroup group, string name, T defaultValue, OptionStorageLocation2 storageLocation) { var option = new Option2<T>( "CodeStyleOptions", group, name, defaultValue, ImmutableArray.Create(storageLocation)); s_allOptionsBuilder.Add(option); return option; } private static Option2<T> CreateCommonOption<T>( OptionGroup group, string name, T defaultValue, OptionStorageLocation2 storageLocation1, OptionStorageLocation2 storageLocation2) { var option = new Option2<T>( "CodeStyleOptions", group, name, defaultValue, ImmutableArray.Create(storageLocation1, storageLocation2)); s_allOptionsBuilder.Add(option); return option; } /// <remarks> /// When user preferences are not yet set for a style, we fall back to the default value. /// One such default(s), is that the feature is turned on, so that codegen consumes it, /// but with silent enforcement, so that the user is not prompted about their usage. /// </remarks> internal static readonly CodeStyleOption2<bool> TrueWithSilentEnforcement = new(value: true, notification: NotificationOption2.Silent); internal static readonly CodeStyleOption2<bool> FalseWithSilentEnforcement = new(value: false, notification: NotificationOption2.Silent); internal static readonly CodeStyleOption2<bool> TrueWithSuggestionEnforcement = new(value: true, notification: NotificationOption2.Suggestion); internal static readonly CodeStyleOption2<bool> FalseWithSuggestionEnforcement = new(value: false, notification: NotificationOption2.Suggestion); private static PerLanguageOption2<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 PerLanguageOption2<CodeStyleOption2<bool>> CreateQualifyAccessOption(string optionName, string editorconfigKeyName) => CreateOption( CodeStyleOptionGroups.ThisOrMe, optionName, defaultValue: CodeStyleOption2<bool>.Default, editorconfigKeyName, $"TextEditor.%LANGUAGE%.Specific.{optionName}"); /// <summary> /// This option says if we should simplify away the <see langword="this"/>. or <see langword="Me"/>. in field access expressions. /// </summary> public static readonly PerLanguageOption2<CodeStyleOption2<bool>> QualifyFieldAccess = CreateQualifyAccessOption( nameof(QualifyFieldAccess), "dotnet_style_qualification_for_field"); /// <summary> /// This option says if we should simplify away the <see langword="this"/>. or <see langword="Me"/>. in property access expressions. /// </summary> public static readonly PerLanguageOption2<CodeStyleOption2<bool>> QualifyPropertyAccess = CreateQualifyAccessOption( nameof(QualifyPropertyAccess), "dotnet_style_qualification_for_property"); /// <summary> /// This option says if we should simplify away the <see langword="this"/>. or <see langword="Me"/>. in method access expressions. /// </summary> public static readonly PerLanguageOption2<CodeStyleOption2<bool>> QualifyMethodAccess = CreateQualifyAccessOption( nameof(QualifyMethodAccess), "dotnet_style_qualification_for_method"); /// <summary> /// This option says if we should simplify away the <see langword="this"/>. or <see langword="Me"/>. in event access expressions. /// </summary> public static readonly PerLanguageOption2<CodeStyleOption2<bool>> QualifyEventAccess = CreateQualifyAccessOption( nameof(QualifyEventAccess), "dotnet_style_qualification_for_event"); /// <summary> /// This option says if we should prefer keyword for Intrinsic Predefined Types in Declarations /// </summary> public static readonly PerLanguageOption2<CodeStyleOption2<bool>> PreferIntrinsicPredefinedTypeKeywordInDeclaration = CreateOption( CodeStyleOptionGroups.PredefinedTypeNameUsage, nameof(PreferIntrinsicPredefinedTypeKeywordInDeclaration), defaultValue: TrueWithSilentEnforcement, "dotnet_style_predefined_type_for_locals_parameters_members", "TextEditor.%LANGUAGE%.Specific.PreferIntrinsicPredefinedTypeKeywordInDeclaration.CodeStyle"); /// <summary> /// This option says if we should prefer keyword for Intrinsic Predefined Types in Member Access Expression /// </summary> public static readonly PerLanguageOption2<CodeStyleOption2<bool>> PreferIntrinsicPredefinedTypeKeywordInMemberAccess = CreateOption( CodeStyleOptionGroups.PredefinedTypeNameUsage, nameof(PreferIntrinsicPredefinedTypeKeywordInMemberAccess), defaultValue: TrueWithSilentEnforcement, "dotnet_style_predefined_type_for_member_access", "TextEditor.%LANGUAGE%.Specific.PreferIntrinsicPredefinedTypeKeywordInMemberAccess.CodeStyle"); internal static readonly PerLanguageOption2<CodeStyleOption2<bool>> PreferObjectInitializer = CreateOption( CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferObjectInitializer), defaultValue: TrueWithSuggestionEnforcement, "dotnet_style_object_initializer", "TextEditor.%LANGUAGE%.Specific.PreferObjectInitializer"); internal static readonly PerLanguageOption2<CodeStyleOption2<bool>> PreferCollectionInitializer = CreateOption( CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferCollectionInitializer), defaultValue: TrueWithSuggestionEnforcement, "dotnet_style_collection_initializer", "TextEditor.%LANGUAGE%.Specific.PreferCollectionInitializer"); // TODO: Should both the below "_FadeOutCode" options be added to AllOptions? internal static readonly PerLanguageOption2<bool> PreferObjectInitializer_FadeOutCode = new( "CodeStyleOptions", nameof(PreferObjectInitializer_FadeOutCode), defaultValue: false, storageLocation: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.PreferObjectInitializer_FadeOutCode")); internal static readonly PerLanguageOption2<bool> PreferCollectionInitializer_FadeOutCode = new( "CodeStyleOptions", nameof(PreferCollectionInitializer_FadeOutCode), defaultValue: false, storageLocation: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.PreferCollectionInitializer_FadeOutCode")); internal static readonly PerLanguageOption2<CodeStyleOption2<bool>> PreferSimplifiedBooleanExpressions = CreateOption( CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferSimplifiedBooleanExpressions), defaultValue: TrueWithSuggestionEnforcement, "dotnet_style_prefer_simplified_boolean_expressions", "TextEditor.%LANGUAGE%.Specific.PreferSimplifiedBooleanExpressions"); internal static readonly PerLanguageOption2<OperatorPlacementWhenWrappingPreference> OperatorPlacementWhenWrapping = CreateOption( CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(OperatorPlacementWhenWrapping), defaultValue: OperatorPlacementWhenWrappingPreference.BeginningOfLine, new EditorConfigStorageLocation<OperatorPlacementWhenWrappingPreference>( "dotnet_style_operator_placement_when_wrapping", OperatorPlacementUtilities.Parse, OperatorPlacementUtilities.GetEditorConfigString)); internal static readonly PerLanguageOption2<CodeStyleOption2<bool>> PreferCoalesceExpression = CreateOption( CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferCoalesceExpression), defaultValue: TrueWithSuggestionEnforcement, "dotnet_style_coalesce_expression", "TextEditor.%LANGUAGE%.Specific.PreferCoalesceExpression"); internal static readonly PerLanguageOption2<CodeStyleOption2<bool>> PreferNullPropagation = CreateOption( CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferNullPropagation), defaultValue: TrueWithSuggestionEnforcement, "dotnet_style_null_propagation", "TextEditor.%LANGUAGE%.Specific.PreferNullPropagation"); internal static readonly PerLanguageOption2<CodeStyleOption2<bool>> PreferExplicitTupleNames = CreateOption( CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferExplicitTupleNames), defaultValue: TrueWithSuggestionEnforcement, "dotnet_style_explicit_tuple_names", "TextEditor.%LANGUAGE%.Specific.PreferExplicitTupleNames"); internal static readonly PerLanguageOption2<CodeStyleOption2<bool>> PreferAutoProperties = CreateOption( CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferAutoProperties), defaultValue: TrueWithSilentEnforcement, "dotnet_style_prefer_auto_properties", "TextEditor.%LANGUAGE%.Specific.PreferAutoProperties"); internal static readonly PerLanguageOption2<CodeStyleOption2<bool>> PreferInferredTupleNames = CreateOption( CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferInferredTupleNames), defaultValue: TrueWithSuggestionEnforcement, "dotnet_style_prefer_inferred_tuple_names", $"TextEditor.%LANGUAGE%.Specific.{nameof(PreferInferredTupleNames)}"); internal static readonly PerLanguageOption2<CodeStyleOption2<bool>> PreferInferredAnonymousTypeMemberNames = CreateOption( CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferInferredAnonymousTypeMemberNames), defaultValue: TrueWithSuggestionEnforcement, "dotnet_style_prefer_inferred_anonymous_type_member_names", $"TextEditor.%LANGUAGE%.Specific.{nameof(PreferInferredAnonymousTypeMemberNames)}"); internal static readonly PerLanguageOption2<CodeStyleOption2<bool>> PreferIsNullCheckOverReferenceEqualityMethod = CreateOption( CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferIsNullCheckOverReferenceEqualityMethod), defaultValue: TrueWithSuggestionEnforcement, "dotnet_style_prefer_is_null_check_over_reference_equality_method", $"TextEditor.%LANGUAGE%.Specific.{nameof(PreferIsNullCheckOverReferenceEqualityMethod)}"); internal static readonly PerLanguageOption2<CodeStyleOption2<bool>> PreferConditionalExpressionOverAssignment = CreateOption( CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferConditionalExpressionOverAssignment), defaultValue: TrueWithSilentEnforcement, "dotnet_style_prefer_conditional_expression_over_assignment", "TextEditor.%LANGUAGE%.Specific.PreferConditionalExpressionOverAssignment"); internal static readonly PerLanguageOption2<CodeStyleOption2<bool>> PreferConditionalExpressionOverReturn = CreateOption( CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferConditionalExpressionOverReturn), defaultValue: TrueWithSilentEnforcement, "dotnet_style_prefer_conditional_expression_over_return", "TextEditor.%LANGUAGE%.Specific.PreferConditionalExpressionOverReturn"); internal static readonly PerLanguageOption2<CodeStyleOption2<bool>> PreferCompoundAssignment = CreateOption( CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferCompoundAssignment), defaultValue: TrueWithSuggestionEnforcement, "dotnet_style_prefer_compound_assignment", "TextEditor.%LANGUAGE%.Specific.PreferCompoundAssignment"); internal static readonly PerLanguageOption2<CodeStyleOption2<bool>> PreferSimplifiedInterpolation = CreateOption( CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferSimplifiedInterpolation), defaultValue: TrueWithSuggestionEnforcement, "dotnet_style_prefer_simplified_interpolation", $"TextEditor.%LANGUAGE%.Specific.{nameof(PreferSimplifiedInterpolation)}"); private static readonly CodeStyleOption2<UnusedParametersPreference> s_preferAllMethodsUnusedParametersPreference = new(UnusedParametersPreference.AllMethods, NotificationOption2.Suggestion); // TODO: https://github.com/dotnet/roslyn/issues/31225 tracks adding CodeQualityOption<T> and CodeQualityOptions // and moving this option to CodeQualityOptions. internal static readonly PerLanguageOption2<CodeStyleOption2<UnusedParametersPreference>> UnusedParameters = CreateOption( CodeStyleOptionGroups.Parameter, nameof(UnusedParameters), defaultValue: s_preferAllMethodsUnusedParametersPreference, new EditorConfigStorageLocation<CodeStyleOption2<UnusedParametersPreference>>( "dotnet_code_quality_unused_parameters", s => ParseUnusedParametersPreference(s, s_preferAllMethodsUnusedParametersPreference), o => GetUnusedParametersPreferenceEditorConfigString(o, s_preferAllMethodsUnusedParametersPreference)), new RoamingProfileStorageLocation($"TextEditor.%LANGUAGE%.Specific.{nameof(UnusedParameters)}Preference")); private static readonly CodeStyleOption2<AccessibilityModifiersRequired> s_requireAccessibilityModifiersDefault = new(AccessibilityModifiersRequired.ForNonInterfaceMembers, NotificationOption2.Silent); internal static readonly PerLanguageOption2<CodeStyleOption2<AccessibilityModifiersRequired>> RequireAccessibilityModifiers = CreateOption( CodeStyleOptionGroups.Modifier, nameof(RequireAccessibilityModifiers), defaultValue: s_requireAccessibilityModifiersDefault, new EditorConfigStorageLocation<CodeStyleOption2<AccessibilityModifiersRequired>>( "dotnet_style_require_accessibility_modifiers", s => ParseAccessibilityModifiersRequired(s, s_requireAccessibilityModifiersDefault), v => GetAccessibilityModifiersRequiredEditorConfigString(v, s_requireAccessibilityModifiersDefault)), new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.RequireAccessibilityModifiers")); internal static readonly PerLanguageOption2<CodeStyleOption2<bool>> PreferReadonly = CreateOption( CodeStyleOptionGroups.Field, nameof(PreferReadonly), defaultValue: TrueWithSuggestionEnforcement, "dotnet_style_readonly_field", "TextEditor.%LANGUAGE%.Specific.PreferReadonly"); internal static readonly Option2<string> FileHeaderTemplate = CreateCommonOption( CodeStyleOptionGroups.Usings, nameof(FileHeaderTemplate), defaultValue: "", EditorConfigStorageLocation.ForStringOption("file_header_template", emptyStringRepresentation: "unset")); internal static readonly Option2<string> RemoveUnnecessarySuppressionExclusions = CreateCommonOption( CodeStyleOptionGroups.Suppressions, nameof(RemoveUnnecessarySuppressionExclusions), defaultValue: "", EditorConfigStorageLocation.ForStringOption("dotnet_remove_unnecessary_suppression_exclusions", emptyStringRepresentation: "none"), new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.RemoveUnnecessarySuppressionExclusions")); private static readonly BidirectionalMap<string, AccessibilityModifiersRequired> s_accessibilityModifiersRequiredMap = new(new[] { KeyValuePairUtil.Create("never", AccessibilityModifiersRequired.Never), KeyValuePairUtil.Create("always", AccessibilityModifiersRequired.Always), KeyValuePairUtil.Create("for_non_interface_members", AccessibilityModifiersRequired.ForNonInterfaceMembers), KeyValuePairUtil.Create("omit_if_default", AccessibilityModifiersRequired.OmitIfDefault), }); private static CodeStyleOption2<AccessibilityModifiersRequired> ParseAccessibilityModifiersRequired(string optionString, CodeStyleOption2<AccessibilityModifiersRequired> defaultValue) { if (TryGetCodeStyleValueAndOptionalNotification(optionString, defaultValue.Notification, out var value, out var notificationOpt)) { Debug.Assert(s_accessibilityModifiersRequiredMap.ContainsKey(value)); return new CodeStyleOption2<AccessibilityModifiersRequired>(s_accessibilityModifiersRequiredMap.GetValueOrDefault(value), notificationOpt); } return s_requireAccessibilityModifiersDefault; } private static string GetAccessibilityModifiersRequiredEditorConfigString(CodeStyleOption2<AccessibilityModifiersRequired> option, CodeStyleOption2<AccessibilityModifiersRequired> defaultValue) { // If they provide 'never', they don't need a notification level. if (option.Notification == null) { Debug.Assert(s_accessibilityModifiersRequiredMap.ContainsValue(AccessibilityModifiersRequired.Never)); return s_accessibilityModifiersRequiredMap.GetKeyOrDefault(AccessibilityModifiersRequired.Never)!; } Debug.Assert(s_accessibilityModifiersRequiredMap.ContainsValue(option.Value)); return $"{s_accessibilityModifiersRequiredMap.GetKeyOrDefault(option.Value)}{GetEditorConfigStringNotificationPart(option, defaultValue)}"; } private static readonly CodeStyleOption2<ParenthesesPreference> s_alwaysForClarityPreference = new(ParenthesesPreference.AlwaysForClarity, NotificationOption2.Silent); private static readonly CodeStyleOption2<ParenthesesPreference> s_neverIfUnnecessaryPreference = new(ParenthesesPreference.NeverIfUnnecessary, NotificationOption2.Silent); private static PerLanguageOption2<CodeStyleOption2<ParenthesesPreference>> CreateParenthesesOption( string fieldName, CodeStyleOption2<ParenthesesPreference> defaultValue, string styleName) { return CreateOption( CodeStyleOptionGroups.Parentheses, fieldName, defaultValue, new EditorConfigStorageLocation<CodeStyleOption2<ParenthesesPreference>>( styleName, s => ParseParenthesesPreference(s, defaultValue), v => GetParenthesesPreferenceEditorConfigString(v, defaultValue)), new RoamingProfileStorageLocation($"TextEditor.%LANGUAGE%.Specific.{fieldName}Preference")); } internal static readonly PerLanguageOption2<CodeStyleOption2<ParenthesesPreference>> ArithmeticBinaryParentheses = CreateParenthesesOption( nameof(ArithmeticBinaryParentheses), s_alwaysForClarityPreference, "dotnet_style_parentheses_in_arithmetic_binary_operators"); internal static readonly PerLanguageOption2<CodeStyleOption2<ParenthesesPreference>> OtherBinaryParentheses = CreateParenthesesOption( nameof(OtherBinaryParentheses), s_alwaysForClarityPreference, "dotnet_style_parentheses_in_other_binary_operators"); internal static readonly PerLanguageOption2<CodeStyleOption2<ParenthesesPreference>> RelationalBinaryParentheses = CreateParenthesesOption( nameof(RelationalBinaryParentheses), s_alwaysForClarityPreference, "dotnet_style_parentheses_in_relational_binary_operators"); internal static readonly PerLanguageOption2<CodeStyleOption2<ParenthesesPreference>> OtherParentheses = CreateParenthesesOption( nameof(OtherParentheses), s_neverIfUnnecessaryPreference, "dotnet_style_parentheses_in_other_operators"); private static readonly BidirectionalMap<string, ParenthesesPreference> s_parenthesesPreferenceMap = new(new[] { KeyValuePairUtil.Create("always_for_clarity", ParenthesesPreference.AlwaysForClarity), KeyValuePairUtil.Create("never_if_unnecessary", ParenthesesPreference.NeverIfUnnecessary), }); private static readonly BidirectionalMap<string, UnusedParametersPreference> s_unusedParametersPreferenceMap = new(new[] { KeyValuePairUtil.Create("non_public", UnusedParametersPreference.NonPublicMethods), KeyValuePairUtil.Create("all", UnusedParametersPreference.AllMethods), }); internal static readonly PerLanguageOption2<CodeStyleOption2<bool>> PreferSystemHashCode = CreateOption( CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferSystemHashCode), defaultValue: TrueWithSuggestionEnforcement, new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.PreferSystemHashCode")); public static readonly PerLanguageOption2<CodeStyleOption2<bool>> PreferNamespaceAndFolderMatchStructure = CreateOption( CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferNamespaceAndFolderMatchStructure), defaultValue: TrueWithSuggestionEnforcement, editorconfigKeyName: "dotnet_style_namespace_match_folder", roamingProfileStorageKeyName: $"TextEditor.%LANGUAGE%.Specific.{nameof(PreferNamespaceAndFolderMatchStructure)}"); internal static readonly PerLanguageOption2<CodeStyleOption2<bool>> AllowMultipleBlankLines = CreateOption( CodeStyleOptionGroups.NewLinePreferences, nameof(AllowMultipleBlankLines), defaultValue: TrueWithSilentEnforcement, "dotnet_style_allow_multiple_blank_lines_experimental", "TextEditor.%LANGUAGE%.Specific.AllowMultipleBlankLines"); internal static readonly PerLanguageOption2<CodeStyleOption2<bool>> AllowStatementImmediatelyAfterBlock = CreateOption( CodeStyleOptionGroups.NewLinePreferences, nameof(AllowStatementImmediatelyAfterBlock), defaultValue: TrueWithSilentEnforcement, "dotnet_style_allow_statement_immediately_after_block_experimental", "TextEditor.%LANGUAGE%.Specific.AllowStatementImmediatelyAfterBlock"); static CodeStyleOptions2() { // 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(); } private static CodeStyleOption2<ParenthesesPreference> ParseParenthesesPreference( string optionString, CodeStyleOption2<ParenthesesPreference> defaultValue) { if (TryGetCodeStyleValueAndOptionalNotification(optionString, defaultValue.Notification, out var value, out var notification)) { Debug.Assert(s_parenthesesPreferenceMap.ContainsKey(value)); return new CodeStyleOption2<ParenthesesPreference>(s_parenthesesPreferenceMap.GetValueOrDefault(value), notification); } return defaultValue; } private static string GetParenthesesPreferenceEditorConfigString(CodeStyleOption2<ParenthesesPreference> option, CodeStyleOption2<ParenthesesPreference> defaultValue) { Debug.Assert(s_parenthesesPreferenceMap.ContainsValue(option.Value)); var value = s_parenthesesPreferenceMap.GetKeyOrDefault(option.Value) ?? s_parenthesesPreferenceMap.GetKeyOrDefault(ParenthesesPreference.AlwaysForClarity); return option.Notification == null ? value! : $"{value}{GetEditorConfigStringNotificationPart(option, defaultValue)}"; } private static CodeStyleOption2<UnusedParametersPreference> ParseUnusedParametersPreference(string optionString, CodeStyleOption2<UnusedParametersPreference> defaultValue) { if (TryGetCodeStyleValueAndOptionalNotification(optionString, defaultValue.Notification, out var value, out var notification)) { return new CodeStyleOption2<UnusedParametersPreference>(s_unusedParametersPreferenceMap.GetValueOrDefault(value), notification); } return defaultValue; } private static string GetUnusedParametersPreferenceEditorConfigString(CodeStyleOption2<UnusedParametersPreference> option, CodeStyleOption2<UnusedParametersPreference> defaultValue) { Debug.Assert(s_unusedParametersPreferenceMap.ContainsValue(option.Value)); var value = s_unusedParametersPreferenceMap.GetKeyOrDefault(option.Value) ?? s_unusedParametersPreferenceMap.GetKeyOrDefault(defaultValue.Value); return option.Notification == null ? value! : $"{value}{GetEditorConfigStringNotificationPart(option, defaultValue)}"; } } internal static class CodeStyleOptionGroups { public static readonly OptionGroup Usings = new(CompilerExtensionsResources.Organize_usings, priority: 1); public static readonly OptionGroup ThisOrMe = new(CompilerExtensionsResources.this_dot_and_Me_dot_preferences, priority: 2); public static readonly OptionGroup PredefinedTypeNameUsage = new(CompilerExtensionsResources.Language_keywords_vs_BCL_types_preferences, priority: 3); public static readonly OptionGroup Parentheses = new(CompilerExtensionsResources.Parentheses_preferences, priority: 4); public static readonly OptionGroup Modifier = new(CompilerExtensionsResources.Modifier_preferences, priority: 5); public static readonly OptionGroup ExpressionLevelPreferences = new(CompilerExtensionsResources.Expression_level_preferences, priority: 6); public static readonly OptionGroup Field = new(CompilerExtensionsResources.Field_preferences, priority: 7); public static readonly OptionGroup Parameter = new(CompilerExtensionsResources.Parameter_preferences, priority: 8); public static readonly OptionGroup Suppressions = new(CompilerExtensionsResources.Suppression_preferences, priority: 9); public static readonly OptionGroup NewLinePreferences = new(CompilerExtensionsResources.New_line_preferences, priority: 10); } }
// Licensed to the .NET Foundation under one or more 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.Diagnostics; using Microsoft.CodeAnalysis.Options; using Roslyn.Utilities; using static Microsoft.CodeAnalysis.CodeStyle.CodeStyleHelpers; namespace Microsoft.CodeAnalysis.CodeStyle { internal static class CodeStyleOptions2 { private static readonly ImmutableArray<IOption2>.Builder s_allOptionsBuilder = ImmutableArray.CreateBuilder<IOption2>(); internal static ImmutableArray<IOption2> AllOptions { get; } private static PerLanguageOption2<T> CreateOption<T>( OptionGroup group, string name, T defaultValue, OptionStorageLocation2 storageLocation) { var option = new PerLanguageOption2<T>( "CodeStyleOptions", group, name, defaultValue, ImmutableArray.Create(storageLocation)); s_allOptionsBuilder.Add(option); return option; } private static PerLanguageOption2<T> CreateOption<T>( OptionGroup group, string name, T defaultValue, OptionStorageLocation2 storageLocation1, OptionStorageLocation2 storageLocation2) { var option = new PerLanguageOption2<T>( "CodeStyleOptions", group, name, defaultValue, ImmutableArray.Create(storageLocation1, storageLocation2)); s_allOptionsBuilder.Add(option); return option; } private static Option2<T> CreateCommonOption<T>(OptionGroup group, string name, T defaultValue, OptionStorageLocation2 storageLocation) { var option = new Option2<T>( "CodeStyleOptions", group, name, defaultValue, ImmutableArray.Create(storageLocation)); s_allOptionsBuilder.Add(option); return option; } private static Option2<T> CreateCommonOption<T>( OptionGroup group, string name, T defaultValue, OptionStorageLocation2 storageLocation1, OptionStorageLocation2 storageLocation2) { var option = new Option2<T>( "CodeStyleOptions", group, name, defaultValue, ImmutableArray.Create(storageLocation1, storageLocation2)); s_allOptionsBuilder.Add(option); return option; } /// <remarks> /// When user preferences are not yet set for a style, we fall back to the default value. /// One such default(s), is that the feature is turned on, so that codegen consumes it, /// but with silent enforcement, so that the user is not prompted about their usage. /// </remarks> internal static readonly CodeStyleOption2<bool> TrueWithSilentEnforcement = new(value: true, notification: NotificationOption2.Silent); internal static readonly CodeStyleOption2<bool> FalseWithSilentEnforcement = new(value: false, notification: NotificationOption2.Silent); internal static readonly CodeStyleOption2<bool> TrueWithSuggestionEnforcement = new(value: true, notification: NotificationOption2.Suggestion); internal static readonly CodeStyleOption2<bool> FalseWithSuggestionEnforcement = new(value: false, notification: NotificationOption2.Suggestion); private static PerLanguageOption2<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 PerLanguageOption2<CodeStyleOption2<bool>> CreateQualifyAccessOption(string optionName, string editorconfigKeyName) => CreateOption( CodeStyleOptionGroups.ThisOrMe, optionName, defaultValue: CodeStyleOption2<bool>.Default, editorconfigKeyName, $"TextEditor.%LANGUAGE%.Specific.{optionName}"); /// <summary> /// This option says if we should simplify away the <see langword="this"/>. or <see langword="Me"/>. in field access expressions. /// </summary> public static readonly PerLanguageOption2<CodeStyleOption2<bool>> QualifyFieldAccess = CreateQualifyAccessOption( nameof(QualifyFieldAccess), "dotnet_style_qualification_for_field"); /// <summary> /// This option says if we should simplify away the <see langword="this"/>. or <see langword="Me"/>. in property access expressions. /// </summary> public static readonly PerLanguageOption2<CodeStyleOption2<bool>> QualifyPropertyAccess = CreateQualifyAccessOption( nameof(QualifyPropertyAccess), "dotnet_style_qualification_for_property"); /// <summary> /// This option says if we should simplify away the <see langword="this"/>. or <see langword="Me"/>. in method access expressions. /// </summary> public static readonly PerLanguageOption2<CodeStyleOption2<bool>> QualifyMethodAccess = CreateQualifyAccessOption( nameof(QualifyMethodAccess), "dotnet_style_qualification_for_method"); /// <summary> /// This option says if we should simplify away the <see langword="this"/>. or <see langword="Me"/>. in event access expressions. /// </summary> public static readonly PerLanguageOption2<CodeStyleOption2<bool>> QualifyEventAccess = CreateQualifyAccessOption( nameof(QualifyEventAccess), "dotnet_style_qualification_for_event"); /// <summary> /// This option says if we should prefer keyword for Intrinsic Predefined Types in Declarations /// </summary> public static readonly PerLanguageOption2<CodeStyleOption2<bool>> PreferIntrinsicPredefinedTypeKeywordInDeclaration = CreateOption( CodeStyleOptionGroups.PredefinedTypeNameUsage, nameof(PreferIntrinsicPredefinedTypeKeywordInDeclaration), defaultValue: TrueWithSilentEnforcement, "dotnet_style_predefined_type_for_locals_parameters_members", "TextEditor.%LANGUAGE%.Specific.PreferIntrinsicPredefinedTypeKeywordInDeclaration.CodeStyle"); /// <summary> /// This option says if we should prefer keyword for Intrinsic Predefined Types in Member Access Expression /// </summary> public static readonly PerLanguageOption2<CodeStyleOption2<bool>> PreferIntrinsicPredefinedTypeKeywordInMemberAccess = CreateOption( CodeStyleOptionGroups.PredefinedTypeNameUsage, nameof(PreferIntrinsicPredefinedTypeKeywordInMemberAccess), defaultValue: TrueWithSilentEnforcement, "dotnet_style_predefined_type_for_member_access", "TextEditor.%LANGUAGE%.Specific.PreferIntrinsicPredefinedTypeKeywordInMemberAccess.CodeStyle"); internal static readonly PerLanguageOption2<CodeStyleOption2<bool>> PreferObjectInitializer = CreateOption( CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferObjectInitializer), defaultValue: TrueWithSuggestionEnforcement, "dotnet_style_object_initializer", "TextEditor.%LANGUAGE%.Specific.PreferObjectInitializer"); internal static readonly PerLanguageOption2<CodeStyleOption2<bool>> PreferCollectionInitializer = CreateOption( CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferCollectionInitializer), defaultValue: TrueWithSuggestionEnforcement, "dotnet_style_collection_initializer", "TextEditor.%LANGUAGE%.Specific.PreferCollectionInitializer"); // TODO: Should both the below "_FadeOutCode" options be added to AllOptions? internal static readonly PerLanguageOption2<bool> PreferObjectInitializer_FadeOutCode = new( "CodeStyleOptions", nameof(PreferObjectInitializer_FadeOutCode), defaultValue: false, storageLocation: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.PreferObjectInitializer_FadeOutCode")); internal static readonly PerLanguageOption2<bool> PreferCollectionInitializer_FadeOutCode = new( "CodeStyleOptions", nameof(PreferCollectionInitializer_FadeOutCode), defaultValue: false, storageLocation: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.PreferCollectionInitializer_FadeOutCode")); internal static readonly PerLanguageOption2<CodeStyleOption2<bool>> PreferSimplifiedBooleanExpressions = CreateOption( CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferSimplifiedBooleanExpressions), defaultValue: TrueWithSuggestionEnforcement, "dotnet_style_prefer_simplified_boolean_expressions", "TextEditor.%LANGUAGE%.Specific.PreferSimplifiedBooleanExpressions"); internal static readonly PerLanguageOption2<OperatorPlacementWhenWrappingPreference> OperatorPlacementWhenWrapping = CreateOption( CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(OperatorPlacementWhenWrapping), defaultValue: OperatorPlacementWhenWrappingPreference.BeginningOfLine, new EditorConfigStorageLocation<OperatorPlacementWhenWrappingPreference>( "dotnet_style_operator_placement_when_wrapping", OperatorPlacementUtilities.Parse, OperatorPlacementUtilities.GetEditorConfigString)); internal static readonly PerLanguageOption2<CodeStyleOption2<bool>> PreferCoalesceExpression = CreateOption( CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferCoalesceExpression), defaultValue: TrueWithSuggestionEnforcement, "dotnet_style_coalesce_expression", "TextEditor.%LANGUAGE%.Specific.PreferCoalesceExpression"); internal static readonly PerLanguageOption2<CodeStyleOption2<bool>> PreferNullPropagation = CreateOption( CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferNullPropagation), defaultValue: TrueWithSuggestionEnforcement, "dotnet_style_null_propagation", "TextEditor.%LANGUAGE%.Specific.PreferNullPropagation"); internal static readonly PerLanguageOption2<CodeStyleOption2<bool>> PreferExplicitTupleNames = CreateOption( CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferExplicitTupleNames), defaultValue: TrueWithSuggestionEnforcement, "dotnet_style_explicit_tuple_names", "TextEditor.%LANGUAGE%.Specific.PreferExplicitTupleNames"); internal static readonly PerLanguageOption2<CodeStyleOption2<bool>> PreferAutoProperties = CreateOption( CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferAutoProperties), defaultValue: TrueWithSilentEnforcement, "dotnet_style_prefer_auto_properties", "TextEditor.%LANGUAGE%.Specific.PreferAutoProperties"); internal static readonly PerLanguageOption2<CodeStyleOption2<bool>> PreferInferredTupleNames = CreateOption( CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferInferredTupleNames), defaultValue: TrueWithSuggestionEnforcement, "dotnet_style_prefer_inferred_tuple_names", $"TextEditor.%LANGUAGE%.Specific.{nameof(PreferInferredTupleNames)}"); internal static readonly PerLanguageOption2<CodeStyleOption2<bool>> PreferInferredAnonymousTypeMemberNames = CreateOption( CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferInferredAnonymousTypeMemberNames), defaultValue: TrueWithSuggestionEnforcement, "dotnet_style_prefer_inferred_anonymous_type_member_names", $"TextEditor.%LANGUAGE%.Specific.{nameof(PreferInferredAnonymousTypeMemberNames)}"); internal static readonly PerLanguageOption2<CodeStyleOption2<bool>> PreferIsNullCheckOverReferenceEqualityMethod = CreateOption( CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferIsNullCheckOverReferenceEqualityMethod), defaultValue: TrueWithSuggestionEnforcement, "dotnet_style_prefer_is_null_check_over_reference_equality_method", $"TextEditor.%LANGUAGE%.Specific.{nameof(PreferIsNullCheckOverReferenceEqualityMethod)}"); internal static readonly PerLanguageOption2<CodeStyleOption2<bool>> PreferConditionalExpressionOverAssignment = CreateOption( CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferConditionalExpressionOverAssignment), defaultValue: TrueWithSilentEnforcement, "dotnet_style_prefer_conditional_expression_over_assignment", "TextEditor.%LANGUAGE%.Specific.PreferConditionalExpressionOverAssignment"); internal static readonly PerLanguageOption2<CodeStyleOption2<bool>> PreferConditionalExpressionOverReturn = CreateOption( CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferConditionalExpressionOverReturn), defaultValue: TrueWithSilentEnforcement, "dotnet_style_prefer_conditional_expression_over_return", "TextEditor.%LANGUAGE%.Specific.PreferConditionalExpressionOverReturn"); internal static readonly PerLanguageOption2<CodeStyleOption2<bool>> PreferCompoundAssignment = CreateOption( CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferCompoundAssignment), defaultValue: TrueWithSuggestionEnforcement, "dotnet_style_prefer_compound_assignment", "TextEditor.%LANGUAGE%.Specific.PreferCompoundAssignment"); internal static readonly PerLanguageOption2<CodeStyleOption2<bool>> PreferSimplifiedInterpolation = CreateOption( CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferSimplifiedInterpolation), defaultValue: TrueWithSuggestionEnforcement, "dotnet_style_prefer_simplified_interpolation", $"TextEditor.%LANGUAGE%.Specific.{nameof(PreferSimplifiedInterpolation)}"); private static readonly CodeStyleOption2<UnusedParametersPreference> s_preferAllMethodsUnusedParametersPreference = new(UnusedParametersPreference.AllMethods, NotificationOption2.Suggestion); // TODO: https://github.com/dotnet/roslyn/issues/31225 tracks adding CodeQualityOption<T> and CodeQualityOptions // and moving this option to CodeQualityOptions. internal static readonly PerLanguageOption2<CodeStyleOption2<UnusedParametersPreference>> UnusedParameters = CreateOption( CodeStyleOptionGroups.Parameter, nameof(UnusedParameters), defaultValue: s_preferAllMethodsUnusedParametersPreference, new EditorConfigStorageLocation<CodeStyleOption2<UnusedParametersPreference>>( "dotnet_code_quality_unused_parameters", s => ParseUnusedParametersPreference(s, s_preferAllMethodsUnusedParametersPreference), o => GetUnusedParametersPreferenceEditorConfigString(o, s_preferAllMethodsUnusedParametersPreference)), new RoamingProfileStorageLocation($"TextEditor.%LANGUAGE%.Specific.{nameof(UnusedParameters)}Preference")); private static readonly CodeStyleOption2<AccessibilityModifiersRequired> s_requireAccessibilityModifiersDefault = new(AccessibilityModifiersRequired.ForNonInterfaceMembers, NotificationOption2.Silent); internal static readonly PerLanguageOption2<CodeStyleOption2<AccessibilityModifiersRequired>> RequireAccessibilityModifiers = CreateOption( CodeStyleOptionGroups.Modifier, nameof(RequireAccessibilityModifiers), defaultValue: s_requireAccessibilityModifiersDefault, new EditorConfigStorageLocation<CodeStyleOption2<AccessibilityModifiersRequired>>( "dotnet_style_require_accessibility_modifiers", s => ParseAccessibilityModifiersRequired(s, s_requireAccessibilityModifiersDefault), v => GetAccessibilityModifiersRequiredEditorConfigString(v, s_requireAccessibilityModifiersDefault)), new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.RequireAccessibilityModifiers")); internal static readonly PerLanguageOption2<CodeStyleOption2<bool>> PreferReadonly = CreateOption( CodeStyleOptionGroups.Field, nameof(PreferReadonly), defaultValue: TrueWithSuggestionEnforcement, "dotnet_style_readonly_field", "TextEditor.%LANGUAGE%.Specific.PreferReadonly"); internal static readonly Option2<string> FileHeaderTemplate = CreateCommonOption( CodeStyleOptionGroups.Usings, nameof(FileHeaderTemplate), defaultValue: "", EditorConfigStorageLocation.ForStringOption("file_header_template", emptyStringRepresentation: "unset")); internal static readonly Option2<string> RemoveUnnecessarySuppressionExclusions = CreateCommonOption( CodeStyleOptionGroups.Suppressions, nameof(RemoveUnnecessarySuppressionExclusions), defaultValue: "", EditorConfigStorageLocation.ForStringOption("dotnet_remove_unnecessary_suppression_exclusions", emptyStringRepresentation: "none"), new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.RemoveUnnecessarySuppressionExclusions")); private static readonly BidirectionalMap<string, AccessibilityModifiersRequired> s_accessibilityModifiersRequiredMap = new(new[] { KeyValuePairUtil.Create("never", AccessibilityModifiersRequired.Never), KeyValuePairUtil.Create("always", AccessibilityModifiersRequired.Always), KeyValuePairUtil.Create("for_non_interface_members", AccessibilityModifiersRequired.ForNonInterfaceMembers), KeyValuePairUtil.Create("omit_if_default", AccessibilityModifiersRequired.OmitIfDefault), }); private static CodeStyleOption2<AccessibilityModifiersRequired> ParseAccessibilityModifiersRequired(string optionString, CodeStyleOption2<AccessibilityModifiersRequired> defaultValue) { if (TryGetCodeStyleValueAndOptionalNotification(optionString, defaultValue.Notification, out var value, out var notificationOpt)) { Debug.Assert(s_accessibilityModifiersRequiredMap.ContainsKey(value)); return new CodeStyleOption2<AccessibilityModifiersRequired>(s_accessibilityModifiersRequiredMap.GetValueOrDefault(value), notificationOpt); } return s_requireAccessibilityModifiersDefault; } private static string GetAccessibilityModifiersRequiredEditorConfigString(CodeStyleOption2<AccessibilityModifiersRequired> option, CodeStyleOption2<AccessibilityModifiersRequired> defaultValue) { // If they provide 'never', they don't need a notification level. if (option.Notification == null) { Debug.Assert(s_accessibilityModifiersRequiredMap.ContainsValue(AccessibilityModifiersRequired.Never)); return s_accessibilityModifiersRequiredMap.GetKeyOrDefault(AccessibilityModifiersRequired.Never)!; } Debug.Assert(s_accessibilityModifiersRequiredMap.ContainsValue(option.Value)); return $"{s_accessibilityModifiersRequiredMap.GetKeyOrDefault(option.Value)}{GetEditorConfigStringNotificationPart(option, defaultValue)}"; } private static readonly CodeStyleOption2<ParenthesesPreference> s_alwaysForClarityPreference = new(ParenthesesPreference.AlwaysForClarity, NotificationOption2.Silent); private static readonly CodeStyleOption2<ParenthesesPreference> s_neverIfUnnecessaryPreference = new(ParenthesesPreference.NeverIfUnnecessary, NotificationOption2.Silent); private static PerLanguageOption2<CodeStyleOption2<ParenthesesPreference>> CreateParenthesesOption( string fieldName, CodeStyleOption2<ParenthesesPreference> defaultValue, string styleName) { return CreateOption( CodeStyleOptionGroups.Parentheses, fieldName, defaultValue, new EditorConfigStorageLocation<CodeStyleOption2<ParenthesesPreference>>( styleName, s => ParseParenthesesPreference(s, defaultValue), v => GetParenthesesPreferenceEditorConfigString(v, defaultValue)), new RoamingProfileStorageLocation($"TextEditor.%LANGUAGE%.Specific.{fieldName}Preference")); } internal static readonly PerLanguageOption2<CodeStyleOption2<ParenthesesPreference>> ArithmeticBinaryParentheses = CreateParenthesesOption( nameof(ArithmeticBinaryParentheses), s_alwaysForClarityPreference, "dotnet_style_parentheses_in_arithmetic_binary_operators"); internal static readonly PerLanguageOption2<CodeStyleOption2<ParenthesesPreference>> OtherBinaryParentheses = CreateParenthesesOption( nameof(OtherBinaryParentheses), s_alwaysForClarityPreference, "dotnet_style_parentheses_in_other_binary_operators"); internal static readonly PerLanguageOption2<CodeStyleOption2<ParenthesesPreference>> RelationalBinaryParentheses = CreateParenthesesOption( nameof(RelationalBinaryParentheses), s_alwaysForClarityPreference, "dotnet_style_parentheses_in_relational_binary_operators"); internal static readonly PerLanguageOption2<CodeStyleOption2<ParenthesesPreference>> OtherParentheses = CreateParenthesesOption( nameof(OtherParentheses), s_neverIfUnnecessaryPreference, "dotnet_style_parentheses_in_other_operators"); private static readonly BidirectionalMap<string, ParenthesesPreference> s_parenthesesPreferenceMap = new(new[] { KeyValuePairUtil.Create("always_for_clarity", ParenthesesPreference.AlwaysForClarity), KeyValuePairUtil.Create("never_if_unnecessary", ParenthesesPreference.NeverIfUnnecessary), }); private static readonly BidirectionalMap<string, UnusedParametersPreference> s_unusedParametersPreferenceMap = new(new[] { KeyValuePairUtil.Create("non_public", UnusedParametersPreference.NonPublicMethods), KeyValuePairUtil.Create("all", UnusedParametersPreference.AllMethods), }); internal static readonly PerLanguageOption2<CodeStyleOption2<bool>> PreferSystemHashCode = CreateOption( CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferSystemHashCode), defaultValue: TrueWithSuggestionEnforcement, new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.PreferSystemHashCode")); public static readonly PerLanguageOption2<CodeStyleOption2<bool>> PreferNamespaceAndFolderMatchStructure = CreateOption( CodeStyleOptionGroups.ExpressionLevelPreferences, nameof(PreferNamespaceAndFolderMatchStructure), defaultValue: TrueWithSuggestionEnforcement, editorconfigKeyName: "dotnet_style_namespace_match_folder", roamingProfileStorageKeyName: $"TextEditor.%LANGUAGE%.Specific.{nameof(PreferNamespaceAndFolderMatchStructure)}"); internal static readonly PerLanguageOption2<CodeStyleOption2<bool>> AllowMultipleBlankLines = CreateOption( CodeStyleOptionGroups.NewLinePreferences, nameof(AllowMultipleBlankLines), defaultValue: TrueWithSilentEnforcement, "dotnet_style_allow_multiple_blank_lines_experimental", "TextEditor.%LANGUAGE%.Specific.AllowMultipleBlankLines"); internal static readonly PerLanguageOption2<CodeStyleOption2<bool>> AllowStatementImmediatelyAfterBlock = CreateOption( CodeStyleOptionGroups.NewLinePreferences, nameof(AllowStatementImmediatelyAfterBlock), defaultValue: TrueWithSilentEnforcement, "dotnet_style_allow_statement_immediately_after_block_experimental", "TextEditor.%LANGUAGE%.Specific.AllowStatementImmediatelyAfterBlock"); static CodeStyleOptions2() { // 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(); } private static CodeStyleOption2<ParenthesesPreference> ParseParenthesesPreference( string optionString, CodeStyleOption2<ParenthesesPreference> defaultValue) { if (TryGetCodeStyleValueAndOptionalNotification(optionString, defaultValue.Notification, out var value, out var notification)) { Debug.Assert(s_parenthesesPreferenceMap.ContainsKey(value)); return new CodeStyleOption2<ParenthesesPreference>(s_parenthesesPreferenceMap.GetValueOrDefault(value), notification); } return defaultValue; } private static string GetParenthesesPreferenceEditorConfigString(CodeStyleOption2<ParenthesesPreference> option, CodeStyleOption2<ParenthesesPreference> defaultValue) { Debug.Assert(s_parenthesesPreferenceMap.ContainsValue(option.Value)); var value = s_parenthesesPreferenceMap.GetKeyOrDefault(option.Value) ?? s_parenthesesPreferenceMap.GetKeyOrDefault(ParenthesesPreference.AlwaysForClarity); return option.Notification == null ? value! : $"{value}{GetEditorConfigStringNotificationPart(option, defaultValue)}"; } private static CodeStyleOption2<UnusedParametersPreference> ParseUnusedParametersPreference(string optionString, CodeStyleOption2<UnusedParametersPreference> defaultValue) { if (TryGetCodeStyleValueAndOptionalNotification(optionString, defaultValue.Notification, out var value, out var notification)) { return new CodeStyleOption2<UnusedParametersPreference>(s_unusedParametersPreferenceMap.GetValueOrDefault(value), notification); } return defaultValue; } private static string GetUnusedParametersPreferenceEditorConfigString(CodeStyleOption2<UnusedParametersPreference> option, CodeStyleOption2<UnusedParametersPreference> defaultValue) { Debug.Assert(s_unusedParametersPreferenceMap.ContainsValue(option.Value)); var value = s_unusedParametersPreferenceMap.GetKeyOrDefault(option.Value) ?? s_unusedParametersPreferenceMap.GetKeyOrDefault(defaultValue.Value); return option.Notification == null ? value! : $"{value}{GetEditorConfigStringNotificationPart(option, defaultValue)}"; } } internal static class CodeStyleOptionGroups { public static readonly OptionGroup Usings = new(CompilerExtensionsResources.Organize_usings, priority: 1); public static readonly OptionGroup ThisOrMe = new(CompilerExtensionsResources.this_dot_and_Me_dot_preferences, priority: 2); public static readonly OptionGroup PredefinedTypeNameUsage = new(CompilerExtensionsResources.Language_keywords_vs_BCL_types_preferences, priority: 3); public static readonly OptionGroup Parentheses = new(CompilerExtensionsResources.Parentheses_preferences, priority: 4); public static readonly OptionGroup Modifier = new(CompilerExtensionsResources.Modifier_preferences, priority: 5); public static readonly OptionGroup ExpressionLevelPreferences = new(CompilerExtensionsResources.Expression_level_preferences, priority: 6); public static readonly OptionGroup Field = new(CompilerExtensionsResources.Field_preferences, priority: 7); public static readonly OptionGroup Parameter = new(CompilerExtensionsResources.Parameter_preferences, priority: 8); public static readonly OptionGroup Suppressions = new(CompilerExtensionsResources.Suppression_preferences, priority: 9); public static readonly OptionGroup NewLinePreferences = new(CompilerExtensionsResources.New_line_preferences, priority: 10); } }
-1
dotnet/roslyn
56,450
Implement INamespaceTypeReference.GetUnit for RootModuleType
Fixes #56412.
AlekseyTs
"2021-09-16T16:44:04Z"
"2021-09-17T18:21:59Z"
4b06ee428bafa0141c9eb3250003a19109dcfc86
d695369176aa109f0e0fb8b0019294aaa0823a54
Implement INamespaceTypeReference.GetUnit for RootModuleType. Fixes #56412.
./src/Features/CSharp/Portable/Debugging/CSharpBreakpointResolutionService.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.Composition; using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.EditAndContinue; using Microsoft.CodeAnalysis.Debugging; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.Debugging { [ExportLanguageService(typeof(IBreakpointResolutionService), LanguageNames.CSharp), Shared] internal partial class CSharpBreakpointResolutionService : IBreakpointResolutionService { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public CSharpBreakpointResolutionService() { } /// <summary> /// Returns null if a breakpoint can't be placed at the specified position. /// </summary> public async Task<BreakpointResolutionResult> ResolveBreakpointAsync(Document document, TextSpan textSpan, CancellationToken cancellationToken) { try { var tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); if (!BreakpointSpans.TryGetBreakpointSpan(tree, textSpan.Start, cancellationToken, out var span)) { return null; } if (span.Length == 0) { return BreakpointResolutionResult.CreateLineResult(document); } return BreakpointResolutionResult.CreateSpanResult(document, span); } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { return null; } } public Task<IEnumerable<BreakpointResolutionResult>> ResolveBreakpointsAsync(Solution solution, string name, CancellationToken cancellationToken) => new BreakpointResolver(solution, name).DoAsync(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; using System.Collections.Generic; using System.Composition; using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.EditAndContinue; using Microsoft.CodeAnalysis.Debugging; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.Debugging { [ExportLanguageService(typeof(IBreakpointResolutionService), LanguageNames.CSharp), Shared] internal partial class CSharpBreakpointResolutionService : IBreakpointResolutionService { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public CSharpBreakpointResolutionService() { } /// <summary> /// Returns null if a breakpoint can't be placed at the specified position. /// </summary> public async Task<BreakpointResolutionResult> ResolveBreakpointAsync(Document document, TextSpan textSpan, CancellationToken cancellationToken) { try { var tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); if (!BreakpointSpans.TryGetBreakpointSpan(tree, textSpan.Start, cancellationToken, out var span)) { return null; } if (span.Length == 0) { return BreakpointResolutionResult.CreateLineResult(document); } return BreakpointResolutionResult.CreateSpanResult(document, span); } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { return null; } } public Task<IEnumerable<BreakpointResolutionResult>> ResolveBreakpointsAsync(Solution solution, string name, CancellationToken cancellationToken) => new BreakpointResolver(solution, name).DoAsync(cancellationToken); } }
-1
dotnet/roslyn
56,450
Implement INamespaceTypeReference.GetUnit for RootModuleType
Fixes #56412.
AlekseyTs
"2021-09-16T16:44:04Z"
"2021-09-17T18:21:59Z"
4b06ee428bafa0141c9eb3250003a19109dcfc86
d695369176aa109f0e0fb8b0019294aaa0823a54
Implement INamespaceTypeReference.GetUnit for RootModuleType. Fixes #56412.
./src/VisualStudio/CSharp/Impl/Options/IntelliSenseOptionPageStrings.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.VisualStudio.LanguageServices.CSharp.Options { internal static class IntelliSenseOptionPageStrings { public static string Option_Show_completion_list_after_a_character_is_typed => CSharpVSResources.Show_completion_list_after_a_character_is_typed; public static string Option_Show_completion_list_after_a_character_is_deleted => CSharpVSResources.Show_completion_list_after_a_character_is_deleted; public static string Option_Completion { get { return CSharpVSResources.Completion; } } public static string Option_SelectionInCompletionList { get { return CSharpVSResources.Selection_In_Completion_List; } } public static string Option_ShowKeywords { get { return CSharpVSResources.Place_keywords_in_completion_lists; } } public static string Option_ShowSnippets { get { return CSharpVSResources.Place_code_snippets_in_completion_lists; } } public static string Option_Highlight_matching_portions_of_completion_list_items => CSharpVSResources.Highlight_matching_portions_of_completion_list_items; public static string Option_Show_completion_item_filters => CSharpVSResources.Show_completion_item_filters; public static string Option_Automatically_complete_statement_on_semicolon => CSharpVSResources.Automatically_complete_statement_on_semicolon; public static string Enter_key_behavior_Title => CSharpVSResources.Enter_key_behavior_colon; public static string Option_Never_add_new_line_on_enter => CSharpVSResources.Never_add_new_line_on_enter; public static string Option_Only_add_new_line_on_enter_with_whole_word => CSharpVSResources.Only_add_new_line_on_enter_after_end_of_fully_typed_word; public static string Option_Always_add_new_line_on_enter => CSharpVSResources.Always_add_new_line_on_enter; public static string Snippets_behavior => CSharpVSResources.Snippets_behavior; public static string Option_Never_include_snippets => CSharpVSResources.Never_include_snippets; public static string Option_Always_include_snippets => CSharpVSResources.Always_include_snippets; public static string Option_Include_snippets_when_question_Tab_is_typed_after_an_identifier => CSharpVSResources.Include_snippets_when_Tab_is_typed_after_an_identifier; public static string Option_Show_name_suggestions => CSharpVSResources.Show_name_suggestions; public static string Option_Show_items_from_unimported_namespaces => CSharpVSResources.Show_items_from_unimported_namespaces; public static string Option_Tab_twice_to_insert_arguments => ServicesVSResources.Tab_twice_to_insert_arguments; public static string Automatically_show_completion_list_in_argument_lists => CSharpVSResources.Automatically_show_completion_list_in_argument_lists; } }
// Licensed to the .NET Foundation under one or more 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.VisualStudio.LanguageServices.CSharp.Options { internal static class IntelliSenseOptionPageStrings { public static string Option_Show_completion_list_after_a_character_is_typed => CSharpVSResources.Show_completion_list_after_a_character_is_typed; public static string Option_Show_completion_list_after_a_character_is_deleted => CSharpVSResources.Show_completion_list_after_a_character_is_deleted; public static string Option_Completion { get { return CSharpVSResources.Completion; } } public static string Option_SelectionInCompletionList { get { return CSharpVSResources.Selection_In_Completion_List; } } public static string Option_ShowKeywords { get { return CSharpVSResources.Place_keywords_in_completion_lists; } } public static string Option_ShowSnippets { get { return CSharpVSResources.Place_code_snippets_in_completion_lists; } } public static string Option_Highlight_matching_portions_of_completion_list_items => CSharpVSResources.Highlight_matching_portions_of_completion_list_items; public static string Option_Show_completion_item_filters => CSharpVSResources.Show_completion_item_filters; public static string Option_Automatically_complete_statement_on_semicolon => CSharpVSResources.Automatically_complete_statement_on_semicolon; public static string Enter_key_behavior_Title => CSharpVSResources.Enter_key_behavior_colon; public static string Option_Never_add_new_line_on_enter => CSharpVSResources.Never_add_new_line_on_enter; public static string Option_Only_add_new_line_on_enter_with_whole_word => CSharpVSResources.Only_add_new_line_on_enter_after_end_of_fully_typed_word; public static string Option_Always_add_new_line_on_enter => CSharpVSResources.Always_add_new_line_on_enter; public static string Snippets_behavior => CSharpVSResources.Snippets_behavior; public static string Option_Never_include_snippets => CSharpVSResources.Never_include_snippets; public static string Option_Always_include_snippets => CSharpVSResources.Always_include_snippets; public static string Option_Include_snippets_when_question_Tab_is_typed_after_an_identifier => CSharpVSResources.Include_snippets_when_Tab_is_typed_after_an_identifier; public static string Option_Show_name_suggestions => CSharpVSResources.Show_name_suggestions; public static string Option_Show_items_from_unimported_namespaces => CSharpVSResources.Show_items_from_unimported_namespaces; public static string Option_Tab_twice_to_insert_arguments => ServicesVSResources.Tab_twice_to_insert_arguments; public static string Automatically_show_completion_list_in_argument_lists => CSharpVSResources.Automatically_show_completion_list_in_argument_lists; } }
-1
dotnet/roslyn
56,450
Implement INamespaceTypeReference.GetUnit for RootModuleType
Fixes #56412.
AlekseyTs
"2021-09-16T16:44:04Z"
"2021-09-17T18:21:59Z"
4b06ee428bafa0141c9eb3250003a19109dcfc86
d695369176aa109f0e0fb8b0019294aaa0823a54
Implement INamespaceTypeReference.GetUnit for RootModuleType. Fixes #56412.
./src/Analyzers/CSharp/CodeFixes/MisplacedUsingDirectives/MisplacedUsingDirectivesCodeFixProvider.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.Composition; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.AddImports; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Simplification; using Roslyn.Utilities; #if CODE_STYLE using OptionSet = Microsoft.CodeAnalysis.Diagnostics.AnalyzerConfigOptions; #else using Microsoft.CodeAnalysis.Options; #endif namespace Microsoft.CodeAnalysis.CSharp.MisplacedUsingDirectives { /// <summary> /// Implements a code fix for all misplaced using statements. /// </summary> [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.MoveMisplacedUsingDirectives)] [Shared] internal sealed partial class MisplacedUsingDirectivesCodeFixProvider : CodeFixProvider { private static readonly SyntaxAnnotation s_usingPlacementCodeFixAnnotation = new SyntaxAnnotation(nameof(s_usingPlacementCodeFixAnnotation)); [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public MisplacedUsingDirectivesCodeFixProvider() { } public override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(IDEDiagnosticIds.MoveMisplacedUsingDirectivesDiagnosticId); public override FixAllProvider GetFixAllProvider() { // Since we work on an entire document at a time fixing all contained diagnostics, the batch fixer should not have merge conflicts. return WellKnownFixAllProviders.BatchFixer; } public override async Task RegisterCodeFixesAsync(CodeFixContext context) { var document = context.Document; var cancellationToken = context.CancellationToken; var syntaxRoot = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var compilationUnit = (CompilationUnitSyntax)syntaxRoot; #if CODE_STYLE var options = document.Project.AnalyzerOptions.GetAnalyzerOptionSet(syntaxRoot.SyntaxTree, cancellationToken); #else var options = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false); #endif // Read the preferred placement option and verify if it can be applied to this code file. // There are cases where we will not be able to fix the diagnostic and the user will need to resolve // it manually. var (placement, preferPreservation) = DeterminePlacement(compilationUnit, options); if (preferPreservation) return; foreach (var diagnostic in context.Diagnostics) { context.RegisterCodeFix( new MoveMisplacedUsingsCodeAction(token => GetTransformedDocumentAsync(document, compilationUnit, GetAllUsingDirectives(compilationUnit), placement, token)), diagnostic); } } internal static async Task<Document> TransformDocumentIfRequiredAsync(Document document, CancellationToken cancellationToken) { var syntaxRoot = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var compilationUnit = (CompilationUnitSyntax)syntaxRoot; #if CODE_STYLE var options = document.Project.AnalyzerOptions.GetAnalyzerOptionSet(syntaxRoot.SyntaxTree, cancellationToken); #else var options = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false); #endif var (placement, preferPreservation) = DeterminePlacement(compilationUnit, options); if (preferPreservation) { return document; } // We are called from a diagnostic, but also for all new documents, so check if there are any usings at all // otherwise there is nothing to do. var allUsingDirectives = GetAllUsingDirectives(compilationUnit); if (allUsingDirectives.Count == 0) { return document; } return await GetTransformedDocumentAsync(document, compilationUnit, allUsingDirectives, placement, cancellationToken).ConfigureAwait(false); } private static ImmutableList<UsingDirectiveSyntax> GetAllUsingDirectives(CompilationUnitSyntax compilationUnit) { return compilationUnit .DescendantNodes(node => node is CompilationUnitSyntax or BaseNamespaceDeclarationSyntax) .OfType<UsingDirectiveSyntax>().ToImmutableList(); } private static async Task<Document> GetTransformedDocumentAsync( Document document, CompilationUnitSyntax compilationUnit, IEnumerable<UsingDirectiveSyntax> allUsingDirectives, AddImportPlacement placement, CancellationToken cancellationToken) { var bannerService = document.GetRequiredLanguageService<IFileBannerFactsService>(); // Expand usings so that they can be properly simplified after they are relocated. var compilationUnitWithExpandedUsings = await ExpandUsingDirectivesAsync(document, compilationUnit, allUsingDirectives, cancellationToken).ConfigureAwait(false); // Remove the file header from the compilation unit so that we do not lose it when making changes to usings. var (compilationUnitWithoutHeader, fileHeader) = RemoveFileHeader(compilationUnitWithExpandedUsings, bannerService); // A blanket warning that this codefix may change code so that it does not compile. var warningAnnotation = WarningAnnotation.Create(CSharpAnalyzersResources.Warning_colon_Moving_using_directives_may_change_code_meaning); var newCompilationUnit = placement == AddImportPlacement.InsideNamespace ? MoveUsingsInsideNamespace(compilationUnitWithoutHeader, warningAnnotation) : MoveUsingsOutsideNamespaces(compilationUnitWithoutHeader, warningAnnotation); // Re-attach the header now that using have been moved and LeadingTrivia is no longer being altered. var newCompilationUnitWithHeader = AddFileHeader(newCompilationUnit, fileHeader); var newDocument = document.WithSyntaxRoot(newCompilationUnitWithHeader); // Simplify usings now that they have been moved and are in the proper context. var options = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false); return await Simplifier.ReduceAsync(newDocument, Simplifier.Annotation, options, cancellationToken).ConfigureAwait(false); } private static async Task<CompilationUnitSyntax> ExpandUsingDirectivesAsync(Document document, CompilationUnitSyntax containerNode, IEnumerable<UsingDirectiveSyntax> allUsingDirectives, CancellationToken cancellationToken) { // Create a map between the original node and the future expanded node. var expandUsingDirectiveTasks = allUsingDirectives.ToDictionary( usingDirective => (SyntaxNode)usingDirective, usingDirective => ExpandUsingDirectiveAsync(document, usingDirective, cancellationToken)); // Wait for all using directives to be expanded await Task.WhenAll(expandUsingDirectiveTasks.Values).ConfigureAwait(false); // Replace using directives with their expanded version. return containerNode.ReplaceNodes( expandUsingDirectiveTasks.Keys, (node, _) => expandUsingDirectiveTasks[node].Result); } private static async Task<SyntaxNode> ExpandUsingDirectiveAsync(Document document, SyntaxNode node, CancellationToken cancellationToken) { var usingDirective = (UsingDirectiveSyntax)node; var newName = await Simplifier.ExpandAsync(usingDirective.Name, document, cancellationToken: cancellationToken).ConfigureAwait(false); return usingDirective.WithName(newName); } private static CompilationUnitSyntax MoveUsingsInsideNamespace(CompilationUnitSyntax compilationUnit, SyntaxAnnotation warningAnnotation) { // Get the compilation unit usings and set them up to format when moved. var usingsToAdd = compilationUnit.Usings.Select( directive => directive.WithAdditionalAnnotations(Formatter.Annotation, warningAnnotation)); // Remove usings and fix leading trivia for compilation unit. var compilationUnitWithoutUsings = compilationUnit.WithUsings(default); var compilationUnitWithoutBlankLine = RemoveLeadingBlankLinesFromFirstMember(compilationUnitWithoutUsings); // Fix the leading trivia for the namespace declaration. var namespaceDeclaration = (BaseNamespaceDeclarationSyntax)compilationUnitWithoutBlankLine.Members[0]; var namespaceDeclarationWithBlankLine = EnsureLeadingBlankLineBeforeFirstMember(namespaceDeclaration); // Update the namespace declaration with the usings from the compilation unit. var newUsings = namespaceDeclarationWithBlankLine.Usings.InsertRange(0, usingsToAdd); var namespaceDeclarationWithUsings = namespaceDeclarationWithBlankLine.WithUsings(newUsings); // Update the compilation unit with the new namespace declaration return compilationUnitWithoutBlankLine.ReplaceNode(namespaceDeclaration, namespaceDeclarationWithUsings); } private static CompilationUnitSyntax MoveUsingsOutsideNamespaces(CompilationUnitSyntax compilationUnit, SyntaxAnnotation warningAnnotation) { var namespaceDeclarations = compilationUnit.Members.OfType<BaseNamespaceDeclarationSyntax>(); var namespaceDeclarationMap = namespaceDeclarations.ToDictionary( namespaceDeclaration => namespaceDeclaration, namespaceDeclaration => RemoveUsingsFromNamespace(namespaceDeclaration)); // Replace the namespace declarations in the compilation with the ones without using directives. var compilationUnitWithReplacedNamespaces = compilationUnit.ReplaceNodes( namespaceDeclarations, (node, _) => namespaceDeclarationMap[node].namespaceWithoutUsings); // Get the using directives from the namespaces and set them up to format when moved. var usingsToAdd = namespaceDeclarationMap.Values.SelectMany(result => result.usingsFromNamespace) .Select(directive => directive.WithAdditionalAnnotations(Formatter.Annotation, warningAnnotation)); var (deduplicatedUsings, orphanedTrivia) = RemoveDuplicateUsings(compilationUnit.Usings, usingsToAdd.ToImmutableArray()); // Update the compilation unit with the usings from the namespace declaration. var newUsings = compilationUnitWithReplacedNamespaces.Usings.AddRange(deduplicatedUsings); var compilationUnitWithUsings = compilationUnitWithReplacedNamespaces.WithUsings(newUsings); // Fix the leading trivia for the compilation unit. var compilationUnitWithSeparatorLine = EnsureLeadingBlankLineBeforeFirstMember(compilationUnitWithUsings); if (!orphanedTrivia.Any()) { return compilationUnitWithSeparatorLine; } // Add leading trivia that was orphaned from removing duplicate using directives to the first member in the compilation unit. var firstMember = compilationUnitWithSeparatorLine.Members[0]; return compilationUnitWithSeparatorLine.ReplaceNode(firstMember, firstMember.WithPrependedLeadingTrivia(orphanedTrivia)); } private static (BaseNamespaceDeclarationSyntax namespaceWithoutUsings, IEnumerable<UsingDirectiveSyntax> usingsFromNamespace) RemoveUsingsFromNamespace( BaseNamespaceDeclarationSyntax usingContainer) { var namespaceDeclarations = usingContainer.Members.OfType<BaseNamespaceDeclarationSyntax>(); var namespaceDeclarationMap = namespaceDeclarations.ToDictionary( namespaceDeclaration => namespaceDeclaration, namespaceDeclaration => RemoveUsingsFromNamespace(namespaceDeclaration)); // Get the using directives from the namespaces. var usingsFromNamespaces = namespaceDeclarationMap.Values.SelectMany(result => result.usingsFromNamespace); var allUsings = usingContainer.Usings.AsEnumerable().Concat(usingsFromNamespaces); // Replace the namespace declarations in the compilation with the ones without using directives. var namespaceDeclarationWithReplacedNamespaces = usingContainer.ReplaceNodes( namespaceDeclarations, (node, _) => namespaceDeclarationMap[node].namespaceWithoutUsings); // Remove usings and fix leading trivia for namespace declaration. var namespaceDeclarationWithoutUsings = namespaceDeclarationWithReplacedNamespaces.WithUsings(default); var namespaceDeclarationWithoutBlankLine = RemoveLeadingBlankLinesFromFirstMember(namespaceDeclarationWithoutUsings); return (namespaceDeclarationWithoutBlankLine, allUsings); } private static (IEnumerable<UsingDirectiveSyntax> deduplicatedUsings, IEnumerable<SyntaxTrivia> orphanedTrivia) RemoveDuplicateUsings( IEnumerable<UsingDirectiveSyntax> existingUsings, ImmutableArray<UsingDirectiveSyntax> usingsToAdd) { var seenUsings = existingUsings.ToList(); var deduplicatedUsingsBuilder = ImmutableArray.CreateBuilder<UsingDirectiveSyntax>(); var orphanedTrivia = Enumerable.Empty<SyntaxTrivia>(); foreach (var usingDirective in usingsToAdd) { // Check is the node is a duplicate. if (seenUsings.Any(seenUsingDirective => seenUsingDirective.IsEquivalentTo(usingDirective, topLevel: false))) { // If there was trivia from the duplicate node, check if any of the trivia is necessary to keep. var leadingTrivia = usingDirective.GetLeadingTrivia(); if (leadingTrivia.Any(trivia => !trivia.IsWhitespaceOrEndOfLine())) { // Capture the meaningful trivia so we can prepend it to the next kept node. orphanedTrivia = orphanedTrivia.Concat(leadingTrivia); } } else { seenUsings.Add(usingDirective); // Add any orphaned trivia to this node. deduplicatedUsingsBuilder.Add(usingDirective.WithPrependedLeadingTrivia(orphanedTrivia)); orphanedTrivia = Enumerable.Empty<SyntaxTrivia>(); } } return (deduplicatedUsingsBuilder.ToImmutable(), orphanedTrivia); } private static SyntaxList<MemberDeclarationSyntax> GetMembers(SyntaxNode node) => node switch { CompilationUnitSyntax compilationUnit => compilationUnit.Members, BaseNamespaceDeclarationSyntax namespaceDeclaration => namespaceDeclaration.Members, _ => throw ExceptionUtilities.UnexpectedValue(node) }; private static TSyntaxNode RemoveLeadingBlankLinesFromFirstMember<TSyntaxNode>(TSyntaxNode node) where TSyntaxNode : SyntaxNode { var members = GetMembers(node); if (members.Count == 0) { return node; } var firstMember = members.First(); var firstMemberTrivia = firstMember.GetLeadingTrivia(); // If there is no leading trivia, then return the node as it is. if (firstMemberTrivia.Count == 0) { return node; } var newTrivia = SplitIntoLines(firstMemberTrivia) .SkipWhile(trivia => trivia.All(t => t.IsWhitespaceOrEndOfLine()) && trivia.Last().IsKind(SyntaxKind.EndOfLineTrivia)) .SelectMany(t => t); var newFirstMember = firstMember.WithLeadingTrivia(newTrivia); return node.ReplaceNode(firstMember, newFirstMember); } private static IEnumerable<IEnumerable<SyntaxTrivia>> SplitIntoLines(SyntaxTriviaList triviaList) { var index = 0; for (var i = 0; i < triviaList.Count; i++) { if (triviaList[i].IsEndOfLine()) { yield return triviaList.TakeRange(index, i); index = i + 1; } } if (index < triviaList.Count) { yield return triviaList.TakeRange(index, triviaList.Count - 1); } } private static TSyntaxNode EnsureLeadingBlankLineBeforeFirstMember<TSyntaxNode>(TSyntaxNode node) where TSyntaxNode : SyntaxNode { var members = GetMembers(node); if (members.Count == 0) { return node; } var firstMember = members.First(); var firstMemberTrivia = firstMember.GetLeadingTrivia(); // If the first member already contains a leading new line then, this will already break up the usings from these members. if (firstMemberTrivia.Count > 0 && firstMemberTrivia.First().IsKind(SyntaxKind.EndOfLineTrivia)) { return node; } var newFirstMember = firstMember.WithLeadingTrivia(firstMemberTrivia.Insert(0, SyntaxFactory.CarriageReturnLineFeed)); return node.ReplaceNode(firstMember, newFirstMember); } private static (AddImportPlacement placement, bool preferPreservation) DeterminePlacement(CompilationUnitSyntax compilationUnit, OptionSet options) { var codeStyleOption = options.GetOption(CSharpCodeStyleOptions.PreferredUsingDirectivePlacement); var placement = codeStyleOption.Value; var preferPreservation = codeStyleOption.Notification == NotificationOption2.None; if (preferPreservation || placement == AddImportPlacement.OutsideNamespace) return (placement, preferPreservation); // Determine if we can safely apply the InsideNamespace preference. // Do not offer a code fix when there are multiple namespaces in the source file. When there are // nested namespaces it is not clear if inner usings can be moved outwards without causing // collisions. Also, when moving usings inwards it is complex to determine which namespaces they // should be moved into. // Only move using declarations inside the namespace when // - There are no global attributes // - There are no type definitions outside of the single top level namespace // - There is only a single namespace declared at the top level var forcePreservation = compilationUnit.AttributeLists.Any() || compilationUnit.Members.Count > 1 || !HasOneNamespace(compilationUnit); return (AddImportPlacement.InsideNamespace, forcePreservation); } private static bool HasOneNamespace(CompilationUnitSyntax compilationUnit) { // Find all the NamespaceDeclarations var allNamespaces = compilationUnit .DescendantNodes(node => node is CompilationUnitSyntax or BaseNamespaceDeclarationSyntax) .OfType<BaseNamespaceDeclarationSyntax>(); // To determine if there are multiple namespaces we only need to look for at least two. return allNamespaces.Take(2).Count() == 1; } private static (CompilationUnitSyntax compilationUnitWithoutHeader, ImmutableArray<SyntaxTrivia> header) RemoveFileHeader( CompilationUnitSyntax syntaxRoot, IFileBannerFactsService bannerService) { var fileHeader = bannerService.GetFileBanner(syntaxRoot); var leadingTrivia = syntaxRoot.GetLeadingTrivia(); for (var i = fileHeader.Length - 1; i >= 0; i--) { leadingTrivia = leadingTrivia.RemoveAt(i); } var newCompilationUnit = syntaxRoot.WithLeadingTrivia(leadingTrivia); return (newCompilationUnit, fileHeader); } private static CompilationUnitSyntax AddFileHeader(CompilationUnitSyntax compilationUnit, ImmutableArray<SyntaxTrivia> fileHeader) { if (fileHeader.IsEmpty) { return compilationUnit; } // Add leading trivia to the first token. var firstToken = compilationUnit.GetFirstToken(includeZeroWidth: true); var newLeadingTrivia = firstToken.LeadingTrivia.InsertRange(0, fileHeader); var newFirstToken = firstToken.WithLeadingTrivia(newLeadingTrivia); return compilationUnit.ReplaceToken(firstToken, newFirstToken); } private class MoveMisplacedUsingsCodeAction : CustomCodeActions.DocumentChangeAction { public MoveMisplacedUsingsCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument) : base(CSharpAnalyzersResources.Move_misplaced_using_directives, createChangedDocument, nameof(CSharpAnalyzersResources.Move_misplaced_using_directives)) { } } } }
// Licensed to the .NET Foundation under one or more 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.Composition; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.AddImports; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Simplification; using Roslyn.Utilities; #if CODE_STYLE using OptionSet = Microsoft.CodeAnalysis.Diagnostics.AnalyzerConfigOptions; #else using Microsoft.CodeAnalysis.Options; #endif namespace Microsoft.CodeAnalysis.CSharp.MisplacedUsingDirectives { /// <summary> /// Implements a code fix for all misplaced using statements. /// </summary> [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.MoveMisplacedUsingDirectives)] [Shared] internal sealed partial class MisplacedUsingDirectivesCodeFixProvider : CodeFixProvider { private static readonly SyntaxAnnotation s_usingPlacementCodeFixAnnotation = new SyntaxAnnotation(nameof(s_usingPlacementCodeFixAnnotation)); [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public MisplacedUsingDirectivesCodeFixProvider() { } public override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(IDEDiagnosticIds.MoveMisplacedUsingDirectivesDiagnosticId); public override FixAllProvider GetFixAllProvider() { // Since we work on an entire document at a time fixing all contained diagnostics, the batch fixer should not have merge conflicts. return WellKnownFixAllProviders.BatchFixer; } public override async Task RegisterCodeFixesAsync(CodeFixContext context) { var document = context.Document; var cancellationToken = context.CancellationToken; var syntaxRoot = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var compilationUnit = (CompilationUnitSyntax)syntaxRoot; #if CODE_STYLE var options = document.Project.AnalyzerOptions.GetAnalyzerOptionSet(syntaxRoot.SyntaxTree, cancellationToken); #else var options = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false); #endif // Read the preferred placement option and verify if it can be applied to this code file. // There are cases where we will not be able to fix the diagnostic and the user will need to resolve // it manually. var (placement, preferPreservation) = DeterminePlacement(compilationUnit, options); if (preferPreservation) return; foreach (var diagnostic in context.Diagnostics) { context.RegisterCodeFix( new MoveMisplacedUsingsCodeAction(token => GetTransformedDocumentAsync(document, compilationUnit, GetAllUsingDirectives(compilationUnit), placement, token)), diagnostic); } } internal static async Task<Document> TransformDocumentIfRequiredAsync(Document document, CancellationToken cancellationToken) { var syntaxRoot = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var compilationUnit = (CompilationUnitSyntax)syntaxRoot; #if CODE_STYLE var options = document.Project.AnalyzerOptions.GetAnalyzerOptionSet(syntaxRoot.SyntaxTree, cancellationToken); #else var options = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false); #endif var (placement, preferPreservation) = DeterminePlacement(compilationUnit, options); if (preferPreservation) { return document; } // We are called from a diagnostic, but also for all new documents, so check if there are any usings at all // otherwise there is nothing to do. var allUsingDirectives = GetAllUsingDirectives(compilationUnit); if (allUsingDirectives.Count == 0) { return document; } return await GetTransformedDocumentAsync(document, compilationUnit, allUsingDirectives, placement, cancellationToken).ConfigureAwait(false); } private static ImmutableList<UsingDirectiveSyntax> GetAllUsingDirectives(CompilationUnitSyntax compilationUnit) { return compilationUnit .DescendantNodes(node => node is CompilationUnitSyntax or BaseNamespaceDeclarationSyntax) .OfType<UsingDirectiveSyntax>().ToImmutableList(); } private static async Task<Document> GetTransformedDocumentAsync( Document document, CompilationUnitSyntax compilationUnit, IEnumerable<UsingDirectiveSyntax> allUsingDirectives, AddImportPlacement placement, CancellationToken cancellationToken) { var bannerService = document.GetRequiredLanguageService<IFileBannerFactsService>(); // Expand usings so that they can be properly simplified after they are relocated. var compilationUnitWithExpandedUsings = await ExpandUsingDirectivesAsync(document, compilationUnit, allUsingDirectives, cancellationToken).ConfigureAwait(false); // Remove the file header from the compilation unit so that we do not lose it when making changes to usings. var (compilationUnitWithoutHeader, fileHeader) = RemoveFileHeader(compilationUnitWithExpandedUsings, bannerService); // A blanket warning that this codefix may change code so that it does not compile. var warningAnnotation = WarningAnnotation.Create(CSharpAnalyzersResources.Warning_colon_Moving_using_directives_may_change_code_meaning); var newCompilationUnit = placement == AddImportPlacement.InsideNamespace ? MoveUsingsInsideNamespace(compilationUnitWithoutHeader, warningAnnotation) : MoveUsingsOutsideNamespaces(compilationUnitWithoutHeader, warningAnnotation); // Re-attach the header now that using have been moved and LeadingTrivia is no longer being altered. var newCompilationUnitWithHeader = AddFileHeader(newCompilationUnit, fileHeader); var newDocument = document.WithSyntaxRoot(newCompilationUnitWithHeader); // Simplify usings now that they have been moved and are in the proper context. var options = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false); return await Simplifier.ReduceAsync(newDocument, Simplifier.Annotation, options, cancellationToken).ConfigureAwait(false); } private static async Task<CompilationUnitSyntax> ExpandUsingDirectivesAsync(Document document, CompilationUnitSyntax containerNode, IEnumerable<UsingDirectiveSyntax> allUsingDirectives, CancellationToken cancellationToken) { // Create a map between the original node and the future expanded node. var expandUsingDirectiveTasks = allUsingDirectives.ToDictionary( usingDirective => (SyntaxNode)usingDirective, usingDirective => ExpandUsingDirectiveAsync(document, usingDirective, cancellationToken)); // Wait for all using directives to be expanded await Task.WhenAll(expandUsingDirectiveTasks.Values).ConfigureAwait(false); // Replace using directives with their expanded version. return containerNode.ReplaceNodes( expandUsingDirectiveTasks.Keys, (node, _) => expandUsingDirectiveTasks[node].Result); } private static async Task<SyntaxNode> ExpandUsingDirectiveAsync(Document document, SyntaxNode node, CancellationToken cancellationToken) { var usingDirective = (UsingDirectiveSyntax)node; var newName = await Simplifier.ExpandAsync(usingDirective.Name, document, cancellationToken: cancellationToken).ConfigureAwait(false); return usingDirective.WithName(newName); } private static CompilationUnitSyntax MoveUsingsInsideNamespace(CompilationUnitSyntax compilationUnit, SyntaxAnnotation warningAnnotation) { // Get the compilation unit usings and set them up to format when moved. var usingsToAdd = compilationUnit.Usings.Select( directive => directive.WithAdditionalAnnotations(Formatter.Annotation, warningAnnotation)); // Remove usings and fix leading trivia for compilation unit. var compilationUnitWithoutUsings = compilationUnit.WithUsings(default); var compilationUnitWithoutBlankLine = RemoveLeadingBlankLinesFromFirstMember(compilationUnitWithoutUsings); // Fix the leading trivia for the namespace declaration. var namespaceDeclaration = (BaseNamespaceDeclarationSyntax)compilationUnitWithoutBlankLine.Members[0]; var namespaceDeclarationWithBlankLine = EnsureLeadingBlankLineBeforeFirstMember(namespaceDeclaration); // Update the namespace declaration with the usings from the compilation unit. var newUsings = namespaceDeclarationWithBlankLine.Usings.InsertRange(0, usingsToAdd); var namespaceDeclarationWithUsings = namespaceDeclarationWithBlankLine.WithUsings(newUsings); // Update the compilation unit with the new namespace declaration return compilationUnitWithoutBlankLine.ReplaceNode(namespaceDeclaration, namespaceDeclarationWithUsings); } private static CompilationUnitSyntax MoveUsingsOutsideNamespaces(CompilationUnitSyntax compilationUnit, SyntaxAnnotation warningAnnotation) { var namespaceDeclarations = compilationUnit.Members.OfType<BaseNamespaceDeclarationSyntax>(); var namespaceDeclarationMap = namespaceDeclarations.ToDictionary( namespaceDeclaration => namespaceDeclaration, namespaceDeclaration => RemoveUsingsFromNamespace(namespaceDeclaration)); // Replace the namespace declarations in the compilation with the ones without using directives. var compilationUnitWithReplacedNamespaces = compilationUnit.ReplaceNodes( namespaceDeclarations, (node, _) => namespaceDeclarationMap[node].namespaceWithoutUsings); // Get the using directives from the namespaces and set them up to format when moved. var usingsToAdd = namespaceDeclarationMap.Values.SelectMany(result => result.usingsFromNamespace) .Select(directive => directive.WithAdditionalAnnotations(Formatter.Annotation, warningAnnotation)); var (deduplicatedUsings, orphanedTrivia) = RemoveDuplicateUsings(compilationUnit.Usings, usingsToAdd.ToImmutableArray()); // Update the compilation unit with the usings from the namespace declaration. var newUsings = compilationUnitWithReplacedNamespaces.Usings.AddRange(deduplicatedUsings); var compilationUnitWithUsings = compilationUnitWithReplacedNamespaces.WithUsings(newUsings); // Fix the leading trivia for the compilation unit. var compilationUnitWithSeparatorLine = EnsureLeadingBlankLineBeforeFirstMember(compilationUnitWithUsings); if (!orphanedTrivia.Any()) { return compilationUnitWithSeparatorLine; } // Add leading trivia that was orphaned from removing duplicate using directives to the first member in the compilation unit. var firstMember = compilationUnitWithSeparatorLine.Members[0]; return compilationUnitWithSeparatorLine.ReplaceNode(firstMember, firstMember.WithPrependedLeadingTrivia(orphanedTrivia)); } private static (BaseNamespaceDeclarationSyntax namespaceWithoutUsings, IEnumerable<UsingDirectiveSyntax> usingsFromNamespace) RemoveUsingsFromNamespace( BaseNamespaceDeclarationSyntax usingContainer) { var namespaceDeclarations = usingContainer.Members.OfType<BaseNamespaceDeclarationSyntax>(); var namespaceDeclarationMap = namespaceDeclarations.ToDictionary( namespaceDeclaration => namespaceDeclaration, namespaceDeclaration => RemoveUsingsFromNamespace(namespaceDeclaration)); // Get the using directives from the namespaces. var usingsFromNamespaces = namespaceDeclarationMap.Values.SelectMany(result => result.usingsFromNamespace); var allUsings = usingContainer.Usings.AsEnumerable().Concat(usingsFromNamespaces); // Replace the namespace declarations in the compilation with the ones without using directives. var namespaceDeclarationWithReplacedNamespaces = usingContainer.ReplaceNodes( namespaceDeclarations, (node, _) => namespaceDeclarationMap[node].namespaceWithoutUsings); // Remove usings and fix leading trivia for namespace declaration. var namespaceDeclarationWithoutUsings = namespaceDeclarationWithReplacedNamespaces.WithUsings(default); var namespaceDeclarationWithoutBlankLine = RemoveLeadingBlankLinesFromFirstMember(namespaceDeclarationWithoutUsings); return (namespaceDeclarationWithoutBlankLine, allUsings); } private static (IEnumerable<UsingDirectiveSyntax> deduplicatedUsings, IEnumerable<SyntaxTrivia> orphanedTrivia) RemoveDuplicateUsings( IEnumerable<UsingDirectiveSyntax> existingUsings, ImmutableArray<UsingDirectiveSyntax> usingsToAdd) { var seenUsings = existingUsings.ToList(); var deduplicatedUsingsBuilder = ImmutableArray.CreateBuilder<UsingDirectiveSyntax>(); var orphanedTrivia = Enumerable.Empty<SyntaxTrivia>(); foreach (var usingDirective in usingsToAdd) { // Check is the node is a duplicate. if (seenUsings.Any(seenUsingDirective => seenUsingDirective.IsEquivalentTo(usingDirective, topLevel: false))) { // If there was trivia from the duplicate node, check if any of the trivia is necessary to keep. var leadingTrivia = usingDirective.GetLeadingTrivia(); if (leadingTrivia.Any(trivia => !trivia.IsWhitespaceOrEndOfLine())) { // Capture the meaningful trivia so we can prepend it to the next kept node. orphanedTrivia = orphanedTrivia.Concat(leadingTrivia); } } else { seenUsings.Add(usingDirective); // Add any orphaned trivia to this node. deduplicatedUsingsBuilder.Add(usingDirective.WithPrependedLeadingTrivia(orphanedTrivia)); orphanedTrivia = Enumerable.Empty<SyntaxTrivia>(); } } return (deduplicatedUsingsBuilder.ToImmutable(), orphanedTrivia); } private static SyntaxList<MemberDeclarationSyntax> GetMembers(SyntaxNode node) => node switch { CompilationUnitSyntax compilationUnit => compilationUnit.Members, BaseNamespaceDeclarationSyntax namespaceDeclaration => namespaceDeclaration.Members, _ => throw ExceptionUtilities.UnexpectedValue(node) }; private static TSyntaxNode RemoveLeadingBlankLinesFromFirstMember<TSyntaxNode>(TSyntaxNode node) where TSyntaxNode : SyntaxNode { var members = GetMembers(node); if (members.Count == 0) { return node; } var firstMember = members.First(); var firstMemberTrivia = firstMember.GetLeadingTrivia(); // If there is no leading trivia, then return the node as it is. if (firstMemberTrivia.Count == 0) { return node; } var newTrivia = SplitIntoLines(firstMemberTrivia) .SkipWhile(trivia => trivia.All(t => t.IsWhitespaceOrEndOfLine()) && trivia.Last().IsKind(SyntaxKind.EndOfLineTrivia)) .SelectMany(t => t); var newFirstMember = firstMember.WithLeadingTrivia(newTrivia); return node.ReplaceNode(firstMember, newFirstMember); } private static IEnumerable<IEnumerable<SyntaxTrivia>> SplitIntoLines(SyntaxTriviaList triviaList) { var index = 0; for (var i = 0; i < triviaList.Count; i++) { if (triviaList[i].IsEndOfLine()) { yield return triviaList.TakeRange(index, i); index = i + 1; } } if (index < triviaList.Count) { yield return triviaList.TakeRange(index, triviaList.Count - 1); } } private static TSyntaxNode EnsureLeadingBlankLineBeforeFirstMember<TSyntaxNode>(TSyntaxNode node) where TSyntaxNode : SyntaxNode { var members = GetMembers(node); if (members.Count == 0) { return node; } var firstMember = members.First(); var firstMemberTrivia = firstMember.GetLeadingTrivia(); // If the first member already contains a leading new line then, this will already break up the usings from these members. if (firstMemberTrivia.Count > 0 && firstMemberTrivia.First().IsKind(SyntaxKind.EndOfLineTrivia)) { return node; } var newFirstMember = firstMember.WithLeadingTrivia(firstMemberTrivia.Insert(0, SyntaxFactory.CarriageReturnLineFeed)); return node.ReplaceNode(firstMember, newFirstMember); } private static (AddImportPlacement placement, bool preferPreservation) DeterminePlacement(CompilationUnitSyntax compilationUnit, OptionSet options) { var codeStyleOption = options.GetOption(CSharpCodeStyleOptions.PreferredUsingDirectivePlacement); var placement = codeStyleOption.Value; var preferPreservation = codeStyleOption.Notification == NotificationOption2.None; if (preferPreservation || placement == AddImportPlacement.OutsideNamespace) return (placement, preferPreservation); // Determine if we can safely apply the InsideNamespace preference. // Do not offer a code fix when there are multiple namespaces in the source file. When there are // nested namespaces it is not clear if inner usings can be moved outwards without causing // collisions. Also, when moving usings inwards it is complex to determine which namespaces they // should be moved into. // Only move using declarations inside the namespace when // - There are no global attributes // - There are no type definitions outside of the single top level namespace // - There is only a single namespace declared at the top level var forcePreservation = compilationUnit.AttributeLists.Any() || compilationUnit.Members.Count > 1 || !HasOneNamespace(compilationUnit); return (AddImportPlacement.InsideNamespace, forcePreservation); } private static bool HasOneNamespace(CompilationUnitSyntax compilationUnit) { // Find all the NamespaceDeclarations var allNamespaces = compilationUnit .DescendantNodes(node => node is CompilationUnitSyntax or BaseNamespaceDeclarationSyntax) .OfType<BaseNamespaceDeclarationSyntax>(); // To determine if there are multiple namespaces we only need to look for at least two. return allNamespaces.Take(2).Count() == 1; } private static (CompilationUnitSyntax compilationUnitWithoutHeader, ImmutableArray<SyntaxTrivia> header) RemoveFileHeader( CompilationUnitSyntax syntaxRoot, IFileBannerFactsService bannerService) { var fileHeader = bannerService.GetFileBanner(syntaxRoot); var leadingTrivia = syntaxRoot.GetLeadingTrivia(); for (var i = fileHeader.Length - 1; i >= 0; i--) { leadingTrivia = leadingTrivia.RemoveAt(i); } var newCompilationUnit = syntaxRoot.WithLeadingTrivia(leadingTrivia); return (newCompilationUnit, fileHeader); } private static CompilationUnitSyntax AddFileHeader(CompilationUnitSyntax compilationUnit, ImmutableArray<SyntaxTrivia> fileHeader) { if (fileHeader.IsEmpty) { return compilationUnit; } // Add leading trivia to the first token. var firstToken = compilationUnit.GetFirstToken(includeZeroWidth: true); var newLeadingTrivia = firstToken.LeadingTrivia.InsertRange(0, fileHeader); var newFirstToken = firstToken.WithLeadingTrivia(newLeadingTrivia); return compilationUnit.ReplaceToken(firstToken, newFirstToken); } private class MoveMisplacedUsingsCodeAction : CustomCodeActions.DocumentChangeAction { public MoveMisplacedUsingsCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument) : base(CSharpAnalyzersResources.Move_misplaced_using_directives, createChangedDocument, nameof(CSharpAnalyzersResources.Move_misplaced_using_directives)) { } } } }
-1
dotnet/roslyn
56,450
Implement INamespaceTypeReference.GetUnit for RootModuleType
Fixes #56412.
AlekseyTs
"2021-09-16T16:44:04Z"
"2021-09-17T18:21:59Z"
4b06ee428bafa0141c9eb3250003a19109dcfc86
d695369176aa109f0e0fb8b0019294aaa0823a54
Implement INamespaceTypeReference.GetUnit for RootModuleType. Fixes #56412.
./src/Compilers/Core/Portable/PEWriter/LocalScope.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.Diagnostics; using System.Linq; using Microsoft.CodeAnalysis; namespace Microsoft.Cci { /// <summary> /// A range of CLR IL operations that comprise a lexical scope. /// </summary> internal struct LocalScope { /// <summary> /// The offset of the first operation in the scope. /// </summary> public readonly int StartOffset; /// <summary> /// The offset of the first operation outside of the scope, or the method body length. /// </summary> public readonly int EndOffset; private readonly ImmutableArray<ILocalDefinition> _constants; private readonly ImmutableArray<ILocalDefinition> _locals; internal LocalScope(int offset, int endOffset, ImmutableArray<ILocalDefinition> constants, ImmutableArray<ILocalDefinition> locals) { Debug.Assert(!locals.Any(l => l.Name == null)); Debug.Assert(!constants.Any(c => c.Name == null)); Debug.Assert(offset >= 0); Debug.Assert(endOffset > offset); StartOffset = offset; EndOffset = endOffset; _constants = constants; _locals = locals; } public int Length => EndOffset - StartOffset; /// <summary> /// Returns zero or more local constant definitions that are local to the given scope. /// </summary> public ImmutableArray<ILocalDefinition> Constants => _constants.NullToEmpty(); /// <summary> /// Returns zero or more local variable definitions that are local to the given scope. /// </summary> public ImmutableArray<ILocalDefinition> Variables => _locals.NullToEmpty(); } }
// Licensed to the .NET Foundation under one or more 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.Diagnostics; using System.Linq; using Microsoft.CodeAnalysis; namespace Microsoft.Cci { /// <summary> /// A range of CLR IL operations that comprise a lexical scope. /// </summary> internal struct LocalScope { /// <summary> /// The offset of the first operation in the scope. /// </summary> public readonly int StartOffset; /// <summary> /// The offset of the first operation outside of the scope, or the method body length. /// </summary> public readonly int EndOffset; private readonly ImmutableArray<ILocalDefinition> _constants; private readonly ImmutableArray<ILocalDefinition> _locals; internal LocalScope(int offset, int endOffset, ImmutableArray<ILocalDefinition> constants, ImmutableArray<ILocalDefinition> locals) { Debug.Assert(!locals.Any(l => l.Name == null)); Debug.Assert(!constants.Any(c => c.Name == null)); Debug.Assert(offset >= 0); Debug.Assert(endOffset > offset); StartOffset = offset; EndOffset = endOffset; _constants = constants; _locals = locals; } public int Length => EndOffset - StartOffset; /// <summary> /// Returns zero or more local constant definitions that are local to the given scope. /// </summary> public ImmutableArray<ILocalDefinition> Constants => _constants.NullToEmpty(); /// <summary> /// Returns zero or more local variable definitions that are local to the given scope. /// </summary> public ImmutableArray<ILocalDefinition> Variables => _locals.NullToEmpty(); } }
-1
dotnet/roslyn
56,450
Implement INamespaceTypeReference.GetUnit for RootModuleType
Fixes #56412.
AlekseyTs
"2021-09-16T16:44:04Z"
"2021-09-17T18:21:59Z"
4b06ee428bafa0141c9eb3250003a19109dcfc86
d695369176aa109f0e0fb8b0019294aaa0823a54
Implement INamespaceTypeReference.GetUnit for RootModuleType. Fixes #56412.
./src/Compilers/CSharp/Portable/Symbols/TypeSymbol.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.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Runtime.CompilerServices; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Symbols; using Roslyn.Utilities; #pragma warning disable CS0660 namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// A TypeSymbol is a base class for all the symbols that represent a type /// in C#. /// </summary> internal abstract partial class TypeSymbol : NamespaceOrTypeSymbol, ITypeSymbolInternal { // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // Changes to the public interface of this class should remain synchronized with the VB version. // Do not make any changes to the public interface without making the corresponding change // to the VB version. // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // TODO (tomat): Consider changing this to an empty name. This name shouldn't ever leak to the user in error messages. internal const string ImplicitTypeName = "<invalid-global-code>"; // InterfaceInfo for a common case of a type not implementing anything directly or indirectly. private static readonly InterfaceInfo s_noInterfaces = new InterfaceInfo(); private ImmutableHashSet<Symbol> _lazyAbstractMembers; private InterfaceInfo _lazyInterfaceInfo; private class InterfaceInfo { // all directly implemented interfaces, their bases and all interfaces to the bases of the type recursively internal ImmutableArray<NamedTypeSymbol> allInterfaces; /// <summary> /// <see cref="TypeSymbol.InterfacesAndTheirBaseInterfacesNoUseSiteDiagnostics"/> /// </summary> internal MultiDictionary<NamedTypeSymbol, NamedTypeSymbol> interfacesAndTheirBaseInterfaces; internal static readonly MultiDictionary<NamedTypeSymbol, NamedTypeSymbol> EmptyInterfacesAndTheirBaseInterfaces = new MultiDictionary<NamedTypeSymbol, NamedTypeSymbol>(0, SymbolEqualityComparer.CLRSignature); // Key is implemented member (method, property, or event), value is implementing member (from the // perspective of this type). Don't allocate until someone needs it. private ConcurrentDictionary<Symbol, SymbolAndDiagnostics> _implementationForInterfaceMemberMap; public ConcurrentDictionary<Symbol, SymbolAndDiagnostics> ImplementationForInterfaceMemberMap { get { var map = _implementationForInterfaceMemberMap; if (map != null) { return map; } // PERF: Avoid over-allocation. In many cases, there's only 1 entry and we don't expect concurrent updates. map = new ConcurrentDictionary<Symbol, SymbolAndDiagnostics>(concurrencyLevel: 1, capacity: 1, comparer: SymbolEqualityComparer.ConsiderEverything); return Interlocked.CompareExchange(ref _implementationForInterfaceMemberMap, map, null) ?? map; } } /// <summary> /// key = interface method/property/event compared using <see cref="ExplicitInterfaceImplementationTargetMemberEqualityComparer"/>, /// value = explicitly implementing methods/properties/events declared on this type (normally a single value, multiple in case of /// an error). /// </summary> internal MultiDictionary<Symbol, Symbol> explicitInterfaceImplementationMap; #nullable enable internal ImmutableDictionary<MethodSymbol, MethodSymbol>? synthesizedMethodImplMap; #nullable disable internal bool IsDefaultValue() { return allInterfaces.IsDefault && interfacesAndTheirBaseInterfaces == null && _implementationForInterfaceMemberMap == null && explicitInterfaceImplementationMap == null && synthesizedMethodImplMap == null; } } private InterfaceInfo GetInterfaceInfo() { var info = _lazyInterfaceInfo; if (info != null) { Debug.Assert(info != s_noInterfaces || info.IsDefaultValue(), "default value was modified"); return info; } for (var baseType = this; !ReferenceEquals(baseType, null); baseType = baseType.BaseTypeNoUseSiteDiagnostics) { var interfaces = (baseType.TypeKind == TypeKind.TypeParameter) ? ((TypeParameterSymbol)baseType).EffectiveInterfacesNoUseSiteDiagnostics : baseType.InterfacesNoUseSiteDiagnostics(); if (!interfaces.IsEmpty) { // it looks like we or one of our bases implements something. info = new InterfaceInfo(); // NOTE: we are assigning lazyInterfaceInfo via interlocked not for correctness, // we just do not want to override an existing info that could be partially filled. return Interlocked.CompareExchange(ref _lazyInterfaceInfo, info, null) ?? info; } } // if we have got here it means neither we nor our bases implement anything _lazyInterfaceInfo = info = s_noInterfaces; return info; } /// <summary> /// The original definition of this symbol. If this symbol is constructed from another /// symbol by type substitution then OriginalDefinition gets the original symbol as it was defined in /// source or metadata. /// </summary> public new TypeSymbol OriginalDefinition { get { return OriginalTypeSymbolDefinition; } } protected virtual TypeSymbol OriginalTypeSymbolDefinition { get { return this; } } protected sealed override Symbol OriginalSymbolDefinition { get { return this.OriginalTypeSymbolDefinition; } } /// <summary> /// Gets the BaseType of this type. If the base type could not be determined, then /// an instance of ErrorType is returned. If this kind of type does not have a base type /// (for example, interfaces), null is returned. Also the special class System.Object /// always has a BaseType of null. /// </summary> internal abstract NamedTypeSymbol BaseTypeNoUseSiteDiagnostics { get; } internal NamedTypeSymbol BaseTypeWithDefinitionUseSiteDiagnostics(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var result = BaseTypeNoUseSiteDiagnostics; if ((object)result != null) { result.OriginalDefinition.AddUseSiteInfo(ref useSiteInfo); } return result; } internal NamedTypeSymbol BaseTypeOriginalDefinition(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var result = BaseTypeNoUseSiteDiagnostics; if ((object)result != null) { result = result.OriginalDefinition; result.AddUseSiteInfo(ref useSiteInfo); } return result; } /// <summary> /// Gets the set of interfaces that this type directly implements. This set does not include /// interfaces that are base interfaces of directly implemented interfaces. /// </summary> internal abstract ImmutableArray<NamedTypeSymbol> InterfacesNoUseSiteDiagnostics(ConsList<TypeSymbol> basesBeingResolved = null); /// <summary> /// The list of all interfaces of which this type is a declared subtype, excluding this type /// itself. This includes all declared base interfaces, all declared base interfaces of base /// types, and all declared base interfaces of those results (recursively). Each result /// appears exactly once in the list. This list is topologically sorted by the inheritance /// relationship: if interface type A extends interface type B, then A precedes B in the /// list. This is not quite the same as "all interfaces of which this type is a proper /// subtype" because it does not take into account variance: AllInterfaces for /// IEnumerable&lt;string&gt; will not include IEnumerable&lt;object&gt; /// </summary> internal ImmutableArray<NamedTypeSymbol> AllInterfacesNoUseSiteDiagnostics { get { return GetAllInterfaces(); } } internal ImmutableArray<NamedTypeSymbol> AllInterfacesWithDefinitionUseSiteDiagnostics(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var result = AllInterfacesNoUseSiteDiagnostics; // Since bases affect content of AllInterfaces set, we need to make sure they all are good. var current = this; do { current = current.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo); } while ((object)current != null); foreach (var iface in result) { iface.OriginalDefinition.AddUseSiteInfo(ref useSiteInfo); } return result; } /// <summary> /// If this is a type parameter returns its effective base class, otherwise returns this type. /// </summary> internal TypeSymbol EffectiveTypeNoUseSiteDiagnostics { get { return this.IsTypeParameter() ? ((TypeParameterSymbol)this).EffectiveBaseClassNoUseSiteDiagnostics : this; } } internal TypeSymbol EffectiveType(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { return this.IsTypeParameter() ? ((TypeParameterSymbol)this).EffectiveBaseClass(ref useSiteInfo) : this; } /// <summary> /// Returns true if this type derives from a given type. /// </summary> internal bool IsDerivedFrom(TypeSymbol type, TypeCompareKind comparison, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)type != null); Debug.Assert(!type.IsTypeParameter()); if ((object)this == (object)type) { return false; } var t = this.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo); while ((object)t != null) { if (type.Equals(t, comparison)) { return true; } t = t.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo); } return false; } /// <summary> /// Returns true if this type is equal or derives from a given type. /// </summary> internal bool IsEqualToOrDerivedFrom(TypeSymbol type, TypeCompareKind comparison, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { return this.Equals(type, comparison) || this.IsDerivedFrom(type, comparison, ref useSiteInfo); } /// <summary> /// Determines if this type symbol represent the same type as another, according to the language /// semantics. /// </summary> /// <param name="t2">The other type.</param> /// <param name="compareKind"> /// What kind of comparison to use? /// You can ignore custom modifiers, ignore the distinction between object and dynamic, or ignore tuple element names differences. /// </param> /// <returns>True if the types are equivalent.</returns> internal virtual bool Equals(TypeSymbol t2, TypeCompareKind compareKind) { return ReferenceEquals(this, t2); } public sealed override bool Equals(Symbol other, TypeCompareKind compareKind) { var t2 = other as TypeSymbol; if (t2 is null) { return false; } return this.Equals(t2, compareKind); } /// <summary> /// We ignore custom modifiers, and the distinction between dynamic and object, when computing a type's hash code. /// </summary> /// <returns></returns> public override int GetHashCode() { return RuntimeHelpers.GetHashCode(this); } protected virtual ImmutableArray<NamedTypeSymbol> GetAllInterfaces() { var info = this.GetInterfaceInfo(); if (info == s_noInterfaces) { return ImmutableArray<NamedTypeSymbol>.Empty; } if (info.allInterfaces.IsDefault) { ImmutableInterlocked.InterlockedInitialize(ref info.allInterfaces, MakeAllInterfaces()); } return info.allInterfaces; } /// Produce all implemented interfaces in topologically sorted order. We use /// TypeSymbol.Interfaces as the source of edge data, which has had cycles and infinitely /// long dependency cycles removed. Consequently, it is possible (and we do) use the /// simplest version of Tarjan's topological sorting algorithm. protected virtual ImmutableArray<NamedTypeSymbol> MakeAllInterfaces() { var result = ArrayBuilder<NamedTypeSymbol>.GetInstance(); var visited = new HashSet<NamedTypeSymbol>(SymbolEqualityComparer.ConsiderEverything); for (var baseType = this; !ReferenceEquals(baseType, null); baseType = baseType.BaseTypeNoUseSiteDiagnostics) { var interfaces = (baseType.TypeKind == TypeKind.TypeParameter) ? ((TypeParameterSymbol)baseType).EffectiveInterfacesNoUseSiteDiagnostics : baseType.InterfacesNoUseSiteDiagnostics(); for (int i = interfaces.Length - 1; i >= 0; i--) { addAllInterfaces(interfaces[i], visited, result); } } result.ReverseContents(); return result.ToImmutableAndFree(); static void addAllInterfaces(NamedTypeSymbol @interface, HashSet<NamedTypeSymbol> visited, ArrayBuilder<NamedTypeSymbol> result) { if (visited.Add(@interface)) { ImmutableArray<NamedTypeSymbol> baseInterfaces = @interface.InterfacesNoUseSiteDiagnostics(); for (int i = baseInterfaces.Length - 1; i >= 0; i--) { var baseInterface = baseInterfaces[i]; addAllInterfaces(baseInterface, visited, result); } result.Add(@interface); } } } /// <summary> /// Gets the set of interfaces that this type directly implements, plus the base interfaces /// of all such types. Keys are compared using <see cref="SymbolEqualityComparer.CLRSignature"/>, /// values are distinct interfaces corresponding to the key, according to <see cref="TypeCompareKind.ConsiderEverything"/> rules. /// </summary> /// <remarks> /// CONSIDER: it probably isn't truly necessary to cache this. If space gets tight, consider /// alternative approaches (recompute every time, cache on the side, only store on some types, /// etc). /// </remarks> internal MultiDictionary<NamedTypeSymbol, NamedTypeSymbol> InterfacesAndTheirBaseInterfacesNoUseSiteDiagnostics { get { var info = this.GetInterfaceInfo(); if (info == s_noInterfaces) { Debug.Assert(InterfaceInfo.EmptyInterfacesAndTheirBaseInterfaces.IsEmpty); return InterfaceInfo.EmptyInterfacesAndTheirBaseInterfaces; } if (info.interfacesAndTheirBaseInterfaces == null) { Interlocked.CompareExchange(ref info.interfacesAndTheirBaseInterfaces, MakeInterfacesAndTheirBaseInterfaces(this.InterfacesNoUseSiteDiagnostics()), null); } return info.interfacesAndTheirBaseInterfaces; } } internal MultiDictionary<NamedTypeSymbol, NamedTypeSymbol> InterfacesAndTheirBaseInterfacesWithDefinitionUseSiteDiagnostics(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var result = InterfacesAndTheirBaseInterfacesNoUseSiteDiagnostics; foreach (var iface in result.Keys) { iface.OriginalDefinition.AddUseSiteInfo(ref useSiteInfo); } return result; } // Note: Unlike MakeAllInterfaces, this doesn't need to be virtual. It depends on // AllInterfaces for its implementation, so it will pick up all changes to MakeAllInterfaces // indirectly. private static MultiDictionary<NamedTypeSymbol, NamedTypeSymbol> MakeInterfacesAndTheirBaseInterfaces(ImmutableArray<NamedTypeSymbol> declaredInterfaces) { var resultBuilder = new MultiDictionary<NamedTypeSymbol, NamedTypeSymbol>(declaredInterfaces.Length, SymbolEqualityComparer.CLRSignature, SymbolEqualityComparer.ConsiderEverything); foreach (var @interface in declaredInterfaces) { if (resultBuilder.Add(@interface, @interface)) { foreach (var baseInterface in @interface.AllInterfacesNoUseSiteDiagnostics) { resultBuilder.Add(baseInterface, baseInterface); } } } return resultBuilder; } /// <summary> /// Returns the corresponding symbol in this type or a base type that implements /// interfaceMember (either implicitly or explicitly), or null if no such symbol exists /// (which might be either because this type doesn't implement the container of /// interfaceMember, or this type doesn't supply a member that successfully implements /// interfaceMember). /// </summary> /// <param name="interfaceMember"> /// Must be a non-null interface property, method, or event. /// </param> public Symbol FindImplementationForInterfaceMember(Symbol interfaceMember) { if ((object)interfaceMember == null) { throw new ArgumentNullException(nameof(interfaceMember)); } if (!interfaceMember.IsImplementableInterfaceMember()) { return null; } if (this.IsInterfaceType()) { if (interfaceMember.IsStatic) { return null; } var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; return FindMostSpecificImplementation(interfaceMember, (NamedTypeSymbol)this, ref discardedUseSiteInfo); } return FindImplementationForInterfaceMemberInNonInterface(interfaceMember); } /// <summary> /// Returns true if this type is known to be a reference type. It is never the case that /// IsReferenceType and IsValueType both return true. However, for an unconstrained type /// parameter, IsReferenceType and IsValueType will both return false. /// </summary> public abstract bool IsReferenceType { get; } /// <summary> /// Returns true if this type is known to be a value type. It is never the case that /// IsReferenceType and IsValueType both return true. However, for an unconstrained type /// parameter, IsReferenceType and IsValueType will both return false. /// </summary> public abstract bool IsValueType { get; } // Only the compiler can create TypeSymbols. internal TypeSymbol() { } /// <summary> /// Gets the kind of this type. /// </summary> public abstract TypeKind TypeKind { get; } /// <summary> /// Gets corresponding special TypeId of this type. /// </summary> /// <remarks> /// Not preserved in types constructed from this one. /// </remarks> public virtual SpecialType SpecialType { get { return SpecialType.None; } } /// <summary> /// Gets corresponding primitive type code for this type declaration. /// </summary> internal Microsoft.Cci.PrimitiveTypeCode PrimitiveTypeCode => TypeKind switch { TypeKind.Pointer => Microsoft.Cci.PrimitiveTypeCode.Pointer, TypeKind.FunctionPointer => Microsoft.Cci.PrimitiveTypeCode.FunctionPointer, _ => SpecialTypes.GetTypeCode(SpecialType) }; #region Use-Site Diagnostics /// <summary> /// Return error code that has highest priority while calculating use site error for this symbol. /// </summary> protected override int HighestPriorityUseSiteError { get { return (int)ErrorCode.ERR_BogusType; } } public sealed override bool HasUnsupportedMetadata { get { DiagnosticInfo info = GetUseSiteInfo().DiagnosticInfo; return (object)info != null && info.Code == (int)ErrorCode.ERR_BogusType; } } internal abstract bool GetUnificationUseSiteDiagnosticRecursive(ref DiagnosticInfo result, Symbol owner, ref HashSet<TypeSymbol> checkedTypes); #endregion /// <summary> /// Is this a symbol for an anonymous type (including delegate). /// </summary> public virtual bool IsAnonymousType { get { return false; } } /// <summary> /// Is this a symbol for a Tuple. /// </summary> public virtual bool IsTupleType => false; /// <summary> /// True if the type represents a native integer. In C#, the types represented /// by language keywords 'nint' and 'nuint'. /// </summary> internal virtual bool IsNativeIntegerType => false; /// <summary> /// Verify if the given type is a tuple of a given cardinality, or can be used to back a tuple type /// with the given cardinality. /// </summary> internal bool IsTupleTypeOfCardinality(int targetCardinality) { if (IsTupleType) { return TupleElementTypesWithAnnotations.Length == targetCardinality; } return false; } /// <summary> /// If this symbol represents a tuple type, get the types of the tuple's elements. /// </summary> public virtual ImmutableArray<TypeWithAnnotations> TupleElementTypesWithAnnotations => default(ImmutableArray<TypeWithAnnotations>); /// <summary> /// If this symbol represents a tuple type, get the names of the tuple's elements. /// </summary> public virtual ImmutableArray<string> TupleElementNames => default(ImmutableArray<string>); /// <summary> /// If this symbol represents a tuple type, get the fields for the tuple's elements. /// Otherwise, returns default. /// </summary> public virtual ImmutableArray<FieldSymbol> TupleElements => default(ImmutableArray<FieldSymbol>); #nullable enable /// <summary> /// Is this type a managed type (false for everything but enum, pointer, and /// some struct types). /// </summary> /// <remarks> /// See Type::computeManagedType. /// </remarks> internal bool IsManagedType(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) => GetManagedKind(ref useSiteInfo) == ManagedKind.Managed; internal bool IsManagedTypeNoUseSiteDiagnostics { get { var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; return IsManagedType(ref discardedUseSiteInfo); } } /// <summary> /// Indicates whether a type is managed or not (i.e. you can take a pointer to it). /// Contains additional cases to help implement FeatureNotAvailable diagnostics. /// </summary> internal abstract ManagedKind GetManagedKind(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo); internal ManagedKind ManagedKindNoUseSiteDiagnostics { get { var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; return GetManagedKind(ref discardedUseSiteInfo); } } #nullable disable internal bool NeedsNullableAttribute() { return TypeWithAnnotations.NeedsNullableAttribute(typeWithAnnotationsOpt: default, typeOpt: this); } internal abstract void AddNullableTransforms(ArrayBuilder<byte> transforms); internal abstract bool ApplyNullableTransforms(byte defaultTransformFlag, ImmutableArray<byte> transforms, ref int position, out TypeSymbol result); internal abstract TypeSymbol SetNullabilityForReferenceTypes(Func<TypeWithAnnotations, TypeWithAnnotations> transform); internal TypeSymbol SetUnknownNullabilityForReferenceTypes() { return SetNullabilityForReferenceTypes(s_setUnknownNullability); } private static readonly Func<TypeWithAnnotations, TypeWithAnnotations> s_setUnknownNullability = (type) => type.SetUnknownNullabilityForReferenceTypes(); /// <summary> /// Merges features of the type with another type where there is an identity conversion between them. /// The features to be merged are /// object vs dynamic (dynamic wins), tuple names (dropped in case of conflict), and nullable /// annotations (e.g. in type arguments). /// </summary> internal abstract TypeSymbol MergeEquivalentTypes(TypeSymbol other, VarianceKind variance); /// <summary> /// Returns true if the type may contain embedded references /// </summary> public abstract bool IsRefLikeType { get; } /// <summary> /// Returns true if the type is a readonly struct /// </summary> public abstract bool IsReadOnly { get; } public string ToDisplayString(CodeAnalysis.NullableFlowState topLevelNullability, SymbolDisplayFormat format = null) { return SymbolDisplay.ToDisplayString((ITypeSymbol)ISymbol, topLevelNullability, format); } public ImmutableArray<SymbolDisplayPart> ToDisplayParts(CodeAnalysis.NullableFlowState topLevelNullability, SymbolDisplayFormat format = null) { return SymbolDisplay.ToDisplayParts((ITypeSymbol)ISymbol, topLevelNullability, format); } public string ToMinimalDisplayString( SemanticModel semanticModel, CodeAnalysis.NullableFlowState topLevelNullability, int position, SymbolDisplayFormat format = null) { return SymbolDisplay.ToMinimalDisplayString((ITypeSymbol)ISymbol, topLevelNullability, semanticModel, position, format); } public ImmutableArray<SymbolDisplayPart> ToMinimalDisplayParts( SemanticModel semanticModel, CodeAnalysis.NullableFlowState topLevelNullability, int position, SymbolDisplayFormat format = null) { return SymbolDisplay.ToMinimalDisplayParts((ITypeSymbol)ISymbol, topLevelNullability, semanticModel, position, format); } #region Interface member checks /// <summary> /// Locate implementation of the <paramref name="interfaceMember"/> in context of the current type. /// The method is using cache to optimize subsequent calls for the same <paramref name="interfaceMember"/>. /// </summary> /// <param name="interfaceMember">Member for which an implementation should be found.</param> /// <param name="ignoreImplementationInInterfacesIfResultIsNotReady"> /// The process of looking up an implementation for an accessor can involve figuring out how corresponding event/property is implemented, /// <see cref="CheckForImplementationOfCorrespondingPropertyOrEvent"/>. And the process of looking up an implementation for a property can /// involve figuring out how corresponding accessors are implemented, <see cref="FindMostSpecificImplementationInInterfaces"/>. This can /// lead to cycles, which could be avoided if we ignore the presence of implementations in interfaces for the purpose of /// <see cref="CheckForImplementationOfCorrespondingPropertyOrEvent"/>. Fortunately, logic in it allows us to ignore the presence of /// implementations in interfaces and we use that. /// When the value of this parameter is true and the result that takes presence of implementations in interfaces into account is not /// available from the cache, the lookup will be performed ignoring the presence of implementations in interfaces. Otherwise, result from /// the cache is returned. /// When the value of the parameter is false, the result from the cache is returned, or calculated, taking presence of implementations /// in interfaces into account and then cached. /// This means that: /// - A symbol from an interface can still be returned even when <paramref name="ignoreImplementationInInterfacesIfResultIsNotReady"/> is true. /// A subsequent call with <paramref name="ignoreImplementationInInterfacesIfResultIsNotReady"/> false will return the same value. /// - If symbol from a non-interface is returned when <paramref name="ignoreImplementationInInterfacesIfResultIsNotReady"/> is true. A subsequent /// call with <paramref name="ignoreImplementationInInterfacesIfResultIsNotReady"/> false will return the same value. /// - If no symbol is returned for <paramref name="ignoreImplementationInInterfacesIfResultIsNotReady"/> true. A subsequent call with /// <paramref name="ignoreImplementationInInterfacesIfResultIsNotReady"/> might return a symbol, but that symbol guaranteed to be from an interface. /// - If the first request is done with <paramref name="ignoreImplementationInInterfacesIfResultIsNotReady"/> false. A subsequent call /// is guaranteed to return the same result regardless of <paramref name="ignoreImplementationInInterfacesIfResultIsNotReady"/> value. /// </param> internal SymbolAndDiagnostics FindImplementationForInterfaceMemberInNonInterfaceWithDiagnostics(Symbol interfaceMember, bool ignoreImplementationInInterfacesIfResultIsNotReady = false) { Debug.Assert((object)interfaceMember != null); Debug.Assert(!this.IsInterfaceType()); if (this.IsInterfaceType()) { return SymbolAndDiagnostics.Empty; } var interfaceType = interfaceMember.ContainingType; if ((object)interfaceType == null || !interfaceType.IsInterface) { return SymbolAndDiagnostics.Empty; } switch (interfaceMember.Kind) { case SymbolKind.Method: case SymbolKind.Property: case SymbolKind.Event: var info = this.GetInterfaceInfo(); if (info == s_noInterfaces) { return SymbolAndDiagnostics.Empty; } // PERF: Avoid delegate allocation by splitting GetOrAdd into TryGetValue+TryAdd var map = info.ImplementationForInterfaceMemberMap; SymbolAndDiagnostics result; if (map.TryGetValue(interfaceMember, out result)) { return result; } result = ComputeImplementationAndDiagnosticsForInterfaceMember(interfaceMember, ignoreImplementationInInterfaces: ignoreImplementationInInterfacesIfResultIsNotReady, out bool implementationInInterfacesMightChangeResult); Debug.Assert(ignoreImplementationInInterfacesIfResultIsNotReady || !implementationInInterfacesMightChangeResult); Debug.Assert(!implementationInInterfacesMightChangeResult || result.Symbol is null); if (!implementationInInterfacesMightChangeResult) { map.TryAdd(interfaceMember, result); } return result; default: return SymbolAndDiagnostics.Empty; } } internal Symbol FindImplementationForInterfaceMemberInNonInterface(Symbol interfaceMember, bool ignoreImplementationInInterfacesIfResultIsNotReady = false) { return FindImplementationForInterfaceMemberInNonInterfaceWithDiagnostics(interfaceMember, ignoreImplementationInInterfacesIfResultIsNotReady).Symbol; } private SymbolAndDiagnostics ComputeImplementationAndDiagnosticsForInterfaceMember(Symbol interfaceMember, bool ignoreImplementationInInterfaces, out bool implementationInInterfacesMightChangeResult) { var diagnostics = BindingDiagnosticBag.GetInstance(withDiagnostics: true, withDependencies: this.DeclaringCompilation is object); var implementingMember = ComputeImplementationForInterfaceMember(interfaceMember, this, diagnostics, ignoreImplementationInInterfaces, out implementationInInterfacesMightChangeResult); var implementingMemberAndDiagnostics = new SymbolAndDiagnostics(implementingMember, diagnostics.ToReadOnlyAndFree()); return implementingMemberAndDiagnostics; } /// <summary> /// Performs interface mapping (spec 13.4.4). /// </summary> /// <remarks> /// CONSIDER: we could probably do less work in the metadata and retargeting cases - we won't use the diagnostics. /// </remarks> /// <param name="interfaceMember">A non-null implementable member on an interface type.</param> /// <param name="implementingType">The type implementing the interface property (usually "this").</param> /// <param name="diagnostics">Bag to which to add diagnostics.</param> /// <param name="ignoreImplementationInInterfaces">Do not consider implementation in an interface as a valid candidate for the purpose of this computation.</param> /// <param name="implementationInInterfacesMightChangeResult"> /// Returns true when <paramref name="ignoreImplementationInInterfaces"/> is true, the method fails to locate an implementation and an implementation in /// an interface, if any (its presence is not checked), could potentially be a candidate. Returns false otherwise. /// When true is returned, a different call with <paramref name="ignoreImplementationInInterfaces"/> false might return a symbol. That symbol, if any, /// is guaranteed to be from an interface. /// This parameter is used to optimize caching in <see cref="FindImplementationForInterfaceMemberInNonInterfaceWithDiagnostics"/>. /// </param> /// <returns>The implementing property or null, if there isn't one.</returns> private static Symbol ComputeImplementationForInterfaceMember(Symbol interfaceMember, TypeSymbol implementingType, BindingDiagnosticBag diagnostics, bool ignoreImplementationInInterfaces, out bool implementationInInterfacesMightChangeResult) { Debug.Assert(!implementingType.IsInterfaceType()); Debug.Assert(interfaceMember.Kind == SymbolKind.Method || interfaceMember.Kind == SymbolKind.Property || interfaceMember.Kind == SymbolKind.Event); Debug.Assert(interfaceMember.IsImplementableInterfaceMember()); NamedTypeSymbol interfaceType = interfaceMember.ContainingType; Debug.Assert((object)interfaceType != null && interfaceType.IsInterface); bool seenTypeDeclaringInterface = false; // NOTE: In other areas of the compiler, we check whether the member is from a specific compilation. // We could do the same thing here, but that would mean that callers of the public API would have // to pass in a Compilation object when asking about interface implementation. This extra cost eliminates // the small benefit of getting identical answers from "imported" symbols, regardless of whether they // are imported as source or metadata symbols. // // ACASEY: As of 2013/01/24, we are not aware of any cases where the source and metadata behaviors // disagree *in code that can be emitted*. (If there are any, they are likely to involved ambiguous // overrides, which typically arise through combinations of ref/out and generics.) In incorrect code, // the source behavior is somewhat more generous (e.g. accepting a method with the wrong return type), // but we do not guarantee that incorrect source will be treated in the same way as incorrect metadata. // // NOTE: The batch compiler is not affected by this discrepancy, since compilations don't call these // APIs on symbols from other compilations. bool implementingTypeIsFromSomeCompilation = false; Symbol implicitImpl = null; Symbol closestMismatch = null; bool canBeImplementedImplicitlyInCSharp9 = interfaceMember.DeclaredAccessibility == Accessibility.Public && !interfaceMember.IsEventOrPropertyWithImplementableNonPublicAccessor(); TypeSymbol implementingBaseOpt = null; // Calculated only if canBeImplementedImplicitly == false bool implementingTypeImplementsInterface = false; CSharpCompilation compilation = implementingType.DeclaringCompilation; var useSiteInfo = compilation is object ? new CompoundUseSiteInfo<AssemblySymbol>(diagnostics, compilation.Assembly) : CompoundUseSiteInfo<AssemblySymbol>.DiscardedDependencies; for (TypeSymbol currType = implementingType; (object)currType != null; currType = currType.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo)) { // NOTE: In the case of PE symbols, it is possible to see an explicit implementation // on a type that does not declare the corresponding interface (or one of its // subinterfaces). In such cases, we want to return the explicit implementation, // even if it doesn't participate in interface mapping according to the C# rules. // pass 1: check for explicit impls (can't assume name matches) MultiDictionary<Symbol, Symbol>.ValueSet explicitImpl = currType.GetExplicitImplementationForInterfaceMember(interfaceMember); if (explicitImpl.Count == 1) { implementationInInterfacesMightChangeResult = false; return explicitImpl.Single(); } else if (explicitImpl.Count > 1) { if ((object)currType == implementingType || implementingTypeImplementsInterface) { diagnostics.Add(ErrorCode.ERR_DuplicateExplicitImpl, implementingType.Locations[0], interfaceMember); } implementationInInterfacesMightChangeResult = false; return null; } bool checkPendingExplicitImplementations = ((object)currType != implementingType || !currType.IsDefinition); if (checkPendingExplicitImplementations && interfaceMember is MethodSymbol interfaceMethod && currType.InterfacesAndTheirBaseInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo).ContainsKey(interfaceType)) { // Check for implementations that are going to be explicit once types are emitted MethodSymbol bodyOfSynthesizedMethodImpl = currType.GetBodyOfSynthesizedInterfaceMethodImpl(interfaceMethod); if (bodyOfSynthesizedMethodImpl is object) { implementationInInterfacesMightChangeResult = false; return bodyOfSynthesizedMethodImpl; } } if (IsExplicitlyImplementedViaAccessors(checkPendingExplicitImplementations, interfaceMember, currType, ref useSiteInfo, out Symbol currTypeExplicitImpl)) { // We are looking for a property or event implementation and found an explicit implementation // for its accessor(s) in this type. Stop the process and return event/property associated // with the accessor(s), if any. implementationInInterfacesMightChangeResult = false; // NOTE: may be null. return currTypeExplicitImpl; } if (!seenTypeDeclaringInterface || (!canBeImplementedImplicitlyInCSharp9 && (object)implementingBaseOpt == null)) { if (currType.InterfacesAndTheirBaseInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo).ContainsKey(interfaceType)) { if (!seenTypeDeclaringInterface) { implementingTypeIsFromSomeCompilation = currType.OriginalDefinition.ContainingModule is not PEModuleSymbol; seenTypeDeclaringInterface = true; } if ((object)currType == implementingType) { implementingTypeImplementsInterface = true; } else if (!canBeImplementedImplicitlyInCSharp9 && (object)implementingBaseOpt == null) { implementingBaseOpt = currType; } } } // We want the implementation from the most derived type at or above the first one to // include the interface (or a subinterface) in its interface list if (seenTypeDeclaringInterface && (!interfaceMember.IsStatic || implementingTypeIsFromSomeCompilation)) { //pass 2: check for implicit impls (name must match) Symbol currTypeImplicitImpl; Symbol currTypeCloseMismatch; FindPotentialImplicitImplementationMemberDeclaredInType( interfaceMember, implementingTypeIsFromSomeCompilation, currType, out currTypeImplicitImpl, out currTypeCloseMismatch); if ((object)currTypeImplicitImpl != null) { implicitImpl = currTypeImplicitImpl; break; } if ((object)closestMismatch == null) { closestMismatch = currTypeCloseMismatch; } } } Debug.Assert(!canBeImplementedImplicitlyInCSharp9 || (object)implementingBaseOpt == null); bool tryDefaultInterfaceImplementation = !interfaceMember.IsStatic; // Dev10 has some extra restrictions and extra wiggle room when finding implicit // implementations for interface accessors. Perform some extra checks and possibly // update the result (i.e. implicitImpl). if (interfaceMember.IsAccessor()) { Symbol originalImplicitImpl = implicitImpl; CheckForImplementationOfCorrespondingPropertyOrEvent((MethodSymbol)interfaceMember, implementingType, implementingTypeIsFromSomeCompilation, ref implicitImpl); // If we discarded the candidate, we don't want default interface implementation to take over later, since runtime might still use the discarded candidate. if (originalImplicitImpl is object && implicitImpl is null) { tryDefaultInterfaceImplementation = false; } } Symbol defaultImpl = null; if ((object)implicitImpl == null && seenTypeDeclaringInterface && tryDefaultInterfaceImplementation) { if (ignoreImplementationInInterfaces) { implementationInInterfacesMightChangeResult = true; } else { // Check for default interface implementations defaultImpl = FindMostSpecificImplementationInInterfaces(interfaceMember, implementingType, ref useSiteInfo, diagnostics); implementationInInterfacesMightChangeResult = false; } } else { implementationInInterfacesMightChangeResult = false; } diagnostics.Add( #if !DEBUG // Don't optimize in DEBUG for better coverage for the GetInterfaceLocation function. useSiteInfo.Diagnostics is null || !implementingTypeImplementsInterface ? Location.None : #endif GetInterfaceLocation(interfaceMember, implementingType), useSiteInfo); if (defaultImpl is object) { if (implementingTypeImplementsInterface) { ReportDefaultInterfaceImplementationMatchDiagnostics(interfaceMember, implementingType, defaultImpl, diagnostics); } return defaultImpl; } if (implementingTypeImplementsInterface) { if ((object)implicitImpl != null) { if (!canBeImplementedImplicitlyInCSharp9) { if (interfaceMember.Kind == SymbolKind.Method && (object)implementingBaseOpt == null) // Otherwise any approprite errors are going to be reported for the base. { LanguageVersion requiredVersion = MessageID.IDS_FeatureImplicitImplementationOfNonPublicMembers.RequiredVersion(); LanguageVersion? availableVersion = implementingType.DeclaringCompilation?.LanguageVersion; if (requiredVersion > availableVersion) { diagnostics.Add(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, GetInterfaceLocation(interfaceMember, implementingType), implementingType, interfaceMember, implicitImpl, availableVersion.GetValueOrDefault().ToDisplayString(), new CSharpRequiredLanguageVersion(requiredVersion)); } } } ReportImplicitImplementationMatchDiagnostics(interfaceMember, implementingType, implicitImpl, diagnostics); } else if ((object)closestMismatch != null) { ReportImplicitImplementationMismatchDiagnostics(interfaceMember, implementingType, closestMismatch, diagnostics); } } return implicitImpl; } private static Symbol FindMostSpecificImplementationInInterfaces(Symbol interfaceMember, TypeSymbol implementingType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, BindingDiagnosticBag diagnostics) { Debug.Assert(!implementingType.IsInterfaceType()); Debug.Assert(!interfaceMember.IsStatic); // If we are dealing with a property or event and an implementation of at least one accessor is not from an interface, it // wouldn't be right to say that the event/property is implemented in an interface because its accessor isn't. (MethodSymbol interfaceAccessor1, MethodSymbol interfaceAccessor2) = GetImplementableAccessors(interfaceMember); if (stopLookup(interfaceAccessor1, implementingType) || stopLookup(interfaceAccessor2, implementingType)) { return null; } Symbol defaultImpl = FindMostSpecificImplementationInBases(interfaceMember, implementingType, ref useSiteInfo, out Symbol conflict1, out Symbol conflict2); if ((object)conflict1 != null) { Debug.Assert((object)defaultImpl == null); Debug.Assert((object)conflict2 != null); diagnostics.Add(ErrorCode.ERR_MostSpecificImplementationIsNotFound, GetInterfaceLocation(interfaceMember, implementingType), interfaceMember, conflict1, conflict2); } else { Debug.Assert(((object)conflict2 == null)); } return defaultImpl; static bool stopLookup(MethodSymbol interfaceAccessor, TypeSymbol implementingType) { if (interfaceAccessor is null) { return false; } SymbolAndDiagnostics symbolAndDiagnostics = implementingType.FindImplementationForInterfaceMemberInNonInterfaceWithDiagnostics(interfaceAccessor); if (symbolAndDiagnostics.Symbol is object) { return !symbolAndDiagnostics.Symbol.ContainingType.IsInterface; } // It is still possible that we actually looked for the accessor in interfaces, but failed due to an ambiguity. // Let's try to look for a property to improve diagnostics in this scenario. return !symbolAndDiagnostics.Diagnostics.Diagnostics.Any(d => d.Code == (int)ErrorCode.ERR_MostSpecificImplementationIsNotFound); } } private static Symbol FindMostSpecificImplementation(Symbol interfaceMember, NamedTypeSymbol implementingInterface, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { MultiDictionary<Symbol, Symbol>.ValueSet implementingMember = FindImplementationInInterface(interfaceMember, implementingInterface); switch (implementingMember.Count) { case 0: (MethodSymbol interfaceAccessor1, MethodSymbol interfaceAccessor2) = GetImplementableAccessors(interfaceMember); // If interface actually implements an event or property accessor, but doesn't implement the event/property, // do not look for its implementation in bases. if ((interfaceAccessor1 is object && FindImplementationInInterface(interfaceAccessor1, implementingInterface).Count != 0) || (interfaceAccessor2 is object && FindImplementationInInterface(interfaceAccessor2, implementingInterface).Count != 0)) { return null; } return FindMostSpecificImplementationInBases(interfaceMember, implementingInterface, ref useSiteInfo, out var _, out var _); case 1: { Symbol result = implementingMember.Single(); if (result.IsAbstract) { return null; } return result; } default: return null; } } /// <summary> /// One implementation M1 is considered more specific than another implementation M2 /// if M1 is declared on interface T1, M2 is declared on interface T2, and /// T1 contains T2 among its direct or indirect interfaces. /// </summary> private static Symbol FindMostSpecificImplementationInBases( Symbol interfaceMember, TypeSymbol implementingType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, out Symbol conflictingImplementation1, out Symbol conflictingImplementation2) { ImmutableArray<NamedTypeSymbol> allInterfaces = implementingType.AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo); if (allInterfaces.IsEmpty) { conflictingImplementation1 = null; conflictingImplementation2 = null; return null; } // Properties or events can be implemented in an unconventional manner, i.e. implementing accessors might not be tied to a property/event. // If we simply look for a more specific implementing property/event, we might find one with not most specific implementing accessors. // Returning a property/event like that would be incorrect because runtime will use most specific accessor, or it will fail because there will // be an ambiguity for the accessor implementation. // So, for events and properties we look for most specific implementation of corresponding accessors and then try to tie them back to // an event/property, if any. (MethodSymbol interfaceAccessor1, MethodSymbol interfaceAccessor2) = GetImplementableAccessors(interfaceMember); if (interfaceAccessor1 is null && interfaceAccessor2 is null) { return findMostSpecificImplementationInBases(interfaceMember, allInterfaces, ref useSiteInfo, out conflictingImplementation1, out conflictingImplementation2); } Symbol accessorImpl1 = findMostSpecificImplementationInBases(interfaceAccessor1 ?? interfaceAccessor2, allInterfaces, ref useSiteInfo, out Symbol conflictingAccessorImplementation11, out Symbol conflictingAccessorImplementation12); if (accessorImpl1 is null && conflictingAccessorImplementation11 is null) // implementation of accessor is not found { conflictingImplementation1 = null; conflictingImplementation2 = null; return null; } if (interfaceAccessor1 is null || interfaceAccessor2 is null) { if (accessorImpl1 is object) { conflictingImplementation1 = null; conflictingImplementation2 = null; return findImplementationInInterface(interfaceMember, accessorImpl1); } conflictingImplementation1 = findImplementationInInterface(interfaceMember, conflictingAccessorImplementation11); conflictingImplementation2 = findImplementationInInterface(interfaceMember, conflictingAccessorImplementation12); if ((conflictingImplementation1 is null) != (conflictingImplementation2 is null)) { conflictingImplementation1 = null; conflictingImplementation2 = null; } return null; } Symbol accessorImpl2 = findMostSpecificImplementationInBases(interfaceAccessor2, allInterfaces, ref useSiteInfo, out Symbol conflictingAccessorImplementation21, out Symbol conflictingAccessorImplementation22); if ((accessorImpl2 is null && conflictingAccessorImplementation21 is null) || // implementation of accessor is not found (accessorImpl1 is null) != (accessorImpl2 is null)) // there is most specific implementation for one accessor and an ambiguous implementation for the other accessor. { conflictingImplementation1 = null; conflictingImplementation2 = null; return null; } if (accessorImpl1 is object) { conflictingImplementation1 = null; conflictingImplementation2 = null; return findImplementationInInterface(interfaceMember, accessorImpl1, accessorImpl2); } conflictingImplementation1 = findImplementationInInterface(interfaceMember, conflictingAccessorImplementation11, conflictingAccessorImplementation21); conflictingImplementation2 = findImplementationInInterface(interfaceMember, conflictingAccessorImplementation12, conflictingAccessorImplementation22); if ((conflictingImplementation1 is null) != (conflictingImplementation2 is null)) { // One pair of conflicting accessors can be tied to an event/property, but the other cannot be tied to an event/property. // Dropping conflict information since it only affects diagnostic. conflictingImplementation1 = null; conflictingImplementation2 = null; } return null; static Symbol findImplementationInInterface(Symbol interfaceMember, Symbol inplementingAccessor1, Symbol implementingAccessor2 = null) { NamedTypeSymbol implementingInterface = inplementingAccessor1.ContainingType; if (implementingAccessor2 is object && !implementingInterface.Equals(implementingAccessor2.ContainingType, TypeCompareKind.ConsiderEverything)) { // Implementing accessors are from different types, they cannot be tied to the same event/property. return null; } MultiDictionary<Symbol, Symbol>.ValueSet implementingMember = FindImplementationInInterface(interfaceMember, implementingInterface); switch (implementingMember.Count) { case 1: return implementingMember.Single(); default: return null; } } static Symbol findMostSpecificImplementationInBases( Symbol interfaceMember, ImmutableArray<NamedTypeSymbol> allInterfaces, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, out Symbol conflictingImplementation1, out Symbol conflictingImplementation2) { var implementations = ArrayBuilder<(MultiDictionary<Symbol, Symbol>.ValueSet MethodSet, MultiDictionary<NamedTypeSymbol, NamedTypeSymbol> Bases)>.GetInstance(); foreach (var interfaceType in allInterfaces) { if (!interfaceType.IsInterface) { // this code is reachable in error situations continue; } MultiDictionary<Symbol, Symbol>.ValueSet candidate = FindImplementationInInterface(interfaceMember, interfaceType); if (candidate.Count == 0) { continue; } for (int i = 0; i < implementations.Count; i++) { (MultiDictionary<Symbol, Symbol>.ValueSet methodSet, MultiDictionary<NamedTypeSymbol, NamedTypeSymbol> bases) = implementations[i]; Symbol previous = methodSet.First(); NamedTypeSymbol previousContainingType = previous.ContainingType; if (previousContainingType.Equals(interfaceType, TypeCompareKind.CLRSignatureCompareOptions)) { // Last equivalent match wins implementations[i] = (candidate, bases); candidate = default; break; } if (bases == null) { Debug.Assert(implementations.Count == 1); bases = previousContainingType.InterfacesAndTheirBaseInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo); implementations[i] = (methodSet, bases); } if (bases.ContainsKey(interfaceType)) { // Previous candidate is more specific candidate = default; break; } } if (candidate.Count == 0) { continue; } if (implementations.Count != 0) { MultiDictionary<NamedTypeSymbol, NamedTypeSymbol> bases = interfaceType.InterfacesAndTheirBaseInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo); for (int i = implementations.Count - 1; i >= 0; i--) { if (bases.ContainsKey(implementations[i].MethodSet.First().ContainingType)) { // new candidate is more specific implementations.RemoveAt(i); } } implementations.Add((candidate, bases)); } else { implementations.Add((candidate, null)); } } Symbol result; switch (implementations.Count) { case 0: result = null; conflictingImplementation1 = null; conflictingImplementation2 = null; break; case 1: MultiDictionary<Symbol, Symbol>.ValueSet methodSet = implementations[0].MethodSet; switch (methodSet.Count) { case 1: result = methodSet.Single(); if (result.IsAbstract) { result = null; } break; default: result = null; break; } conflictingImplementation1 = null; conflictingImplementation2 = null; break; default: result = null; conflictingImplementation1 = implementations[0].MethodSet.First(); conflictingImplementation2 = implementations[1].MethodSet.First(); break; } implementations.Free(); return result; } } internal static MultiDictionary<Symbol, Symbol>.ValueSet FindImplementationInInterface(Symbol interfaceMember, NamedTypeSymbol interfaceType) { Debug.Assert(interfaceType.IsInterface); Debug.Assert(!interfaceMember.IsStatic); NamedTypeSymbol containingType = interfaceMember.ContainingType; if (containingType.Equals(interfaceType, TypeCompareKind.CLRSignatureCompareOptions)) { if (!interfaceMember.IsAbstract) { if (!containingType.Equals(interfaceType, TypeCompareKind.ConsiderEverything)) { interfaceMember = interfaceMember.OriginalDefinition.SymbolAsMember(interfaceType); } return new MultiDictionary<Symbol, Symbol>.ValueSet(interfaceMember); } return default; } return interfaceType.GetExplicitImplementationForInterfaceMember(interfaceMember); } private static (MethodSymbol interfaceAccessor1, MethodSymbol interfaceAccessor2) GetImplementableAccessors(Symbol interfaceMember) { MethodSymbol interfaceAccessor1; MethodSymbol interfaceAccessor2; switch (interfaceMember.Kind) { case SymbolKind.Property: { PropertySymbol interfaceProperty = (PropertySymbol)interfaceMember; interfaceAccessor1 = interfaceProperty.GetMethod; interfaceAccessor2 = interfaceProperty.SetMethod; break; } case SymbolKind.Event: { EventSymbol interfaceEvent = (EventSymbol)interfaceMember; interfaceAccessor1 = interfaceEvent.AddMethod; interfaceAccessor2 = interfaceEvent.RemoveMethod; break; } default: { interfaceAccessor1 = null; interfaceAccessor2 = null; break; } } if (!interfaceAccessor1.IsImplementable()) { interfaceAccessor1 = null; } if (!interfaceAccessor2.IsImplementable()) { interfaceAccessor2 = null; } return (interfaceAccessor1, interfaceAccessor2); } /// <summary> /// Since dev11 didn't expose a symbol API, it had the luxury of being able to accept a base class's claim that /// it implements an interface. Roslyn, on the other hand, needs to be able to point to an implementing symbol /// for each interface member. /// /// DevDiv #718115 was triggered by some unusual metadata in a Microsoft reference assembly (Silverlight System.Windows.dll). /// The issue was that a type explicitly implemented the accessors of an interface event, but did not tie them together with /// an event declaration. To make matters worse, it declared its own protected event with the same name as the interface /// event (presumably to back the explicit implementation). As a result, when Roslyn was asked to find the implementing member /// for the interface event, it found the protected event and reported an appropriate diagnostic. What it should have done /// (and does do now) is recognize that no event associated with the accessors explicitly implementing the interface accessors /// and returned null. /// /// We resolved this issue by introducing a new step into the interface mapping algorithm: after failing to find an explicit /// implementation in a type, but before searching for an implicit implementation in that type, check for an explicit implementation /// of an associated accessor. If there is such an implementation, then immediately return the associated property or event, /// even if it is null. That is, never attempt to find an implicit implementation for an interface property or event with an /// explicitly implemented accessor. /// </summary> private static bool IsExplicitlyImplementedViaAccessors(bool checkPendingExplicitImplementations, Symbol interfaceMember, TypeSymbol currType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, out Symbol implementingMember) { (MethodSymbol interfaceAccessor1, MethodSymbol interfaceAccessor2) = GetImplementableAccessors(interfaceMember); Symbol associated1; Symbol associated2; if (TryGetExplicitImplementationAssociatedPropertyOrEvent(checkPendingExplicitImplementations, interfaceAccessor1, currType, ref useSiteInfo, out associated1) | // NB: not || TryGetExplicitImplementationAssociatedPropertyOrEvent(checkPendingExplicitImplementations, interfaceAccessor2, currType, ref useSiteInfo, out associated2)) { // If there's more than one associated property/event, don't do anything special - just let the algorithm // fail in the usual way. if ((object)associated1 == null || (object)associated2 == null || associated1 == associated2) { implementingMember = associated1 ?? associated2; // In source, we should already have seen an explicit implementation for the interface property/event. // If we haven't then there is no implementation. We need this check to match dev11 in some edge cases // (e.g. IndexerTests.AmbiguousExplicitIndexerImplementation). Such cases already fail // to roundtrip correctly, so it's not important to check for a particular compilation. if ((object)implementingMember != null && implementingMember.OriginalDefinition.ContainingModule is not PEModuleSymbol && implementingMember.IsExplicitInterfaceImplementation()) { implementingMember = null; } } else { implementingMember = null; } return true; } implementingMember = null; return false; } private static bool TryGetExplicitImplementationAssociatedPropertyOrEvent(bool checkPendingExplicitImplementations, MethodSymbol interfaceAccessor, TypeSymbol currType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, out Symbol associated) { if ((object)interfaceAccessor != null) { // NB: uses a map that was built (and saved) when we checked for an explicit // implementation of the interface member. MultiDictionary<Symbol, Symbol>.ValueSet set = currType.GetExplicitImplementationForInterfaceMember(interfaceAccessor); if (set.Count == 1) { Symbol implementation = set.Single(); associated = implementation.Kind == SymbolKind.Method ? ((MethodSymbol)implementation).AssociatedSymbol : null; return true; } if (checkPendingExplicitImplementations && currType.InterfacesAndTheirBaseInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo).ContainsKey(interfaceAccessor.ContainingType)) { // Check for implementations that are going to be explicit once types are emitted MethodSymbol bodyOfSynthesizedMethodImpl = currType.GetBodyOfSynthesizedInterfaceMethodImpl(interfaceAccessor); if (bodyOfSynthesizedMethodImpl is object) { associated = bodyOfSynthesizedMethodImpl.AssociatedSymbol; return true; } } } associated = null; return false; } /// <summary> /// If we were looking for an accessor, then look for an accessor on the implementation of the /// corresponding interface property/event. If it is valid as an implementation (ignoring the name), /// then prefer it to our current result if: /// 1) our current result is null; or /// 2) our current result is on the same type. /// /// If there is no corresponding accessor on the implementation of the corresponding interface /// property/event and we found an accessor, then the accessor we found is invalid, so clear it. /// </summary> private static void CheckForImplementationOfCorrespondingPropertyOrEvent(MethodSymbol interfaceMethod, TypeSymbol implementingType, bool implementingTypeIsFromSomeCompilation, ref Symbol implicitImpl) { Debug.Assert(!implementingType.IsInterfaceType()); Debug.Assert(interfaceMethod.IsAccessor()); Symbol associatedInterfacePropertyOrEvent = interfaceMethod.AssociatedSymbol; // Do not make any adjustments based on presence of default interface implementation for the property or event. // We don't want an addition of default interface implementation to change an error situation to success for // scenarios where the default interface implementation wouldn't actually be used at runtime. // When we find an implicit implementation candidate, we don't want to not discard it if we would discard it when // default interface implementation was missing. Why would presence of default interface implementation suddenly // make the candidate suiatable to implement the interface? Also, if we discard the candidate, we don't want default interface // implementation to take over later, since runtime might still use the discarded candidate. // When we don't find any implicit implementation candidate, returning accessor of default interface implementation // doesn't actually help much because we would find it anyway (it is implemented explicitly). Symbol implementingPropertyOrEvent = implementingType.FindImplementationForInterfaceMemberInNonInterface(associatedInterfacePropertyOrEvent, ignoreImplementationInInterfacesIfResultIsNotReady: true); // NB: uses cache MethodSymbol correspondingImplementingAccessor = null; if ((object)implementingPropertyOrEvent != null && !implementingPropertyOrEvent.ContainingType.IsInterface) { switch (interfaceMethod.MethodKind) { case MethodKind.PropertyGet: correspondingImplementingAccessor = ((PropertySymbol)implementingPropertyOrEvent).GetOwnOrInheritedGetMethod(); break; case MethodKind.PropertySet: correspondingImplementingAccessor = ((PropertySymbol)implementingPropertyOrEvent).GetOwnOrInheritedSetMethod(); break; case MethodKind.EventAdd: correspondingImplementingAccessor = ((EventSymbol)implementingPropertyOrEvent).GetOwnOrInheritedAddMethod(); break; case MethodKind.EventRemove: correspondingImplementingAccessor = ((EventSymbol)implementingPropertyOrEvent).GetOwnOrInheritedRemoveMethod(); break; default: throw ExceptionUtilities.UnexpectedValue(interfaceMethod.MethodKind); } } if (correspondingImplementingAccessor == implicitImpl) { return; } else if ((object)correspondingImplementingAccessor == null && (object)implicitImpl != null && implicitImpl.IsAccessor()) { // If we found an accessor, but it's not (directly or indirectly) on the property implementation, // then it's not a valid match. implicitImpl = null; } else if ((object)correspondingImplementingAccessor != null && ((object)implicitImpl == null || TypeSymbol.Equals(correspondingImplementingAccessor.ContainingType, implicitImpl.ContainingType, TypeCompareKind.ConsiderEverything2))) { // Suppose the interface accessor and the implementing accessor have different names. // In Dev10, as long as the corresponding properties have an implementation relationship, // then the accessor can be considered an implementation, even though the name is different. // Later on, when we check that implementation signatures match exactly // (in SourceMemberContainerTypeSymbol.SynthesizeInterfaceMemberImplementation), // they won't (because of the names) and an explicit implementation method will be synthesized. MethodSymbol interfaceAccessorWithImplementationName = new SignatureOnlyMethodSymbol( correspondingImplementingAccessor.Name, interfaceMethod.ContainingType, interfaceMethod.MethodKind, interfaceMethod.CallingConvention, interfaceMethod.TypeParameters, interfaceMethod.Parameters, interfaceMethod.RefKind, interfaceMethod.IsInitOnly, interfaceMethod.IsStatic, interfaceMethod.ReturnTypeWithAnnotations, interfaceMethod.RefCustomModifiers, interfaceMethod.ExplicitInterfaceImplementations); // Make sure that the corresponding accessor is a real implementation. if (IsInterfaceMemberImplementation(correspondingImplementingAccessor, interfaceAccessorWithImplementationName, implementingTypeIsFromSomeCompilation)) { implicitImpl = correspondingImplementingAccessor; } } } private static void ReportDefaultInterfaceImplementationMatchDiagnostics(Symbol interfaceMember, TypeSymbol implementingType, Symbol implicitImpl, BindingDiagnosticBag diagnostics) { if (interfaceMember.Kind == SymbolKind.Method && implementingType.ContainingModule != implicitImpl.ContainingModule) { // The default implementation is coming from a different module, which means that we probably didn't check // for the required runtime capability or language version LanguageVersion requiredVersion = MessageID.IDS_DefaultInterfaceImplementation.RequiredVersion(); LanguageVersion? availableVersion = implementingType.DeclaringCompilation?.LanguageVersion; if (requiredVersion > availableVersion) { diagnostics.Add(ErrorCode.ERR_LanguageVersionDoesNotSupportDefaultInterfaceImplementationForMember, GetInterfaceLocation(interfaceMember, implementingType), implicitImpl, interfaceMember, implementingType, MessageID.IDS_DefaultInterfaceImplementation.Localize(), availableVersion.GetValueOrDefault().ToDisplayString(), new CSharpRequiredLanguageVersion(requiredVersion)); } if (!implementingType.ContainingAssembly.RuntimeSupportsDefaultInterfaceImplementation) { diagnostics.Add(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementationForMember, GetInterfaceLocation(interfaceMember, implementingType), implicitImpl, interfaceMember, implementingType); } } } /// <summary> /// These diagnostics are for members that do implicitly implement an interface member, but do so /// in an undesirable way. /// </summary> private static void ReportImplicitImplementationMatchDiagnostics(Symbol interfaceMember, TypeSymbol implementingType, Symbol implicitImpl, BindingDiagnosticBag diagnostics) { bool reportedAnError = false; if (interfaceMember.Kind == SymbolKind.Method) { var interfaceMethod = (MethodSymbol)interfaceMember; bool implicitImplIsAccessor = implicitImpl.IsAccessor(); bool interfaceMethodIsAccessor = interfaceMethod.IsAccessor(); if (interfaceMethodIsAccessor && !implicitImplIsAccessor && !interfaceMethod.IsIndexedPropertyAccessor()) { diagnostics.Add(ErrorCode.ERR_MethodImplementingAccessor, GetImplicitImplementationDiagnosticLocation(interfaceMember, implementingType, implicitImpl), implicitImpl, interfaceMethod, implementingType); } else if (!interfaceMethodIsAccessor && implicitImplIsAccessor) { diagnostics.Add(ErrorCode.ERR_AccessorImplementingMethod, GetImplicitImplementationDiagnosticLocation(interfaceMember, implementingType, implicitImpl), implicitImpl, interfaceMethod, implementingType); } else { var implicitImplMethod = (MethodSymbol)implicitImpl; if (implicitImplMethod.IsConditional) { // CS0629: Conditional member '{0}' cannot implement interface member '{1}' in type '{2}' diagnostics.Add(ErrorCode.ERR_InterfaceImplementedByConditional, GetImplicitImplementationDiagnosticLocation(interfaceMember, implementingType, implicitImpl), implicitImpl, interfaceMethod, implementingType); } else if (implicitImplMethod.IsStatic && implicitImplMethod.MethodKind == MethodKind.Ordinary && implicitImplMethod.GetUnmanagedCallersOnlyAttributeData(forceComplete: true) is not null) { diagnostics.Add(ErrorCode.ERR_InterfaceImplementedByUnmanagedCallersOnlyMethod, GetImplicitImplementationDiagnosticLocation(interfaceMember, implementingType, implicitImpl), implicitImpl, interfaceMethod, implementingType); } else if (ReportAnyMismatchedConstraints(interfaceMethod, implementingType, implicitImplMethod, diagnostics)) { reportedAnError = true; } } } if (implicitImpl.ContainsTupleNames() && MemberSignatureComparer.ConsideringTupleNamesCreatesDifference(implicitImpl, interfaceMember)) { // it is ok to implement implicitly with no tuple names, for compatibility with C# 6, but otherwise names should match diagnostics.Add(ErrorCode.ERR_ImplBadTupleNames, GetImplicitImplementationDiagnosticLocation(interfaceMember, implementingType, implicitImpl), implicitImpl, interfaceMember); reportedAnError = true; } if (!reportedAnError && implementingType.DeclaringCompilation != null) { CheckNullableReferenceTypeMismatchOnImplementingMember(implementingType, implicitImpl, interfaceMember, isExplicit: false, diagnostics); } // In constructed types, it is possible to see multiple members with the same (runtime) signature. // Now that we know which member will implement the interface member, confirm that it is the only // such member. if (!implicitImpl.ContainingType.IsDefinition) { foreach (Symbol member in implicitImpl.ContainingType.GetMembers(implicitImpl.Name)) { if (member.DeclaredAccessibility != Accessibility.Public || member.IsStatic || member == implicitImpl) { //do nothing - not an ambiguous implementation } else if (MemberSignatureComparer.RuntimeImplicitImplementationComparer.Equals(interfaceMember, member) && !member.IsAccessor()) { // CONSIDER: Dev10 does not seem to report this for indexers or their accessors. diagnostics.Add(ErrorCode.WRN_MultipleRuntimeImplementationMatches, GetImplicitImplementationDiagnosticLocation(interfaceMember, implementingType, member), member, interfaceMember, implementingType); } } } if (implicitImpl.IsStatic && !implementingType.ContainingAssembly.RuntimeSupportsStaticAbstractMembersInInterfaces) { diagnostics.Add(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, GetInterfaceLocation(interfaceMember, implementingType), implicitImpl, interfaceMember, implementingType); } } internal static void CheckNullableReferenceTypeMismatchOnImplementingMember(TypeSymbol implementingType, Symbol implementingMember, Symbol interfaceMember, bool isExplicit, BindingDiagnosticBag diagnostics) { if (!implementingMember.IsImplicitlyDeclared && !implementingMember.IsAccessor()) { CSharpCompilation compilation = implementingType.DeclaringCompilation; if (interfaceMember.Kind == SymbolKind.Event) { var implementingEvent = (EventSymbol)implementingMember; var implementedEvent = (EventSymbol)interfaceMember; SourceMemberContainerTypeSymbol.CheckValidNullableEventOverride(compilation, implementedEvent, implementingEvent, diagnostics, (diagnostics, implementedEvent, implementingEvent, arg) => { if (arg.isExplicit) { diagnostics.Add(ErrorCode.WRN_NullabilityMismatchInTypeOnExplicitImplementation, implementingEvent.Locations[0], new FormattedSymbol(implementedEvent, SymbolDisplayFormat.MinimallyQualifiedFormat)); } else { diagnostics.Add(ErrorCode.WRN_NullabilityMismatchInTypeOnImplicitImplementation, GetImplicitImplementationDiagnosticLocation(implementedEvent, arg.implementingType, implementingEvent), new FormattedSymbol(implementingEvent, SymbolDisplayFormat.MinimallyQualifiedFormat), new FormattedSymbol(implementedEvent, SymbolDisplayFormat.MinimallyQualifiedFormat)); } }, (implementingType, isExplicit)); } else { ReportMismatchInReturnType<(TypeSymbol implementingType, bool isExplicit)> reportMismatchInReturnType = (diagnostics, implementedMethod, implementingMethod, topLevel, arg) => { if (arg.isExplicit) { // We use ConstructedFrom symbols here and below to not leak methods with Ignored annotations in type arguments // into diagnostics diagnostics.Add(topLevel ? ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnExplicitImplementation : ErrorCode.WRN_NullabilityMismatchInReturnTypeOnExplicitImplementation, implementingMethod.Locations[0], new FormattedSymbol(implementedMethod.ConstructedFrom, SymbolDisplayFormat.MinimallyQualifiedFormat)); } else { diagnostics.Add(topLevel ? ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnImplicitImplementation : ErrorCode.WRN_NullabilityMismatchInReturnTypeOnImplicitImplementation, GetImplicitImplementationDiagnosticLocation(implementedMethod, arg.implementingType, implementingMethod), new FormattedSymbol(implementingMethod, SymbolDisplayFormat.MinimallyQualifiedFormat), new FormattedSymbol(implementedMethod.ConstructedFrom, SymbolDisplayFormat.MinimallyQualifiedFormat)); } }; ReportMismatchInParameterType<(TypeSymbol implementingType, bool isExplicit)> reportMismatchInParameterType = (diagnostics, implementedMethod, implementingMethod, implementingParameter, topLevel, arg) => { if (arg.isExplicit) { diagnostics.Add(topLevel ? ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnExplicitImplementation : ErrorCode.WRN_NullabilityMismatchInParameterTypeOnExplicitImplementation, implementingMethod.Locations[0], new FormattedSymbol(implementingParameter, SymbolDisplayFormat.ShortFormat), new FormattedSymbol(implementedMethod.ConstructedFrom, SymbolDisplayFormat.MinimallyQualifiedFormat)); } else { diagnostics.Add(topLevel ? ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnImplicitImplementation : ErrorCode.WRN_NullabilityMismatchInParameterTypeOnImplicitImplementation, GetImplicitImplementationDiagnosticLocation(implementedMethod, arg.implementingType, implementingMethod), new FormattedSymbol(implementingParameter, SymbolDisplayFormat.ShortFormat), new FormattedSymbol(implementingMethod, SymbolDisplayFormat.MinimallyQualifiedFormat), new FormattedSymbol(implementedMethod.ConstructedFrom, SymbolDisplayFormat.MinimallyQualifiedFormat)); } }; switch (interfaceMember.Kind) { case SymbolKind.Property: var implementingProperty = (PropertySymbol)implementingMember; var implementedProperty = (PropertySymbol)interfaceMember; if (implementedProperty.GetMethod.IsImplementable()) { MethodSymbol implementingGetMethod = implementingProperty.GetOwnOrInheritedGetMethod(); SourceMemberContainerTypeSymbol.CheckValidNullableMethodOverride( compilation, implementedProperty.GetMethod, implementingGetMethod, diagnostics, reportMismatchInReturnType, // Don't check parameters on the getter if there is a setter // because they will be a subset of the setter (!implementedProperty.SetMethod.IsImplementable() || implementingGetMethod?.AssociatedSymbol != implementingProperty || implementingProperty.GetOwnOrInheritedSetMethod()?.AssociatedSymbol != implementingProperty) ? reportMismatchInParameterType : null, (implementingType, isExplicit)); } if (implementedProperty.SetMethod.IsImplementable()) { SourceMemberContainerTypeSymbol.CheckValidNullableMethodOverride( compilation, implementedProperty.SetMethod, implementingProperty.GetOwnOrInheritedSetMethod(), diagnostics, null, reportMismatchInParameterType, (implementingType, isExplicit)); } break; case SymbolKind.Method: var implementingMethod = (MethodSymbol)implementingMember; var implementedMethod = (MethodSymbol)interfaceMember; if (implementedMethod.IsGenericMethod) { implementedMethod = implementedMethod.Construct(TypeMap.TypeParametersAsTypeSymbolsWithIgnoredAnnotations(implementingMethod.TypeParameters)); } SourceMemberContainerTypeSymbol.CheckValidNullableMethodOverride( compilation, implementedMethod, implementingMethod, diagnostics, reportMismatchInReturnType, reportMismatchInParameterType, (implementingType, isExplicit)); break; default: throw ExceptionUtilities.UnexpectedValue(interfaceMember.Kind); } } } } /// <summary> /// These diagnostics are for members that almost, but not actually, implicitly implement an interface member. /// </summary> private static void ReportImplicitImplementationMismatchDiagnostics(Symbol interfaceMember, TypeSymbol implementingType, Symbol closestMismatch, BindingDiagnosticBag diagnostics) { // Determine a better location for diagnostic squiggles. Squiggle the interface rather than the class. Location interfaceLocation = GetInterfaceLocation(interfaceMember, implementingType); if (closestMismatch.IsStatic != interfaceMember.IsStatic) { diagnostics.Add(closestMismatch.IsStatic ? ErrorCode.ERR_CloseUnimplementedInterfaceMemberStatic : ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotStatic, interfaceLocation, implementingType, interfaceMember, closestMismatch); } else if (closestMismatch.DeclaredAccessibility != Accessibility.Public) { ErrorCode errorCode = interfaceMember.IsAccessor() ? ErrorCode.ERR_UnimplementedInterfaceAccessor : ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic; diagnostics.Add(errorCode, interfaceLocation, implementingType, interfaceMember, closestMismatch); } else if (HaveInitOnlyMismatch(interfaceMember, closestMismatch)) { diagnostics.Add(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongInitOnly, interfaceLocation, implementingType, interfaceMember, closestMismatch); } else //return ref kind or type doesn't match { RefKind interfaceMemberRefKind = RefKind.None; TypeSymbol interfaceMemberReturnType; switch (interfaceMember.Kind) { case SymbolKind.Method: var method = (MethodSymbol)interfaceMember; interfaceMemberRefKind = method.RefKind; interfaceMemberReturnType = method.ReturnType; break; case SymbolKind.Property: var property = (PropertySymbol)interfaceMember; interfaceMemberRefKind = property.RefKind; interfaceMemberReturnType = property.Type; break; case SymbolKind.Event: interfaceMemberReturnType = ((EventSymbol)interfaceMember).Type; break; default: throw ExceptionUtilities.UnexpectedValue(interfaceMember.Kind); } bool hasRefReturnMismatch = false; switch (closestMismatch.Kind) { case SymbolKind.Method: hasRefReturnMismatch = ((MethodSymbol)closestMismatch).RefKind != interfaceMemberRefKind; break; case SymbolKind.Property: hasRefReturnMismatch = ((PropertySymbol)closestMismatch).RefKind != interfaceMemberRefKind; break; } DiagnosticInfo useSiteDiagnostic; if ((object)interfaceMemberReturnType != null && (useSiteDiagnostic = interfaceMemberReturnType.GetUseSiteInfo().DiagnosticInfo) != null && useSiteDiagnostic.DefaultSeverity == DiagnosticSeverity.Error) { diagnostics.Add(useSiteDiagnostic, interfaceLocation); } else if (hasRefReturnMismatch) { diagnostics.Add(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongRefReturn, interfaceLocation, implementingType, interfaceMember, closestMismatch); } else { diagnostics.Add(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, interfaceLocation, implementingType, interfaceMember, closestMismatch, interfaceMemberReturnType); } } } internal static bool HaveInitOnlyMismatch(Symbol one, Symbol other) { if (!(one is MethodSymbol oneMethod)) { return false; } if (!(other is MethodSymbol otherMethod)) { return false; } return oneMethod.IsInitOnly != otherMethod.IsInitOnly; } /// <summary> /// Determine a better location for diagnostic squiggles. Squiggle the interface rather than the class. /// </summary> private static Location GetInterfaceLocation(Symbol interfaceMember, TypeSymbol implementingType) { Debug.Assert((object)implementingType != null); var @interface = interfaceMember.ContainingType; SourceMemberContainerTypeSymbol snt = null; if (implementingType.InterfacesAndTheirBaseInterfacesNoUseSiteDiagnostics[@interface].Contains(@interface)) { snt = implementingType as SourceMemberContainerTypeSymbol; } return snt?.GetImplementsLocation(@interface) ?? implementingType.Locations.FirstOrNone(); } private static bool ReportAnyMismatchedConstraints(MethodSymbol interfaceMethod, TypeSymbol implementingType, MethodSymbol implicitImpl, BindingDiagnosticBag diagnostics) { Debug.Assert(interfaceMethod.Arity == implicitImpl.Arity); bool result = false; var arity = interfaceMethod.Arity; if (arity > 0) { var typeParameters1 = interfaceMethod.TypeParameters; var typeParameters2 = implicitImpl.TypeParameters; var indexedTypeParameters = IndexedTypeParameterSymbol.Take(arity); var typeMap1 = new TypeMap(typeParameters1, indexedTypeParameters, allowAlpha: true); var typeMap2 = new TypeMap(typeParameters2, indexedTypeParameters, allowAlpha: true); // Report any mismatched method constraints. for (int i = 0; i < arity; i++) { var typeParameter1 = typeParameters1[i]; var typeParameter2 = typeParameters2[i]; if (!MemberSignatureComparer.HaveSameConstraints(typeParameter1, typeMap1, typeParameter2, typeMap2)) { // If the matching method for the interface member is defined on the implementing type, // the matching method location is used for the error. Otherwise, the location of the // implementing type is used. (This differs from Dev10 which associates the error with // the closest method always. That behavior can be confusing though, since in the case // of "interface I { M; } class A { M; } class B : A, I { }", this means reporting an error on // A.M that it does not satisfy I.M even though A does not implement I. Furthermore if // A is defined in metadata, there is no location for A.M. Instead, we simply report the // error on B if the match to I.M is in a base class.) diagnostics.Add(ErrorCode.ERR_ImplBadConstraints, GetImplicitImplementationDiagnosticLocation(interfaceMethod, implementingType, implicitImpl), typeParameter2.Name, implicitImpl, typeParameter1.Name, interfaceMethod); } else if (!MemberSignatureComparer.HaveSameNullabilityInConstraints(typeParameter1, typeMap1, typeParameter2, typeMap2)) { diagnostics.Add(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, GetImplicitImplementationDiagnosticLocation(interfaceMethod, implementingType, implicitImpl), typeParameter2.Name, implicitImpl, typeParameter1.Name, interfaceMethod); } } } return result; } internal static Location GetImplicitImplementationDiagnosticLocation(Symbol interfaceMember, TypeSymbol implementingType, Symbol member) { if (TypeSymbol.Equals(member.ContainingType, implementingType, TypeCompareKind.ConsiderEverything2)) { return member.Locations[0]; } else { var @interface = interfaceMember.ContainingType; SourceMemberContainerTypeSymbol snt = implementingType as SourceMemberContainerTypeSymbol; return snt?.GetImplementsLocation(@interface) ?? implementingType.Locations[0]; } } /// <summary> /// Search the declared members of a type for one that could be an implementation /// of a given interface member (depending on interface declarations). /// </summary> /// <param name="interfaceMember">The interface member being implemented.</param> /// <param name="implementingTypeIsFromSomeCompilation">True if the implementing type is from some compilation (i.e. not from metadata).</param> /// <param name="currType">The type on which we are looking for a declared implementation of the interface member.</param> /// <param name="implicitImpl">A member on currType that could implement the interface, or null.</param> /// <param name="closeMismatch">A member on currType that could have been an attempt to implement the interface, or null.</param> /// <remarks> /// There is some similarity between this member and OverriddenOrHiddenMembersHelpers.FindOverriddenOrHiddenMembersInType. /// When making changes to this member, think about whether or not they should also be applied in MemberSymbol. /// One key difference is that custom modifiers are considered when looking up overridden members, but /// not when looking up implicit implementations. We're preserving this behavior from Dev10. /// </remarks> private static void FindPotentialImplicitImplementationMemberDeclaredInType( Symbol interfaceMember, bool implementingTypeIsFromSomeCompilation, TypeSymbol currType, out Symbol implicitImpl, out Symbol closeMismatch) { implicitImpl = null; closeMismatch = null; bool? isOperator = null; if (interfaceMember is MethodSymbol interfaceMethod) { isOperator = interfaceMethod.MethodKind is MethodKind.UserDefinedOperator or MethodKind.Conversion; } foreach (Symbol member in currType.GetMembers(interfaceMember.Name)) { if (member.Kind == interfaceMember.Kind) { if (isOperator.HasValue && (((MethodSymbol)member).MethodKind is MethodKind.UserDefinedOperator or MethodKind.Conversion) != isOperator.GetValueOrDefault()) { continue; } if (IsInterfaceMemberImplementation(member, interfaceMember, implementingTypeIsFromSomeCompilation)) { implicitImpl = member; return; } // If we haven't found a match, do a weaker comparison that ignores static-ness, accessibility, and return type. else if ((object)closeMismatch == null && implementingTypeIsFromSomeCompilation) { // We can ignore custom modifiers here, because our goal is to improve the helpfulness // of an error we're already giving, rather than to generate a new error. if (MemberSignatureComparer.CSharpCloseImplicitImplementationComparer.Equals(interfaceMember, member)) { closeMismatch = member; } } } } } /// <summary> /// To implement an interface member, a candidate member must be public, non-static, and have /// the same signature. "Have the same signature" has a looser definition if the type implementing /// the interface is from source. /// </summary> /// <remarks> /// PROPERTIES: /// NOTE: we're not checking whether this property has at least the accessors /// declared in the interface. Dev10 considers it a match either way and, /// reports failure to implement accessors separately. /// /// If the implementing type (i.e. the type with the interface in its interface /// list) is in source, then we can ignore custom modifiers in/on the property /// type because they will be copied into the bridge property that explicitly /// implements the interface property (or they would be, if we created such /// a bridge property). Bridge *methods* (not properties) are inserted in /// SourceMemberContainerTypeSymbol.SynthesizeInterfaceMemberImplementation. /// /// CONSIDER: The spec for interface mapping (13.4.4) could be interpreted to mean that this /// property is not an implementation unless it has an accessor for each accessor of the /// interface property. For now, we prefer to represent that case as having an implemented /// property and an unimplemented accessor because it makes finding accessor implementations /// much easier. If we decide that we want the API to report the property as unimplemented, /// then it might be appropriate to keep current result internally and just check the accessors /// before returning the value from the public API (similar to the way MethodSymbol.OverriddenMethod /// filters MethodSymbol.OverriddenOrHiddenMembers. /// </remarks> private static bool IsInterfaceMemberImplementation(Symbol candidateMember, Symbol interfaceMember, bool implementingTypeIsFromSomeCompilation) { if (candidateMember.DeclaredAccessibility != Accessibility.Public || candidateMember.IsStatic != interfaceMember.IsStatic) { return false; } else if (HaveInitOnlyMismatch(candidateMember, interfaceMember)) { return false; } else if (implementingTypeIsFromSomeCompilation) { // We're specifically ignoring custom modifiers for source types because that's what Dev10 does. // Inexact matches are acceptable because we'll just generate bridge members - explicit implementations // with exact signatures that delegate to the inexact match. This happens automatically in // SourceMemberContainerTypeSymbol.SynthesizeInterfaceMemberImplementation. return MemberSignatureComparer.CSharpImplicitImplementationComparer.Equals(interfaceMember, candidateMember); } else { // NOTE: Dev10 seems to use the C# rules in this case as well, but it doesn't give diagnostics about // the failure of a metadata type to implement an interface so there's no problem with reporting the // CLI interpretation instead. For example, using this comparer might allow a member with a ref // parameter to implement a member with an out parameter - which Dev10 would not allow - but that's // okay because Dev10's behavior is not observable. return MemberSignatureComparer.RuntimeImplicitImplementationComparer.Equals(interfaceMember, candidateMember); } } protected MultiDictionary<Symbol, Symbol>.ValueSet GetExplicitImplementationForInterfaceMember(Symbol interfaceMember) { var info = this.GetInterfaceInfo(); if (info == s_noInterfaces) { return default; } if (info.explicitInterfaceImplementationMap == null) { Interlocked.CompareExchange(ref info.explicitInterfaceImplementationMap, MakeExplicitInterfaceImplementationMap(), null); } return info.explicitInterfaceImplementationMap[interfaceMember]; } private MultiDictionary<Symbol, Symbol> MakeExplicitInterfaceImplementationMap() { var map = new MultiDictionary<Symbol, Symbol>(ExplicitInterfaceImplementationTargetMemberEqualityComparer.Instance); foreach (var member in this.GetMembersUnordered()) { foreach (var interfaceMember in member.GetExplicitInterfaceImplementations()) { Debug.Assert(interfaceMember.Kind != SymbolKind.Method || (object)interfaceMember == ((MethodSymbol)interfaceMember).ConstructedFrom); map.Add(interfaceMember, member); } } return map; } #nullable enable /// <summary> /// If implementation of an interface method <paramref name="interfaceMethod"/> will be accompanied with /// a MethodImpl entry in metadata, information about which isn't already exposed through /// <see cref="MethodSymbol.ExplicitInterfaceImplementations"/> API, this method returns the "Body" part /// of the MethodImpl entry, i.e. the method that implements the <paramref name="interfaceMethod"/>. /// Some of the MethodImpl entries could require synthetic forwarding methods. In such cases, /// the result is the method that the language considers to implement the <paramref name="interfaceMethod"/>, /// rather than the forwarding method. In other words, it is the method that the forwarding method forwards to. /// </summary> /// <param name="interfaceMethod">The interface method that is going to be implemented by using synthesized MethodImpl entry.</param> /// <returns></returns> protected MethodSymbol? GetBodyOfSynthesizedInterfaceMethodImpl(MethodSymbol interfaceMethod) { var info = this.GetInterfaceInfo(); if (info == s_noInterfaces) { return null; } if (info.synthesizedMethodImplMap == null) { Interlocked.CompareExchange(ref info.synthesizedMethodImplMap, makeSynthesizedMethodImplMap(), null); } if (info.synthesizedMethodImplMap.TryGetValue(interfaceMethod, out MethodSymbol? result)) { return result; } return null; ImmutableDictionary<MethodSymbol, MethodSymbol> makeSynthesizedMethodImplMap() { var map = ImmutableDictionary.CreateBuilder<MethodSymbol, MethodSymbol>(ExplicitInterfaceImplementationTargetMemberEqualityComparer.Instance); foreach ((MethodSymbol body, MethodSymbol implemented) in this.SynthesizedInterfaceMethodImpls()) { map.Add(implemented, body); } return map.ToImmutable(); } } /// <summary> /// Returns information about interface method implementations that will be accompanied with /// MethodImpl entries in metadata, information about which isn't already exposed through /// <see cref="MethodSymbol.ExplicitInterfaceImplementations"/> API. The "Body" is the method that /// implements the interface method "Implemented". /// Some of the MethodImpl entries could require synthetic forwarding methods. In such cases, /// the "Body" is the method that the language considers to implement the interface method, /// the "Implemented", rather than the forwarding method. In other words, it is the method that /// the forwarding method forwards to. /// </summary> internal abstract IEnumerable<(MethodSymbol Body, MethodSymbol Implemented)> SynthesizedInterfaceMethodImpls(); #nullable disable protected class ExplicitInterfaceImplementationTargetMemberEqualityComparer : IEqualityComparer<Symbol> { public static readonly ExplicitInterfaceImplementationTargetMemberEqualityComparer Instance = new ExplicitInterfaceImplementationTargetMemberEqualityComparer(); private ExplicitInterfaceImplementationTargetMemberEqualityComparer() { } public bool Equals(Symbol x, Symbol y) { return x.OriginalDefinition == y.OriginalDefinition && x.ContainingType.Equals(y.ContainingType, TypeCompareKind.CLRSignatureCompareOptions); } public int GetHashCode(Symbol obj) { return obj.OriginalDefinition.GetHashCode(); } } #endregion Interface member checks #region Abstract base type checks /// <summary> /// The set of abstract members in declared in this type or declared in a base type and not overridden. /// </summary> internal ImmutableHashSet<Symbol> AbstractMembers { get { if (_lazyAbstractMembers == null) { Interlocked.CompareExchange(ref _lazyAbstractMembers, ComputeAbstractMembers(), null); } return _lazyAbstractMembers; } } private ImmutableHashSet<Symbol> ComputeAbstractMembers() { var abstractMembers = ImmutableHashSet.Create<Symbol>(); var overriddenMembers = ImmutableHashSet.Create<Symbol>(); foreach (var member in this.GetMembersUnordered()) { if (this.IsAbstract && member.IsAbstract && member.Kind != SymbolKind.NamedType) { abstractMembers = abstractMembers.Add(member); } Symbol overriddenMember = null; switch (member.Kind) { case SymbolKind.Method: { overriddenMember = ((MethodSymbol)member).OverriddenMethod; break; } case SymbolKind.Property: { overriddenMember = ((PropertySymbol)member).OverriddenProperty; break; } case SymbolKind.Event: { overriddenMember = ((EventSymbol)member).OverriddenEvent; break; } } if ((object)overriddenMember != null) { overriddenMembers = overriddenMembers.Add(overriddenMember); } } if ((object)this.BaseTypeNoUseSiteDiagnostics != null && this.BaseTypeNoUseSiteDiagnostics.IsAbstract) { foreach (var baseAbstractMember in this.BaseTypeNoUseSiteDiagnostics.AbstractMembers) { if (!overriddenMembers.Contains(baseAbstractMember)) { abstractMembers = abstractMembers.Add(baseAbstractMember); } } } return abstractMembers; } #endregion Abstract base type checks [Obsolete("Use TypeWithAnnotations.Is method.", true)] internal bool Equals(TypeWithAnnotations other) { throw ExceptionUtilities.Unreachable; } public static bool Equals(TypeSymbol left, TypeSymbol right, TypeCompareKind comparison) { if (left is null) { return right is null; } return left.Equals(right, comparison); } [Obsolete("Use 'TypeSymbol.Equals(TypeSymbol, TypeSymbol, TypeCompareKind)' method.", true)] public static bool operator ==(TypeSymbol left, TypeSymbol right) => throw ExceptionUtilities.Unreachable; [Obsolete("Use 'TypeSymbol.Equals(TypeSymbol, TypeSymbol, TypeCompareKind)' method.", true)] public static bool operator !=(TypeSymbol left, TypeSymbol right) => throw ExceptionUtilities.Unreachable; [Obsolete("Use 'TypeSymbol.Equals(TypeSymbol, TypeSymbol, TypeCompareKind)' method.", true)] public static bool operator ==(Symbol left, TypeSymbol right) => throw ExceptionUtilities.Unreachable; [Obsolete("Use 'TypeSymbol.Equals(TypeSymbol, TypeSymbol, TypeCompareKind)' method.", true)] public static bool operator !=(Symbol left, TypeSymbol right) => throw ExceptionUtilities.Unreachable; [Obsolete("Use 'TypeSymbol.Equals(TypeSymbol, TypeSymbol, TypeCompareKind)' method.", true)] public static bool operator ==(TypeSymbol left, Symbol right) => throw ExceptionUtilities.Unreachable; [Obsolete("Use 'TypeSymbol.Equals(TypeSymbol, TypeSymbol, TypeCompareKind)' method.", true)] public static bool operator !=(TypeSymbol left, Symbol right) => throw ExceptionUtilities.Unreachable; internal ITypeSymbol GetITypeSymbol(CodeAnalysis.NullableAnnotation nullableAnnotation) { if (nullableAnnotation == DefaultNullableAnnotation) { return (ITypeSymbol)this.ISymbol; } return CreateITypeSymbol(nullableAnnotation); } internal CodeAnalysis.NullableAnnotation DefaultNullableAnnotation => NullableAnnotationExtensions.ToPublicAnnotation(this, NullableAnnotation.Oblivious); protected abstract ITypeSymbol CreateITypeSymbol(CodeAnalysis.NullableAnnotation nullableAnnotation); TypeKind ITypeSymbolInternal.TypeKind => this.TypeKind; SpecialType ITypeSymbolInternal.SpecialType => this.SpecialType; bool ITypeSymbolInternal.IsReferenceType => this.IsReferenceType; bool ITypeSymbolInternal.IsValueType => this.IsValueType; ITypeSymbol ITypeSymbolInternal.GetITypeSymbol() { return GetITypeSymbol(DefaultNullableAnnotation); } internal abstract bool IsRecord { get; } internal abstract bool IsRecordStruct { 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 System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Runtime.CompilerServices; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Symbols; using Roslyn.Utilities; #pragma warning disable CS0660 namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// A TypeSymbol is a base class for all the symbols that represent a type /// in C#. /// </summary> internal abstract partial class TypeSymbol : NamespaceOrTypeSymbol, ITypeSymbolInternal { // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // Changes to the public interface of this class should remain synchronized with the VB version. // Do not make any changes to the public interface without making the corresponding change // to the VB version. // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // TODO (tomat): Consider changing this to an empty name. This name shouldn't ever leak to the user in error messages. internal const string ImplicitTypeName = "<invalid-global-code>"; // InterfaceInfo for a common case of a type not implementing anything directly or indirectly. private static readonly InterfaceInfo s_noInterfaces = new InterfaceInfo(); private ImmutableHashSet<Symbol> _lazyAbstractMembers; private InterfaceInfo _lazyInterfaceInfo; private class InterfaceInfo { // all directly implemented interfaces, their bases and all interfaces to the bases of the type recursively internal ImmutableArray<NamedTypeSymbol> allInterfaces; /// <summary> /// <see cref="TypeSymbol.InterfacesAndTheirBaseInterfacesNoUseSiteDiagnostics"/> /// </summary> internal MultiDictionary<NamedTypeSymbol, NamedTypeSymbol> interfacesAndTheirBaseInterfaces; internal static readonly MultiDictionary<NamedTypeSymbol, NamedTypeSymbol> EmptyInterfacesAndTheirBaseInterfaces = new MultiDictionary<NamedTypeSymbol, NamedTypeSymbol>(0, SymbolEqualityComparer.CLRSignature); // Key is implemented member (method, property, or event), value is implementing member (from the // perspective of this type). Don't allocate until someone needs it. private ConcurrentDictionary<Symbol, SymbolAndDiagnostics> _implementationForInterfaceMemberMap; public ConcurrentDictionary<Symbol, SymbolAndDiagnostics> ImplementationForInterfaceMemberMap { get { var map = _implementationForInterfaceMemberMap; if (map != null) { return map; } // PERF: Avoid over-allocation. In many cases, there's only 1 entry and we don't expect concurrent updates. map = new ConcurrentDictionary<Symbol, SymbolAndDiagnostics>(concurrencyLevel: 1, capacity: 1, comparer: SymbolEqualityComparer.ConsiderEverything); return Interlocked.CompareExchange(ref _implementationForInterfaceMemberMap, map, null) ?? map; } } /// <summary> /// key = interface method/property/event compared using <see cref="ExplicitInterfaceImplementationTargetMemberEqualityComparer"/>, /// value = explicitly implementing methods/properties/events declared on this type (normally a single value, multiple in case of /// an error). /// </summary> internal MultiDictionary<Symbol, Symbol> explicitInterfaceImplementationMap; #nullable enable internal ImmutableDictionary<MethodSymbol, MethodSymbol>? synthesizedMethodImplMap; #nullable disable internal bool IsDefaultValue() { return allInterfaces.IsDefault && interfacesAndTheirBaseInterfaces == null && _implementationForInterfaceMemberMap == null && explicitInterfaceImplementationMap == null && synthesizedMethodImplMap == null; } } private InterfaceInfo GetInterfaceInfo() { var info = _lazyInterfaceInfo; if (info != null) { Debug.Assert(info != s_noInterfaces || info.IsDefaultValue(), "default value was modified"); return info; } for (var baseType = this; !ReferenceEquals(baseType, null); baseType = baseType.BaseTypeNoUseSiteDiagnostics) { var interfaces = (baseType.TypeKind == TypeKind.TypeParameter) ? ((TypeParameterSymbol)baseType).EffectiveInterfacesNoUseSiteDiagnostics : baseType.InterfacesNoUseSiteDiagnostics(); if (!interfaces.IsEmpty) { // it looks like we or one of our bases implements something. info = new InterfaceInfo(); // NOTE: we are assigning lazyInterfaceInfo via interlocked not for correctness, // we just do not want to override an existing info that could be partially filled. return Interlocked.CompareExchange(ref _lazyInterfaceInfo, info, null) ?? info; } } // if we have got here it means neither we nor our bases implement anything _lazyInterfaceInfo = info = s_noInterfaces; return info; } /// <summary> /// The original definition of this symbol. If this symbol is constructed from another /// symbol by type substitution then OriginalDefinition gets the original symbol as it was defined in /// source or metadata. /// </summary> public new TypeSymbol OriginalDefinition { get { return OriginalTypeSymbolDefinition; } } protected virtual TypeSymbol OriginalTypeSymbolDefinition { get { return this; } } protected sealed override Symbol OriginalSymbolDefinition { get { return this.OriginalTypeSymbolDefinition; } } /// <summary> /// Gets the BaseType of this type. If the base type could not be determined, then /// an instance of ErrorType is returned. If this kind of type does not have a base type /// (for example, interfaces), null is returned. Also the special class System.Object /// always has a BaseType of null. /// </summary> internal abstract NamedTypeSymbol BaseTypeNoUseSiteDiagnostics { get; } internal NamedTypeSymbol BaseTypeWithDefinitionUseSiteDiagnostics(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var result = BaseTypeNoUseSiteDiagnostics; if ((object)result != null) { result.OriginalDefinition.AddUseSiteInfo(ref useSiteInfo); } return result; } internal NamedTypeSymbol BaseTypeOriginalDefinition(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var result = BaseTypeNoUseSiteDiagnostics; if ((object)result != null) { result = result.OriginalDefinition; result.AddUseSiteInfo(ref useSiteInfo); } return result; } /// <summary> /// Gets the set of interfaces that this type directly implements. This set does not include /// interfaces that are base interfaces of directly implemented interfaces. /// </summary> internal abstract ImmutableArray<NamedTypeSymbol> InterfacesNoUseSiteDiagnostics(ConsList<TypeSymbol> basesBeingResolved = null); /// <summary> /// The list of all interfaces of which this type is a declared subtype, excluding this type /// itself. This includes all declared base interfaces, all declared base interfaces of base /// types, and all declared base interfaces of those results (recursively). Each result /// appears exactly once in the list. This list is topologically sorted by the inheritance /// relationship: if interface type A extends interface type B, then A precedes B in the /// list. This is not quite the same as "all interfaces of which this type is a proper /// subtype" because it does not take into account variance: AllInterfaces for /// IEnumerable&lt;string&gt; will not include IEnumerable&lt;object&gt; /// </summary> internal ImmutableArray<NamedTypeSymbol> AllInterfacesNoUseSiteDiagnostics { get { return GetAllInterfaces(); } } internal ImmutableArray<NamedTypeSymbol> AllInterfacesWithDefinitionUseSiteDiagnostics(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var result = AllInterfacesNoUseSiteDiagnostics; // Since bases affect content of AllInterfaces set, we need to make sure they all are good. var current = this; do { current = current.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo); } while ((object)current != null); foreach (var iface in result) { iface.OriginalDefinition.AddUseSiteInfo(ref useSiteInfo); } return result; } /// <summary> /// If this is a type parameter returns its effective base class, otherwise returns this type. /// </summary> internal TypeSymbol EffectiveTypeNoUseSiteDiagnostics { get { return this.IsTypeParameter() ? ((TypeParameterSymbol)this).EffectiveBaseClassNoUseSiteDiagnostics : this; } } internal TypeSymbol EffectiveType(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { return this.IsTypeParameter() ? ((TypeParameterSymbol)this).EffectiveBaseClass(ref useSiteInfo) : this; } /// <summary> /// Returns true if this type derives from a given type. /// </summary> internal bool IsDerivedFrom(TypeSymbol type, TypeCompareKind comparison, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)type != null); Debug.Assert(!type.IsTypeParameter()); if ((object)this == (object)type) { return false; } var t = this.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo); while ((object)t != null) { if (type.Equals(t, comparison)) { return true; } t = t.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo); } return false; } /// <summary> /// Returns true if this type is equal or derives from a given type. /// </summary> internal bool IsEqualToOrDerivedFrom(TypeSymbol type, TypeCompareKind comparison, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { return this.Equals(type, comparison) || this.IsDerivedFrom(type, comparison, ref useSiteInfo); } /// <summary> /// Determines if this type symbol represent the same type as another, according to the language /// semantics. /// </summary> /// <param name="t2">The other type.</param> /// <param name="compareKind"> /// What kind of comparison to use? /// You can ignore custom modifiers, ignore the distinction between object and dynamic, or ignore tuple element names differences. /// </param> /// <returns>True if the types are equivalent.</returns> internal virtual bool Equals(TypeSymbol t2, TypeCompareKind compareKind) { return ReferenceEquals(this, t2); } public sealed override bool Equals(Symbol other, TypeCompareKind compareKind) { var t2 = other as TypeSymbol; if (t2 is null) { return false; } return this.Equals(t2, compareKind); } /// <summary> /// We ignore custom modifiers, and the distinction between dynamic and object, when computing a type's hash code. /// </summary> /// <returns></returns> public override int GetHashCode() { return RuntimeHelpers.GetHashCode(this); } protected virtual ImmutableArray<NamedTypeSymbol> GetAllInterfaces() { var info = this.GetInterfaceInfo(); if (info == s_noInterfaces) { return ImmutableArray<NamedTypeSymbol>.Empty; } if (info.allInterfaces.IsDefault) { ImmutableInterlocked.InterlockedInitialize(ref info.allInterfaces, MakeAllInterfaces()); } return info.allInterfaces; } /// Produce all implemented interfaces in topologically sorted order. We use /// TypeSymbol.Interfaces as the source of edge data, which has had cycles and infinitely /// long dependency cycles removed. Consequently, it is possible (and we do) use the /// simplest version of Tarjan's topological sorting algorithm. protected virtual ImmutableArray<NamedTypeSymbol> MakeAllInterfaces() { var result = ArrayBuilder<NamedTypeSymbol>.GetInstance(); var visited = new HashSet<NamedTypeSymbol>(SymbolEqualityComparer.ConsiderEverything); for (var baseType = this; !ReferenceEquals(baseType, null); baseType = baseType.BaseTypeNoUseSiteDiagnostics) { var interfaces = (baseType.TypeKind == TypeKind.TypeParameter) ? ((TypeParameterSymbol)baseType).EffectiveInterfacesNoUseSiteDiagnostics : baseType.InterfacesNoUseSiteDiagnostics(); for (int i = interfaces.Length - 1; i >= 0; i--) { addAllInterfaces(interfaces[i], visited, result); } } result.ReverseContents(); return result.ToImmutableAndFree(); static void addAllInterfaces(NamedTypeSymbol @interface, HashSet<NamedTypeSymbol> visited, ArrayBuilder<NamedTypeSymbol> result) { if (visited.Add(@interface)) { ImmutableArray<NamedTypeSymbol> baseInterfaces = @interface.InterfacesNoUseSiteDiagnostics(); for (int i = baseInterfaces.Length - 1; i >= 0; i--) { var baseInterface = baseInterfaces[i]; addAllInterfaces(baseInterface, visited, result); } result.Add(@interface); } } } /// <summary> /// Gets the set of interfaces that this type directly implements, plus the base interfaces /// of all such types. Keys are compared using <see cref="SymbolEqualityComparer.CLRSignature"/>, /// values are distinct interfaces corresponding to the key, according to <see cref="TypeCompareKind.ConsiderEverything"/> rules. /// </summary> /// <remarks> /// CONSIDER: it probably isn't truly necessary to cache this. If space gets tight, consider /// alternative approaches (recompute every time, cache on the side, only store on some types, /// etc). /// </remarks> internal MultiDictionary<NamedTypeSymbol, NamedTypeSymbol> InterfacesAndTheirBaseInterfacesNoUseSiteDiagnostics { get { var info = this.GetInterfaceInfo(); if (info == s_noInterfaces) { Debug.Assert(InterfaceInfo.EmptyInterfacesAndTheirBaseInterfaces.IsEmpty); return InterfaceInfo.EmptyInterfacesAndTheirBaseInterfaces; } if (info.interfacesAndTheirBaseInterfaces == null) { Interlocked.CompareExchange(ref info.interfacesAndTheirBaseInterfaces, MakeInterfacesAndTheirBaseInterfaces(this.InterfacesNoUseSiteDiagnostics()), null); } return info.interfacesAndTheirBaseInterfaces; } } internal MultiDictionary<NamedTypeSymbol, NamedTypeSymbol> InterfacesAndTheirBaseInterfacesWithDefinitionUseSiteDiagnostics(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var result = InterfacesAndTheirBaseInterfacesNoUseSiteDiagnostics; foreach (var iface in result.Keys) { iface.OriginalDefinition.AddUseSiteInfo(ref useSiteInfo); } return result; } // Note: Unlike MakeAllInterfaces, this doesn't need to be virtual. It depends on // AllInterfaces for its implementation, so it will pick up all changes to MakeAllInterfaces // indirectly. private static MultiDictionary<NamedTypeSymbol, NamedTypeSymbol> MakeInterfacesAndTheirBaseInterfaces(ImmutableArray<NamedTypeSymbol> declaredInterfaces) { var resultBuilder = new MultiDictionary<NamedTypeSymbol, NamedTypeSymbol>(declaredInterfaces.Length, SymbolEqualityComparer.CLRSignature, SymbolEqualityComparer.ConsiderEverything); foreach (var @interface in declaredInterfaces) { if (resultBuilder.Add(@interface, @interface)) { foreach (var baseInterface in @interface.AllInterfacesNoUseSiteDiagnostics) { resultBuilder.Add(baseInterface, baseInterface); } } } return resultBuilder; } /// <summary> /// Returns the corresponding symbol in this type or a base type that implements /// interfaceMember (either implicitly or explicitly), or null if no such symbol exists /// (which might be either because this type doesn't implement the container of /// interfaceMember, or this type doesn't supply a member that successfully implements /// interfaceMember). /// </summary> /// <param name="interfaceMember"> /// Must be a non-null interface property, method, or event. /// </param> public Symbol FindImplementationForInterfaceMember(Symbol interfaceMember) { if ((object)interfaceMember == null) { throw new ArgumentNullException(nameof(interfaceMember)); } if (!interfaceMember.IsImplementableInterfaceMember()) { return null; } if (this.IsInterfaceType()) { if (interfaceMember.IsStatic) { return null; } var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; return FindMostSpecificImplementation(interfaceMember, (NamedTypeSymbol)this, ref discardedUseSiteInfo); } return FindImplementationForInterfaceMemberInNonInterface(interfaceMember); } /// <summary> /// Returns true if this type is known to be a reference type. It is never the case that /// IsReferenceType and IsValueType both return true. However, for an unconstrained type /// parameter, IsReferenceType and IsValueType will both return false. /// </summary> public abstract bool IsReferenceType { get; } /// <summary> /// Returns true if this type is known to be a value type. It is never the case that /// IsReferenceType and IsValueType both return true. However, for an unconstrained type /// parameter, IsReferenceType and IsValueType will both return false. /// </summary> public abstract bool IsValueType { get; } // Only the compiler can create TypeSymbols. internal TypeSymbol() { } /// <summary> /// Gets the kind of this type. /// </summary> public abstract TypeKind TypeKind { get; } /// <summary> /// Gets corresponding special TypeId of this type. /// </summary> /// <remarks> /// Not preserved in types constructed from this one. /// </remarks> public virtual SpecialType SpecialType { get { return SpecialType.None; } } /// <summary> /// Gets corresponding primitive type code for this type declaration. /// </summary> internal Microsoft.Cci.PrimitiveTypeCode PrimitiveTypeCode => TypeKind switch { TypeKind.Pointer => Microsoft.Cci.PrimitiveTypeCode.Pointer, TypeKind.FunctionPointer => Microsoft.Cci.PrimitiveTypeCode.FunctionPointer, _ => SpecialTypes.GetTypeCode(SpecialType) }; #region Use-Site Diagnostics /// <summary> /// Return error code that has highest priority while calculating use site error for this symbol. /// </summary> protected override int HighestPriorityUseSiteError { get { return (int)ErrorCode.ERR_BogusType; } } public sealed override bool HasUnsupportedMetadata { get { DiagnosticInfo info = GetUseSiteInfo().DiagnosticInfo; return (object)info != null && info.Code == (int)ErrorCode.ERR_BogusType; } } internal abstract bool GetUnificationUseSiteDiagnosticRecursive(ref DiagnosticInfo result, Symbol owner, ref HashSet<TypeSymbol> checkedTypes); #endregion /// <summary> /// Is this a symbol for an anonymous type (including delegate). /// </summary> public virtual bool IsAnonymousType { get { return false; } } /// <summary> /// Is this a symbol for a Tuple. /// </summary> public virtual bool IsTupleType => false; /// <summary> /// True if the type represents a native integer. In C#, the types represented /// by language keywords 'nint' and 'nuint'. /// </summary> internal virtual bool IsNativeIntegerType => false; /// <summary> /// Verify if the given type is a tuple of a given cardinality, or can be used to back a tuple type /// with the given cardinality. /// </summary> internal bool IsTupleTypeOfCardinality(int targetCardinality) { if (IsTupleType) { return TupleElementTypesWithAnnotations.Length == targetCardinality; } return false; } /// <summary> /// If this symbol represents a tuple type, get the types of the tuple's elements. /// </summary> public virtual ImmutableArray<TypeWithAnnotations> TupleElementTypesWithAnnotations => default(ImmutableArray<TypeWithAnnotations>); /// <summary> /// If this symbol represents a tuple type, get the names of the tuple's elements. /// </summary> public virtual ImmutableArray<string> TupleElementNames => default(ImmutableArray<string>); /// <summary> /// If this symbol represents a tuple type, get the fields for the tuple's elements. /// Otherwise, returns default. /// </summary> public virtual ImmutableArray<FieldSymbol> TupleElements => default(ImmutableArray<FieldSymbol>); #nullable enable /// <summary> /// Is this type a managed type (false for everything but enum, pointer, and /// some struct types). /// </summary> /// <remarks> /// See Type::computeManagedType. /// </remarks> internal bool IsManagedType(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) => GetManagedKind(ref useSiteInfo) == ManagedKind.Managed; internal bool IsManagedTypeNoUseSiteDiagnostics { get { var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; return IsManagedType(ref discardedUseSiteInfo); } } /// <summary> /// Indicates whether a type is managed or not (i.e. you can take a pointer to it). /// Contains additional cases to help implement FeatureNotAvailable diagnostics. /// </summary> internal abstract ManagedKind GetManagedKind(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo); internal ManagedKind ManagedKindNoUseSiteDiagnostics { get { var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; return GetManagedKind(ref discardedUseSiteInfo); } } #nullable disable internal bool NeedsNullableAttribute() { return TypeWithAnnotations.NeedsNullableAttribute(typeWithAnnotationsOpt: default, typeOpt: this); } internal abstract void AddNullableTransforms(ArrayBuilder<byte> transforms); internal abstract bool ApplyNullableTransforms(byte defaultTransformFlag, ImmutableArray<byte> transforms, ref int position, out TypeSymbol result); internal abstract TypeSymbol SetNullabilityForReferenceTypes(Func<TypeWithAnnotations, TypeWithAnnotations> transform); internal TypeSymbol SetUnknownNullabilityForReferenceTypes() { return SetNullabilityForReferenceTypes(s_setUnknownNullability); } private static readonly Func<TypeWithAnnotations, TypeWithAnnotations> s_setUnknownNullability = (type) => type.SetUnknownNullabilityForReferenceTypes(); /// <summary> /// Merges features of the type with another type where there is an identity conversion between them. /// The features to be merged are /// object vs dynamic (dynamic wins), tuple names (dropped in case of conflict), and nullable /// annotations (e.g. in type arguments). /// </summary> internal abstract TypeSymbol MergeEquivalentTypes(TypeSymbol other, VarianceKind variance); /// <summary> /// Returns true if the type may contain embedded references /// </summary> public abstract bool IsRefLikeType { get; } /// <summary> /// Returns true if the type is a readonly struct /// </summary> public abstract bool IsReadOnly { get; } public string ToDisplayString(CodeAnalysis.NullableFlowState topLevelNullability, SymbolDisplayFormat format = null) { return SymbolDisplay.ToDisplayString((ITypeSymbol)ISymbol, topLevelNullability, format); } public ImmutableArray<SymbolDisplayPart> ToDisplayParts(CodeAnalysis.NullableFlowState topLevelNullability, SymbolDisplayFormat format = null) { return SymbolDisplay.ToDisplayParts((ITypeSymbol)ISymbol, topLevelNullability, format); } public string ToMinimalDisplayString( SemanticModel semanticModel, CodeAnalysis.NullableFlowState topLevelNullability, int position, SymbolDisplayFormat format = null) { return SymbolDisplay.ToMinimalDisplayString((ITypeSymbol)ISymbol, topLevelNullability, semanticModel, position, format); } public ImmutableArray<SymbolDisplayPart> ToMinimalDisplayParts( SemanticModel semanticModel, CodeAnalysis.NullableFlowState topLevelNullability, int position, SymbolDisplayFormat format = null) { return SymbolDisplay.ToMinimalDisplayParts((ITypeSymbol)ISymbol, topLevelNullability, semanticModel, position, format); } #region Interface member checks /// <summary> /// Locate implementation of the <paramref name="interfaceMember"/> in context of the current type. /// The method is using cache to optimize subsequent calls for the same <paramref name="interfaceMember"/>. /// </summary> /// <param name="interfaceMember">Member for which an implementation should be found.</param> /// <param name="ignoreImplementationInInterfacesIfResultIsNotReady"> /// The process of looking up an implementation for an accessor can involve figuring out how corresponding event/property is implemented, /// <see cref="CheckForImplementationOfCorrespondingPropertyOrEvent"/>. And the process of looking up an implementation for a property can /// involve figuring out how corresponding accessors are implemented, <see cref="FindMostSpecificImplementationInInterfaces"/>. This can /// lead to cycles, which could be avoided if we ignore the presence of implementations in interfaces for the purpose of /// <see cref="CheckForImplementationOfCorrespondingPropertyOrEvent"/>. Fortunately, logic in it allows us to ignore the presence of /// implementations in interfaces and we use that. /// When the value of this parameter is true and the result that takes presence of implementations in interfaces into account is not /// available from the cache, the lookup will be performed ignoring the presence of implementations in interfaces. Otherwise, result from /// the cache is returned. /// When the value of the parameter is false, the result from the cache is returned, or calculated, taking presence of implementations /// in interfaces into account and then cached. /// This means that: /// - A symbol from an interface can still be returned even when <paramref name="ignoreImplementationInInterfacesIfResultIsNotReady"/> is true. /// A subsequent call with <paramref name="ignoreImplementationInInterfacesIfResultIsNotReady"/> false will return the same value. /// - If symbol from a non-interface is returned when <paramref name="ignoreImplementationInInterfacesIfResultIsNotReady"/> is true. A subsequent /// call with <paramref name="ignoreImplementationInInterfacesIfResultIsNotReady"/> false will return the same value. /// - If no symbol is returned for <paramref name="ignoreImplementationInInterfacesIfResultIsNotReady"/> true. A subsequent call with /// <paramref name="ignoreImplementationInInterfacesIfResultIsNotReady"/> might return a symbol, but that symbol guaranteed to be from an interface. /// - If the first request is done with <paramref name="ignoreImplementationInInterfacesIfResultIsNotReady"/> false. A subsequent call /// is guaranteed to return the same result regardless of <paramref name="ignoreImplementationInInterfacesIfResultIsNotReady"/> value. /// </param> internal SymbolAndDiagnostics FindImplementationForInterfaceMemberInNonInterfaceWithDiagnostics(Symbol interfaceMember, bool ignoreImplementationInInterfacesIfResultIsNotReady = false) { Debug.Assert((object)interfaceMember != null); Debug.Assert(!this.IsInterfaceType()); if (this.IsInterfaceType()) { return SymbolAndDiagnostics.Empty; } var interfaceType = interfaceMember.ContainingType; if ((object)interfaceType == null || !interfaceType.IsInterface) { return SymbolAndDiagnostics.Empty; } switch (interfaceMember.Kind) { case SymbolKind.Method: case SymbolKind.Property: case SymbolKind.Event: var info = this.GetInterfaceInfo(); if (info == s_noInterfaces) { return SymbolAndDiagnostics.Empty; } // PERF: Avoid delegate allocation by splitting GetOrAdd into TryGetValue+TryAdd var map = info.ImplementationForInterfaceMemberMap; SymbolAndDiagnostics result; if (map.TryGetValue(interfaceMember, out result)) { return result; } result = ComputeImplementationAndDiagnosticsForInterfaceMember(interfaceMember, ignoreImplementationInInterfaces: ignoreImplementationInInterfacesIfResultIsNotReady, out bool implementationInInterfacesMightChangeResult); Debug.Assert(ignoreImplementationInInterfacesIfResultIsNotReady || !implementationInInterfacesMightChangeResult); Debug.Assert(!implementationInInterfacesMightChangeResult || result.Symbol is null); if (!implementationInInterfacesMightChangeResult) { map.TryAdd(interfaceMember, result); } return result; default: return SymbolAndDiagnostics.Empty; } } internal Symbol FindImplementationForInterfaceMemberInNonInterface(Symbol interfaceMember, bool ignoreImplementationInInterfacesIfResultIsNotReady = false) { return FindImplementationForInterfaceMemberInNonInterfaceWithDiagnostics(interfaceMember, ignoreImplementationInInterfacesIfResultIsNotReady).Symbol; } private SymbolAndDiagnostics ComputeImplementationAndDiagnosticsForInterfaceMember(Symbol interfaceMember, bool ignoreImplementationInInterfaces, out bool implementationInInterfacesMightChangeResult) { var diagnostics = BindingDiagnosticBag.GetInstance(withDiagnostics: true, withDependencies: this.DeclaringCompilation is object); var implementingMember = ComputeImplementationForInterfaceMember(interfaceMember, this, diagnostics, ignoreImplementationInInterfaces, out implementationInInterfacesMightChangeResult); var implementingMemberAndDiagnostics = new SymbolAndDiagnostics(implementingMember, diagnostics.ToReadOnlyAndFree()); return implementingMemberAndDiagnostics; } /// <summary> /// Performs interface mapping (spec 13.4.4). /// </summary> /// <remarks> /// CONSIDER: we could probably do less work in the metadata and retargeting cases - we won't use the diagnostics. /// </remarks> /// <param name="interfaceMember">A non-null implementable member on an interface type.</param> /// <param name="implementingType">The type implementing the interface property (usually "this").</param> /// <param name="diagnostics">Bag to which to add diagnostics.</param> /// <param name="ignoreImplementationInInterfaces">Do not consider implementation in an interface as a valid candidate for the purpose of this computation.</param> /// <param name="implementationInInterfacesMightChangeResult"> /// Returns true when <paramref name="ignoreImplementationInInterfaces"/> is true, the method fails to locate an implementation and an implementation in /// an interface, if any (its presence is not checked), could potentially be a candidate. Returns false otherwise. /// When true is returned, a different call with <paramref name="ignoreImplementationInInterfaces"/> false might return a symbol. That symbol, if any, /// is guaranteed to be from an interface. /// This parameter is used to optimize caching in <see cref="FindImplementationForInterfaceMemberInNonInterfaceWithDiagnostics"/>. /// </param> /// <returns>The implementing property or null, if there isn't one.</returns> private static Symbol ComputeImplementationForInterfaceMember(Symbol interfaceMember, TypeSymbol implementingType, BindingDiagnosticBag diagnostics, bool ignoreImplementationInInterfaces, out bool implementationInInterfacesMightChangeResult) { Debug.Assert(!implementingType.IsInterfaceType()); Debug.Assert(interfaceMember.Kind == SymbolKind.Method || interfaceMember.Kind == SymbolKind.Property || interfaceMember.Kind == SymbolKind.Event); Debug.Assert(interfaceMember.IsImplementableInterfaceMember()); NamedTypeSymbol interfaceType = interfaceMember.ContainingType; Debug.Assert((object)interfaceType != null && interfaceType.IsInterface); bool seenTypeDeclaringInterface = false; // NOTE: In other areas of the compiler, we check whether the member is from a specific compilation. // We could do the same thing here, but that would mean that callers of the public API would have // to pass in a Compilation object when asking about interface implementation. This extra cost eliminates // the small benefit of getting identical answers from "imported" symbols, regardless of whether they // are imported as source or metadata symbols. // // ACASEY: As of 2013/01/24, we are not aware of any cases where the source and metadata behaviors // disagree *in code that can be emitted*. (If there are any, they are likely to involved ambiguous // overrides, which typically arise through combinations of ref/out and generics.) In incorrect code, // the source behavior is somewhat more generous (e.g. accepting a method with the wrong return type), // but we do not guarantee that incorrect source will be treated in the same way as incorrect metadata. // // NOTE: The batch compiler is not affected by this discrepancy, since compilations don't call these // APIs on symbols from other compilations. bool implementingTypeIsFromSomeCompilation = false; Symbol implicitImpl = null; Symbol closestMismatch = null; bool canBeImplementedImplicitlyInCSharp9 = interfaceMember.DeclaredAccessibility == Accessibility.Public && !interfaceMember.IsEventOrPropertyWithImplementableNonPublicAccessor(); TypeSymbol implementingBaseOpt = null; // Calculated only if canBeImplementedImplicitly == false bool implementingTypeImplementsInterface = false; CSharpCompilation compilation = implementingType.DeclaringCompilation; var useSiteInfo = compilation is object ? new CompoundUseSiteInfo<AssemblySymbol>(diagnostics, compilation.Assembly) : CompoundUseSiteInfo<AssemblySymbol>.DiscardedDependencies; for (TypeSymbol currType = implementingType; (object)currType != null; currType = currType.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo)) { // NOTE: In the case of PE symbols, it is possible to see an explicit implementation // on a type that does not declare the corresponding interface (or one of its // subinterfaces). In such cases, we want to return the explicit implementation, // even if it doesn't participate in interface mapping according to the C# rules. // pass 1: check for explicit impls (can't assume name matches) MultiDictionary<Symbol, Symbol>.ValueSet explicitImpl = currType.GetExplicitImplementationForInterfaceMember(interfaceMember); if (explicitImpl.Count == 1) { implementationInInterfacesMightChangeResult = false; return explicitImpl.Single(); } else if (explicitImpl.Count > 1) { if ((object)currType == implementingType || implementingTypeImplementsInterface) { diagnostics.Add(ErrorCode.ERR_DuplicateExplicitImpl, implementingType.Locations[0], interfaceMember); } implementationInInterfacesMightChangeResult = false; return null; } bool checkPendingExplicitImplementations = ((object)currType != implementingType || !currType.IsDefinition); if (checkPendingExplicitImplementations && interfaceMember is MethodSymbol interfaceMethod && currType.InterfacesAndTheirBaseInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo).ContainsKey(interfaceType)) { // Check for implementations that are going to be explicit once types are emitted MethodSymbol bodyOfSynthesizedMethodImpl = currType.GetBodyOfSynthesizedInterfaceMethodImpl(interfaceMethod); if (bodyOfSynthesizedMethodImpl is object) { implementationInInterfacesMightChangeResult = false; return bodyOfSynthesizedMethodImpl; } } if (IsExplicitlyImplementedViaAccessors(checkPendingExplicitImplementations, interfaceMember, currType, ref useSiteInfo, out Symbol currTypeExplicitImpl)) { // We are looking for a property or event implementation and found an explicit implementation // for its accessor(s) in this type. Stop the process and return event/property associated // with the accessor(s), if any. implementationInInterfacesMightChangeResult = false; // NOTE: may be null. return currTypeExplicitImpl; } if (!seenTypeDeclaringInterface || (!canBeImplementedImplicitlyInCSharp9 && (object)implementingBaseOpt == null)) { if (currType.InterfacesAndTheirBaseInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo).ContainsKey(interfaceType)) { if (!seenTypeDeclaringInterface) { implementingTypeIsFromSomeCompilation = currType.OriginalDefinition.ContainingModule is not PEModuleSymbol; seenTypeDeclaringInterface = true; } if ((object)currType == implementingType) { implementingTypeImplementsInterface = true; } else if (!canBeImplementedImplicitlyInCSharp9 && (object)implementingBaseOpt == null) { implementingBaseOpt = currType; } } } // We want the implementation from the most derived type at or above the first one to // include the interface (or a subinterface) in its interface list if (seenTypeDeclaringInterface && (!interfaceMember.IsStatic || implementingTypeIsFromSomeCompilation)) { //pass 2: check for implicit impls (name must match) Symbol currTypeImplicitImpl; Symbol currTypeCloseMismatch; FindPotentialImplicitImplementationMemberDeclaredInType( interfaceMember, implementingTypeIsFromSomeCompilation, currType, out currTypeImplicitImpl, out currTypeCloseMismatch); if ((object)currTypeImplicitImpl != null) { implicitImpl = currTypeImplicitImpl; break; } if ((object)closestMismatch == null) { closestMismatch = currTypeCloseMismatch; } } } Debug.Assert(!canBeImplementedImplicitlyInCSharp9 || (object)implementingBaseOpt == null); bool tryDefaultInterfaceImplementation = !interfaceMember.IsStatic; // Dev10 has some extra restrictions and extra wiggle room when finding implicit // implementations for interface accessors. Perform some extra checks and possibly // update the result (i.e. implicitImpl). if (interfaceMember.IsAccessor()) { Symbol originalImplicitImpl = implicitImpl; CheckForImplementationOfCorrespondingPropertyOrEvent((MethodSymbol)interfaceMember, implementingType, implementingTypeIsFromSomeCompilation, ref implicitImpl); // If we discarded the candidate, we don't want default interface implementation to take over later, since runtime might still use the discarded candidate. if (originalImplicitImpl is object && implicitImpl is null) { tryDefaultInterfaceImplementation = false; } } Symbol defaultImpl = null; if ((object)implicitImpl == null && seenTypeDeclaringInterface && tryDefaultInterfaceImplementation) { if (ignoreImplementationInInterfaces) { implementationInInterfacesMightChangeResult = true; } else { // Check for default interface implementations defaultImpl = FindMostSpecificImplementationInInterfaces(interfaceMember, implementingType, ref useSiteInfo, diagnostics); implementationInInterfacesMightChangeResult = false; } } else { implementationInInterfacesMightChangeResult = false; } diagnostics.Add( #if !DEBUG // Don't optimize in DEBUG for better coverage for the GetInterfaceLocation function. useSiteInfo.Diagnostics is null || !implementingTypeImplementsInterface ? Location.None : #endif GetInterfaceLocation(interfaceMember, implementingType), useSiteInfo); if (defaultImpl is object) { if (implementingTypeImplementsInterface) { ReportDefaultInterfaceImplementationMatchDiagnostics(interfaceMember, implementingType, defaultImpl, diagnostics); } return defaultImpl; } if (implementingTypeImplementsInterface) { if ((object)implicitImpl != null) { if (!canBeImplementedImplicitlyInCSharp9) { if (interfaceMember.Kind == SymbolKind.Method && (object)implementingBaseOpt == null) // Otherwise any approprite errors are going to be reported for the base. { LanguageVersion requiredVersion = MessageID.IDS_FeatureImplicitImplementationOfNonPublicMembers.RequiredVersion(); LanguageVersion? availableVersion = implementingType.DeclaringCompilation?.LanguageVersion; if (requiredVersion > availableVersion) { diagnostics.Add(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, GetInterfaceLocation(interfaceMember, implementingType), implementingType, interfaceMember, implicitImpl, availableVersion.GetValueOrDefault().ToDisplayString(), new CSharpRequiredLanguageVersion(requiredVersion)); } } } ReportImplicitImplementationMatchDiagnostics(interfaceMember, implementingType, implicitImpl, diagnostics); } else if ((object)closestMismatch != null) { ReportImplicitImplementationMismatchDiagnostics(interfaceMember, implementingType, closestMismatch, diagnostics); } } return implicitImpl; } private static Symbol FindMostSpecificImplementationInInterfaces(Symbol interfaceMember, TypeSymbol implementingType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, BindingDiagnosticBag diagnostics) { Debug.Assert(!implementingType.IsInterfaceType()); Debug.Assert(!interfaceMember.IsStatic); // If we are dealing with a property or event and an implementation of at least one accessor is not from an interface, it // wouldn't be right to say that the event/property is implemented in an interface because its accessor isn't. (MethodSymbol interfaceAccessor1, MethodSymbol interfaceAccessor2) = GetImplementableAccessors(interfaceMember); if (stopLookup(interfaceAccessor1, implementingType) || stopLookup(interfaceAccessor2, implementingType)) { return null; } Symbol defaultImpl = FindMostSpecificImplementationInBases(interfaceMember, implementingType, ref useSiteInfo, out Symbol conflict1, out Symbol conflict2); if ((object)conflict1 != null) { Debug.Assert((object)defaultImpl == null); Debug.Assert((object)conflict2 != null); diagnostics.Add(ErrorCode.ERR_MostSpecificImplementationIsNotFound, GetInterfaceLocation(interfaceMember, implementingType), interfaceMember, conflict1, conflict2); } else { Debug.Assert(((object)conflict2 == null)); } return defaultImpl; static bool stopLookup(MethodSymbol interfaceAccessor, TypeSymbol implementingType) { if (interfaceAccessor is null) { return false; } SymbolAndDiagnostics symbolAndDiagnostics = implementingType.FindImplementationForInterfaceMemberInNonInterfaceWithDiagnostics(interfaceAccessor); if (symbolAndDiagnostics.Symbol is object) { return !symbolAndDiagnostics.Symbol.ContainingType.IsInterface; } // It is still possible that we actually looked for the accessor in interfaces, but failed due to an ambiguity. // Let's try to look for a property to improve diagnostics in this scenario. return !symbolAndDiagnostics.Diagnostics.Diagnostics.Any(d => d.Code == (int)ErrorCode.ERR_MostSpecificImplementationIsNotFound); } } private static Symbol FindMostSpecificImplementation(Symbol interfaceMember, NamedTypeSymbol implementingInterface, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { MultiDictionary<Symbol, Symbol>.ValueSet implementingMember = FindImplementationInInterface(interfaceMember, implementingInterface); switch (implementingMember.Count) { case 0: (MethodSymbol interfaceAccessor1, MethodSymbol interfaceAccessor2) = GetImplementableAccessors(interfaceMember); // If interface actually implements an event or property accessor, but doesn't implement the event/property, // do not look for its implementation in bases. if ((interfaceAccessor1 is object && FindImplementationInInterface(interfaceAccessor1, implementingInterface).Count != 0) || (interfaceAccessor2 is object && FindImplementationInInterface(interfaceAccessor2, implementingInterface).Count != 0)) { return null; } return FindMostSpecificImplementationInBases(interfaceMember, implementingInterface, ref useSiteInfo, out var _, out var _); case 1: { Symbol result = implementingMember.Single(); if (result.IsAbstract) { return null; } return result; } default: return null; } } /// <summary> /// One implementation M1 is considered more specific than another implementation M2 /// if M1 is declared on interface T1, M2 is declared on interface T2, and /// T1 contains T2 among its direct or indirect interfaces. /// </summary> private static Symbol FindMostSpecificImplementationInBases( Symbol interfaceMember, TypeSymbol implementingType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, out Symbol conflictingImplementation1, out Symbol conflictingImplementation2) { ImmutableArray<NamedTypeSymbol> allInterfaces = implementingType.AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo); if (allInterfaces.IsEmpty) { conflictingImplementation1 = null; conflictingImplementation2 = null; return null; } // Properties or events can be implemented in an unconventional manner, i.e. implementing accessors might not be tied to a property/event. // If we simply look for a more specific implementing property/event, we might find one with not most specific implementing accessors. // Returning a property/event like that would be incorrect because runtime will use most specific accessor, or it will fail because there will // be an ambiguity for the accessor implementation. // So, for events and properties we look for most specific implementation of corresponding accessors and then try to tie them back to // an event/property, if any. (MethodSymbol interfaceAccessor1, MethodSymbol interfaceAccessor2) = GetImplementableAccessors(interfaceMember); if (interfaceAccessor1 is null && interfaceAccessor2 is null) { return findMostSpecificImplementationInBases(interfaceMember, allInterfaces, ref useSiteInfo, out conflictingImplementation1, out conflictingImplementation2); } Symbol accessorImpl1 = findMostSpecificImplementationInBases(interfaceAccessor1 ?? interfaceAccessor2, allInterfaces, ref useSiteInfo, out Symbol conflictingAccessorImplementation11, out Symbol conflictingAccessorImplementation12); if (accessorImpl1 is null && conflictingAccessorImplementation11 is null) // implementation of accessor is not found { conflictingImplementation1 = null; conflictingImplementation2 = null; return null; } if (interfaceAccessor1 is null || interfaceAccessor2 is null) { if (accessorImpl1 is object) { conflictingImplementation1 = null; conflictingImplementation2 = null; return findImplementationInInterface(interfaceMember, accessorImpl1); } conflictingImplementation1 = findImplementationInInterface(interfaceMember, conflictingAccessorImplementation11); conflictingImplementation2 = findImplementationInInterface(interfaceMember, conflictingAccessorImplementation12); if ((conflictingImplementation1 is null) != (conflictingImplementation2 is null)) { conflictingImplementation1 = null; conflictingImplementation2 = null; } return null; } Symbol accessorImpl2 = findMostSpecificImplementationInBases(interfaceAccessor2, allInterfaces, ref useSiteInfo, out Symbol conflictingAccessorImplementation21, out Symbol conflictingAccessorImplementation22); if ((accessorImpl2 is null && conflictingAccessorImplementation21 is null) || // implementation of accessor is not found (accessorImpl1 is null) != (accessorImpl2 is null)) // there is most specific implementation for one accessor and an ambiguous implementation for the other accessor. { conflictingImplementation1 = null; conflictingImplementation2 = null; return null; } if (accessorImpl1 is object) { conflictingImplementation1 = null; conflictingImplementation2 = null; return findImplementationInInterface(interfaceMember, accessorImpl1, accessorImpl2); } conflictingImplementation1 = findImplementationInInterface(interfaceMember, conflictingAccessorImplementation11, conflictingAccessorImplementation21); conflictingImplementation2 = findImplementationInInterface(interfaceMember, conflictingAccessorImplementation12, conflictingAccessorImplementation22); if ((conflictingImplementation1 is null) != (conflictingImplementation2 is null)) { // One pair of conflicting accessors can be tied to an event/property, but the other cannot be tied to an event/property. // Dropping conflict information since it only affects diagnostic. conflictingImplementation1 = null; conflictingImplementation2 = null; } return null; static Symbol findImplementationInInterface(Symbol interfaceMember, Symbol inplementingAccessor1, Symbol implementingAccessor2 = null) { NamedTypeSymbol implementingInterface = inplementingAccessor1.ContainingType; if (implementingAccessor2 is object && !implementingInterface.Equals(implementingAccessor2.ContainingType, TypeCompareKind.ConsiderEverything)) { // Implementing accessors are from different types, they cannot be tied to the same event/property. return null; } MultiDictionary<Symbol, Symbol>.ValueSet implementingMember = FindImplementationInInterface(interfaceMember, implementingInterface); switch (implementingMember.Count) { case 1: return implementingMember.Single(); default: return null; } } static Symbol findMostSpecificImplementationInBases( Symbol interfaceMember, ImmutableArray<NamedTypeSymbol> allInterfaces, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, out Symbol conflictingImplementation1, out Symbol conflictingImplementation2) { var implementations = ArrayBuilder<(MultiDictionary<Symbol, Symbol>.ValueSet MethodSet, MultiDictionary<NamedTypeSymbol, NamedTypeSymbol> Bases)>.GetInstance(); foreach (var interfaceType in allInterfaces) { if (!interfaceType.IsInterface) { // this code is reachable in error situations continue; } MultiDictionary<Symbol, Symbol>.ValueSet candidate = FindImplementationInInterface(interfaceMember, interfaceType); if (candidate.Count == 0) { continue; } for (int i = 0; i < implementations.Count; i++) { (MultiDictionary<Symbol, Symbol>.ValueSet methodSet, MultiDictionary<NamedTypeSymbol, NamedTypeSymbol> bases) = implementations[i]; Symbol previous = methodSet.First(); NamedTypeSymbol previousContainingType = previous.ContainingType; if (previousContainingType.Equals(interfaceType, TypeCompareKind.CLRSignatureCompareOptions)) { // Last equivalent match wins implementations[i] = (candidate, bases); candidate = default; break; } if (bases == null) { Debug.Assert(implementations.Count == 1); bases = previousContainingType.InterfacesAndTheirBaseInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo); implementations[i] = (methodSet, bases); } if (bases.ContainsKey(interfaceType)) { // Previous candidate is more specific candidate = default; break; } } if (candidate.Count == 0) { continue; } if (implementations.Count != 0) { MultiDictionary<NamedTypeSymbol, NamedTypeSymbol> bases = interfaceType.InterfacesAndTheirBaseInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo); for (int i = implementations.Count - 1; i >= 0; i--) { if (bases.ContainsKey(implementations[i].MethodSet.First().ContainingType)) { // new candidate is more specific implementations.RemoveAt(i); } } implementations.Add((candidate, bases)); } else { implementations.Add((candidate, null)); } } Symbol result; switch (implementations.Count) { case 0: result = null; conflictingImplementation1 = null; conflictingImplementation2 = null; break; case 1: MultiDictionary<Symbol, Symbol>.ValueSet methodSet = implementations[0].MethodSet; switch (methodSet.Count) { case 1: result = methodSet.Single(); if (result.IsAbstract) { result = null; } break; default: result = null; break; } conflictingImplementation1 = null; conflictingImplementation2 = null; break; default: result = null; conflictingImplementation1 = implementations[0].MethodSet.First(); conflictingImplementation2 = implementations[1].MethodSet.First(); break; } implementations.Free(); return result; } } internal static MultiDictionary<Symbol, Symbol>.ValueSet FindImplementationInInterface(Symbol interfaceMember, NamedTypeSymbol interfaceType) { Debug.Assert(interfaceType.IsInterface); Debug.Assert(!interfaceMember.IsStatic); NamedTypeSymbol containingType = interfaceMember.ContainingType; if (containingType.Equals(interfaceType, TypeCompareKind.CLRSignatureCompareOptions)) { if (!interfaceMember.IsAbstract) { if (!containingType.Equals(interfaceType, TypeCompareKind.ConsiderEverything)) { interfaceMember = interfaceMember.OriginalDefinition.SymbolAsMember(interfaceType); } return new MultiDictionary<Symbol, Symbol>.ValueSet(interfaceMember); } return default; } return interfaceType.GetExplicitImplementationForInterfaceMember(interfaceMember); } private static (MethodSymbol interfaceAccessor1, MethodSymbol interfaceAccessor2) GetImplementableAccessors(Symbol interfaceMember) { MethodSymbol interfaceAccessor1; MethodSymbol interfaceAccessor2; switch (interfaceMember.Kind) { case SymbolKind.Property: { PropertySymbol interfaceProperty = (PropertySymbol)interfaceMember; interfaceAccessor1 = interfaceProperty.GetMethod; interfaceAccessor2 = interfaceProperty.SetMethod; break; } case SymbolKind.Event: { EventSymbol interfaceEvent = (EventSymbol)interfaceMember; interfaceAccessor1 = interfaceEvent.AddMethod; interfaceAccessor2 = interfaceEvent.RemoveMethod; break; } default: { interfaceAccessor1 = null; interfaceAccessor2 = null; break; } } if (!interfaceAccessor1.IsImplementable()) { interfaceAccessor1 = null; } if (!interfaceAccessor2.IsImplementable()) { interfaceAccessor2 = null; } return (interfaceAccessor1, interfaceAccessor2); } /// <summary> /// Since dev11 didn't expose a symbol API, it had the luxury of being able to accept a base class's claim that /// it implements an interface. Roslyn, on the other hand, needs to be able to point to an implementing symbol /// for each interface member. /// /// DevDiv #718115 was triggered by some unusual metadata in a Microsoft reference assembly (Silverlight System.Windows.dll). /// The issue was that a type explicitly implemented the accessors of an interface event, but did not tie them together with /// an event declaration. To make matters worse, it declared its own protected event with the same name as the interface /// event (presumably to back the explicit implementation). As a result, when Roslyn was asked to find the implementing member /// for the interface event, it found the protected event and reported an appropriate diagnostic. What it should have done /// (and does do now) is recognize that no event associated with the accessors explicitly implementing the interface accessors /// and returned null. /// /// We resolved this issue by introducing a new step into the interface mapping algorithm: after failing to find an explicit /// implementation in a type, but before searching for an implicit implementation in that type, check for an explicit implementation /// of an associated accessor. If there is such an implementation, then immediately return the associated property or event, /// even if it is null. That is, never attempt to find an implicit implementation for an interface property or event with an /// explicitly implemented accessor. /// </summary> private static bool IsExplicitlyImplementedViaAccessors(bool checkPendingExplicitImplementations, Symbol interfaceMember, TypeSymbol currType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, out Symbol implementingMember) { (MethodSymbol interfaceAccessor1, MethodSymbol interfaceAccessor2) = GetImplementableAccessors(interfaceMember); Symbol associated1; Symbol associated2; if (TryGetExplicitImplementationAssociatedPropertyOrEvent(checkPendingExplicitImplementations, interfaceAccessor1, currType, ref useSiteInfo, out associated1) | // NB: not || TryGetExplicitImplementationAssociatedPropertyOrEvent(checkPendingExplicitImplementations, interfaceAccessor2, currType, ref useSiteInfo, out associated2)) { // If there's more than one associated property/event, don't do anything special - just let the algorithm // fail in the usual way. if ((object)associated1 == null || (object)associated2 == null || associated1 == associated2) { implementingMember = associated1 ?? associated2; // In source, we should already have seen an explicit implementation for the interface property/event. // If we haven't then there is no implementation. We need this check to match dev11 in some edge cases // (e.g. IndexerTests.AmbiguousExplicitIndexerImplementation). Such cases already fail // to roundtrip correctly, so it's not important to check for a particular compilation. if ((object)implementingMember != null && implementingMember.OriginalDefinition.ContainingModule is not PEModuleSymbol && implementingMember.IsExplicitInterfaceImplementation()) { implementingMember = null; } } else { implementingMember = null; } return true; } implementingMember = null; return false; } private static bool TryGetExplicitImplementationAssociatedPropertyOrEvent(bool checkPendingExplicitImplementations, MethodSymbol interfaceAccessor, TypeSymbol currType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, out Symbol associated) { if ((object)interfaceAccessor != null) { // NB: uses a map that was built (and saved) when we checked for an explicit // implementation of the interface member. MultiDictionary<Symbol, Symbol>.ValueSet set = currType.GetExplicitImplementationForInterfaceMember(interfaceAccessor); if (set.Count == 1) { Symbol implementation = set.Single(); associated = implementation.Kind == SymbolKind.Method ? ((MethodSymbol)implementation).AssociatedSymbol : null; return true; } if (checkPendingExplicitImplementations && currType.InterfacesAndTheirBaseInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo).ContainsKey(interfaceAccessor.ContainingType)) { // Check for implementations that are going to be explicit once types are emitted MethodSymbol bodyOfSynthesizedMethodImpl = currType.GetBodyOfSynthesizedInterfaceMethodImpl(interfaceAccessor); if (bodyOfSynthesizedMethodImpl is object) { associated = bodyOfSynthesizedMethodImpl.AssociatedSymbol; return true; } } } associated = null; return false; } /// <summary> /// If we were looking for an accessor, then look for an accessor on the implementation of the /// corresponding interface property/event. If it is valid as an implementation (ignoring the name), /// then prefer it to our current result if: /// 1) our current result is null; or /// 2) our current result is on the same type. /// /// If there is no corresponding accessor on the implementation of the corresponding interface /// property/event and we found an accessor, then the accessor we found is invalid, so clear it. /// </summary> private static void CheckForImplementationOfCorrespondingPropertyOrEvent(MethodSymbol interfaceMethod, TypeSymbol implementingType, bool implementingTypeIsFromSomeCompilation, ref Symbol implicitImpl) { Debug.Assert(!implementingType.IsInterfaceType()); Debug.Assert(interfaceMethod.IsAccessor()); Symbol associatedInterfacePropertyOrEvent = interfaceMethod.AssociatedSymbol; // Do not make any adjustments based on presence of default interface implementation for the property or event. // We don't want an addition of default interface implementation to change an error situation to success for // scenarios where the default interface implementation wouldn't actually be used at runtime. // When we find an implicit implementation candidate, we don't want to not discard it if we would discard it when // default interface implementation was missing. Why would presence of default interface implementation suddenly // make the candidate suiatable to implement the interface? Also, if we discard the candidate, we don't want default interface // implementation to take over later, since runtime might still use the discarded candidate. // When we don't find any implicit implementation candidate, returning accessor of default interface implementation // doesn't actually help much because we would find it anyway (it is implemented explicitly). Symbol implementingPropertyOrEvent = implementingType.FindImplementationForInterfaceMemberInNonInterface(associatedInterfacePropertyOrEvent, ignoreImplementationInInterfacesIfResultIsNotReady: true); // NB: uses cache MethodSymbol correspondingImplementingAccessor = null; if ((object)implementingPropertyOrEvent != null && !implementingPropertyOrEvent.ContainingType.IsInterface) { switch (interfaceMethod.MethodKind) { case MethodKind.PropertyGet: correspondingImplementingAccessor = ((PropertySymbol)implementingPropertyOrEvent).GetOwnOrInheritedGetMethod(); break; case MethodKind.PropertySet: correspondingImplementingAccessor = ((PropertySymbol)implementingPropertyOrEvent).GetOwnOrInheritedSetMethod(); break; case MethodKind.EventAdd: correspondingImplementingAccessor = ((EventSymbol)implementingPropertyOrEvent).GetOwnOrInheritedAddMethod(); break; case MethodKind.EventRemove: correspondingImplementingAccessor = ((EventSymbol)implementingPropertyOrEvent).GetOwnOrInheritedRemoveMethod(); break; default: throw ExceptionUtilities.UnexpectedValue(interfaceMethod.MethodKind); } } if (correspondingImplementingAccessor == implicitImpl) { return; } else if ((object)correspondingImplementingAccessor == null && (object)implicitImpl != null && implicitImpl.IsAccessor()) { // If we found an accessor, but it's not (directly or indirectly) on the property implementation, // then it's not a valid match. implicitImpl = null; } else if ((object)correspondingImplementingAccessor != null && ((object)implicitImpl == null || TypeSymbol.Equals(correspondingImplementingAccessor.ContainingType, implicitImpl.ContainingType, TypeCompareKind.ConsiderEverything2))) { // Suppose the interface accessor and the implementing accessor have different names. // In Dev10, as long as the corresponding properties have an implementation relationship, // then the accessor can be considered an implementation, even though the name is different. // Later on, when we check that implementation signatures match exactly // (in SourceMemberContainerTypeSymbol.SynthesizeInterfaceMemberImplementation), // they won't (because of the names) and an explicit implementation method will be synthesized. MethodSymbol interfaceAccessorWithImplementationName = new SignatureOnlyMethodSymbol( correspondingImplementingAccessor.Name, interfaceMethod.ContainingType, interfaceMethod.MethodKind, interfaceMethod.CallingConvention, interfaceMethod.TypeParameters, interfaceMethod.Parameters, interfaceMethod.RefKind, interfaceMethod.IsInitOnly, interfaceMethod.IsStatic, interfaceMethod.ReturnTypeWithAnnotations, interfaceMethod.RefCustomModifiers, interfaceMethod.ExplicitInterfaceImplementations); // Make sure that the corresponding accessor is a real implementation. if (IsInterfaceMemberImplementation(correspondingImplementingAccessor, interfaceAccessorWithImplementationName, implementingTypeIsFromSomeCompilation)) { implicitImpl = correspondingImplementingAccessor; } } } private static void ReportDefaultInterfaceImplementationMatchDiagnostics(Symbol interfaceMember, TypeSymbol implementingType, Symbol implicitImpl, BindingDiagnosticBag diagnostics) { if (interfaceMember.Kind == SymbolKind.Method && implementingType.ContainingModule != implicitImpl.ContainingModule) { // The default implementation is coming from a different module, which means that we probably didn't check // for the required runtime capability or language version LanguageVersion requiredVersion = MessageID.IDS_DefaultInterfaceImplementation.RequiredVersion(); LanguageVersion? availableVersion = implementingType.DeclaringCompilation?.LanguageVersion; if (requiredVersion > availableVersion) { diagnostics.Add(ErrorCode.ERR_LanguageVersionDoesNotSupportDefaultInterfaceImplementationForMember, GetInterfaceLocation(interfaceMember, implementingType), implicitImpl, interfaceMember, implementingType, MessageID.IDS_DefaultInterfaceImplementation.Localize(), availableVersion.GetValueOrDefault().ToDisplayString(), new CSharpRequiredLanguageVersion(requiredVersion)); } if (!implementingType.ContainingAssembly.RuntimeSupportsDefaultInterfaceImplementation) { diagnostics.Add(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementationForMember, GetInterfaceLocation(interfaceMember, implementingType), implicitImpl, interfaceMember, implementingType); } } } /// <summary> /// These diagnostics are for members that do implicitly implement an interface member, but do so /// in an undesirable way. /// </summary> private static void ReportImplicitImplementationMatchDiagnostics(Symbol interfaceMember, TypeSymbol implementingType, Symbol implicitImpl, BindingDiagnosticBag diagnostics) { bool reportedAnError = false; if (interfaceMember.Kind == SymbolKind.Method) { var interfaceMethod = (MethodSymbol)interfaceMember; bool implicitImplIsAccessor = implicitImpl.IsAccessor(); bool interfaceMethodIsAccessor = interfaceMethod.IsAccessor(); if (interfaceMethodIsAccessor && !implicitImplIsAccessor && !interfaceMethod.IsIndexedPropertyAccessor()) { diagnostics.Add(ErrorCode.ERR_MethodImplementingAccessor, GetImplicitImplementationDiagnosticLocation(interfaceMember, implementingType, implicitImpl), implicitImpl, interfaceMethod, implementingType); } else if (!interfaceMethodIsAccessor && implicitImplIsAccessor) { diagnostics.Add(ErrorCode.ERR_AccessorImplementingMethod, GetImplicitImplementationDiagnosticLocation(interfaceMember, implementingType, implicitImpl), implicitImpl, interfaceMethod, implementingType); } else { var implicitImplMethod = (MethodSymbol)implicitImpl; if (implicitImplMethod.IsConditional) { // CS0629: Conditional member '{0}' cannot implement interface member '{1}' in type '{2}' diagnostics.Add(ErrorCode.ERR_InterfaceImplementedByConditional, GetImplicitImplementationDiagnosticLocation(interfaceMember, implementingType, implicitImpl), implicitImpl, interfaceMethod, implementingType); } else if (implicitImplMethod.IsStatic && implicitImplMethod.MethodKind == MethodKind.Ordinary && implicitImplMethod.GetUnmanagedCallersOnlyAttributeData(forceComplete: true) is not null) { diagnostics.Add(ErrorCode.ERR_InterfaceImplementedByUnmanagedCallersOnlyMethod, GetImplicitImplementationDiagnosticLocation(interfaceMember, implementingType, implicitImpl), implicitImpl, interfaceMethod, implementingType); } else if (ReportAnyMismatchedConstraints(interfaceMethod, implementingType, implicitImplMethod, diagnostics)) { reportedAnError = true; } } } if (implicitImpl.ContainsTupleNames() && MemberSignatureComparer.ConsideringTupleNamesCreatesDifference(implicitImpl, interfaceMember)) { // it is ok to implement implicitly with no tuple names, for compatibility with C# 6, but otherwise names should match diagnostics.Add(ErrorCode.ERR_ImplBadTupleNames, GetImplicitImplementationDiagnosticLocation(interfaceMember, implementingType, implicitImpl), implicitImpl, interfaceMember); reportedAnError = true; } if (!reportedAnError && implementingType.DeclaringCompilation != null) { CheckNullableReferenceTypeMismatchOnImplementingMember(implementingType, implicitImpl, interfaceMember, isExplicit: false, diagnostics); } // In constructed types, it is possible to see multiple members with the same (runtime) signature. // Now that we know which member will implement the interface member, confirm that it is the only // such member. if (!implicitImpl.ContainingType.IsDefinition) { foreach (Symbol member in implicitImpl.ContainingType.GetMembers(implicitImpl.Name)) { if (member.DeclaredAccessibility != Accessibility.Public || member.IsStatic || member == implicitImpl) { //do nothing - not an ambiguous implementation } else if (MemberSignatureComparer.RuntimeImplicitImplementationComparer.Equals(interfaceMember, member) && !member.IsAccessor()) { // CONSIDER: Dev10 does not seem to report this for indexers or their accessors. diagnostics.Add(ErrorCode.WRN_MultipleRuntimeImplementationMatches, GetImplicitImplementationDiagnosticLocation(interfaceMember, implementingType, member), member, interfaceMember, implementingType); } } } if (implicitImpl.IsStatic && !implementingType.ContainingAssembly.RuntimeSupportsStaticAbstractMembersInInterfaces) { diagnostics.Add(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember, GetInterfaceLocation(interfaceMember, implementingType), implicitImpl, interfaceMember, implementingType); } } internal static void CheckNullableReferenceTypeMismatchOnImplementingMember(TypeSymbol implementingType, Symbol implementingMember, Symbol interfaceMember, bool isExplicit, BindingDiagnosticBag diagnostics) { if (!implementingMember.IsImplicitlyDeclared && !implementingMember.IsAccessor()) { CSharpCompilation compilation = implementingType.DeclaringCompilation; if (interfaceMember.Kind == SymbolKind.Event) { var implementingEvent = (EventSymbol)implementingMember; var implementedEvent = (EventSymbol)interfaceMember; SourceMemberContainerTypeSymbol.CheckValidNullableEventOverride(compilation, implementedEvent, implementingEvent, diagnostics, (diagnostics, implementedEvent, implementingEvent, arg) => { if (arg.isExplicit) { diagnostics.Add(ErrorCode.WRN_NullabilityMismatchInTypeOnExplicitImplementation, implementingEvent.Locations[0], new FormattedSymbol(implementedEvent, SymbolDisplayFormat.MinimallyQualifiedFormat)); } else { diagnostics.Add(ErrorCode.WRN_NullabilityMismatchInTypeOnImplicitImplementation, GetImplicitImplementationDiagnosticLocation(implementedEvent, arg.implementingType, implementingEvent), new FormattedSymbol(implementingEvent, SymbolDisplayFormat.MinimallyQualifiedFormat), new FormattedSymbol(implementedEvent, SymbolDisplayFormat.MinimallyQualifiedFormat)); } }, (implementingType, isExplicit)); } else { ReportMismatchInReturnType<(TypeSymbol implementingType, bool isExplicit)> reportMismatchInReturnType = (diagnostics, implementedMethod, implementingMethod, topLevel, arg) => { if (arg.isExplicit) { // We use ConstructedFrom symbols here and below to not leak methods with Ignored annotations in type arguments // into diagnostics diagnostics.Add(topLevel ? ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnExplicitImplementation : ErrorCode.WRN_NullabilityMismatchInReturnTypeOnExplicitImplementation, implementingMethod.Locations[0], new FormattedSymbol(implementedMethod.ConstructedFrom, SymbolDisplayFormat.MinimallyQualifiedFormat)); } else { diagnostics.Add(topLevel ? ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnImplicitImplementation : ErrorCode.WRN_NullabilityMismatchInReturnTypeOnImplicitImplementation, GetImplicitImplementationDiagnosticLocation(implementedMethod, arg.implementingType, implementingMethod), new FormattedSymbol(implementingMethod, SymbolDisplayFormat.MinimallyQualifiedFormat), new FormattedSymbol(implementedMethod.ConstructedFrom, SymbolDisplayFormat.MinimallyQualifiedFormat)); } }; ReportMismatchInParameterType<(TypeSymbol implementingType, bool isExplicit)> reportMismatchInParameterType = (diagnostics, implementedMethod, implementingMethod, implementingParameter, topLevel, arg) => { if (arg.isExplicit) { diagnostics.Add(topLevel ? ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnExplicitImplementation : ErrorCode.WRN_NullabilityMismatchInParameterTypeOnExplicitImplementation, implementingMethod.Locations[0], new FormattedSymbol(implementingParameter, SymbolDisplayFormat.ShortFormat), new FormattedSymbol(implementedMethod.ConstructedFrom, SymbolDisplayFormat.MinimallyQualifiedFormat)); } else { diagnostics.Add(topLevel ? ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnImplicitImplementation : ErrorCode.WRN_NullabilityMismatchInParameterTypeOnImplicitImplementation, GetImplicitImplementationDiagnosticLocation(implementedMethod, arg.implementingType, implementingMethod), new FormattedSymbol(implementingParameter, SymbolDisplayFormat.ShortFormat), new FormattedSymbol(implementingMethod, SymbolDisplayFormat.MinimallyQualifiedFormat), new FormattedSymbol(implementedMethod.ConstructedFrom, SymbolDisplayFormat.MinimallyQualifiedFormat)); } }; switch (interfaceMember.Kind) { case SymbolKind.Property: var implementingProperty = (PropertySymbol)implementingMember; var implementedProperty = (PropertySymbol)interfaceMember; if (implementedProperty.GetMethod.IsImplementable()) { MethodSymbol implementingGetMethod = implementingProperty.GetOwnOrInheritedGetMethod(); SourceMemberContainerTypeSymbol.CheckValidNullableMethodOverride( compilation, implementedProperty.GetMethod, implementingGetMethod, diagnostics, reportMismatchInReturnType, // Don't check parameters on the getter if there is a setter // because they will be a subset of the setter (!implementedProperty.SetMethod.IsImplementable() || implementingGetMethod?.AssociatedSymbol != implementingProperty || implementingProperty.GetOwnOrInheritedSetMethod()?.AssociatedSymbol != implementingProperty) ? reportMismatchInParameterType : null, (implementingType, isExplicit)); } if (implementedProperty.SetMethod.IsImplementable()) { SourceMemberContainerTypeSymbol.CheckValidNullableMethodOverride( compilation, implementedProperty.SetMethod, implementingProperty.GetOwnOrInheritedSetMethod(), diagnostics, null, reportMismatchInParameterType, (implementingType, isExplicit)); } break; case SymbolKind.Method: var implementingMethod = (MethodSymbol)implementingMember; var implementedMethod = (MethodSymbol)interfaceMember; if (implementedMethod.IsGenericMethod) { implementedMethod = implementedMethod.Construct(TypeMap.TypeParametersAsTypeSymbolsWithIgnoredAnnotations(implementingMethod.TypeParameters)); } SourceMemberContainerTypeSymbol.CheckValidNullableMethodOverride( compilation, implementedMethod, implementingMethod, diagnostics, reportMismatchInReturnType, reportMismatchInParameterType, (implementingType, isExplicit)); break; default: throw ExceptionUtilities.UnexpectedValue(interfaceMember.Kind); } } } } /// <summary> /// These diagnostics are for members that almost, but not actually, implicitly implement an interface member. /// </summary> private static void ReportImplicitImplementationMismatchDiagnostics(Symbol interfaceMember, TypeSymbol implementingType, Symbol closestMismatch, BindingDiagnosticBag diagnostics) { // Determine a better location for diagnostic squiggles. Squiggle the interface rather than the class. Location interfaceLocation = GetInterfaceLocation(interfaceMember, implementingType); if (closestMismatch.IsStatic != interfaceMember.IsStatic) { diagnostics.Add(closestMismatch.IsStatic ? ErrorCode.ERR_CloseUnimplementedInterfaceMemberStatic : ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotStatic, interfaceLocation, implementingType, interfaceMember, closestMismatch); } else if (closestMismatch.DeclaredAccessibility != Accessibility.Public) { ErrorCode errorCode = interfaceMember.IsAccessor() ? ErrorCode.ERR_UnimplementedInterfaceAccessor : ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic; diagnostics.Add(errorCode, interfaceLocation, implementingType, interfaceMember, closestMismatch); } else if (HaveInitOnlyMismatch(interfaceMember, closestMismatch)) { diagnostics.Add(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongInitOnly, interfaceLocation, implementingType, interfaceMember, closestMismatch); } else //return ref kind or type doesn't match { RefKind interfaceMemberRefKind = RefKind.None; TypeSymbol interfaceMemberReturnType; switch (interfaceMember.Kind) { case SymbolKind.Method: var method = (MethodSymbol)interfaceMember; interfaceMemberRefKind = method.RefKind; interfaceMemberReturnType = method.ReturnType; break; case SymbolKind.Property: var property = (PropertySymbol)interfaceMember; interfaceMemberRefKind = property.RefKind; interfaceMemberReturnType = property.Type; break; case SymbolKind.Event: interfaceMemberReturnType = ((EventSymbol)interfaceMember).Type; break; default: throw ExceptionUtilities.UnexpectedValue(interfaceMember.Kind); } bool hasRefReturnMismatch = false; switch (closestMismatch.Kind) { case SymbolKind.Method: hasRefReturnMismatch = ((MethodSymbol)closestMismatch).RefKind != interfaceMemberRefKind; break; case SymbolKind.Property: hasRefReturnMismatch = ((PropertySymbol)closestMismatch).RefKind != interfaceMemberRefKind; break; } DiagnosticInfo useSiteDiagnostic; if ((object)interfaceMemberReturnType != null && (useSiteDiagnostic = interfaceMemberReturnType.GetUseSiteInfo().DiagnosticInfo) != null && useSiteDiagnostic.DefaultSeverity == DiagnosticSeverity.Error) { diagnostics.Add(useSiteDiagnostic, interfaceLocation); } else if (hasRefReturnMismatch) { diagnostics.Add(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongRefReturn, interfaceLocation, implementingType, interfaceMember, closestMismatch); } else { diagnostics.Add(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, interfaceLocation, implementingType, interfaceMember, closestMismatch, interfaceMemberReturnType); } } } internal static bool HaveInitOnlyMismatch(Symbol one, Symbol other) { if (!(one is MethodSymbol oneMethod)) { return false; } if (!(other is MethodSymbol otherMethod)) { return false; } return oneMethod.IsInitOnly != otherMethod.IsInitOnly; } /// <summary> /// Determine a better location for diagnostic squiggles. Squiggle the interface rather than the class. /// </summary> private static Location GetInterfaceLocation(Symbol interfaceMember, TypeSymbol implementingType) { Debug.Assert((object)implementingType != null); var @interface = interfaceMember.ContainingType; SourceMemberContainerTypeSymbol snt = null; if (implementingType.InterfacesAndTheirBaseInterfacesNoUseSiteDiagnostics[@interface].Contains(@interface)) { snt = implementingType as SourceMemberContainerTypeSymbol; } return snt?.GetImplementsLocation(@interface) ?? implementingType.Locations.FirstOrNone(); } private static bool ReportAnyMismatchedConstraints(MethodSymbol interfaceMethod, TypeSymbol implementingType, MethodSymbol implicitImpl, BindingDiagnosticBag diagnostics) { Debug.Assert(interfaceMethod.Arity == implicitImpl.Arity); bool result = false; var arity = interfaceMethod.Arity; if (arity > 0) { var typeParameters1 = interfaceMethod.TypeParameters; var typeParameters2 = implicitImpl.TypeParameters; var indexedTypeParameters = IndexedTypeParameterSymbol.Take(arity); var typeMap1 = new TypeMap(typeParameters1, indexedTypeParameters, allowAlpha: true); var typeMap2 = new TypeMap(typeParameters2, indexedTypeParameters, allowAlpha: true); // Report any mismatched method constraints. for (int i = 0; i < arity; i++) { var typeParameter1 = typeParameters1[i]; var typeParameter2 = typeParameters2[i]; if (!MemberSignatureComparer.HaveSameConstraints(typeParameter1, typeMap1, typeParameter2, typeMap2)) { // If the matching method for the interface member is defined on the implementing type, // the matching method location is used for the error. Otherwise, the location of the // implementing type is used. (This differs from Dev10 which associates the error with // the closest method always. That behavior can be confusing though, since in the case // of "interface I { M; } class A { M; } class B : A, I { }", this means reporting an error on // A.M that it does not satisfy I.M even though A does not implement I. Furthermore if // A is defined in metadata, there is no location for A.M. Instead, we simply report the // error on B if the match to I.M is in a base class.) diagnostics.Add(ErrorCode.ERR_ImplBadConstraints, GetImplicitImplementationDiagnosticLocation(interfaceMethod, implementingType, implicitImpl), typeParameter2.Name, implicitImpl, typeParameter1.Name, interfaceMethod); } else if (!MemberSignatureComparer.HaveSameNullabilityInConstraints(typeParameter1, typeMap1, typeParameter2, typeMap2)) { diagnostics.Add(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, GetImplicitImplementationDiagnosticLocation(interfaceMethod, implementingType, implicitImpl), typeParameter2.Name, implicitImpl, typeParameter1.Name, interfaceMethod); } } } return result; } internal static Location GetImplicitImplementationDiagnosticLocation(Symbol interfaceMember, TypeSymbol implementingType, Symbol member) { if (TypeSymbol.Equals(member.ContainingType, implementingType, TypeCompareKind.ConsiderEverything2)) { return member.Locations[0]; } else { var @interface = interfaceMember.ContainingType; SourceMemberContainerTypeSymbol snt = implementingType as SourceMemberContainerTypeSymbol; return snt?.GetImplementsLocation(@interface) ?? implementingType.Locations[0]; } } /// <summary> /// Search the declared members of a type for one that could be an implementation /// of a given interface member (depending on interface declarations). /// </summary> /// <param name="interfaceMember">The interface member being implemented.</param> /// <param name="implementingTypeIsFromSomeCompilation">True if the implementing type is from some compilation (i.e. not from metadata).</param> /// <param name="currType">The type on which we are looking for a declared implementation of the interface member.</param> /// <param name="implicitImpl">A member on currType that could implement the interface, or null.</param> /// <param name="closeMismatch">A member on currType that could have been an attempt to implement the interface, or null.</param> /// <remarks> /// There is some similarity between this member and OverriddenOrHiddenMembersHelpers.FindOverriddenOrHiddenMembersInType. /// When making changes to this member, think about whether or not they should also be applied in MemberSymbol. /// One key difference is that custom modifiers are considered when looking up overridden members, but /// not when looking up implicit implementations. We're preserving this behavior from Dev10. /// </remarks> private static void FindPotentialImplicitImplementationMemberDeclaredInType( Symbol interfaceMember, bool implementingTypeIsFromSomeCompilation, TypeSymbol currType, out Symbol implicitImpl, out Symbol closeMismatch) { implicitImpl = null; closeMismatch = null; bool? isOperator = null; if (interfaceMember is MethodSymbol interfaceMethod) { isOperator = interfaceMethod.MethodKind is MethodKind.UserDefinedOperator or MethodKind.Conversion; } foreach (Symbol member in currType.GetMembers(interfaceMember.Name)) { if (member.Kind == interfaceMember.Kind) { if (isOperator.HasValue && (((MethodSymbol)member).MethodKind is MethodKind.UserDefinedOperator or MethodKind.Conversion) != isOperator.GetValueOrDefault()) { continue; } if (IsInterfaceMemberImplementation(member, interfaceMember, implementingTypeIsFromSomeCompilation)) { implicitImpl = member; return; } // If we haven't found a match, do a weaker comparison that ignores static-ness, accessibility, and return type. else if ((object)closeMismatch == null && implementingTypeIsFromSomeCompilation) { // We can ignore custom modifiers here, because our goal is to improve the helpfulness // of an error we're already giving, rather than to generate a new error. if (MemberSignatureComparer.CSharpCloseImplicitImplementationComparer.Equals(interfaceMember, member)) { closeMismatch = member; } } } } } /// <summary> /// To implement an interface member, a candidate member must be public, non-static, and have /// the same signature. "Have the same signature" has a looser definition if the type implementing /// the interface is from source. /// </summary> /// <remarks> /// PROPERTIES: /// NOTE: we're not checking whether this property has at least the accessors /// declared in the interface. Dev10 considers it a match either way and, /// reports failure to implement accessors separately. /// /// If the implementing type (i.e. the type with the interface in its interface /// list) is in source, then we can ignore custom modifiers in/on the property /// type because they will be copied into the bridge property that explicitly /// implements the interface property (or they would be, if we created such /// a bridge property). Bridge *methods* (not properties) are inserted in /// SourceMemberContainerTypeSymbol.SynthesizeInterfaceMemberImplementation. /// /// CONSIDER: The spec for interface mapping (13.4.4) could be interpreted to mean that this /// property is not an implementation unless it has an accessor for each accessor of the /// interface property. For now, we prefer to represent that case as having an implemented /// property and an unimplemented accessor because it makes finding accessor implementations /// much easier. If we decide that we want the API to report the property as unimplemented, /// then it might be appropriate to keep current result internally and just check the accessors /// before returning the value from the public API (similar to the way MethodSymbol.OverriddenMethod /// filters MethodSymbol.OverriddenOrHiddenMembers. /// </remarks> private static bool IsInterfaceMemberImplementation(Symbol candidateMember, Symbol interfaceMember, bool implementingTypeIsFromSomeCompilation) { if (candidateMember.DeclaredAccessibility != Accessibility.Public || candidateMember.IsStatic != interfaceMember.IsStatic) { return false; } else if (HaveInitOnlyMismatch(candidateMember, interfaceMember)) { return false; } else if (implementingTypeIsFromSomeCompilation) { // We're specifically ignoring custom modifiers for source types because that's what Dev10 does. // Inexact matches are acceptable because we'll just generate bridge members - explicit implementations // with exact signatures that delegate to the inexact match. This happens automatically in // SourceMemberContainerTypeSymbol.SynthesizeInterfaceMemberImplementation. return MemberSignatureComparer.CSharpImplicitImplementationComparer.Equals(interfaceMember, candidateMember); } else { // NOTE: Dev10 seems to use the C# rules in this case as well, but it doesn't give diagnostics about // the failure of a metadata type to implement an interface so there's no problem with reporting the // CLI interpretation instead. For example, using this comparer might allow a member with a ref // parameter to implement a member with an out parameter - which Dev10 would not allow - but that's // okay because Dev10's behavior is not observable. return MemberSignatureComparer.RuntimeImplicitImplementationComparer.Equals(interfaceMember, candidateMember); } } protected MultiDictionary<Symbol, Symbol>.ValueSet GetExplicitImplementationForInterfaceMember(Symbol interfaceMember) { var info = this.GetInterfaceInfo(); if (info == s_noInterfaces) { return default; } if (info.explicitInterfaceImplementationMap == null) { Interlocked.CompareExchange(ref info.explicitInterfaceImplementationMap, MakeExplicitInterfaceImplementationMap(), null); } return info.explicitInterfaceImplementationMap[interfaceMember]; } private MultiDictionary<Symbol, Symbol> MakeExplicitInterfaceImplementationMap() { var map = new MultiDictionary<Symbol, Symbol>(ExplicitInterfaceImplementationTargetMemberEqualityComparer.Instance); foreach (var member in this.GetMembersUnordered()) { foreach (var interfaceMember in member.GetExplicitInterfaceImplementations()) { Debug.Assert(interfaceMember.Kind != SymbolKind.Method || (object)interfaceMember == ((MethodSymbol)interfaceMember).ConstructedFrom); map.Add(interfaceMember, member); } } return map; } #nullable enable /// <summary> /// If implementation of an interface method <paramref name="interfaceMethod"/> will be accompanied with /// a MethodImpl entry in metadata, information about which isn't already exposed through /// <see cref="MethodSymbol.ExplicitInterfaceImplementations"/> API, this method returns the "Body" part /// of the MethodImpl entry, i.e. the method that implements the <paramref name="interfaceMethod"/>. /// Some of the MethodImpl entries could require synthetic forwarding methods. In such cases, /// the result is the method that the language considers to implement the <paramref name="interfaceMethod"/>, /// rather than the forwarding method. In other words, it is the method that the forwarding method forwards to. /// </summary> /// <param name="interfaceMethod">The interface method that is going to be implemented by using synthesized MethodImpl entry.</param> /// <returns></returns> protected MethodSymbol? GetBodyOfSynthesizedInterfaceMethodImpl(MethodSymbol interfaceMethod) { var info = this.GetInterfaceInfo(); if (info == s_noInterfaces) { return null; } if (info.synthesizedMethodImplMap == null) { Interlocked.CompareExchange(ref info.synthesizedMethodImplMap, makeSynthesizedMethodImplMap(), null); } if (info.synthesizedMethodImplMap.TryGetValue(interfaceMethod, out MethodSymbol? result)) { return result; } return null; ImmutableDictionary<MethodSymbol, MethodSymbol> makeSynthesizedMethodImplMap() { var map = ImmutableDictionary.CreateBuilder<MethodSymbol, MethodSymbol>(ExplicitInterfaceImplementationTargetMemberEqualityComparer.Instance); foreach ((MethodSymbol body, MethodSymbol implemented) in this.SynthesizedInterfaceMethodImpls()) { map.Add(implemented, body); } return map.ToImmutable(); } } /// <summary> /// Returns information about interface method implementations that will be accompanied with /// MethodImpl entries in metadata, information about which isn't already exposed through /// <see cref="MethodSymbol.ExplicitInterfaceImplementations"/> API. The "Body" is the method that /// implements the interface method "Implemented". /// Some of the MethodImpl entries could require synthetic forwarding methods. In such cases, /// the "Body" is the method that the language considers to implement the interface method, /// the "Implemented", rather than the forwarding method. In other words, it is the method that /// the forwarding method forwards to. /// </summary> internal abstract IEnumerable<(MethodSymbol Body, MethodSymbol Implemented)> SynthesizedInterfaceMethodImpls(); #nullable disable protected class ExplicitInterfaceImplementationTargetMemberEqualityComparer : IEqualityComparer<Symbol> { public static readonly ExplicitInterfaceImplementationTargetMemberEqualityComparer Instance = new ExplicitInterfaceImplementationTargetMemberEqualityComparer(); private ExplicitInterfaceImplementationTargetMemberEqualityComparer() { } public bool Equals(Symbol x, Symbol y) { return x.OriginalDefinition == y.OriginalDefinition && x.ContainingType.Equals(y.ContainingType, TypeCompareKind.CLRSignatureCompareOptions); } public int GetHashCode(Symbol obj) { return obj.OriginalDefinition.GetHashCode(); } } #endregion Interface member checks #region Abstract base type checks /// <summary> /// The set of abstract members in declared in this type or declared in a base type and not overridden. /// </summary> internal ImmutableHashSet<Symbol> AbstractMembers { get { if (_lazyAbstractMembers == null) { Interlocked.CompareExchange(ref _lazyAbstractMembers, ComputeAbstractMembers(), null); } return _lazyAbstractMembers; } } private ImmutableHashSet<Symbol> ComputeAbstractMembers() { var abstractMembers = ImmutableHashSet.Create<Symbol>(); var overriddenMembers = ImmutableHashSet.Create<Symbol>(); foreach (var member in this.GetMembersUnordered()) { if (this.IsAbstract && member.IsAbstract && member.Kind != SymbolKind.NamedType) { abstractMembers = abstractMembers.Add(member); } Symbol overriddenMember = null; switch (member.Kind) { case SymbolKind.Method: { overriddenMember = ((MethodSymbol)member).OverriddenMethod; break; } case SymbolKind.Property: { overriddenMember = ((PropertySymbol)member).OverriddenProperty; break; } case SymbolKind.Event: { overriddenMember = ((EventSymbol)member).OverriddenEvent; break; } } if ((object)overriddenMember != null) { overriddenMembers = overriddenMembers.Add(overriddenMember); } } if ((object)this.BaseTypeNoUseSiteDiagnostics != null && this.BaseTypeNoUseSiteDiagnostics.IsAbstract) { foreach (var baseAbstractMember in this.BaseTypeNoUseSiteDiagnostics.AbstractMembers) { if (!overriddenMembers.Contains(baseAbstractMember)) { abstractMembers = abstractMembers.Add(baseAbstractMember); } } } return abstractMembers; } #endregion Abstract base type checks [Obsolete("Use TypeWithAnnotations.Is method.", true)] internal bool Equals(TypeWithAnnotations other) { throw ExceptionUtilities.Unreachable; } public static bool Equals(TypeSymbol left, TypeSymbol right, TypeCompareKind comparison) { if (left is null) { return right is null; } return left.Equals(right, comparison); } [Obsolete("Use 'TypeSymbol.Equals(TypeSymbol, TypeSymbol, TypeCompareKind)' method.", true)] public static bool operator ==(TypeSymbol left, TypeSymbol right) => throw ExceptionUtilities.Unreachable; [Obsolete("Use 'TypeSymbol.Equals(TypeSymbol, TypeSymbol, TypeCompareKind)' method.", true)] public static bool operator !=(TypeSymbol left, TypeSymbol right) => throw ExceptionUtilities.Unreachable; [Obsolete("Use 'TypeSymbol.Equals(TypeSymbol, TypeSymbol, TypeCompareKind)' method.", true)] public static bool operator ==(Symbol left, TypeSymbol right) => throw ExceptionUtilities.Unreachable; [Obsolete("Use 'TypeSymbol.Equals(TypeSymbol, TypeSymbol, TypeCompareKind)' method.", true)] public static bool operator !=(Symbol left, TypeSymbol right) => throw ExceptionUtilities.Unreachable; [Obsolete("Use 'TypeSymbol.Equals(TypeSymbol, TypeSymbol, TypeCompareKind)' method.", true)] public static bool operator ==(TypeSymbol left, Symbol right) => throw ExceptionUtilities.Unreachable; [Obsolete("Use 'TypeSymbol.Equals(TypeSymbol, TypeSymbol, TypeCompareKind)' method.", true)] public static bool operator !=(TypeSymbol left, Symbol right) => throw ExceptionUtilities.Unreachable; internal ITypeSymbol GetITypeSymbol(CodeAnalysis.NullableAnnotation nullableAnnotation) { if (nullableAnnotation == DefaultNullableAnnotation) { return (ITypeSymbol)this.ISymbol; } return CreateITypeSymbol(nullableAnnotation); } internal CodeAnalysis.NullableAnnotation DefaultNullableAnnotation => NullableAnnotationExtensions.ToPublicAnnotation(this, NullableAnnotation.Oblivious); protected abstract ITypeSymbol CreateITypeSymbol(CodeAnalysis.NullableAnnotation nullableAnnotation); TypeKind ITypeSymbolInternal.TypeKind => this.TypeKind; SpecialType ITypeSymbolInternal.SpecialType => this.SpecialType; bool ITypeSymbolInternal.IsReferenceType => this.IsReferenceType; bool ITypeSymbolInternal.IsValueType => this.IsValueType; ITypeSymbol ITypeSymbolInternal.GetITypeSymbol() { return GetITypeSymbol(DefaultNullableAnnotation); } internal abstract bool IsRecord { get; } internal abstract bool IsRecordStruct { get; } } }
-1
dotnet/roslyn
56,433
Only allow Contract.ThrowIfNull() to be called on nullable types
We had some places we were calling it on bools.
jasonmalinowski
"2021-09-16T01:20:43Z"
"2021-09-16T18:44:11Z"
736fc1b5e6e2847689c0154b3e5f23ea99dd56af
6d0f4e3f972ceb561b04574e7f957a4ff458e272
Only allow Contract.ThrowIfNull() to be called on nullable types. We had some places we were calling it on bools.
./src/Features/Core/Portable/Completion/Providers/AbstractSymbolCompletionProvider.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.Linq; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Completion.Log; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Extensions.ContextQuery; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Tags; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Completion.Providers { internal abstract partial class AbstractSymbolCompletionProvider<TSyntaxContext> : LSPCompletionProvider where TSyntaxContext : SyntaxContext { // PERF: Many CompletionProviders derive AbstractSymbolCompletionProvider and therefore // compute identical contexts. This actually shows up on the 2-core typing test. // Cache the most recent document/position/computed SyntaxContext to reduce repeat computation. private static readonly ConditionalWeakTable<Document, Tuple<int, AsyncLazy<TSyntaxContext>>> s_cachedDocuments = new(); private bool? _isTargetTypeCompletionFilterExperimentEnabled = null; protected AbstractSymbolCompletionProvider() { } protected abstract Task<ImmutableArray<(ISymbol symbol, bool preselect)>> GetSymbolsAsync(CompletionContext? completionContext, TSyntaxContext syntaxContext, int position, OptionSet options, CancellationToken cancellationToken); protected abstract (string displayText, string suffix, string insertionText) GetDisplayAndSuffixAndInsertionText(ISymbol symbol, TSyntaxContext context); protected virtual CompletionItemRules GetCompletionItemRules(ImmutableArray<(ISymbol symbol, bool preselect)> symbols) => CompletionItemRules.Default; protected bool IsTargetTypeCompletionFilterExperimentEnabled(OptionSet options) { _isTargetTypeCompletionFilterExperimentEnabled ??= options.GetOption(CompletionOptions.TargetTypedCompletionFilterFeatureFlag); return _isTargetTypeCompletionFilterExperimentEnabled == true; } /// <param name="typeConvertibilityCache">A cache to use for repeated lookups. This should be created with <see cref="SymbolEqualityComparer.Default"/> /// because we ignore nullability.</param> private static bool ShouldIncludeInTargetTypedCompletionList( ISymbol symbol, ImmutableArray<ITypeSymbol> inferredTypes, SemanticModel semanticModel, int position, Dictionary<ITypeSymbol, bool> typeConvertibilityCache) { // When searching for identifiers of type C, exclude the symbol for the `C` type itself. if (symbol.Kind == SymbolKind.NamedType) { return false; } // Avoid offering members of object since they too commonly show up and are infrequently desired. if (symbol.ContainingType?.SpecialType == SpecialType.System_Object) { return false; } // Don't offer locals on the right-hand-side of their declaration: `int x = x` if (symbol.Kind == SymbolKind.Local) { var local = (ILocalSymbol)symbol; var declarationSyntax = symbol.DeclaringSyntaxReferences.Select(r => r.GetSyntax()).SingleOrDefault(); if (declarationSyntax != null && position < declarationSyntax.FullSpan.End) { return false; } } var type = symbol.GetMemberType() ?? symbol.GetSymbolType(); if (type == null) { return false; } if (typeConvertibilityCache.TryGetValue(type, out var isConvertible)) { return isConvertible; } typeConvertibilityCache[type] = CompletionUtilities.IsTypeImplicitlyConvertible(semanticModel.Compilation, type, inferredTypes); return typeConvertibilityCache[type]; } /// <summary> /// Given a list of symbols, and a mapping from each symbol to its original SemanticModel, /// creates the list of completion items for them. /// </summary> private ImmutableArray<CompletionItem> CreateItems( CompletionContext completionContext, ImmutableArray<(ISymbol symbol, bool preselect)> symbols, Func<(ISymbol symbol, bool preselect), TSyntaxContext> contextLookup, Dictionary<ISymbol, List<ProjectId>>? invalidProjectMap, List<ProjectId>? totalProjects, TelemetryCounter telemetryCounter) { // We might get symbol w/o name but CanBeReferencedByName is still set to true, // need to filter them out. // https://github.com/dotnet/roslyn/issues/47690 var symbolGroups = from symbol in symbols let texts = GetDisplayAndSuffixAndInsertionText(symbol.symbol, contextLookup(symbol)) where !string.IsNullOrWhiteSpace(texts.displayText) group symbol by texts into g select g; var itemListBuilder = ImmutableArray.CreateBuilder<CompletionItem>(); var typeConvertibilityCache = new Dictionary<ITypeSymbol, bool>(SymbolEqualityComparer.Default); foreach (var symbolGroup in symbolGroups) { var includeItemInTargetTypedCompletion = false; var arbitraryFirstContext = contextLookup(symbolGroup.First()); var symbolList = symbolGroup.ToImmutableArray(); if (IsTargetTypeCompletionFilterExperimentEnabled(completionContext.Options)) { var tick = Environment.TickCount; includeItemInTargetTypedCompletion = TryFindFirstSymbolMatchesTargetTypes(contextLookup, symbolList, typeConvertibilityCache, out var index); if (includeItemInTargetTypedCompletion && index > 0) { // This would ensure a symbol matches target types to be used for description if there's any, // assuming the default implementation of GetDescriptionWorkerAsync is used. var firstMatch = symbolList[index]; symbolList = symbolList.RemoveAt(index); symbolList = symbolList.Insert(0, firstMatch); } telemetryCounter.AddTick(Environment.TickCount - tick); } var item = CreateItem( completionContext, symbolGroup.Key.displayText, symbolGroup.Key.suffix, symbolGroup.Key.insertionText, symbolList, arbitraryFirstContext, invalidProjectMap, totalProjects); if (includeItemInTargetTypedCompletion) { item = item.AddTag(WellKnownTags.TargetTypeMatch); } itemListBuilder.Add(item); } return itemListBuilder.ToImmutable(); } protected static bool TryFindFirstSymbolMatchesTargetTypes( Func<(ISymbol symbol, bool preselect), TSyntaxContext> contextLookup, ImmutableArray<(ISymbol symbol, bool preselect)> symbolList, Dictionary<ITypeSymbol, bool> typeConvertibilityCache, out int index) { for (index = 0; index < symbolList.Length; ++index) { var symbol = symbolList[index]; var syntaxContext = contextLookup(symbol); if (ShouldIncludeInTargetTypedCompletionList(symbol.symbol, syntaxContext.InferredTypes, syntaxContext.SemanticModel, syntaxContext.Position, typeConvertibilityCache)) break; } return index < symbolList.Length; } /// <summary> /// Given a Symbol, creates the completion item for it. /// </summary> private CompletionItem CreateItem( CompletionContext completionContext, string displayText, string displayTextSuffix, string insertionText, ImmutableArray<(ISymbol symbol, bool preselect)> symbols, TSyntaxContext context, Dictionary<ISymbol, List<ProjectId>>? invalidProjectMap, List<ProjectId>? totalProjects) { Contract.ThrowIfNull(symbols); SupportedPlatformData? supportedPlatformData = null; if (invalidProjectMap != null) { List<ProjectId>? invalidProjects = null; foreach (var symbol in symbols) { if (invalidProjectMap.TryGetValue(symbol.symbol, out invalidProjects)) break; } if (invalidProjects != null) supportedPlatformData = new SupportedPlatformData(completionContext.Document.Project.Solution, invalidProjects, totalProjects); } return CreateItem( completionContext, displayText, displayTextSuffix, insertionText, symbols, context, supportedPlatformData); } protected virtual CompletionItem CreateItem( CompletionContext completionContext, string displayText, string displayTextSuffix, string insertionText, ImmutableArray<(ISymbol symbol, bool preselect)> symbols, TSyntaxContext context, SupportedPlatformData? supportedPlatformData) { var preselect = symbols.Any(t => t.preselect); return SymbolCompletionItem.CreateWithSymbolId( displayText: displayText, displayTextSuffix: displayTextSuffix, insertionText: insertionText, filterText: GetFilterText(symbols[0].symbol, displayText, context), contextPosition: context.Position, symbols: symbols.SelectAsArray(t => t.symbol), supportedPlatforms: supportedPlatformData, rules: GetCompletionItemRules(symbols) .WithMatchPriority(preselect ? MatchPriority.Preselect : MatchPriority.Default) .WithSelectionBehavior(context.IsRightSideOfNumericType ? CompletionItemSelectionBehavior.SoftSelection : CompletionItemSelectionBehavior.Default)); } protected virtual string GetFilterText(ISymbol symbol, string displayText, TSyntaxContext context) { return (displayText == symbol.Name) || (displayText.Length > 0 && displayText[0] == '@') || (context.IsAttributeNameContext && symbol.IsAttribute()) ? displayText : symbol.Name; } protected override Task<CompletionDescription> GetDescriptionWorkerAsync(Document document, CompletionItem item, CancellationToken cancellationToken) => SymbolCompletionItem.GetDescriptionAsync(item, document, cancellationToken); public override async Task ProvideCompletionsAsync(CompletionContext completionContext) { try { var document = completionContext.Document; var position = completionContext.Position; var options = completionContext.Options; var cancellationToken = completionContext.CancellationToken; // If we were triggered by typing a character, then do a semantic check to make sure // we're still applicable. If not, then return immediately. if (completionContext.Trigger.Kind == CompletionTriggerKind.Insertion) { var isSemanticTriggerCharacter = await IsSemanticTriggerCharacterAsync(document, position - 1, cancellationToken).ConfigureAwait(false); if (!isSemanticTriggerCharacter) { return; } } completionContext.IsExclusive = IsExclusive(); using (Logger.LogBlock(FunctionId.Completion_SymbolCompletionProvider_GetItemsWorker, cancellationToken)) using (var telemetryCounter = new TelemetryCounter(ShouldCollectTelemetryForTargetTypeCompletion && IsTargetTypeCompletionFilterExperimentEnabled(options))) { var syntaxContext = await GetOrCreateContextAsync(document, position, cancellationToken).ConfigureAwait(false); var regularItems = await GetItemsAsync(completionContext, syntaxContext, document, position, options, telemetryCounter, cancellationToken).ConfigureAwait(false); completionContext.AddItems(regularItems); } } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e)) { // nop } } private async Task<ImmutableArray<CompletionItem>> GetItemsAsync( CompletionContext completionContext, TSyntaxContext syntaxContext, Document document, int position, OptionSet options, TelemetryCounter telemetryCounter, CancellationToken cancellationToken) { var relatedDocumentIds = document.GetLinkedDocumentIds(); options = CompletionUtilities.GetUpdatedRecommendationOptions(options, document.Project.Language); if (relatedDocumentIds.IsEmpty) { var itemsForCurrentDocument = await GetSymbolsAsync(completionContext, syntaxContext, position, options, cancellationToken).ConfigureAwait(false); return CreateItems(completionContext, itemsForCurrentDocument, _ => syntaxContext, invalidProjectMap: null, totalProjects: null, telemetryCounter); } var contextAndSymbolLists = await GetPerContextSymbolsAsync(completionContext, document, position, options, new[] { document.Id }.Concat(relatedDocumentIds), cancellationToken).ConfigureAwait(false); var symbolToContextMap = UnionSymbols(contextAndSymbolLists); var missingSymbolsMap = FindSymbolsMissingInLinkedContexts(symbolToContextMap, contextAndSymbolLists); var totalProjects = contextAndSymbolLists.Select(t => t.documentId.ProjectId).ToList(); return CreateItems( completionContext, symbolToContextMap.Keys.ToImmutableArray(), symbol => symbolToContextMap[symbol], missingSymbolsMap, totalProjects, telemetryCounter); } protected virtual bool IsExclusive() => false; protected virtual Task<bool> IsSemanticTriggerCharacterAsync(Document document, int characterPosition, CancellationToken cancellationToken) => SpecializedTasks.True; private static Dictionary<(ISymbol symbol, bool preselect), TSyntaxContext> UnionSymbols( ImmutableArray<(DocumentId documentId, TSyntaxContext syntaxContext, ImmutableArray<(ISymbol symbol, bool preselect)> symbols)> linkedContextSymbolLists) { // To correctly map symbols back to their SyntaxContext, we do care about assembly identity. var result = new Dictionary<(ISymbol symbol, bool preselect), TSyntaxContext>(CompletionLinkedFilesSymbolEquivalenceComparer.Instance); // We don't care about assembly identity when creating the union. foreach (var (documentId, syntaxContext, symbols) in linkedContextSymbolLists) { // We need to use the SemanticModel any particular symbol came from in order to generate its description correctly. // Therefore, when we add a symbol to set of union symbols, add a mapping from it to its SyntaxContext. foreach (var symbol in symbols.GroupBy(s => new { s.symbol.Name, s.symbol.Kind }).Select(g => g.First())) { if (!result.ContainsKey(symbol)) result.Add(symbol, syntaxContext); } } return result; } private async Task<ImmutableArray<(DocumentId documentId, TSyntaxContext syntaxContext, ImmutableArray<(ISymbol symbol, bool preselect)> symbols)>> GetPerContextSymbolsAsync( CompletionContext completionContext, Document document, int position, OptionSet options, IEnumerable<DocumentId> relatedDocuments, CancellationToken cancellationToken) { var solution = document.Project.Solution; using var _1 = ArrayBuilder<Task<(DocumentId documentId, TSyntaxContext syntaxContext, ImmutableArray<(ISymbol symbol, bool preselect)> symbols)>>.GetInstance(out var tasks); using var _2 = ArrayBuilder<(DocumentId documentId, TSyntaxContext syntaxContext, ImmutableArray<(ISymbol symbol, bool preselect)> symbols)>.GetInstance(out var perContextSymbols); foreach (var relatedDocumentId in relatedDocuments) { tasks.Add(Task.Run(async () => { var relatedDocument = solution.GetRequiredDocument(relatedDocumentId); var syntaxContext = await GetOrCreateContextAsync(relatedDocument, position, cancellationToken).ConfigureAwait(false); var symbols = await TryGetSymbolsForContextAsync(completionContext, syntaxContext, options, cancellationToken).ConfigureAwait(false); return (relatedDocument.Id, syntaxContext, symbols); }, cancellationToken)); } await Task.WhenAll(tasks).ConfigureAwait(false); foreach (var task in tasks) { var (relatedDocumentId, syntaxContext, symbols) = await task.ConfigureAwait(false); if (!symbols.IsDefault) perContextSymbols.Add((relatedDocumentId, syntaxContext, symbols)); } return perContextSymbols.ToImmutable(); } /// <summary> /// If current context is in active region, returns available symbols. Otherwise, returns null. /// </summary> protected async Task<ImmutableArray<(ISymbol symbol, bool preselect)>> TryGetSymbolsForContextAsync( CompletionContext? completionContext, TSyntaxContext syntaxContext, OptionSet options, CancellationToken cancellationToken) { var syntaxFacts = syntaxContext.GetLanguageService<ISyntaxFactsService>(); return syntaxFacts.IsInInactiveRegion(syntaxContext.SyntaxTree, syntaxContext.Position, cancellationToken) ? default : await GetSymbolsAsync(completionContext, syntaxContext, syntaxContext.Position, options, cancellationToken).ConfigureAwait(false); } protected static async Task<TSyntaxContext> CreateContextAsync(Document document, int position, CancellationToken cancellationToken) { var semanticModel = await document.ReuseExistingSpeculativeModelAsync(position, cancellationToken).ConfigureAwait(false); var service = document.GetRequiredLanguageService<ISyntaxContextService>(); return (TSyntaxContext)service.CreateContext(document, semanticModel, position, cancellationToken); } private static Task<TSyntaxContext> GetOrCreateContextAsync(Document document, int position, CancellationToken cancellationToken) { lock (s_cachedDocuments) { var (cachedPosition, cachedLazyContext) = s_cachedDocuments.GetValue( document, d => Tuple.Create(position, new AsyncLazy<TSyntaxContext>(ct => CreateContextAsync(d, position, ct), cacheResult: true))); if (cachedPosition == position) { return cachedLazyContext.GetValueAsync(cancellationToken); } var lazyContext = new AsyncLazy<TSyntaxContext>(ct => CreateContextAsync(document, position, ct), cacheResult: true); s_cachedDocuments.Remove(document); s_cachedDocuments.Add(document, Tuple.Create(position, lazyContext)); return lazyContext.GetValueAsync(cancellationToken); } } /// <summary> /// Given a list of symbols, determine which are not recommended at the same position in linked documents. /// </summary> /// <param name="symbolToContext">The symbols recommended in the active context.</param> /// <param name="linkedContextSymbolLists">The symbols recommended in linked documents</param> /// <returns>The list of projects each recommended symbol did NOT appear in.</returns> private static Dictionary<ISymbol, List<ProjectId>> FindSymbolsMissingInLinkedContexts( Dictionary<(ISymbol symbol, bool preselect), TSyntaxContext> symbolToContext, ImmutableArray<(DocumentId documentId, TSyntaxContext syntaxContext, ImmutableArray<(ISymbol symbol, bool preselect)> symbols)> linkedContextSymbolLists) { var missingSymbols = new Dictionary<ISymbol, List<ProjectId>>(LinkedFilesSymbolEquivalenceComparer.Instance); foreach (var (documentId, syntaxContext, symbols) in linkedContextSymbolLists) { var symbolsMissingInLinkedContext = symbolToContext.Keys.Except(symbols, CompletionLinkedFilesSymbolEquivalenceComparer.Instance); foreach (var (symbol, _) in symbolsMissingInLinkedContext) missingSymbols.GetOrAdd(symbol, m => new List<ProjectId>()).Add(documentId.ProjectId); } return missingSymbols; } public sealed override Task<TextChange?> GetTextChangeAsync(Document document, CompletionItem selectedItem, char? ch, CancellationToken cancellationToken) => Task.FromResult<TextChange?>(new TextChange(selectedItem.Span, GetInsertionText(selectedItem, ch))); private string GetInsertionText(CompletionItem item, char? ch) { return ch == null ? SymbolCompletionItem.GetInsertionText(item) : GetInsertionText(item, ch.Value); } /// <summary> /// Override this if you want to provide customized insertion based on the character typed. /// </summary> protected virtual string GetInsertionText(CompletionItem item, char ch) => SymbolCompletionItem.GetInsertionText(item); // This is used to decide which provider we'd collect target type completion telemetry from. protected virtual bool ShouldCollectTelemetryForTargetTypeCompletion => false; private class TelemetryCounter : IDisposable { private readonly bool _shouldReport; private int _tick; public TelemetryCounter(bool shouldReport) => _shouldReport = shouldReport; public void AddTick(int tick) => _tick += tick; public void Dispose() { if (_shouldReport) { CompletionProvidersLogger.LogTargetTypeCompletionTicksDataPoint(_tick); } } } } }
// Licensed to the .NET Foundation under one or more 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.Linq; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Completion.Log; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Extensions.ContextQuery; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Tags; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Completion.Providers { internal abstract partial class AbstractSymbolCompletionProvider<TSyntaxContext> : LSPCompletionProvider where TSyntaxContext : SyntaxContext { // PERF: Many CompletionProviders derive AbstractSymbolCompletionProvider and therefore // compute identical contexts. This actually shows up on the 2-core typing test. // Cache the most recent document/position/computed SyntaxContext to reduce repeat computation. private static readonly ConditionalWeakTable<Document, Tuple<int, AsyncLazy<TSyntaxContext>>> s_cachedDocuments = new(); private bool? _isTargetTypeCompletionFilterExperimentEnabled = null; protected AbstractSymbolCompletionProvider() { } protected abstract Task<ImmutableArray<(ISymbol symbol, bool preselect)>> GetSymbolsAsync(CompletionContext? completionContext, TSyntaxContext syntaxContext, int position, OptionSet options, CancellationToken cancellationToken); protected abstract (string displayText, string suffix, string insertionText) GetDisplayAndSuffixAndInsertionText(ISymbol symbol, TSyntaxContext context); protected virtual CompletionItemRules GetCompletionItemRules(ImmutableArray<(ISymbol symbol, bool preselect)> symbols) => CompletionItemRules.Default; protected bool IsTargetTypeCompletionFilterExperimentEnabled(OptionSet options) { _isTargetTypeCompletionFilterExperimentEnabled ??= options.GetOption(CompletionOptions.TargetTypedCompletionFilterFeatureFlag); return _isTargetTypeCompletionFilterExperimentEnabled == true; } /// <param name="typeConvertibilityCache">A cache to use for repeated lookups. This should be created with <see cref="SymbolEqualityComparer.Default"/> /// because we ignore nullability.</param> private static bool ShouldIncludeInTargetTypedCompletionList( ISymbol symbol, ImmutableArray<ITypeSymbol> inferredTypes, SemanticModel semanticModel, int position, Dictionary<ITypeSymbol, bool> typeConvertibilityCache) { // When searching for identifiers of type C, exclude the symbol for the `C` type itself. if (symbol.Kind == SymbolKind.NamedType) { return false; } // Avoid offering members of object since they too commonly show up and are infrequently desired. if (symbol.ContainingType?.SpecialType == SpecialType.System_Object) { return false; } // Don't offer locals on the right-hand-side of their declaration: `int x = x` if (symbol.Kind == SymbolKind.Local) { var local = (ILocalSymbol)symbol; var declarationSyntax = symbol.DeclaringSyntaxReferences.Select(r => r.GetSyntax()).SingleOrDefault(); if (declarationSyntax != null && position < declarationSyntax.FullSpan.End) { return false; } } var type = symbol.GetMemberType() ?? symbol.GetSymbolType(); if (type == null) { return false; } if (typeConvertibilityCache.TryGetValue(type, out var isConvertible)) { return isConvertible; } typeConvertibilityCache[type] = CompletionUtilities.IsTypeImplicitlyConvertible(semanticModel.Compilation, type, inferredTypes); return typeConvertibilityCache[type]; } /// <summary> /// Given a list of symbols, and a mapping from each symbol to its original SemanticModel, /// creates the list of completion items for them. /// </summary> private ImmutableArray<CompletionItem> CreateItems( CompletionContext completionContext, ImmutableArray<(ISymbol symbol, bool preselect)> symbols, Func<(ISymbol symbol, bool preselect), TSyntaxContext> contextLookup, Dictionary<ISymbol, List<ProjectId>>? invalidProjectMap, List<ProjectId>? totalProjects, TelemetryCounter telemetryCounter) { // We might get symbol w/o name but CanBeReferencedByName is still set to true, // need to filter them out. // https://github.com/dotnet/roslyn/issues/47690 var symbolGroups = from symbol in symbols let texts = GetDisplayAndSuffixAndInsertionText(symbol.symbol, contextLookup(symbol)) where !string.IsNullOrWhiteSpace(texts.displayText) group symbol by texts into g select g; var itemListBuilder = ImmutableArray.CreateBuilder<CompletionItem>(); var typeConvertibilityCache = new Dictionary<ITypeSymbol, bool>(SymbolEqualityComparer.Default); foreach (var symbolGroup in symbolGroups) { var includeItemInTargetTypedCompletion = false; var arbitraryFirstContext = contextLookup(symbolGroup.First()); var symbolList = symbolGroup.ToImmutableArray(); if (IsTargetTypeCompletionFilterExperimentEnabled(completionContext.Options)) { var tick = Environment.TickCount; includeItemInTargetTypedCompletion = TryFindFirstSymbolMatchesTargetTypes(contextLookup, symbolList, typeConvertibilityCache, out var index); if (includeItemInTargetTypedCompletion && index > 0) { // This would ensure a symbol matches target types to be used for description if there's any, // assuming the default implementation of GetDescriptionWorkerAsync is used. var firstMatch = symbolList[index]; symbolList = symbolList.RemoveAt(index); symbolList = symbolList.Insert(0, firstMatch); } telemetryCounter.AddTick(Environment.TickCount - tick); } var item = CreateItem( completionContext, symbolGroup.Key.displayText, symbolGroup.Key.suffix, symbolGroup.Key.insertionText, symbolList, arbitraryFirstContext, invalidProjectMap, totalProjects); if (includeItemInTargetTypedCompletion) { item = item.AddTag(WellKnownTags.TargetTypeMatch); } itemListBuilder.Add(item); } return itemListBuilder.ToImmutable(); } protected static bool TryFindFirstSymbolMatchesTargetTypes( Func<(ISymbol symbol, bool preselect), TSyntaxContext> contextLookup, ImmutableArray<(ISymbol symbol, bool preselect)> symbolList, Dictionary<ITypeSymbol, bool> typeConvertibilityCache, out int index) { for (index = 0; index < symbolList.Length; ++index) { var symbol = symbolList[index]; var syntaxContext = contextLookup(symbol); if (ShouldIncludeInTargetTypedCompletionList(symbol.symbol, syntaxContext.InferredTypes, syntaxContext.SemanticModel, syntaxContext.Position, typeConvertibilityCache)) break; } return index < symbolList.Length; } /// <summary> /// Given a Symbol, creates the completion item for it. /// </summary> private CompletionItem CreateItem( CompletionContext completionContext, string displayText, string displayTextSuffix, string insertionText, ImmutableArray<(ISymbol symbol, bool preselect)> symbols, TSyntaxContext context, Dictionary<ISymbol, List<ProjectId>>? invalidProjectMap, List<ProjectId>? totalProjects) { Contract.ThrowIfTrue(symbols.IsDefault); SupportedPlatformData? supportedPlatformData = null; if (invalidProjectMap != null) { List<ProjectId>? invalidProjects = null; foreach (var symbol in symbols) { if (invalidProjectMap.TryGetValue(symbol.symbol, out invalidProjects)) break; } if (invalidProjects != null) supportedPlatformData = new SupportedPlatformData(completionContext.Document.Project.Solution, invalidProjects, totalProjects); } return CreateItem( completionContext, displayText, displayTextSuffix, insertionText, symbols, context, supportedPlatformData); } protected virtual CompletionItem CreateItem( CompletionContext completionContext, string displayText, string displayTextSuffix, string insertionText, ImmutableArray<(ISymbol symbol, bool preselect)> symbols, TSyntaxContext context, SupportedPlatformData? supportedPlatformData) { var preselect = symbols.Any(t => t.preselect); return SymbolCompletionItem.CreateWithSymbolId( displayText: displayText, displayTextSuffix: displayTextSuffix, insertionText: insertionText, filterText: GetFilterText(symbols[0].symbol, displayText, context), contextPosition: context.Position, symbols: symbols.SelectAsArray(t => t.symbol), supportedPlatforms: supportedPlatformData, rules: GetCompletionItemRules(symbols) .WithMatchPriority(preselect ? MatchPriority.Preselect : MatchPriority.Default) .WithSelectionBehavior(context.IsRightSideOfNumericType ? CompletionItemSelectionBehavior.SoftSelection : CompletionItemSelectionBehavior.Default)); } protected virtual string GetFilterText(ISymbol symbol, string displayText, TSyntaxContext context) { return (displayText == symbol.Name) || (displayText.Length > 0 && displayText[0] == '@') || (context.IsAttributeNameContext && symbol.IsAttribute()) ? displayText : symbol.Name; } protected override Task<CompletionDescription> GetDescriptionWorkerAsync(Document document, CompletionItem item, CancellationToken cancellationToken) => SymbolCompletionItem.GetDescriptionAsync(item, document, cancellationToken); public override async Task ProvideCompletionsAsync(CompletionContext completionContext) { try { var document = completionContext.Document; var position = completionContext.Position; var options = completionContext.Options; var cancellationToken = completionContext.CancellationToken; // If we were triggered by typing a character, then do a semantic check to make sure // we're still applicable. If not, then return immediately. if (completionContext.Trigger.Kind == CompletionTriggerKind.Insertion) { var isSemanticTriggerCharacter = await IsSemanticTriggerCharacterAsync(document, position - 1, cancellationToken).ConfigureAwait(false); if (!isSemanticTriggerCharacter) { return; } } completionContext.IsExclusive = IsExclusive(); using (Logger.LogBlock(FunctionId.Completion_SymbolCompletionProvider_GetItemsWorker, cancellationToken)) using (var telemetryCounter = new TelemetryCounter(ShouldCollectTelemetryForTargetTypeCompletion && IsTargetTypeCompletionFilterExperimentEnabled(options))) { var syntaxContext = await GetOrCreateContextAsync(document, position, cancellationToken).ConfigureAwait(false); var regularItems = await GetItemsAsync(completionContext, syntaxContext, document, position, options, telemetryCounter, cancellationToken).ConfigureAwait(false); completionContext.AddItems(regularItems); } } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e)) { // nop } } private async Task<ImmutableArray<CompletionItem>> GetItemsAsync( CompletionContext completionContext, TSyntaxContext syntaxContext, Document document, int position, OptionSet options, TelemetryCounter telemetryCounter, CancellationToken cancellationToken) { var relatedDocumentIds = document.GetLinkedDocumentIds(); options = CompletionUtilities.GetUpdatedRecommendationOptions(options, document.Project.Language); if (relatedDocumentIds.IsEmpty) { var itemsForCurrentDocument = await GetSymbolsAsync(completionContext, syntaxContext, position, options, cancellationToken).ConfigureAwait(false); return CreateItems(completionContext, itemsForCurrentDocument, _ => syntaxContext, invalidProjectMap: null, totalProjects: null, telemetryCounter); } var contextAndSymbolLists = await GetPerContextSymbolsAsync(completionContext, document, position, options, new[] { document.Id }.Concat(relatedDocumentIds), cancellationToken).ConfigureAwait(false); var symbolToContextMap = UnionSymbols(contextAndSymbolLists); var missingSymbolsMap = FindSymbolsMissingInLinkedContexts(symbolToContextMap, contextAndSymbolLists); var totalProjects = contextAndSymbolLists.Select(t => t.documentId.ProjectId).ToList(); return CreateItems( completionContext, symbolToContextMap.Keys.ToImmutableArray(), symbol => symbolToContextMap[symbol], missingSymbolsMap, totalProjects, telemetryCounter); } protected virtual bool IsExclusive() => false; protected virtual Task<bool> IsSemanticTriggerCharacterAsync(Document document, int characterPosition, CancellationToken cancellationToken) => SpecializedTasks.True; private static Dictionary<(ISymbol symbol, bool preselect), TSyntaxContext> UnionSymbols( ImmutableArray<(DocumentId documentId, TSyntaxContext syntaxContext, ImmutableArray<(ISymbol symbol, bool preselect)> symbols)> linkedContextSymbolLists) { // To correctly map symbols back to their SyntaxContext, we do care about assembly identity. var result = new Dictionary<(ISymbol symbol, bool preselect), TSyntaxContext>(CompletionLinkedFilesSymbolEquivalenceComparer.Instance); // We don't care about assembly identity when creating the union. foreach (var (documentId, syntaxContext, symbols) in linkedContextSymbolLists) { // We need to use the SemanticModel any particular symbol came from in order to generate its description correctly. // Therefore, when we add a symbol to set of union symbols, add a mapping from it to its SyntaxContext. foreach (var symbol in symbols.GroupBy(s => new { s.symbol.Name, s.symbol.Kind }).Select(g => g.First())) { if (!result.ContainsKey(symbol)) result.Add(symbol, syntaxContext); } } return result; } private async Task<ImmutableArray<(DocumentId documentId, TSyntaxContext syntaxContext, ImmutableArray<(ISymbol symbol, bool preselect)> symbols)>> GetPerContextSymbolsAsync( CompletionContext completionContext, Document document, int position, OptionSet options, IEnumerable<DocumentId> relatedDocuments, CancellationToken cancellationToken) { var solution = document.Project.Solution; using var _1 = ArrayBuilder<Task<(DocumentId documentId, TSyntaxContext syntaxContext, ImmutableArray<(ISymbol symbol, bool preselect)> symbols)>>.GetInstance(out var tasks); using var _2 = ArrayBuilder<(DocumentId documentId, TSyntaxContext syntaxContext, ImmutableArray<(ISymbol symbol, bool preselect)> symbols)>.GetInstance(out var perContextSymbols); foreach (var relatedDocumentId in relatedDocuments) { tasks.Add(Task.Run(async () => { var relatedDocument = solution.GetRequiredDocument(relatedDocumentId); var syntaxContext = await GetOrCreateContextAsync(relatedDocument, position, cancellationToken).ConfigureAwait(false); var symbols = await TryGetSymbolsForContextAsync(completionContext, syntaxContext, options, cancellationToken).ConfigureAwait(false); return (relatedDocument.Id, syntaxContext, symbols); }, cancellationToken)); } await Task.WhenAll(tasks).ConfigureAwait(false); foreach (var task in tasks) { var (relatedDocumentId, syntaxContext, symbols) = await task.ConfigureAwait(false); if (!symbols.IsDefault) perContextSymbols.Add((relatedDocumentId, syntaxContext, symbols)); } return perContextSymbols.ToImmutable(); } /// <summary> /// If current context is in active region, returns available symbols. Otherwise, returns null. /// </summary> protected async Task<ImmutableArray<(ISymbol symbol, bool preselect)>> TryGetSymbolsForContextAsync( CompletionContext? completionContext, TSyntaxContext syntaxContext, OptionSet options, CancellationToken cancellationToken) { var syntaxFacts = syntaxContext.GetLanguageService<ISyntaxFactsService>(); return syntaxFacts.IsInInactiveRegion(syntaxContext.SyntaxTree, syntaxContext.Position, cancellationToken) ? default : await GetSymbolsAsync(completionContext, syntaxContext, syntaxContext.Position, options, cancellationToken).ConfigureAwait(false); } protected static async Task<TSyntaxContext> CreateContextAsync(Document document, int position, CancellationToken cancellationToken) { var semanticModel = await document.ReuseExistingSpeculativeModelAsync(position, cancellationToken).ConfigureAwait(false); var service = document.GetRequiredLanguageService<ISyntaxContextService>(); return (TSyntaxContext)service.CreateContext(document, semanticModel, position, cancellationToken); } private static Task<TSyntaxContext> GetOrCreateContextAsync(Document document, int position, CancellationToken cancellationToken) { lock (s_cachedDocuments) { var (cachedPosition, cachedLazyContext) = s_cachedDocuments.GetValue( document, d => Tuple.Create(position, new AsyncLazy<TSyntaxContext>(ct => CreateContextAsync(d, position, ct), cacheResult: true))); if (cachedPosition == position) { return cachedLazyContext.GetValueAsync(cancellationToken); } var lazyContext = new AsyncLazy<TSyntaxContext>(ct => CreateContextAsync(document, position, ct), cacheResult: true); s_cachedDocuments.Remove(document); s_cachedDocuments.Add(document, Tuple.Create(position, lazyContext)); return lazyContext.GetValueAsync(cancellationToken); } } /// <summary> /// Given a list of symbols, determine which are not recommended at the same position in linked documents. /// </summary> /// <param name="symbolToContext">The symbols recommended in the active context.</param> /// <param name="linkedContextSymbolLists">The symbols recommended in linked documents</param> /// <returns>The list of projects each recommended symbol did NOT appear in.</returns> private static Dictionary<ISymbol, List<ProjectId>> FindSymbolsMissingInLinkedContexts( Dictionary<(ISymbol symbol, bool preselect), TSyntaxContext> symbolToContext, ImmutableArray<(DocumentId documentId, TSyntaxContext syntaxContext, ImmutableArray<(ISymbol symbol, bool preselect)> symbols)> linkedContextSymbolLists) { var missingSymbols = new Dictionary<ISymbol, List<ProjectId>>(LinkedFilesSymbolEquivalenceComparer.Instance); foreach (var (documentId, syntaxContext, symbols) in linkedContextSymbolLists) { var symbolsMissingInLinkedContext = symbolToContext.Keys.Except(symbols, CompletionLinkedFilesSymbolEquivalenceComparer.Instance); foreach (var (symbol, _) in symbolsMissingInLinkedContext) missingSymbols.GetOrAdd(symbol, m => new List<ProjectId>()).Add(documentId.ProjectId); } return missingSymbols; } public sealed override Task<TextChange?> GetTextChangeAsync(Document document, CompletionItem selectedItem, char? ch, CancellationToken cancellationToken) => Task.FromResult<TextChange?>(new TextChange(selectedItem.Span, GetInsertionText(selectedItem, ch))); private string GetInsertionText(CompletionItem item, char? ch) { return ch == null ? SymbolCompletionItem.GetInsertionText(item) : GetInsertionText(item, ch.Value); } /// <summary> /// Override this if you want to provide customized insertion based on the character typed. /// </summary> protected virtual string GetInsertionText(CompletionItem item, char ch) => SymbolCompletionItem.GetInsertionText(item); // This is used to decide which provider we'd collect target type completion telemetry from. protected virtual bool ShouldCollectTelemetryForTargetTypeCompletion => false; private class TelemetryCounter : IDisposable { private readonly bool _shouldReport; private int _tick; public TelemetryCounter(bool shouldReport) => _shouldReport = shouldReport; public void AddTick(int tick) => _tick += tick; public void Dispose() { if (_shouldReport) { CompletionProvidersLogger.LogTargetTypeCompletionTicksDataPoint(_tick); } } } } }
1
dotnet/roslyn
56,433
Only allow Contract.ThrowIfNull() to be called on nullable types
We had some places we were calling it on bools.
jasonmalinowski
"2021-09-16T01:20:43Z"
"2021-09-16T18:44:11Z"
736fc1b5e6e2847689c0154b3e5f23ea99dd56af
6d0f4e3f972ceb561b04574e7f957a4ff458e272
Only allow Contract.ThrowIfNull() to be called on nullable types. We had some places we were calling it on bools.
./src/Interactive/Host/Interactive/Core/InteractiveHost.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.IO; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.ErrorReporting; using Newtonsoft.Json; using Roslyn.Utilities; using StreamJsonRpc; namespace Microsoft.CodeAnalysis.Interactive { /// <summary> /// Represents a process that hosts an interactive session. /// </summary> /// <remarks> /// Handles spawning of the host process and communication between the local callers and the remote session. /// </remarks> internal sealed partial class InteractiveHost : IDisposable { internal const InteractiveHostPlatform DefaultPlatform = InteractiveHostPlatform.Desktop32; /// <summary> /// Use Unicode encoding for STDOUT and STDERR of the InteractiveHost process. /// Ideally, we would use UTF8 but SetConsoleOutputCP Windows API fails with "Invalid Handle" when Console.OutputEncoding is set to UTF8. /// (issue tracked by https://github.com/dotnet/roslyn/issues/47571, https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1253106) /// Unicode is not ideal since the message printed directly to STDOUT/STDERR from native code that do not encode the output are going to be garbled /// (e.g. messages reported by CLR stack overflow and OOM exception handlers: https://github.com/dotnet/runtime/issues/45503). /// </summary> internal static readonly Encoding OutputEncoding = Encoding.Unicode; private static readonly JsonRpcTargetOptions s_jsonRpcTargetOptions = new JsonRpcTargetOptions() { // Do not allow JSON-RPC to automatically subscribe to events and remote their calls. NotifyClientOfEvents = false, // Only allow public methods (may be on internal types) to be invoked remotely. AllowNonPublicInvocation = false }; private readonly Type _replServiceProviderType; private readonly string _initialWorkingDirectory; // adjustable for testing purposes private readonly int _millisecondsTimeout; private const int MaxAttemptsToCreateProcess = 2; private LazyRemoteService? _lazyRemoteService; private int _remoteServiceInstanceId; private TextWriter _output; private TextWriter _errorOutput; private readonly object _outputGuard; private readonly object _errorOutputGuard; /// <remarks> /// Test only setting. /// True to join output writing threads when the host is being disposed. /// We have to join the threads before each test is finished, otherwise xunit won't be able to unload the AppDomain. /// WARNING: Joining the threads might deadlock if <see cref="Dispose()"/> is executing on the UI thread, /// since the threads are dispatching to UI thread to write the output to the editor buffer. /// </remarks> private readonly bool _joinOutputWritingThreadsOnDisposal; internal event Action<InteractiveHostPlatformInfo, InteractiveHostOptions, RemoteExecutionResult>? ProcessInitialized; public InteractiveHost( Type replServiceProviderType, string workingDirectory, int millisecondsTimeout = 5000, bool joinOutputWritingThreadsOnDisposal = false) { _millisecondsTimeout = millisecondsTimeout; _joinOutputWritingThreadsOnDisposal = joinOutputWritingThreadsOnDisposal; _output = TextWriter.Null; _errorOutput = TextWriter.Null; _replServiceProviderType = replServiceProviderType; _initialWorkingDirectory = workingDirectory; _outputGuard = new object(); _errorOutputGuard = new object(); } #region Test hooks internal event Action<char[], int>? OutputReceived; internal event Action<char[], int>? ErrorOutputReceived; internal Process? TryGetProcess() => _lazyRemoteService?.TryGetInitializedService()?.Service?.Process; internal async Task<RemoteService?> TryGetServiceAsync() => (await TryGetOrCreateRemoteServiceAsync().ConfigureAwait(false)).Service; // Triggered whenever we create a fresh process. // The ProcessExited event is not hooked yet. internal event Action<Process>? InteractiveHostProcessCreated; // Triggered whenever InteractiveHost process creation fails. internal event Action<Exception?, int?>? InteractiveHostProcessCreationFailed; #endregion ~InteractiveHost() { DisposeRemoteService(); } // Dispose may be called anytime. public void Dispose() { // Run this in background to avoid deadlocking with UIThread operations performing with active outputs. _ = Task.Run(() => SetOutputs(TextWriter.Null, TextWriter.Null)); DisposeRemoteService(); GC.SuppressFinalize(this); } private void DisposeRemoteService() { Interlocked.Exchange(ref _lazyRemoteService, null)?.Dispose(); } public void SetOutputs(TextWriter output, TextWriter errorOutput) { if (output == null) { throw new ArgumentNullException(nameof(output)); } if (errorOutput == null) { throw new ArgumentNullException(nameof(errorOutput)); } lock (_outputGuard) { _output.Flush(); _output = output; } lock (_errorOutputGuard) { _errorOutput.Flush(); _errorOutput = errorOutput; } } internal void OnOutputReceived(bool error, char[] buffer, int count) { (error ? ErrorOutputReceived : OutputReceived)?.Invoke(buffer, count); var writer = error ? _errorOutput : _output; var guard = error ? _errorOutputGuard : _outputGuard; lock (guard) { writer.Write(buffer, 0, count); } } private void WriteOutputInBackground(bool isError, string firstLine, string? secondLine = null) { var writer = isError ? _errorOutput : _output; var guard = isError ? _errorOutputGuard : _outputGuard; // We cannot guarantee that writers can perform writing synchronously // without deadlocks with other operations. // This could happen, for example, for writers provided by the Interactive Window, // and in the case where the window is being disposed. Task.Run(() => { lock (guard) { writer.WriteLine(firstLine); if (secondLine != null) { writer.WriteLine(secondLine); } } }); } private LazyRemoteService CreateRemoteService(InteractiveHostOptions options, bool skipInitialization) { return new LazyRemoteService(this, options, Interlocked.Increment(ref _remoteServiceInstanceId), skipInitialization); } private Task OnProcessExitedAsync(Process process) { ReportProcessExited(process); return TryGetOrCreateRemoteServiceAsync(); } private void ReportProcessExited(Process process) { int? exitCode; try { exitCode = process.HasExited ? process.ExitCode : (int?)null; } catch { exitCode = null; } if (exitCode.HasValue) { WriteOutputInBackground(isError: true, string.Format(InteractiveHostResources.Hosting_process_exited_with_exit_code_0, exitCode.Value)); } } private async Task<InitializedRemoteService> TryGetOrCreateRemoteServiceAsync() { try { LazyRemoteService? currentRemoteService = _lazyRemoteService; for (int attempt = 0; attempt < MaxAttemptsToCreateProcess; attempt++) { // Remote service may be disposed anytime. if (currentRemoteService == null) { return default; } var initializedService = await currentRemoteService.GetInitializedServiceAsync().ConfigureAwait(false); if (initializedService.Service != null && initializedService.Service.Process.IsAlive()) { return initializedService; } // Service failed to start or initialize or the process died. var newService = CreateRemoteService(currentRemoteService.Options, skipInitialization: !initializedService.InitializationResult.Success); var previousService = Interlocked.CompareExchange(ref _lazyRemoteService, newService, currentRemoteService); if (previousService == currentRemoteService) { // we replaced the service whose process we know is dead: currentRemoteService.Dispose(); currentRemoteService = newService; } else { // the process was reset in between our checks, try to use the new service: newService.Dispose(); currentRemoteService = previousService; } } WriteOutputInBackground(isError: true, InteractiveHostResources.Unable_to_create_hosting_process); } catch (OperationCanceledException) { // The user reset the process during initialization. // The reset operation will recreate the process. } catch (Exception e) when (FatalError.ReportAndPropagate(e)) { throw ExceptionUtilities.Unreachable; } return default; } private async Task<RemoteExecutionResult> ExecuteRemoteAsync(string targetName, params object?[] arguments) => (await InvokeRemoteAsync<RemoteExecutionResult.Data>(targetName, arguments).ConfigureAwait(false))?.Deserialize() ?? default; private async Task<TResult> InvokeRemoteAsync<TResult>(string targetName, params object?[] arguments) { var initializedRemoteService = await TryGetOrCreateRemoteServiceAsync().ConfigureAwait(false); if (initializedRemoteService.Service == null) { return default!; } return await InvokeRemoteAsync<TResult>(initializedRemoteService.Service, targetName, arguments).ConfigureAwait(false); } private static async Task<RemoteExecutionResult> ExecuteRemoteAsync(RemoteService remoteService, string targetName, params object?[] arguments) => (await InvokeRemoteAsync<RemoteExecutionResult.Data>(remoteService, targetName, arguments).ConfigureAwait(false))?.Deserialize() ?? default; private static async Task<TResult> InvokeRemoteAsync<TResult>(RemoteService remoteService, string targetName, params object?[] arguments) { try { return await remoteService.JsonRpc.InvokeAsync<TResult>(targetName, arguments).ConfigureAwait(false); } catch (Exception e) when (e is ObjectDisposedException || !remoteService.Process.IsAlive()) { return default!; } } private static JsonRpc CreateRpc(Stream stream, object? incomingCallTarget) { var jsonFormatter = new JsonMessageFormatter(); // disable interpreting of strings as DateTime during deserialization: jsonFormatter.JsonSerializer.DateParseHandling = DateParseHandling.None; var rpc = new JsonRpc(new HeaderDelimitedMessageHandler(stream, jsonFormatter)) { CancelLocallyInvokedMethodsWhenConnectionIsClosed = true, ExceptionStrategy = ExceptionProcessing.ISerializable, }; if (incomingCallTarget != null) { rpc.AddLocalRpcTarget(incomingCallTarget, s_jsonRpcTargetOptions); } rpc.StartListening(); return rpc; } #region Operations public InteractiveHostOptions? OptionsOpt => _lazyRemoteService?.Options; /// <summary> /// Restarts and reinitializes the host process (or starts a new one if it is not running yet). /// </summary> /// <param name="options">The options to initialize the new process with.</param> public async Task<RemoteExecutionResult> ResetAsync(InteractiveHostOptions options) { try { // replace the existing service with a new one: var newService = CreateRemoteService(options, skipInitialization: false); var oldService = Interlocked.Exchange(ref _lazyRemoteService, newService); if (oldService != null) { oldService.Dispose(); } var initializedService = await TryGetOrCreateRemoteServiceAsync().ConfigureAwait(false); if (initializedService.Service == null) { return default; } return initializedService.InitializationResult; } catch (Exception e) when (FatalError.ReportAndPropagate(e)) { throw ExceptionUtilities.Unreachable; } } /// <summary> /// Asynchronously executes given code in the remote interactive session. /// </summary> /// <param name="code">The code to execute.</param> /// <remarks> /// This method is thread safe but operations are sent to the remote process /// asynchronously so tasks should be executed serially if order is important. /// </remarks> public Task<RemoteExecutionResult> ExecuteAsync(string code) { Contract.ThrowIfNull(code); return ExecuteRemoteAsync(nameof(Service.ExecuteAsync), code); } /// <summary> /// Asynchronously executes given code in the remote interactive session. /// </summary> /// <param name="path">The file to execute.</param> /// <exception cref="ArgumentNullException"><paramref name="path"/> is null.</exception> /// <remarks> /// This method is thread safe but operations are sent to the remote process /// asynchronously so tasks should be executed serially if order is important. /// </remarks> public Task<RemoteExecutionResult> ExecuteFileAsync(string path) { Contract.ThrowIfNull(path); return ExecuteRemoteAsync(nameof(Service.ExecuteFileAsync), path); } /// <summary> /// Asynchronously adds a reference to the set of available references for next submission. /// </summary> /// <param name="reference">The reference to add.</param> /// <remarks> /// This method is thread safe but operations are sent to the remote process /// asynchronously so tasks should be executed serially if order is important. /// </remarks> public Task<bool> AddReferenceAsync(string reference) { Contract.ThrowIfNull(reference); return InvokeRemoteAsync<bool>(nameof(Service.AddReferenceAsync), reference); } /// <summary> /// Sets the current session's search paths and base directory. /// </summary> public Task<RemoteExecutionResult> SetPathsAsync(ImmutableArray<string> referenceSearchPaths, ImmutableArray<string> sourceSearchPaths, string baseDirectory) { Contract.ThrowIfNull(referenceSearchPaths); Contract.ThrowIfNull(sourceSearchPaths); Contract.ThrowIfNull(baseDirectory); return ExecuteRemoteAsync(nameof(Service.SetPathsAsync), referenceSearchPaths, sourceSearchPaths, baseDirectory); } #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. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.IO; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.ErrorReporting; using Newtonsoft.Json; using Roslyn.Utilities; using StreamJsonRpc; namespace Microsoft.CodeAnalysis.Interactive { /// <summary> /// Represents a process that hosts an interactive session. /// </summary> /// <remarks> /// Handles spawning of the host process and communication between the local callers and the remote session. /// </remarks> internal sealed partial class InteractiveHost : IDisposable { internal const InteractiveHostPlatform DefaultPlatform = InteractiveHostPlatform.Desktop32; /// <summary> /// Use Unicode encoding for STDOUT and STDERR of the InteractiveHost process. /// Ideally, we would use UTF8 but SetConsoleOutputCP Windows API fails with "Invalid Handle" when Console.OutputEncoding is set to UTF8. /// (issue tracked by https://github.com/dotnet/roslyn/issues/47571, https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1253106) /// Unicode is not ideal since the message printed directly to STDOUT/STDERR from native code that do not encode the output are going to be garbled /// (e.g. messages reported by CLR stack overflow and OOM exception handlers: https://github.com/dotnet/runtime/issues/45503). /// </summary> internal static readonly Encoding OutputEncoding = Encoding.Unicode; private static readonly JsonRpcTargetOptions s_jsonRpcTargetOptions = new JsonRpcTargetOptions() { // Do not allow JSON-RPC to automatically subscribe to events and remote their calls. NotifyClientOfEvents = false, // Only allow public methods (may be on internal types) to be invoked remotely. AllowNonPublicInvocation = false }; private readonly Type _replServiceProviderType; private readonly string _initialWorkingDirectory; // adjustable for testing purposes private readonly int _millisecondsTimeout; private const int MaxAttemptsToCreateProcess = 2; private LazyRemoteService? _lazyRemoteService; private int _remoteServiceInstanceId; private TextWriter _output; private TextWriter _errorOutput; private readonly object _outputGuard; private readonly object _errorOutputGuard; /// <remarks> /// Test only setting. /// True to join output writing threads when the host is being disposed. /// We have to join the threads before each test is finished, otherwise xunit won't be able to unload the AppDomain. /// WARNING: Joining the threads might deadlock if <see cref="Dispose()"/> is executing on the UI thread, /// since the threads are dispatching to UI thread to write the output to the editor buffer. /// </remarks> private readonly bool _joinOutputWritingThreadsOnDisposal; internal event Action<InteractiveHostPlatformInfo, InteractiveHostOptions, RemoteExecutionResult>? ProcessInitialized; public InteractiveHost( Type replServiceProviderType, string workingDirectory, int millisecondsTimeout = 5000, bool joinOutputWritingThreadsOnDisposal = false) { _millisecondsTimeout = millisecondsTimeout; _joinOutputWritingThreadsOnDisposal = joinOutputWritingThreadsOnDisposal; _output = TextWriter.Null; _errorOutput = TextWriter.Null; _replServiceProviderType = replServiceProviderType; _initialWorkingDirectory = workingDirectory; _outputGuard = new object(); _errorOutputGuard = new object(); } #region Test hooks internal event Action<char[], int>? OutputReceived; internal event Action<char[], int>? ErrorOutputReceived; internal Process? TryGetProcess() => _lazyRemoteService?.TryGetInitializedService()?.Service?.Process; internal async Task<RemoteService?> TryGetServiceAsync() => (await TryGetOrCreateRemoteServiceAsync().ConfigureAwait(false)).Service; // Triggered whenever we create a fresh process. // The ProcessExited event is not hooked yet. internal event Action<Process>? InteractiveHostProcessCreated; // Triggered whenever InteractiveHost process creation fails. internal event Action<Exception?, int?>? InteractiveHostProcessCreationFailed; #endregion ~InteractiveHost() { DisposeRemoteService(); } // Dispose may be called anytime. public void Dispose() { // Run this in background to avoid deadlocking with UIThread operations performing with active outputs. _ = Task.Run(() => SetOutputs(TextWriter.Null, TextWriter.Null)); DisposeRemoteService(); GC.SuppressFinalize(this); } private void DisposeRemoteService() { Interlocked.Exchange(ref _lazyRemoteService, null)?.Dispose(); } public void SetOutputs(TextWriter output, TextWriter errorOutput) { if (output == null) { throw new ArgumentNullException(nameof(output)); } if (errorOutput == null) { throw new ArgumentNullException(nameof(errorOutput)); } lock (_outputGuard) { _output.Flush(); _output = output; } lock (_errorOutputGuard) { _errorOutput.Flush(); _errorOutput = errorOutput; } } internal void OnOutputReceived(bool error, char[] buffer, int count) { (error ? ErrorOutputReceived : OutputReceived)?.Invoke(buffer, count); var writer = error ? _errorOutput : _output; var guard = error ? _errorOutputGuard : _outputGuard; lock (guard) { writer.Write(buffer, 0, count); } } private void WriteOutputInBackground(bool isError, string firstLine, string? secondLine = null) { var writer = isError ? _errorOutput : _output; var guard = isError ? _errorOutputGuard : _outputGuard; // We cannot guarantee that writers can perform writing synchronously // without deadlocks with other operations. // This could happen, for example, for writers provided by the Interactive Window, // and in the case where the window is being disposed. Task.Run(() => { lock (guard) { writer.WriteLine(firstLine); if (secondLine != null) { writer.WriteLine(secondLine); } } }); } private LazyRemoteService CreateRemoteService(InteractiveHostOptions options, bool skipInitialization) { return new LazyRemoteService(this, options, Interlocked.Increment(ref _remoteServiceInstanceId), skipInitialization); } private Task OnProcessExitedAsync(Process process) { ReportProcessExited(process); return TryGetOrCreateRemoteServiceAsync(); } private void ReportProcessExited(Process process) { int? exitCode; try { exitCode = process.HasExited ? process.ExitCode : (int?)null; } catch { exitCode = null; } if (exitCode.HasValue) { WriteOutputInBackground(isError: true, string.Format(InteractiveHostResources.Hosting_process_exited_with_exit_code_0, exitCode.Value)); } } private async Task<InitializedRemoteService> TryGetOrCreateRemoteServiceAsync() { try { LazyRemoteService? currentRemoteService = _lazyRemoteService; for (int attempt = 0; attempt < MaxAttemptsToCreateProcess; attempt++) { // Remote service may be disposed anytime. if (currentRemoteService == null) { return default; } var initializedService = await currentRemoteService.GetInitializedServiceAsync().ConfigureAwait(false); if (initializedService.Service != null && initializedService.Service.Process.IsAlive()) { return initializedService; } // Service failed to start or initialize or the process died. var newService = CreateRemoteService(currentRemoteService.Options, skipInitialization: !initializedService.InitializationResult.Success); var previousService = Interlocked.CompareExchange(ref _lazyRemoteService, newService, currentRemoteService); if (previousService == currentRemoteService) { // we replaced the service whose process we know is dead: currentRemoteService.Dispose(); currentRemoteService = newService; } else { // the process was reset in between our checks, try to use the new service: newService.Dispose(); currentRemoteService = previousService; } } WriteOutputInBackground(isError: true, InteractiveHostResources.Unable_to_create_hosting_process); } catch (OperationCanceledException) { // The user reset the process during initialization. // The reset operation will recreate the process. } catch (Exception e) when (FatalError.ReportAndPropagate(e)) { throw ExceptionUtilities.Unreachable; } return default; } private async Task<RemoteExecutionResult> ExecuteRemoteAsync(string targetName, params object?[] arguments) => (await InvokeRemoteAsync<RemoteExecutionResult.Data>(targetName, arguments).ConfigureAwait(false))?.Deserialize() ?? default; private async Task<TResult> InvokeRemoteAsync<TResult>(string targetName, params object?[] arguments) { var initializedRemoteService = await TryGetOrCreateRemoteServiceAsync().ConfigureAwait(false); if (initializedRemoteService.Service == null) { return default!; } return await InvokeRemoteAsync<TResult>(initializedRemoteService.Service, targetName, arguments).ConfigureAwait(false); } private static async Task<RemoteExecutionResult> ExecuteRemoteAsync(RemoteService remoteService, string targetName, params object?[] arguments) => (await InvokeRemoteAsync<RemoteExecutionResult.Data>(remoteService, targetName, arguments).ConfigureAwait(false))?.Deserialize() ?? default; private static async Task<TResult> InvokeRemoteAsync<TResult>(RemoteService remoteService, string targetName, params object?[] arguments) { try { return await remoteService.JsonRpc.InvokeAsync<TResult>(targetName, arguments).ConfigureAwait(false); } catch (Exception e) when (e is ObjectDisposedException || !remoteService.Process.IsAlive()) { return default!; } } private static JsonRpc CreateRpc(Stream stream, object? incomingCallTarget) { var jsonFormatter = new JsonMessageFormatter(); // disable interpreting of strings as DateTime during deserialization: jsonFormatter.JsonSerializer.DateParseHandling = DateParseHandling.None; var rpc = new JsonRpc(new HeaderDelimitedMessageHandler(stream, jsonFormatter)) { CancelLocallyInvokedMethodsWhenConnectionIsClosed = true, ExceptionStrategy = ExceptionProcessing.ISerializable, }; if (incomingCallTarget != null) { rpc.AddLocalRpcTarget(incomingCallTarget, s_jsonRpcTargetOptions); } rpc.StartListening(); return rpc; } #region Operations public InteractiveHostOptions? OptionsOpt => _lazyRemoteService?.Options; /// <summary> /// Restarts and reinitializes the host process (or starts a new one if it is not running yet). /// </summary> /// <param name="options">The options to initialize the new process with.</param> public async Task<RemoteExecutionResult> ResetAsync(InteractiveHostOptions options) { try { // replace the existing service with a new one: var newService = CreateRemoteService(options, skipInitialization: false); var oldService = Interlocked.Exchange(ref _lazyRemoteService, newService); if (oldService != null) { oldService.Dispose(); } var initializedService = await TryGetOrCreateRemoteServiceAsync().ConfigureAwait(false); if (initializedService.Service == null) { return default; } return initializedService.InitializationResult; } catch (Exception e) when (FatalError.ReportAndPropagate(e)) { throw ExceptionUtilities.Unreachable; } } /// <summary> /// Asynchronously executes given code in the remote interactive session. /// </summary> /// <param name="code">The code to execute.</param> /// <remarks> /// This method is thread safe but operations are sent to the remote process /// asynchronously so tasks should be executed serially if order is important. /// </remarks> public Task<RemoteExecutionResult> ExecuteAsync(string code) { Contract.ThrowIfNull(code); return ExecuteRemoteAsync(nameof(Service.ExecuteAsync), code); } /// <summary> /// Asynchronously executes given code in the remote interactive session. /// </summary> /// <param name="path">The file to execute.</param> /// <exception cref="ArgumentNullException"><paramref name="path"/> is null.</exception> /// <remarks> /// This method is thread safe but operations are sent to the remote process /// asynchronously so tasks should be executed serially if order is important. /// </remarks> public Task<RemoteExecutionResult> ExecuteFileAsync(string path) { Contract.ThrowIfNull(path); return ExecuteRemoteAsync(nameof(Service.ExecuteFileAsync), path); } /// <summary> /// Asynchronously adds a reference to the set of available references for next submission. /// </summary> /// <param name="reference">The reference to add.</param> /// <remarks> /// This method is thread safe but operations are sent to the remote process /// asynchronously so tasks should be executed serially if order is important. /// </remarks> public Task<bool> AddReferenceAsync(string reference) { Contract.ThrowIfNull(reference); return InvokeRemoteAsync<bool>(nameof(Service.AddReferenceAsync), reference); } /// <summary> /// Sets the current session's search paths and base directory. /// </summary> public Task<RemoteExecutionResult> SetPathsAsync(ImmutableArray<string> referenceSearchPaths, ImmutableArray<string> sourceSearchPaths, string baseDirectory) { Contract.ThrowIfTrue(referenceSearchPaths.IsDefault); Contract.ThrowIfTrue(sourceSearchPaths.IsDefault); Contract.ThrowIfNull(baseDirectory); return ExecuteRemoteAsync(nameof(Service.SetPathsAsync), referenceSearchPaths, sourceSearchPaths, baseDirectory); } #endregion } }
1
dotnet/roslyn
56,433
Only allow Contract.ThrowIfNull() to be called on nullable types
We had some places we were calling it on bools.
jasonmalinowski
"2021-09-16T01:20:43Z"
"2021-09-16T18:44:11Z"
736fc1b5e6e2847689c0154b3e5f23ea99dd56af
6d0f4e3f972ceb561b04574e7f957a4ff458e272
Only allow Contract.ThrowIfNull() to be called on nullable types. We had some places we were calling it on bools.
./src/VisualStudio/Core/Impl/SolutionExplorer/SourceGeneratedFileItems/SourceGeneratedFileItemSource.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; using System.Collections.ObjectModel; using System.ComponentModel; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.Internal.VisualStudio.PlatformUI; using Microsoft.VisualStudio.Language.Intellisense; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.SolutionExplorer { internal class SourceGeneratedFileItemSource : Shell.IAttachedCollectionSource, ISupportExpansionEvents { private readonly SourceGeneratorItem _parentGeneratorItem; private readonly Workspace _workspace; private readonly IAsynchronousOperationListener _asyncListener; private readonly IThreadingContext _threadingContext; /// <summary> /// The returned collection of items. Can only be mutated on the UI thread, as other parts of WPF are subscribed to the change /// events and expect that. /// </summary> private readonly BulkObservableCollectionWithInit<BaseItem> _items = new(); /// <summary> /// Gate to guard mutation of <see cref="_cancellationTokenSource"/> and <see cref="_resettableDelay"/>. /// </summary> private readonly object _gate = new object(); private CancellationTokenSource? _cancellationTokenSource; private ResettableDelay? _resettableDelay; public SourceGeneratedFileItemSource(SourceGeneratorItem parentGeneratorItem, Workspace workspace, IAsynchronousOperationListener asyncListener, IThreadingContext threadingContext) { _parentGeneratorItem = parentGeneratorItem; _workspace = workspace; _asyncListener = asyncListener; _threadingContext = threadingContext; } public object SourceItem => _parentGeneratorItem; public bool HasItems { get { // Since we are expensive to compute, always say we have items. return true; } } public IEnumerable Items => _items; private async Task UpdateSourceGeneratedFileItemsAsync(Solution solution, CancellationToken cancellationToken) { var project = solution.GetProject(_parentGeneratorItem.ProjectId); if (project == null) { return; } var sourceGeneratedDocuments = await project.GetSourceGeneratedDocumentsAsync(cancellationToken).ConfigureAwait(false); var sourceGeneratedDocumentsForGeneratorById = sourceGeneratedDocuments.Where(d => d.SourceGeneratorAssemblyName == _parentGeneratorItem.GeneratorAssemblyName && d.SourceGeneratorTypeName == _parentGeneratorItem.GeneratorTypeName) .ToDictionary(d => d.Id); // We must update the list on the UI thread, since the WPF elements bound to our list expect that await _threadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); try { // We're going to incrementally update our items, ensuring we keep the object identity for things we didn't touch. // This is because the Solution Explorer itself will use identity to keep track of active items -- if you have an // item selected and we were to refresh in the background we don't want to lose that selection. If we just removed // and repopulated the list from scratch each time we'd lose the selection. _items.BeginBulkOperation(); // Do we already have a "no files" placeholder item? if (_items.Count == 1 && _items[0] is NoSourceGeneratedFilesPlaceholderItem) { // We do -- if we have no items, we're done, since the placeholder is all that needs to be there; // otherwise remove it since we have real files now if (sourceGeneratedDocumentsForGeneratorById.Count == 0) { return; } else { _items.RemoveAt(0); } } for (var i = 0; i < _items.Count; i++) { // If this item that we already have is still a generated document, we'll remove it from our list; the list when we're // done is going to have the new items remaining. If it no longer exists, remove it from list. if (!sourceGeneratedDocumentsForGeneratorById.Remove(((SourceGeneratedFileItem)_items[i]).DocumentId)) { _items.RemoveAt(i); i--; } } // Whatever is left in sourceGeneratedDocumentsForGeneratorById we should add if (sourceGeneratedDocumentsForGeneratorById.Count == 0) { // We don't have any items at all, so add the placeholder Contract.ThrowIfFalse(_items.Count == 0); _items.Add(new NoSourceGeneratedFilesPlaceholderItem()); return; } foreach (var document in sourceGeneratedDocumentsForGeneratorById.Values) { // Binary search to figure out where to insert var low = 0; var high = _items.Count; while (low < high) { var mid = (low + high) / 2; if (StringComparer.OrdinalIgnoreCase.Compare(document.HintName, ((SourceGeneratedFileItem)_items[mid]).HintName) < 0) { high = mid; } else { low = mid + 1; } } _items.Insert(low, new SourceGeneratedFileItem(document.Id, document.HintName, document.Project.Language, _workspace)); } } finally { _items.EndBulkOperation(); _items.MarkAsInitialized(); } } public void BeforeExpand() { lock (_gate) { // We should not have an existing computation active Contract.ThrowIfNull(_cancellationTokenSource == null); _cancellationTokenSource = new CancellationTokenSource(); var cancellationToken = _cancellationTokenSource.Token; var asyncToken = _asyncListener.BeginAsyncOperation(nameof(SourceGeneratedFileItemSource) + "." + nameof(BeforeExpand)); Task.Run( async () => { // Since the user just expanded this, we want to do a single population aggressively, // where the only reason we'd cancel is if the user collapsed it again. var solution = _workspace.CurrentSolution; await UpdateSourceGeneratedFileItemsAsync(solution, cancellationToken).ConfigureAwait(false); // Now that we've done it the first time, we'll subscribe for future changes lock (_gate) { // It's important we check for cancellation inside our lock: if the user were to collapse // right at this point, we don't want to have a case where we cancelled the work, unsubscribed // in AfterCollapse, and _then_ subscribed here again. cancellationToken.ThrowIfCancellationRequested(); _workspace.WorkspaceChanged += OnWorkpaceChanged; if (_workspace.CurrentSolution != solution) { // The workspace changed while we were doing our initial population, so // refresh it. We'll just call our OnWorkspaceChanged event handler // so this looks like any other change. OnWorkpaceChanged(this, new WorkspaceChangeEventArgs(WorkspaceChangeKind.SolutionChanged, solution, _workspace.CurrentSolution)); } } }, cancellationToken).CompletesAsyncOperation(asyncToken); } } public void AfterCollapse() { StopUpdating(); } private void StopUpdating() { lock (_gate) { _cancellationTokenSource?.Cancel(); _cancellationTokenSource = null; _workspace.WorkspaceChanged -= OnWorkpaceChanged; _resettableDelay = null; } } private void OnWorkpaceChanged(object sender, WorkspaceChangeEventArgs e) { if (!e.NewSolution.ContainsProject(_parentGeneratorItem.ProjectId)) { StopUpdating(); } lock (_gate) { // If we already have a ResettableDelay, just delay it further; otherwise we either have no delay // or the actual processing began, and we need to start over if (_resettableDelay != null) { _resettableDelay.Reset(); } else { // Time to start the work all over again. We'll ensure any previous work is cancelled Contract.ThrowIfNull(_cancellationTokenSource, "We created a token when we expanded, how do we not have one when processing an update?"); _cancellationTokenSource.Cancel(); _cancellationTokenSource = new CancellationTokenSource(); var cancellationToken = _cancellationTokenSource.Token; var asyncToken = _asyncListener.BeginAsyncOperation(nameof(SourceGeneratedFileItemSource) + "." + nameof(OnWorkpaceChanged)); // We're going to go with a really long delay: once the user expands this we will keep it updated, but it's fairly // unlikely to change in a lot of cases if a generator only produces a stable set of names. _resettableDelay = new ResettableDelay(delayInMilliseconds: 5000, _asyncListener, _cancellationTokenSource.Token); _resettableDelay.Task.ContinueWith(_ => { lock (_gate) { // We've started off this work, so if another change comes in we need to start a delay all over again _resettableDelay = null; } cancellationToken.ThrowIfCancellationRequested(); return UpdateSourceGeneratedFileItemsAsync(_workspace.CurrentSolution, cancellationToken); }, cancellationToken, TaskContinuationOptions.OnlyOnRanToCompletion, TaskScheduler.Default).CompletesAsyncOperation(asyncToken); } } } /// <summary> /// This derivation of <see cref="ObservableCollection{T}"/> also supports raising an initialized event through /// <see cref="ISupportInitializeNotification"/>. This is used to show the spinning icon in the solution explorer /// the first time you expand it. /// </summary> private sealed class BulkObservableCollectionWithInit<T> : BulkObservableCollection<T>, ISupportInitializeNotification { public bool IsInitialized { get; private set; } = false; public event EventHandler? Initialized; void ISupportInitialize.BeginInit() { } void ISupportInitialize.EndInit() { } public void MarkAsInitialized() { if (!IsInitialized) { IsInitialized = true; Initialized?.Invoke(this, EventArgs.Empty); } } } } }
// Licensed to the .NET Foundation under one or more 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; using System.Collections.ObjectModel; using System.ComponentModel; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.Internal.VisualStudio.PlatformUI; using Microsoft.VisualStudio.Language.Intellisense; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.SolutionExplorer { internal class SourceGeneratedFileItemSource : Shell.IAttachedCollectionSource, ISupportExpansionEvents { private readonly SourceGeneratorItem _parentGeneratorItem; private readonly Workspace _workspace; private readonly IAsynchronousOperationListener _asyncListener; private readonly IThreadingContext _threadingContext; /// <summary> /// The returned collection of items. Can only be mutated on the UI thread, as other parts of WPF are subscribed to the change /// events and expect that. /// </summary> private readonly BulkObservableCollectionWithInit<BaseItem> _items = new(); /// <summary> /// Gate to guard mutation of <see cref="_cancellationTokenSource"/> and <see cref="_resettableDelay"/>. /// </summary> private readonly object _gate = new object(); private CancellationTokenSource? _cancellationTokenSource; private ResettableDelay? _resettableDelay; public SourceGeneratedFileItemSource(SourceGeneratorItem parentGeneratorItem, Workspace workspace, IAsynchronousOperationListener asyncListener, IThreadingContext threadingContext) { _parentGeneratorItem = parentGeneratorItem; _workspace = workspace; _asyncListener = asyncListener; _threadingContext = threadingContext; } public object SourceItem => _parentGeneratorItem; public bool HasItems { get { // Since we are expensive to compute, always say we have items. return true; } } public IEnumerable Items => _items; private async Task UpdateSourceGeneratedFileItemsAsync(Solution solution, CancellationToken cancellationToken) { var project = solution.GetProject(_parentGeneratorItem.ProjectId); if (project == null) { return; } var sourceGeneratedDocuments = await project.GetSourceGeneratedDocumentsAsync(cancellationToken).ConfigureAwait(false); var sourceGeneratedDocumentsForGeneratorById = sourceGeneratedDocuments.Where(d => d.SourceGeneratorAssemblyName == _parentGeneratorItem.GeneratorAssemblyName && d.SourceGeneratorTypeName == _parentGeneratorItem.GeneratorTypeName) .ToDictionary(d => d.Id); // We must update the list on the UI thread, since the WPF elements bound to our list expect that await _threadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); try { // We're going to incrementally update our items, ensuring we keep the object identity for things we didn't touch. // This is because the Solution Explorer itself will use identity to keep track of active items -- if you have an // item selected and we were to refresh in the background we don't want to lose that selection. If we just removed // and repopulated the list from scratch each time we'd lose the selection. _items.BeginBulkOperation(); // Do we already have a "no files" placeholder item? if (_items.Count == 1 && _items[0] is NoSourceGeneratedFilesPlaceholderItem) { // We do -- if we have no items, we're done, since the placeholder is all that needs to be there; // otherwise remove it since we have real files now if (sourceGeneratedDocumentsForGeneratorById.Count == 0) { return; } else { _items.RemoveAt(0); } } for (var i = 0; i < _items.Count; i++) { // If this item that we already have is still a generated document, we'll remove it from our list; the list when we're // done is going to have the new items remaining. If it no longer exists, remove it from list. if (!sourceGeneratedDocumentsForGeneratorById.Remove(((SourceGeneratedFileItem)_items[i]).DocumentId)) { _items.RemoveAt(i); i--; } } // Whatever is left in sourceGeneratedDocumentsForGeneratorById we should add if (sourceGeneratedDocumentsForGeneratorById.Count == 0) { // We don't have any items at all, so add the placeholder Contract.ThrowIfFalse(_items.Count == 0); _items.Add(new NoSourceGeneratedFilesPlaceholderItem()); return; } foreach (var document in sourceGeneratedDocumentsForGeneratorById.Values) { // Binary search to figure out where to insert var low = 0; var high = _items.Count; while (low < high) { var mid = (low + high) / 2; if (StringComparer.OrdinalIgnoreCase.Compare(document.HintName, ((SourceGeneratedFileItem)_items[mid]).HintName) < 0) { high = mid; } else { low = mid + 1; } } _items.Insert(low, new SourceGeneratedFileItem(document.Id, document.HintName, document.Project.Language, _workspace)); } } finally { _items.EndBulkOperation(); _items.MarkAsInitialized(); } } public void BeforeExpand() { lock (_gate) { // We should not have an existing computation active Contract.ThrowIfTrue(_cancellationTokenSource is not null); _cancellationTokenSource = new CancellationTokenSource(); var cancellationToken = _cancellationTokenSource.Token; var asyncToken = _asyncListener.BeginAsyncOperation(nameof(SourceGeneratedFileItemSource) + "." + nameof(BeforeExpand)); Task.Run( async () => { // Since the user just expanded this, we want to do a single population aggressively, // where the only reason we'd cancel is if the user collapsed it again. var solution = _workspace.CurrentSolution; await UpdateSourceGeneratedFileItemsAsync(solution, cancellationToken).ConfigureAwait(false); // Now that we've done it the first time, we'll subscribe for future changes lock (_gate) { // It's important we check for cancellation inside our lock: if the user were to collapse // right at this point, we don't want to have a case where we cancelled the work, unsubscribed // in AfterCollapse, and _then_ subscribed here again. cancellationToken.ThrowIfCancellationRequested(); _workspace.WorkspaceChanged += OnWorkpaceChanged; if (_workspace.CurrentSolution != solution) { // The workspace changed while we were doing our initial population, so // refresh it. We'll just call our OnWorkspaceChanged event handler // so this looks like any other change. OnWorkpaceChanged(this, new WorkspaceChangeEventArgs(WorkspaceChangeKind.SolutionChanged, solution, _workspace.CurrentSolution)); } } }, cancellationToken).CompletesAsyncOperation(asyncToken); } } public void AfterCollapse() { StopUpdating(); } private void StopUpdating() { lock (_gate) { _cancellationTokenSource?.Cancel(); _cancellationTokenSource = null; _workspace.WorkspaceChanged -= OnWorkpaceChanged; _resettableDelay = null; } } private void OnWorkpaceChanged(object sender, WorkspaceChangeEventArgs e) { if (!e.NewSolution.ContainsProject(_parentGeneratorItem.ProjectId)) { StopUpdating(); } lock (_gate) { // If we already have a ResettableDelay, just delay it further; otherwise we either have no delay // or the actual processing began, and we need to start over if (_resettableDelay != null) { _resettableDelay.Reset(); } else { // Time to start the work all over again. We'll ensure any previous work is cancelled Contract.ThrowIfNull(_cancellationTokenSource, "We created a token when we expanded, how do we not have one when processing an update?"); _cancellationTokenSource.Cancel(); _cancellationTokenSource = new CancellationTokenSource(); var cancellationToken = _cancellationTokenSource.Token; var asyncToken = _asyncListener.BeginAsyncOperation(nameof(SourceGeneratedFileItemSource) + "." + nameof(OnWorkpaceChanged)); // We're going to go with a really long delay: once the user expands this we will keep it updated, but it's fairly // unlikely to change in a lot of cases if a generator only produces a stable set of names. _resettableDelay = new ResettableDelay(delayInMilliseconds: 5000, _asyncListener, _cancellationTokenSource.Token); _resettableDelay.Task.ContinueWith(_ => { lock (_gate) { // We've started off this work, so if another change comes in we need to start a delay all over again _resettableDelay = null; } cancellationToken.ThrowIfCancellationRequested(); return UpdateSourceGeneratedFileItemsAsync(_workspace.CurrentSolution, cancellationToken); }, cancellationToken, TaskContinuationOptions.OnlyOnRanToCompletion, TaskScheduler.Default).CompletesAsyncOperation(asyncToken); } } } /// <summary> /// This derivation of <see cref="ObservableCollection{T}"/> also supports raising an initialized event through /// <see cref="ISupportInitializeNotification"/>. This is used to show the spinning icon in the solution explorer /// the first time you expand it. /// </summary> private sealed class BulkObservableCollectionWithInit<T> : BulkObservableCollection<T>, ISupportInitializeNotification { public bool IsInitialized { get; private set; } = false; public event EventHandler? Initialized; void ISupportInitialize.BeginInit() { } void ISupportInitialize.EndInit() { } public void MarkAsInitialized() { if (!IsInitialized) { IsInitialized = true; Initialized?.Invoke(this, EventArgs.Empty); } } } } }
1
dotnet/roslyn
56,433
Only allow Contract.ThrowIfNull() to be called on nullable types
We had some places we were calling it on bools.
jasonmalinowski
"2021-09-16T01:20:43Z"
"2021-09-16T18:44:11Z"
736fc1b5e6e2847689c0154b3e5f23ea99dd56af
6d0f4e3f972ceb561b04574e7f957a4ff458e272
Only allow Contract.ThrowIfNull() to be called on nullable types. We had some places we were calling it on bools.
./src/VisualStudio/Core/Test.Next/Remote/SerializationValidator.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; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Remote; using Microsoft.CodeAnalysis.Serialization; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Remote.UnitTests { internal sealed class SerializationValidator { private sealed class AssetProvider : AbstractAssetProvider { private readonly SerializationValidator _validator; public AssetProvider(SerializationValidator validator) => _validator = validator; public override Task<T> GetAssetAsync<T>(Checksum checksum, CancellationToken cancellationToken) => _validator.GetValueAsync<T>(checksum); } internal sealed class ChecksumObjectCollection<T> : IEnumerable<T> where T : ChecksumWithChildren { public ImmutableArray<T> Children { get; } /// <summary> /// Indicates what kind of object it is /// <see cref="WellKnownSynchronizationKind"/> for examples. /// /// this will be used in tranportation framework and deserialization service /// to hand shake how to send over data and deserialize serialized data /// </summary> public readonly WellKnownSynchronizationKind Kind; /// <summary> /// Checksum of this object /// </summary> public readonly Checksum Checksum; public ChecksumObjectCollection(SerializationValidator validator, ChecksumCollection collection) { Checksum = collection.Checksum; Kind = collection.GetWellKnownSynchronizationKind(); // using .Result here since we don't want to convert all calls to this to async. // and none of ChecksumWithChildren actually use async Children = ImmutableArray.CreateRange(collection.Select(c => validator.GetValueAsync<T>(c).Result)); } public int Count => Children.Length; public T this[int index] => Children[index]; IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); public IEnumerator<T> GetEnumerator() => Children.Select(t => t).GetEnumerator(); } public SolutionAssetStorage AssetStorage { get; } public ISerializerService Serializer { get; } public HostWorkspaceServices Services { get; } public SerializationValidator(HostWorkspaceServices services) { AssetStorage = services.GetRequiredService<ISolutionAssetStorageProvider>().AssetStorage; Serializer = services.GetRequiredService<ISerializerService>(); Services = services; } public async Task<T> GetValueAsync<T>(Checksum checksum) { var data = (await AssetStorage.GetTestAccessor().GetAssetAsync(checksum, CancellationToken.None).ConfigureAwait(false))!; Contract.ThrowIfNull(data.Value); using var context = SolutionReplicationContext.Create(); using var stream = SerializableBytes.CreateWritableStream(); using (var writer = new ObjectWriter(stream, leaveOpen: true)) { Serializer.Serialize(data.Value, writer, context, CancellationToken.None); } stream.Position = 0; using var reader = ObjectReader.TryGetReader(stream); // deserialize bits to object var result = Serializer.Deserialize<T>(data.Kind, reader, CancellationToken.None); Contract.ThrowIfNull(result); return result; } public async Task<Solution> GetSolutionAsync(SolutionAssetStorage.Scope scope) { var (solutionInfo, _) = await new AssetProvider(this).CreateSolutionInfoAndOptionsAsync(scope.SolutionInfo.SolutionChecksum, CancellationToken.None).ConfigureAwait(false); var workspace = new AdhocWorkspace(Services.HostServices); return workspace.AddSolution(solutionInfo); } public ChecksumObjectCollection<ProjectStateChecksums> ToProjectObjects(ChecksumCollection collection) => new ChecksumObjectCollection<ProjectStateChecksums>(this, collection); public ChecksumObjectCollection<DocumentStateChecksums> ToDocumentObjects(ChecksumCollection collection) => new ChecksumObjectCollection<DocumentStateChecksums>(this, collection); internal async Task VerifyAssetAsync(SolutionStateChecksums solutionObject) { await VerifyAssetSerializationAsync<SolutionInfo.SolutionAttributes>( solutionObject.Attributes, WellKnownSynchronizationKind.SolutionAttributes, (v, k, s) => new SolutionAsset(s.CreateChecksum(v, CancellationToken.None), v)).ConfigureAwait(false); foreach (var projectChecksum in solutionObject.Projects) { var projectObject = await GetValueAsync<ProjectStateChecksums>(projectChecksum).ConfigureAwait(false); await VerifyAssetAsync(projectObject).ConfigureAwait(false); } } internal async Task VerifyAssetAsync(ProjectStateChecksums projectObject) { var info = await VerifyAssetSerializationAsync<ProjectInfo.ProjectAttributes>( projectObject.Info, WellKnownSynchronizationKind.ProjectAttributes, (v, k, s) => new SolutionAsset(s.CreateChecksum(v, CancellationToken.None), v)).ConfigureAwait(false); await VerifyAssetSerializationAsync<CompilationOptions>( projectObject.CompilationOptions, WellKnownSynchronizationKind.CompilationOptions, (v, k, s) => new SolutionAsset(s.CreateChecksum(v, CancellationToken.None), v)); await VerifyAssetSerializationAsync<ParseOptions>( projectObject.ParseOptions, WellKnownSynchronizationKind.ParseOptions, (v, k, s) => new SolutionAsset(s.CreateChecksum(v, CancellationToken.None), v)); foreach (var checksum in projectObject.Documents) { var documentObject = await GetValueAsync<DocumentStateChecksums>(checksum).ConfigureAwait(false); await VerifyAssetAsync(documentObject).ConfigureAwait(false); } foreach (var checksum in projectObject.ProjectReferences) { await VerifyAssetSerializationAsync<ProjectReference>( checksum, WellKnownSynchronizationKind.ProjectReference, (v, k, s) => new SolutionAsset(s.CreateChecksum(v, CancellationToken.None), v)); } foreach (var checksum in projectObject.MetadataReferences) { await VerifyAssetSerializationAsync<MetadataReference>( checksum, WellKnownSynchronizationKind.MetadataReference, (v, k, s) => new SolutionAsset(s.CreateChecksum(v, CancellationToken.None), v)); } foreach (var checksum in projectObject.AnalyzerReferences) { await VerifyAssetSerializationAsync<AnalyzerReference>( checksum, WellKnownSynchronizationKind.AnalyzerReference, (v, k, s) => new SolutionAsset(s.CreateChecksum(v, CancellationToken.None), v)); } foreach (var checksum in projectObject.AdditionalDocuments) { var documentObject = await GetValueAsync<DocumentStateChecksums>(checksum).ConfigureAwait(false); await VerifyAssetAsync(documentObject).ConfigureAwait(false); } foreach (var checksum in projectObject.AnalyzerConfigDocuments) { var documentObject = await GetValueAsync<DocumentStateChecksums>(checksum).ConfigureAwait(false); await VerifyAssetAsync(documentObject).ConfigureAwait(false); } } internal async Task VerifyAssetAsync(DocumentStateChecksums documentObject) { var info = await VerifyAssetSerializationAsync<DocumentInfo.DocumentAttributes>( documentObject.Info, WellKnownSynchronizationKind.DocumentAttributes, (v, k, s) => new SolutionAsset(s.CreateChecksum(v, CancellationToken.None), v)).ConfigureAwait(false); await VerifyAssetSerializationAsync<SerializableSourceText>( documentObject.Text, WellKnownSynchronizationKind.SerializableSourceText, (v, k, s) => new SolutionAsset(s.CreateChecksum(v, CancellationToken.None), v)); } internal async Task<T> VerifyAssetSerializationAsync<T>( Checksum checksum, WellKnownSynchronizationKind kind, Func<T, WellKnownSynchronizationKind, ISerializerService, SolutionAsset> assetGetter) { // re-create asset from object var syncObject = (await AssetStorage.GetTestAccessor().GetAssetAsync(checksum, CancellationToken.None).ConfigureAwait(false))!; var recoveredValue = await GetValueAsync<T>(checksum).ConfigureAwait(false); var recreatedSyncObject = assetGetter(recoveredValue, kind, Serializer); // make sure original object and re-created object are same. SynchronizationObjectEqual(syncObject, recreatedSyncObject); return recoveredValue; } internal async Task VerifySolutionStateSerializationAsync(Solution solution, Checksum solutionChecksum) { var solutionObjectFromSyncObject = await GetValueAsync<SolutionStateChecksums>(solutionChecksum); Contract.ThrowIfFalse(solution.State.TryGetStateChecksums(out var solutionObjectFromSolution)); SolutionStateEqual(solutionObjectFromSolution, solutionObjectFromSyncObject); } internal void SolutionStateEqual(SolutionStateChecksums solutionObject1, SolutionStateChecksums solutionObject2) { ChecksumWithChildrenEqual(solutionObject1, solutionObject2); ProjectStatesEqual(ToProjectObjects(solutionObject1.Projects), ToProjectObjects(solutionObject2.Projects)); } internal void ProjectStateEqual(ProjectStateChecksums projectObjects1, ProjectStateChecksums projectObjects2) { ChecksumWithChildrenEqual(projectObjects1, projectObjects2); ChecksumWithChildrenEqual(ToDocumentObjects(projectObjects1.Documents), ToDocumentObjects(projectObjects2.Documents)); ChecksumWithChildrenEqual(ToDocumentObjects(projectObjects1.AdditionalDocuments), ToDocumentObjects(projectObjects2.AdditionalDocuments)); ChecksumWithChildrenEqual(ToDocumentObjects(projectObjects1.AnalyzerConfigDocuments), ToDocumentObjects(projectObjects2.AnalyzerConfigDocuments)); } internal void ProjectStatesEqual(ChecksumObjectCollection<ProjectStateChecksums> projectObjects1, ChecksumObjectCollection<ProjectStateChecksums> projectObjects2) { SynchronizationObjectEqual(projectObjects1, projectObjects2); Assert.Equal(projectObjects1.Count, projectObjects2.Count); for (var i = 0; i < projectObjects1.Count; i++) { ProjectStateEqual(projectObjects1[i], projectObjects2[i]); } } internal static void ChecksumWithChildrenEqual<T>(ChecksumObjectCollection<T> checksums1, ChecksumObjectCollection<T> checksums2) where T : ChecksumWithChildren { SynchronizationObjectEqual(checksums1, checksums2); Assert.Equal(checksums1.Count, checksums2.Count); for (var i = 0; i < checksums1.Count; i++) { ChecksumWithChildrenEqual(checksums1[i], checksums2[i]); } } internal static void ChecksumWithChildrenEqual(ChecksumWithChildren checksums1, ChecksumWithChildren checksums2) { Assert.Equal(checksums1.Checksum, checksums2.Checksum); Assert.Equal(checksums1.Children.Count, checksums2.Children.Count); for (var i = 0; i < checksums1.Children.Count; i++) { var child1 = checksums1.Children[i]; var child2 = checksums2.Children[i]; Assert.Equal(child1.GetType(), child2.GetType()); if (child1 is Checksum) { Assert.Equal((Checksum)child1, (Checksum)child2); continue; } ChecksumWithChildrenEqual((ChecksumCollection)child1, (ChecksumCollection)child2); } } internal async Task VerifySnapshotInServiceAsync( ProjectStateChecksums projectObject, int expectedDocumentCount, int expectedProjectReferenceCount, int expectedMetadataReferenceCount, int expectedAnalyzerReferenceCount, int expectedAdditionalDocumentCount) { await VerifyChecksumInServiceAsync(projectObject.Checksum, projectObject.GetWellKnownSynchronizationKind()).ConfigureAwait(false); await VerifyChecksumInServiceAsync(projectObject.Info, WellKnownSynchronizationKind.ProjectAttributes).ConfigureAwait(false); await VerifyChecksumInServiceAsync(projectObject.CompilationOptions, WellKnownSynchronizationKind.CompilationOptions).ConfigureAwait(false); await VerifyChecksumInServiceAsync(projectObject.ParseOptions, WellKnownSynchronizationKind.ParseOptions).ConfigureAwait(false); await VerifyCollectionInService(ToDocumentObjects(projectObject.Documents), expectedDocumentCount).ConfigureAwait(false); await VerifyCollectionInService(projectObject.ProjectReferences, expectedProjectReferenceCount, WellKnownSynchronizationKind.ProjectReference).ConfigureAwait(false); await VerifyCollectionInService(projectObject.MetadataReferences, expectedMetadataReferenceCount, WellKnownSynchronizationKind.MetadataReference).ConfigureAwait(false); await VerifyCollectionInService(projectObject.AnalyzerReferences, expectedAnalyzerReferenceCount, WellKnownSynchronizationKind.AnalyzerReference).ConfigureAwait(false); await VerifyCollectionInService(ToDocumentObjects(projectObject.AdditionalDocuments), expectedAdditionalDocumentCount).ConfigureAwait(false); } internal async Task VerifyCollectionInService(ChecksumCollection checksums, int expectedCount, WellKnownSynchronizationKind expectedItemKind) { await VerifyChecksumInServiceAsync(checksums.Checksum, checksums.GetWellKnownSynchronizationKind()).ConfigureAwait(false); Assert.Equal(checksums.Count, expectedCount); foreach (var checksum in checksums) { await VerifyChecksumInServiceAsync(checksum, expectedItemKind).ConfigureAwait(false); } } internal async Task VerifyCollectionInService(ChecksumObjectCollection<DocumentStateChecksums> documents, int expectedCount) { await VerifySynchronizationObjectInServiceAsync(documents).ConfigureAwait(false); Assert.Equal(documents.Count, expectedCount); foreach (var documentId in documents) { await VerifySnapshotInServiceAsync(documentId).ConfigureAwait(false); } } internal async Task VerifySnapshotInServiceAsync(DocumentStateChecksums documentObject) { await VerifyChecksumInServiceAsync(documentObject.Checksum, documentObject.GetWellKnownSynchronizationKind()).ConfigureAwait(false); await VerifyChecksumInServiceAsync(documentObject.Info, WellKnownSynchronizationKind.DocumentAttributes).ConfigureAwait(false); await VerifyChecksumInServiceAsync(documentObject.Text, WellKnownSynchronizationKind.SerializableSourceText).ConfigureAwait(false); } internal async Task VerifySynchronizationObjectInServiceAsync(SolutionAsset syncObject) => await VerifyChecksumInServiceAsync(syncObject.Checksum, syncObject.Kind).ConfigureAwait(false); internal async Task VerifySynchronizationObjectInServiceAsync<T>(ChecksumObjectCollection<T> syncObject) where T : ChecksumWithChildren => await VerifyChecksumInServiceAsync(syncObject.Checksum, syncObject.Kind).ConfigureAwait(false); internal async Task VerifyChecksumInServiceAsync(Checksum checksum, WellKnownSynchronizationKind kind) { Assert.NotNull(checksum); var otherObject = (await AssetStorage.GetTestAccessor().GetAssetAsync(checksum, CancellationToken.None).ConfigureAwait(false))!; ChecksumEqual(checksum, kind, otherObject.Checksum, otherObject.Kind); } internal static void SynchronizationObjectEqual<T>(ChecksumObjectCollection<T> checksumObject1, ChecksumObjectCollection<T> checksumObject2) where T : ChecksumWithChildren => ChecksumEqual(checksumObject1.Checksum, checksumObject1.Kind, checksumObject2.Checksum, checksumObject2.Kind); internal static void SynchronizationObjectEqual<T>(ChecksumObjectCollection<T> checksumObject1, SolutionAsset checksumObject2) where T : ChecksumWithChildren => ChecksumEqual(checksumObject1.Checksum, checksumObject1.Kind, checksumObject2.Checksum, checksumObject2.Kind); internal static void SynchronizationObjectEqual(SolutionAsset checksumObject1, SolutionAsset checksumObject2) => ChecksumEqual(checksumObject1.Checksum, checksumObject1.Kind, checksumObject2.Checksum, checksumObject2.Kind); internal static void ChecksumEqual(Checksum checksum1, WellKnownSynchronizationKind kind1, Checksum checksum2, WellKnownSynchronizationKind kind2) { Assert.Equal(checksum1, checksum2); Assert.Equal(kind1, kind2); } } }
// Licensed to the .NET Foundation under one or more 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; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Remote; using Microsoft.CodeAnalysis.Serialization; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Remote.UnitTests { internal sealed class SerializationValidator { private sealed class AssetProvider : AbstractAssetProvider { private readonly SerializationValidator _validator; public AssetProvider(SerializationValidator validator) => _validator = validator; public override Task<T> GetAssetAsync<T>(Checksum checksum, CancellationToken cancellationToken) => _validator.GetValueAsync<T>(checksum); } internal sealed class ChecksumObjectCollection<T> : IEnumerable<T> where T : ChecksumWithChildren { public ImmutableArray<T> Children { get; } /// <summary> /// Indicates what kind of object it is /// <see cref="WellKnownSynchronizationKind"/> for examples. /// /// this will be used in tranportation framework and deserialization service /// to hand shake how to send over data and deserialize serialized data /// </summary> public readonly WellKnownSynchronizationKind Kind; /// <summary> /// Checksum of this object /// </summary> public readonly Checksum Checksum; public ChecksumObjectCollection(SerializationValidator validator, ChecksumCollection collection) { Checksum = collection.Checksum; Kind = collection.GetWellKnownSynchronizationKind(); // using .Result here since we don't want to convert all calls to this to async. // and none of ChecksumWithChildren actually use async Children = ImmutableArray.CreateRange(collection.Select(c => validator.GetValueAsync<T>(c).Result)); } public int Count => Children.Length; public T this[int index] => Children[index]; IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); public IEnumerator<T> GetEnumerator() => Children.Select(t => t).GetEnumerator(); } public SolutionAssetStorage AssetStorage { get; } public ISerializerService Serializer { get; } public HostWorkspaceServices Services { get; } public SerializationValidator(HostWorkspaceServices services) { AssetStorage = services.GetRequiredService<ISolutionAssetStorageProvider>().AssetStorage; Serializer = services.GetRequiredService<ISerializerService>(); Services = services; } public async Task<T> GetValueAsync<T>(Checksum checksum) { var data = (await AssetStorage.GetTestAccessor().GetAssetAsync(checksum, CancellationToken.None).ConfigureAwait(false))!; Contract.ThrowIfNull(data.Value); using var context = SolutionReplicationContext.Create(); using var stream = SerializableBytes.CreateWritableStream(); using (var writer = new ObjectWriter(stream, leaveOpen: true)) { Serializer.Serialize(data.Value, writer, context, CancellationToken.None); } stream.Position = 0; using var reader = ObjectReader.TryGetReader(stream); // deserialize bits to object var result = Serializer.Deserialize<T>(data.Kind, reader, CancellationToken.None); Contract.ThrowIfNull<object?>(result); return result; } public async Task<Solution> GetSolutionAsync(SolutionAssetStorage.Scope scope) { var (solutionInfo, _) = await new AssetProvider(this).CreateSolutionInfoAndOptionsAsync(scope.SolutionInfo.SolutionChecksum, CancellationToken.None).ConfigureAwait(false); var workspace = new AdhocWorkspace(Services.HostServices); return workspace.AddSolution(solutionInfo); } public ChecksumObjectCollection<ProjectStateChecksums> ToProjectObjects(ChecksumCollection collection) => new ChecksumObjectCollection<ProjectStateChecksums>(this, collection); public ChecksumObjectCollection<DocumentStateChecksums> ToDocumentObjects(ChecksumCollection collection) => new ChecksumObjectCollection<DocumentStateChecksums>(this, collection); internal async Task VerifyAssetAsync(SolutionStateChecksums solutionObject) { await VerifyAssetSerializationAsync<SolutionInfo.SolutionAttributes>( solutionObject.Attributes, WellKnownSynchronizationKind.SolutionAttributes, (v, k, s) => new SolutionAsset(s.CreateChecksum(v, CancellationToken.None), v)).ConfigureAwait(false); foreach (var projectChecksum in solutionObject.Projects) { var projectObject = await GetValueAsync<ProjectStateChecksums>(projectChecksum).ConfigureAwait(false); await VerifyAssetAsync(projectObject).ConfigureAwait(false); } } internal async Task VerifyAssetAsync(ProjectStateChecksums projectObject) { var info = await VerifyAssetSerializationAsync<ProjectInfo.ProjectAttributes>( projectObject.Info, WellKnownSynchronizationKind.ProjectAttributes, (v, k, s) => new SolutionAsset(s.CreateChecksum(v, CancellationToken.None), v)).ConfigureAwait(false); await VerifyAssetSerializationAsync<CompilationOptions>( projectObject.CompilationOptions, WellKnownSynchronizationKind.CompilationOptions, (v, k, s) => new SolutionAsset(s.CreateChecksum(v, CancellationToken.None), v)); await VerifyAssetSerializationAsync<ParseOptions>( projectObject.ParseOptions, WellKnownSynchronizationKind.ParseOptions, (v, k, s) => new SolutionAsset(s.CreateChecksum(v, CancellationToken.None), v)); foreach (var checksum in projectObject.Documents) { var documentObject = await GetValueAsync<DocumentStateChecksums>(checksum).ConfigureAwait(false); await VerifyAssetAsync(documentObject).ConfigureAwait(false); } foreach (var checksum in projectObject.ProjectReferences) { await VerifyAssetSerializationAsync<ProjectReference>( checksum, WellKnownSynchronizationKind.ProjectReference, (v, k, s) => new SolutionAsset(s.CreateChecksum(v, CancellationToken.None), v)); } foreach (var checksum in projectObject.MetadataReferences) { await VerifyAssetSerializationAsync<MetadataReference>( checksum, WellKnownSynchronizationKind.MetadataReference, (v, k, s) => new SolutionAsset(s.CreateChecksum(v, CancellationToken.None), v)); } foreach (var checksum in projectObject.AnalyzerReferences) { await VerifyAssetSerializationAsync<AnalyzerReference>( checksum, WellKnownSynchronizationKind.AnalyzerReference, (v, k, s) => new SolutionAsset(s.CreateChecksum(v, CancellationToken.None), v)); } foreach (var checksum in projectObject.AdditionalDocuments) { var documentObject = await GetValueAsync<DocumentStateChecksums>(checksum).ConfigureAwait(false); await VerifyAssetAsync(documentObject).ConfigureAwait(false); } foreach (var checksum in projectObject.AnalyzerConfigDocuments) { var documentObject = await GetValueAsync<DocumentStateChecksums>(checksum).ConfigureAwait(false); await VerifyAssetAsync(documentObject).ConfigureAwait(false); } } internal async Task VerifyAssetAsync(DocumentStateChecksums documentObject) { var info = await VerifyAssetSerializationAsync<DocumentInfo.DocumentAttributes>( documentObject.Info, WellKnownSynchronizationKind.DocumentAttributes, (v, k, s) => new SolutionAsset(s.CreateChecksum(v, CancellationToken.None), v)).ConfigureAwait(false); await VerifyAssetSerializationAsync<SerializableSourceText>( documentObject.Text, WellKnownSynchronizationKind.SerializableSourceText, (v, k, s) => new SolutionAsset(s.CreateChecksum(v, CancellationToken.None), v)); } internal async Task<T> VerifyAssetSerializationAsync<T>( Checksum checksum, WellKnownSynchronizationKind kind, Func<T, WellKnownSynchronizationKind, ISerializerService, SolutionAsset> assetGetter) { // re-create asset from object var syncObject = (await AssetStorage.GetTestAccessor().GetAssetAsync(checksum, CancellationToken.None).ConfigureAwait(false))!; var recoveredValue = await GetValueAsync<T>(checksum).ConfigureAwait(false); var recreatedSyncObject = assetGetter(recoveredValue, kind, Serializer); // make sure original object and re-created object are same. SynchronizationObjectEqual(syncObject, recreatedSyncObject); return recoveredValue; } internal async Task VerifySolutionStateSerializationAsync(Solution solution, Checksum solutionChecksum) { var solutionObjectFromSyncObject = await GetValueAsync<SolutionStateChecksums>(solutionChecksum); Contract.ThrowIfFalse(solution.State.TryGetStateChecksums(out var solutionObjectFromSolution)); SolutionStateEqual(solutionObjectFromSolution, solutionObjectFromSyncObject); } internal void SolutionStateEqual(SolutionStateChecksums solutionObject1, SolutionStateChecksums solutionObject2) { ChecksumWithChildrenEqual(solutionObject1, solutionObject2); ProjectStatesEqual(ToProjectObjects(solutionObject1.Projects), ToProjectObjects(solutionObject2.Projects)); } internal void ProjectStateEqual(ProjectStateChecksums projectObjects1, ProjectStateChecksums projectObjects2) { ChecksumWithChildrenEqual(projectObjects1, projectObjects2); ChecksumWithChildrenEqual(ToDocumentObjects(projectObjects1.Documents), ToDocumentObjects(projectObjects2.Documents)); ChecksumWithChildrenEqual(ToDocumentObjects(projectObjects1.AdditionalDocuments), ToDocumentObjects(projectObjects2.AdditionalDocuments)); ChecksumWithChildrenEqual(ToDocumentObjects(projectObjects1.AnalyzerConfigDocuments), ToDocumentObjects(projectObjects2.AnalyzerConfigDocuments)); } internal void ProjectStatesEqual(ChecksumObjectCollection<ProjectStateChecksums> projectObjects1, ChecksumObjectCollection<ProjectStateChecksums> projectObjects2) { SynchronizationObjectEqual(projectObjects1, projectObjects2); Assert.Equal(projectObjects1.Count, projectObjects2.Count); for (var i = 0; i < projectObjects1.Count; i++) { ProjectStateEqual(projectObjects1[i], projectObjects2[i]); } } internal static void ChecksumWithChildrenEqual<T>(ChecksumObjectCollection<T> checksums1, ChecksumObjectCollection<T> checksums2) where T : ChecksumWithChildren { SynchronizationObjectEqual(checksums1, checksums2); Assert.Equal(checksums1.Count, checksums2.Count); for (var i = 0; i < checksums1.Count; i++) { ChecksumWithChildrenEqual(checksums1[i], checksums2[i]); } } internal static void ChecksumWithChildrenEqual(ChecksumWithChildren checksums1, ChecksumWithChildren checksums2) { Assert.Equal(checksums1.Checksum, checksums2.Checksum); Assert.Equal(checksums1.Children.Count, checksums2.Children.Count); for (var i = 0; i < checksums1.Children.Count; i++) { var child1 = checksums1.Children[i]; var child2 = checksums2.Children[i]; Assert.Equal(child1.GetType(), child2.GetType()); if (child1 is Checksum) { Assert.Equal((Checksum)child1, (Checksum)child2); continue; } ChecksumWithChildrenEqual((ChecksumCollection)child1, (ChecksumCollection)child2); } } internal async Task VerifySnapshotInServiceAsync( ProjectStateChecksums projectObject, int expectedDocumentCount, int expectedProjectReferenceCount, int expectedMetadataReferenceCount, int expectedAnalyzerReferenceCount, int expectedAdditionalDocumentCount) { await VerifyChecksumInServiceAsync(projectObject.Checksum, projectObject.GetWellKnownSynchronizationKind()).ConfigureAwait(false); await VerifyChecksumInServiceAsync(projectObject.Info, WellKnownSynchronizationKind.ProjectAttributes).ConfigureAwait(false); await VerifyChecksumInServiceAsync(projectObject.CompilationOptions, WellKnownSynchronizationKind.CompilationOptions).ConfigureAwait(false); await VerifyChecksumInServiceAsync(projectObject.ParseOptions, WellKnownSynchronizationKind.ParseOptions).ConfigureAwait(false); await VerifyCollectionInService(ToDocumentObjects(projectObject.Documents), expectedDocumentCount).ConfigureAwait(false); await VerifyCollectionInService(projectObject.ProjectReferences, expectedProjectReferenceCount, WellKnownSynchronizationKind.ProjectReference).ConfigureAwait(false); await VerifyCollectionInService(projectObject.MetadataReferences, expectedMetadataReferenceCount, WellKnownSynchronizationKind.MetadataReference).ConfigureAwait(false); await VerifyCollectionInService(projectObject.AnalyzerReferences, expectedAnalyzerReferenceCount, WellKnownSynchronizationKind.AnalyzerReference).ConfigureAwait(false); await VerifyCollectionInService(ToDocumentObjects(projectObject.AdditionalDocuments), expectedAdditionalDocumentCount).ConfigureAwait(false); } internal async Task VerifyCollectionInService(ChecksumCollection checksums, int expectedCount, WellKnownSynchronizationKind expectedItemKind) { await VerifyChecksumInServiceAsync(checksums.Checksum, checksums.GetWellKnownSynchronizationKind()).ConfigureAwait(false); Assert.Equal(checksums.Count, expectedCount); foreach (var checksum in checksums) { await VerifyChecksumInServiceAsync(checksum, expectedItemKind).ConfigureAwait(false); } } internal async Task VerifyCollectionInService(ChecksumObjectCollection<DocumentStateChecksums> documents, int expectedCount) { await VerifySynchronizationObjectInServiceAsync(documents).ConfigureAwait(false); Assert.Equal(documents.Count, expectedCount); foreach (var documentId in documents) { await VerifySnapshotInServiceAsync(documentId).ConfigureAwait(false); } } internal async Task VerifySnapshotInServiceAsync(DocumentStateChecksums documentObject) { await VerifyChecksumInServiceAsync(documentObject.Checksum, documentObject.GetWellKnownSynchronizationKind()).ConfigureAwait(false); await VerifyChecksumInServiceAsync(documentObject.Info, WellKnownSynchronizationKind.DocumentAttributes).ConfigureAwait(false); await VerifyChecksumInServiceAsync(documentObject.Text, WellKnownSynchronizationKind.SerializableSourceText).ConfigureAwait(false); } internal async Task VerifySynchronizationObjectInServiceAsync(SolutionAsset syncObject) => await VerifyChecksumInServiceAsync(syncObject.Checksum, syncObject.Kind).ConfigureAwait(false); internal async Task VerifySynchronizationObjectInServiceAsync<T>(ChecksumObjectCollection<T> syncObject) where T : ChecksumWithChildren => await VerifyChecksumInServiceAsync(syncObject.Checksum, syncObject.Kind).ConfigureAwait(false); internal async Task VerifyChecksumInServiceAsync(Checksum checksum, WellKnownSynchronizationKind kind) { Assert.NotNull(checksum); var otherObject = (await AssetStorage.GetTestAccessor().GetAssetAsync(checksum, CancellationToken.None).ConfigureAwait(false))!; ChecksumEqual(checksum, kind, otherObject.Checksum, otherObject.Kind); } internal static void SynchronizationObjectEqual<T>(ChecksumObjectCollection<T> checksumObject1, ChecksumObjectCollection<T> checksumObject2) where T : ChecksumWithChildren => ChecksumEqual(checksumObject1.Checksum, checksumObject1.Kind, checksumObject2.Checksum, checksumObject2.Kind); internal static void SynchronizationObjectEqual<T>(ChecksumObjectCollection<T> checksumObject1, SolutionAsset checksumObject2) where T : ChecksumWithChildren => ChecksumEqual(checksumObject1.Checksum, checksumObject1.Kind, checksumObject2.Checksum, checksumObject2.Kind); internal static void SynchronizationObjectEqual(SolutionAsset checksumObject1, SolutionAsset checksumObject2) => ChecksumEqual(checksumObject1.Checksum, checksumObject1.Kind, checksumObject2.Checksum, checksumObject2.Kind); internal static void ChecksumEqual(Checksum checksum1, WellKnownSynchronizationKind kind1, Checksum checksum2, WellKnownSynchronizationKind kind2) { Assert.Equal(checksum1, checksum2); Assert.Equal(kind1, kind2); } } }
1
dotnet/roslyn
56,433
Only allow Contract.ThrowIfNull() to be called on nullable types
We had some places we were calling it on bools.
jasonmalinowski
"2021-09-16T01:20:43Z"
"2021-09-16T18:44:11Z"
736fc1b5e6e2847689c0154b3e5f23ea99dd56af
6d0f4e3f972ceb561b04574e7f957a4ff458e272
Only allow Contract.ThrowIfNull() to be called on nullable types. We had some places we were calling it on bools.
./src/VisualStudio/Xaml/Impl/Implementation/LanguageServer/Handler/OnTypeRename/OnTypeRenameHandler.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.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.Xaml; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServer; using Microsoft.CodeAnalysis.LanguageServer.Handler; using Microsoft.VisualStudio.LanguageServer.Protocol; using Microsoft.VisualStudio.LanguageServices.Xaml.Features.TypeRename; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Xaml.LanguageServer.Handler { [ExportLspRequestHandlerProvider(StringConstants.XamlLanguageName), Shared] [ProvidesMethod(Methods.TextDocumentLinkedEditingRangeName)] internal class OnTypeRenameHandler : AbstractStatelessRequestHandler<LinkedEditingRangeParams, LinkedEditingRanges?> { // From https://www.w3.org/TR/xml/#NT-NameStartChar // Notes: // \u10000-\uEFFFF isn't included as .NET regular expressions only allow 4 chars after \u. // The : shouldn't really be used as start character either so included it in the name char pattern. // We want to allow complete removal and replacement of names so we need to make the start char // optional in the name char pattern. // NameStartChar ::= ":" | [A-Z] | "_" | [a-z] | [#xC0-#xD6] | [#xD8-#xF6] | [#xF8-#x2FF] | [#x370-#x37D] | [#x37F-#x1FFF] | [#x200C-#x200D] | [#x2070-#x218F] | [#x2C00-#x2FEF] | [#x3001-#xD7FF] | [#xF900-#xFDCF] | [#xFDF0-#xFFFD] | [#x10000-#xEFFFF] private const string NameStartCharPattern = "A-Z_a-z" + "\\u00C0-\\u00D6" + "\\u00D8-\\u00F6" + "\\u00F8-\\u02FF" + "\\u0370-\\u037D" + "\\u037F-\\u1FFF" + "\\u200C-\\u200D" + "\\u2070-\\u218F" + "\\u2C00-\\u2FEF" + "\\u3001-\\uD7FF" + "\\uF900-\\uFDCF" + "\\uFDF0-\\uFFFD"; // NameChar ::= NameStartChar | "-" | "." | [0-9] | #xB7 | [#x0300-#x036F] | [#x203F-#x2040] private const string NameCharPattern = NameStartCharPattern + ":\\-.0-9" + "\\u00B7" + "\\u0300-\\u036F" + "\\u203F-\\u2040"; // Name ::= NameStartChar (NameChar)* internal const string NamePattern = $"[{NameStartCharPattern}]?[{NameCharPattern}]*"; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public OnTypeRenameHandler() { } public override string Method => Methods.TextDocumentLinkedEditingRangeName; public override bool MutatesSolutionState => false; public override bool RequiresLSPSolution => true; public override TextDocumentIdentifier? GetTextDocumentIdentifier(LinkedEditingRangeParams request) => request.TextDocument; public override async Task<LinkedEditingRanges?> HandleRequestAsync(LinkedEditingRangeParams request, RequestContext context, CancellationToken cancellationToken) { var document = context.Document; if (document == null) { return null; } var renameService = document.Project.LanguageServices.GetService<IXamlTypeRenameService>(); if (renameService == null) { return null; } var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); var offset = text.Lines.GetPosition(ProtocolConversions.PositionToLinePosition(request.Position)); var result = await renameService.GetTypeRenameAsync(document, offset, cancellationToken).ConfigureAwait(false); if (result == null) { return null; } Contract.ThrowIfNull(result.Ranges); return new LinkedEditingRanges { Ranges = result.Ranges.Select(s => ProtocolConversions.TextSpanToRange(s, text)).ToArray(), WordPattern = result.WordPattern }; } } }
// Licensed to the .NET Foundation under one or more 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.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.Xaml; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServer; using Microsoft.CodeAnalysis.LanguageServer.Handler; using Microsoft.VisualStudio.LanguageServer.Protocol; using Microsoft.VisualStudio.LanguageServices.Xaml.Features.TypeRename; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Xaml.LanguageServer.Handler { [ExportLspRequestHandlerProvider(StringConstants.XamlLanguageName), Shared] [ProvidesMethod(Methods.TextDocumentLinkedEditingRangeName)] internal class OnTypeRenameHandler : AbstractStatelessRequestHandler<LinkedEditingRangeParams, LinkedEditingRanges?> { // From https://www.w3.org/TR/xml/#NT-NameStartChar // Notes: // \u10000-\uEFFFF isn't included as .NET regular expressions only allow 4 chars after \u. // The : shouldn't really be used as start character either so included it in the name char pattern. // We want to allow complete removal and replacement of names so we need to make the start char // optional in the name char pattern. // NameStartChar ::= ":" | [A-Z] | "_" | [a-z] | [#xC0-#xD6] | [#xD8-#xF6] | [#xF8-#x2FF] | [#x370-#x37D] | [#x37F-#x1FFF] | [#x200C-#x200D] | [#x2070-#x218F] | [#x2C00-#x2FEF] | [#x3001-#xD7FF] | [#xF900-#xFDCF] | [#xFDF0-#xFFFD] | [#x10000-#xEFFFF] private const string NameStartCharPattern = "A-Z_a-z" + "\\u00C0-\\u00D6" + "\\u00D8-\\u00F6" + "\\u00F8-\\u02FF" + "\\u0370-\\u037D" + "\\u037F-\\u1FFF" + "\\u200C-\\u200D" + "\\u2070-\\u218F" + "\\u2C00-\\u2FEF" + "\\u3001-\\uD7FF" + "\\uF900-\\uFDCF" + "\\uFDF0-\\uFFFD"; // NameChar ::= NameStartChar | "-" | "." | [0-9] | #xB7 | [#x0300-#x036F] | [#x203F-#x2040] private const string NameCharPattern = NameStartCharPattern + ":\\-.0-9" + "\\u00B7" + "\\u0300-\\u036F" + "\\u203F-\\u2040"; // Name ::= NameStartChar (NameChar)* internal const string NamePattern = $"[{NameStartCharPattern}]?[{NameCharPattern}]*"; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public OnTypeRenameHandler() { } public override string Method => Methods.TextDocumentLinkedEditingRangeName; public override bool MutatesSolutionState => false; public override bool RequiresLSPSolution => true; public override TextDocumentIdentifier? GetTextDocumentIdentifier(LinkedEditingRangeParams request) => request.TextDocument; public override async Task<LinkedEditingRanges?> HandleRequestAsync(LinkedEditingRangeParams request, RequestContext context, CancellationToken cancellationToken) { var document = context.Document; if (document == null) { return null; } var renameService = document.Project.LanguageServices.GetService<IXamlTypeRenameService>(); if (renameService == null) { return null; } var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); var offset = text.Lines.GetPosition(ProtocolConversions.PositionToLinePosition(request.Position)); var result = await renameService.GetTypeRenameAsync(document, offset, cancellationToken).ConfigureAwait(false); if (result == null) { return null; } Contract.ThrowIfTrue(result.Ranges.IsDefault); return new LinkedEditingRanges { Ranges = result.Ranges.Select(s => ProtocolConversions.TextSpanToRange(s, text)).ToArray(), WordPattern = result.WordPattern }; } } }
1
dotnet/roslyn
56,433
Only allow Contract.ThrowIfNull() to be called on nullable types
We had some places we were calling it on bools.
jasonmalinowski
"2021-09-16T01:20:43Z"
"2021-09-16T18:44:11Z"
736fc1b5e6e2847689c0154b3e5f23ea99dd56af
6d0f4e3f972ceb561b04574e7f957a4ff458e272
Only allow Contract.ThrowIfNull() to be called on nullable types. We had some places we were calling it on bools.
./src/Workspaces/Core/Portable/FindSymbols/SymbolTree/SymbolTreeInfo_Metadata.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 System.Reflection; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Serialization; using Microsoft.CodeAnalysis.Storage; using Microsoft.CodeAnalysis.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.FindSymbols { internal partial class SymbolTreeInfo { private static string GetMetadataNameWithoutBackticks(MetadataReader reader, StringHandle name) { var blobReader = reader.GetBlobReader(name); var backtickIndex = blobReader.IndexOf((byte)'`'); if (backtickIndex == -1) { return reader.GetString(name); } unsafe { return MetadataStringDecoder.DefaultUTF8.GetString( blobReader.CurrentPointer, backtickIndex); } } public static MetadataId GetMetadataIdNoThrow(PortableExecutableReference reference) { try { return reference.GetMetadataId(); } catch (Exception e) when (e is BadImageFormatException || e is IOException) { return null; } } private static Metadata GetMetadataNoThrow(PortableExecutableReference reference) { try { return reference.GetMetadata(); } catch (Exception e) when (e is BadImageFormatException || e is IOException) { return null; } } public static ValueTask<SymbolTreeInfo> GetInfoForMetadataReferenceAsync( Solution solution, PortableExecutableReference reference, bool loadOnly, CancellationToken cancellationToken) { var checksum = GetMetadataChecksum(solution, reference, cancellationToken); return GetInfoForMetadataReferenceAsync( solution, reference, checksum, loadOnly, cancellationToken); } /// <summary> /// Produces a <see cref="SymbolTreeInfo"/> for a given <see cref="PortableExecutableReference"/>. /// Note: will never return null; /// </summary> [PerformanceSensitive("https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1224834", OftenCompletesSynchronously = true)] public static async ValueTask<SymbolTreeInfo> GetInfoForMetadataReferenceAsync( Solution solution, PortableExecutableReference reference, Checksum checksum, bool loadOnly, CancellationToken cancellationToken) { var metadataId = GetMetadataIdNoThrow(reference); if (metadataId == null) return CreateEmpty(checksum); if (s_metadataIdToInfo.TryGetValue(metadataId, out var infoTask)) { var info = await infoTask.GetValueAsync(cancellationToken).ConfigureAwait(false); if (info.Checksum == checksum) return info; } var metadata = GetMetadataNoThrow(reference); if (metadata == null) return CreateEmpty(checksum); // If the data isn't in the table, and the client only wants the data if already loaded, then bail out as we // have no results to give. The data will eventually populate in memory due to // SymbolTreeInfoIncrementalAnalyzer eventually getting around to loading it. if (loadOnly) return null; var database = solution.Options.GetPersistentStorageDatabase(); return await GetInfoForMetadataReferenceSlowAsync( solution.Workspace.Services, SolutionKey.ToSolutionKey(solution), reference, checksum, database, metadata, cancellationToken).ConfigureAwait(false); } private static async Task<SymbolTreeInfo> GetInfoForMetadataReferenceSlowAsync( HostWorkspaceServices services, SolutionKey solutionKey, PortableExecutableReference reference, Checksum checksum, StorageDatabase database, Metadata metadata, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); // Important: this captured async lazy may live a long time *without* computing the final results. As such, // it is important that it note capture any large state. For example, it should not hold onto a Solution // instance. var asyncLazy = s_metadataIdToInfo.GetValue( metadata.Id, id => new AsyncLazy<SymbolTreeInfo>( c => TryCreateMetadataSymbolTreeInfoAsync(services, solutionKey, reference, checksum, database, c), cacheResult: true)); return await asyncLazy.GetValueAsync(cancellationToken).ConfigureAwait(false); } [PerformanceSensitive("https://github.com/dotnet/roslyn/issues/33131", AllowCaptures = false)] public static Checksum GetMetadataChecksum( Solution solution, PortableExecutableReference reference, CancellationToken cancellationToken) { // We can reuse the index for any given reference as long as it hasn't changed. // So our checksum is just the checksum for the PEReference itself. // First see if the value is already in the cache, to avoid an allocation if possible. if (ChecksumCache.TryGetValue(reference, out var cached)) { return cached; } // Break things up to the fast path above and this slow path where we allocate a closure. return GetMetadataChecksumSlow(solution, reference, cancellationToken); } private static Checksum GetMetadataChecksumSlow(Solution solution, PortableExecutableReference reference, CancellationToken cancellationToken) { return ChecksumCache.GetOrCreate(reference, _ => { var serializer = solution.Workspace.Services.GetService<ISerializerService>(); var checksum = serializer.CreateChecksum(reference, cancellationToken); // Include serialization format version in our checksum. That way if the // version ever changes, all persisted data won't match the current checksum // we expect, and we'll recompute things. return Checksum.Create(checksum, SerializationFormatChecksum); }); } private static Task<SymbolTreeInfo> TryCreateMetadataSymbolTreeInfoAsync( HostWorkspaceServices services, SolutionKey solutionKey, PortableExecutableReference reference, Checksum checksum, StorageDatabase database, CancellationToken cancellationToken) { var filePath = reference.FilePath; var result = TryLoadOrCreateAsync( services, solutionKey, checksum, database, loadOnly: false, createAsync: () => CreateMetadataSymbolTreeInfoAsync(services, solutionKey, checksum, database, reference), keySuffix: "_Metadata_" + filePath, tryReadObject: reader => TryReadSymbolTreeInfo(reader, checksum, nodes => GetSpellCheckerAsync(services, solutionKey, checksum, database, filePath, nodes)), cancellationToken: cancellationToken); Contract.ThrowIfNull(result != null); return result; } private static Task<SymbolTreeInfo> CreateMetadataSymbolTreeInfoAsync( HostWorkspaceServices services, SolutionKey solutionKey, Checksum checksum, StorageDatabase database, PortableExecutableReference reference) { var creator = new MetadataInfoCreator(services, solutionKey, checksum, database, reference); return Task.FromResult(creator.Create()); } private struct MetadataInfoCreator : IDisposable { private static readonly Predicate<string> s_isNotNullOrEmpty = s => !string.IsNullOrEmpty(s); private static readonly ObjectPool<List<string>> s_stringListPool = SharedPools.Default<List<string>>(); private readonly HostWorkspaceServices _services; private readonly SolutionKey _solutionKey; private readonly Checksum _checksum; private readonly StorageDatabase _database; private readonly PortableExecutableReference _reference; private readonly OrderPreservingMultiDictionary<string, string> _inheritanceMap; private readonly OrderPreservingMultiDictionary<MetadataNode, MetadataNode> _parentToChildren; private readonly MetadataNode _rootNode; // The metadata reader for the current metadata in the PEReference. private MetadataReader _metadataReader; // The set of type definitions we've read out of the current metadata reader. private readonly List<MetadataDefinition> _allTypeDefinitions; // Map from node represents extension method to list of possible parameter type info. // We can have more than one if there's multiple methods with same name but different receiver type. // e.g. // // public static bool AnotherExtensionMethod1(this int x); // public static bool AnotherExtensionMethod1(this bool x); // private readonly MultiDictionary<MetadataNode, ParameterTypeInfo> _extensionMethodToParameterTypeInfo; private bool _containsExtensionsMethod; public MetadataInfoCreator( HostWorkspaceServices services, SolutionKey solutionKey, Checksum checksum, StorageDatabase database, PortableExecutableReference reference) { _services = services; _solutionKey = solutionKey; _checksum = checksum; _database = database; _reference = reference; _metadataReader = null; _allTypeDefinitions = new List<MetadataDefinition>(); _containsExtensionsMethod = false; _inheritanceMap = OrderPreservingMultiDictionary<string, string>.GetInstance(); _parentToChildren = OrderPreservingMultiDictionary<MetadataNode, MetadataNode>.GetInstance(); _extensionMethodToParameterTypeInfo = new MultiDictionary<MetadataNode, ParameterTypeInfo>(); _rootNode = MetadataNode.Allocate(name: ""); } private static ImmutableArray<ModuleMetadata> GetModuleMetadata(Metadata metadata) { try { if (metadata is AssemblyMetadata assembly) { return assembly.GetModules(); } else if (metadata is ModuleMetadata module) { return ImmutableArray.Create(module); } } catch (BadImageFormatException) { // Trying to get the modules of an assembly can throw. For example, if // there is an invalid public-key defined for the assembly. See: // https://devdiv.visualstudio.com/DevDiv/_workitems?id=234447 } return ImmutableArray<ModuleMetadata>.Empty; } internal SymbolTreeInfo Create() { foreach (var moduleMetadata in GetModuleMetadata(GetMetadataNoThrow(_reference))) { try { _metadataReader = moduleMetadata.GetMetadataReader(); // First, walk all the symbols from metadata, populating the parentToChilren // map accordingly. GenerateMetadataNodes(); // Now, once we populated the initial map, go and get all the inheritance // information for all the types in the metadata. This may refer to // types that we haven't seen yet. We'll add those types to the parentToChildren // map accordingly. PopulateInheritanceMap(); // Clear the set of type definitions we read out of this piece of metadata. _allTypeDefinitions.Clear(); } catch (BadImageFormatException) { // any operation off metadata can throw BadImageFormatException continue; } } var extensionMethodsMap = new MultiDictionary<string, ExtensionMethodInfo>(); var unsortedNodes = GenerateUnsortedNodes(extensionMethodsMap); return CreateSymbolTreeInfo( _services, _solutionKey, _checksum, _database, _reference.FilePath, unsortedNodes, _inheritanceMap, extensionMethodsMap); } public void Dispose() { // Return all the metadata nodes back to the pool so that they can be // used for the next PEReference we read. foreach (var (_, children) in _parentToChildren) { foreach (var child in children) MetadataNode.Free(child); } MetadataNode.Free(_rootNode); _parentToChildren.Free(); _inheritanceMap.Free(); } private void GenerateMetadataNodes() { var globalNamespace = _metadataReader.GetNamespaceDefinitionRoot(); var definitionMap = OrderPreservingMultiDictionary<string, MetadataDefinition>.GetInstance(); try { LookupMetadataDefinitions(globalNamespace, definitionMap); foreach (var (name, definitions) in definitionMap) GenerateMetadataNodes(_rootNode, name, definitions); } finally { definitionMap.Free(); } } private void GenerateMetadataNodes( MetadataNode parentNode, string nodeName, OrderPreservingMultiDictionary<string, MetadataDefinition>.ValueSet definitionsWithSameName) { if (!UnicodeCharacterUtilities.IsValidIdentifier(nodeName)) { return; } var childNode = MetadataNode.Allocate(nodeName); _parentToChildren.Add(parentNode, childNode); // Add all child members var definitionMap = OrderPreservingMultiDictionary<string, MetadataDefinition>.GetInstance(); try { foreach (var definition in definitionsWithSameName) { if (definition.Kind == MetadataDefinitionKind.Member) { // We need to support having multiple methods with same name but different receiver type. _extensionMethodToParameterTypeInfo.Add(childNode, definition.ReceiverTypeInfo); } LookupMetadataDefinitions(definition, definitionMap); } foreach (var (name, definitions) in definitionMap) GenerateMetadataNodes(childNode, name, definitions); } finally { definitionMap.Free(); } } private void LookupMetadataDefinitions( MetadataDefinition definition, OrderPreservingMultiDictionary<string, MetadataDefinition> definitionMap) { switch (definition.Kind) { case MetadataDefinitionKind.Namespace: LookupMetadataDefinitions(definition.Namespace, definitionMap); break; case MetadataDefinitionKind.Type: LookupMetadataDefinitions(definition.Type, definitionMap); break; } } private void LookupMetadataDefinitions( TypeDefinition typeDefinition, OrderPreservingMultiDictionary<string, MetadataDefinition> definitionMap) { // Only bother looking for extension methods in static types. // Note this check means we would ignore extension methods declared in assemblies // compiled from VB code, since a module in VB is compiled into class with // "sealed" attribute but not "abstract". // Although this can be addressed by checking custom attributes, // we believe this is not a common scenario to warrant potential perf impact. if ((typeDefinition.Attributes & TypeAttributes.Abstract) != 0 && (typeDefinition.Attributes & TypeAttributes.Sealed) != 0) { foreach (var child in typeDefinition.GetMethods()) { var method = _metadataReader.GetMethodDefinition(child); if ((method.Attributes & MethodAttributes.SpecialName) != 0 || (method.Attributes & MethodAttributes.RTSpecialName) != 0) { continue; } // SymbolTreeInfo is only searched for types and extension methods. // So we don't want to pull in all methods here. As a simple approximation // we just pull in methods that have attributes on them. if ((method.Attributes & MethodAttributes.MemberAccessMask) == MethodAttributes.Public && (method.Attributes & MethodAttributes.Static) != 0 && method.GetParameters().Count > 0 && method.GetCustomAttributes().Count > 0) { // Decode method signature to get the receiver type name (i.e. type name for the first parameter) var blob = _metadataReader.GetBlobReader(method.Signature); var decoder = new SignatureDecoder<ParameterTypeInfo, object>(ParameterTypeInfoProvider.Instance, _metadataReader, genericContext: null); var signature = decoder.DecodeMethodSignature(ref blob); // It'd be good if we don't need to go through all parameters and make unnecessary allocations. // However, this is not possible with meatadata reader API right now (although it's possible by copying code from meatadata reader implementaion) if (signature.ParameterTypes.Length > 0) { _containsExtensionsMethod = true; var firstParameterTypeInfo = signature.ParameterTypes[0]; var definition = new MetadataDefinition(MetadataDefinitionKind.Member, _metadataReader.GetString(method.Name), firstParameterTypeInfo); definitionMap.Add(definition.Name, definition); } } } } foreach (var child in typeDefinition.GetNestedTypes()) { var type = _metadataReader.GetTypeDefinition(child); // We don't include internals from metadata assemblies. It's less likely that // a project would have IVT to it and so it helps us save on memory. It also // means we can avoid loading lots and lots of obfuscated code in the case the // dll was obfuscated. if (IsPublic(type.Attributes)) { var definition = MetadataDefinition.Create(_metadataReader, type); definitionMap.Add(definition.Name, definition); _allTypeDefinitions.Add(definition); } } } private void LookupMetadataDefinitions( NamespaceDefinition namespaceDefinition, OrderPreservingMultiDictionary<string, MetadataDefinition> definitionMap) { foreach (var child in namespaceDefinition.NamespaceDefinitions) { var definition = MetadataDefinition.Create(_metadataReader, child); definitionMap.Add(definition.Name, definition); } foreach (var child in namespaceDefinition.TypeDefinitions) { var typeDefinition = _metadataReader.GetTypeDefinition(child); if (IsPublic(typeDefinition.Attributes)) { var definition = MetadataDefinition.Create(_metadataReader, typeDefinition); definitionMap.Add(definition.Name, definition); _allTypeDefinitions.Add(definition); } } } private static bool IsPublic(TypeAttributes attributes) { var masked = attributes & TypeAttributes.VisibilityMask; return masked == TypeAttributes.Public || masked == TypeAttributes.NestedPublic; } private void PopulateInheritanceMap() { foreach (var typeDefinition in _allTypeDefinitions) { Debug.Assert(typeDefinition.Kind == MetadataDefinitionKind.Type); PopulateInheritance(typeDefinition); } } private void PopulateInheritance(MetadataDefinition metadataTypeDefinition) { var derivedTypeDefinition = metadataTypeDefinition.Type; var interfaceImplHandles = derivedTypeDefinition.GetInterfaceImplementations(); if (derivedTypeDefinition.BaseType.IsNil && interfaceImplHandles.Count == 0) { return; } var derivedTypeSimpleName = metadataTypeDefinition.Name; PopulateInheritance(derivedTypeSimpleName, derivedTypeDefinition.BaseType); foreach (var interfaceImplHandle in interfaceImplHandles) { if (!interfaceImplHandle.IsNil) { var interfaceImpl = _metadataReader.GetInterfaceImplementation(interfaceImplHandle); PopulateInheritance(derivedTypeSimpleName, interfaceImpl.Interface); } } } private void PopulateInheritance( string derivedTypeSimpleName, EntityHandle baseTypeOrInterfaceHandle) { if (baseTypeOrInterfaceHandle.IsNil) { return; } var baseTypeNameParts = s_stringListPool.Allocate(); try { AddBaseTypeNameParts(baseTypeOrInterfaceHandle, baseTypeNameParts); if (baseTypeNameParts.Count > 0 && baseTypeNameParts.TrueForAll(s_isNotNullOrEmpty)) { var lastPart = baseTypeNameParts.Last(); if (!_inheritanceMap.Contains(lastPart, derivedTypeSimpleName)) { _inheritanceMap.Add(baseTypeNameParts.Last(), derivedTypeSimpleName); } // The parent/child map may not know about this base-type yet (for example, // if the base type is a reference to a type outside of this assembly). // Add the base type to our map so we'll be able to resolve it later if // requested. EnsureParentsAndChildren(baseTypeNameParts); } } finally { s_stringListPool.ClearAndFree(baseTypeNameParts); } } private void AddBaseTypeNameParts( EntityHandle baseTypeOrInterfaceHandle, List<string> simpleNames) { var typeDefOrRefHandle = GetTypeDefOrRefHandle(baseTypeOrInterfaceHandle); if (typeDefOrRefHandle.Kind == HandleKind.TypeDefinition) { AddTypeDefinitionNameParts((TypeDefinitionHandle)typeDefOrRefHandle, simpleNames); } else if (typeDefOrRefHandle.Kind == HandleKind.TypeReference) { AddTypeReferenceNameParts((TypeReferenceHandle)typeDefOrRefHandle, simpleNames); } } private void AddTypeDefinitionNameParts( TypeDefinitionHandle handle, List<string> simpleNames) { var typeDefinition = _metadataReader.GetTypeDefinition(handle); var declaringType = typeDefinition.GetDeclaringType(); if (declaringType.IsNil) { // Not a nested type, just add the containing namespace. AddNamespaceParts(typeDefinition.NamespaceDefinition, simpleNames); } else { // We're a nested type, recurse and add the type we're declared in. // It will handle adding the namespace properly. AddTypeDefinitionNameParts(declaringType, simpleNames); } // Now add the simple name of the type itself. simpleNames.Add(GetMetadataNameWithoutBackticks(_metadataReader, typeDefinition.Name)); } private void AddNamespaceParts( StringHandle namespaceHandle, List<string> simpleNames) { var blobReader = _metadataReader.GetBlobReader(namespaceHandle); while (true) { var dotIndex = blobReader.IndexOf((byte)'.'); unsafe { // Note: we won't get any string sharing as we're just using the // default string decoded. However, that's ok. We only produce // these strings when we first read metadata. Then we create and // persist our own index. In the future when we read in that index // there's no way for us to share strings between us and the // compiler at that point. if (dotIndex == -1) { simpleNames.Add(MetadataStringDecoder.DefaultUTF8.GetString( blobReader.CurrentPointer, blobReader.RemainingBytes)); return; } else { simpleNames.Add(MetadataStringDecoder.DefaultUTF8.GetString( blobReader.CurrentPointer, dotIndex)); blobReader.Offset += dotIndex + 1; } } } } private void AddNamespaceParts( NamespaceDefinitionHandle namespaceHandle, List<string> simpleNames) { if (namespaceHandle.IsNil) { return; } var namespaceDefinition = _metadataReader.GetNamespaceDefinition(namespaceHandle); AddNamespaceParts(namespaceDefinition.Parent, simpleNames); simpleNames.Add(_metadataReader.GetString(namespaceDefinition.Name)); } private void AddTypeReferenceNameParts(TypeReferenceHandle handle, List<string> simpleNames) { var typeReference = _metadataReader.GetTypeReference(handle); AddNamespaceParts(typeReference.Namespace, simpleNames); simpleNames.Add(GetMetadataNameWithoutBackticks(_metadataReader, typeReference.Name)); } private EntityHandle GetTypeDefOrRefHandle(EntityHandle baseTypeOrInterfaceHandle) { switch (baseTypeOrInterfaceHandle.Kind) { case HandleKind.TypeDefinition: case HandleKind.TypeReference: return baseTypeOrInterfaceHandle; case HandleKind.TypeSpecification: return FirstEntityHandleProvider.Instance.GetTypeFromSpecification( _metadataReader, (TypeSpecificationHandle)baseTypeOrInterfaceHandle); default: return default; } } private void EnsureParentsAndChildren(List<string> simpleNames) { var currentNode = _rootNode; foreach (var simpleName in simpleNames) { var childNode = GetOrCreateChildNode(currentNode, simpleName); currentNode = childNode; } } private MetadataNode GetOrCreateChildNode( MetadataNode currentNode, string simpleName) { if (_parentToChildren.TryGetValue(currentNode, static (childNode, simpleName) => childNode.Name == simpleName, simpleName, out var childNode)) { // Found an existing child node. Just return that and all // future parts off of it. return childNode; } // Couldn't find a child node with this name. Make a new node for // it and return that for all future parts to be added to. var newChildNode = MetadataNode.Allocate(simpleName); _parentToChildren.Add(currentNode, newChildNode); return newChildNode; } private ImmutableArray<BuilderNode> GenerateUnsortedNodes(MultiDictionary<string, ExtensionMethodInfo> receiverTypeNameToMethodMap) { var unsortedNodes = ArrayBuilder<BuilderNode>.GetInstance(); unsortedNodes.Add(BuilderNode.RootNode); AddUnsortedNodes(unsortedNodes, receiverTypeNameToMethodMap, parentNode: _rootNode, parentIndex: 0, fullyQualifiedContainerName: _containsExtensionsMethod ? "" : null); return unsortedNodes.ToImmutableAndFree(); } private void AddUnsortedNodes(ArrayBuilder<BuilderNode> unsortedNodes, MultiDictionary<string, ExtensionMethodInfo> receiverTypeNameToMethodMap, MetadataNode parentNode, int parentIndex, string fullyQualifiedContainerName) { foreach (var child in _parentToChildren[parentNode]) { var childNode = new BuilderNode(child.Name, parentIndex, _extensionMethodToParameterTypeInfo[child]); var childIndex = unsortedNodes.Count; unsortedNodes.Add(childNode); if (fullyQualifiedContainerName != null) { foreach (var parameterTypeInfo in _extensionMethodToParameterTypeInfo[child]) { // We do not differentiate array of different kinds for simplicity. // e.g. int[], int[][], int[,], etc. are all represented as int[] in the index. // similar for complex receiver types, "[]" means it's an array type, "" otherwise. var parameterTypeName = (parameterTypeInfo.IsComplexType, parameterTypeInfo.IsArray) switch { (true, true) => Extensions.ComplexArrayReceiverTypeName, // complex array type, e.g. "T[,]" (true, false) => Extensions.ComplexReceiverTypeName, // complex non-array type, e.g. "T" (false, true) => parameterTypeInfo.Name + Extensions.ArrayReceiverTypeNameSuffix, // simple array type, e.g. "int[][,]" (false, false) => parameterTypeInfo.Name // simple non-array type, e.g. "int" }; receiverTypeNameToMethodMap.Add(parameterTypeName, new ExtensionMethodInfo(fullyQualifiedContainerName, child.Name)); } } AddUnsortedNodes(unsortedNodes, receiverTypeNameToMethodMap, child, childIndex, Concat(fullyQualifiedContainerName, child.Name)); } static string Concat(string containerName, string name) { if (containerName == null) { return null; } if (containerName.Length == 0) { return name; } return containerName + "." + name; } } } private class MetadataNode { public string Name { get; private set; } private static readonly ObjectPool<MetadataNode> s_pool = SharedPools.Default<MetadataNode>(); public static MetadataNode Allocate(string name) { var node = s_pool.Allocate(); Debug.Assert(node.Name == null); node.Name = name; return node; } public static void Free(MetadataNode node) { Debug.Assert(node.Name != null); node.Name = null; s_pool.Free(node); } } private enum MetadataDefinitionKind { Namespace, Type, Member, } private struct MetadataDefinition { public string Name { get; } public MetadataDefinitionKind Kind { get; } /// <summary> /// Only applies to member kind. Represents the type info of the first parameter. /// </summary> public ParameterTypeInfo ReceiverTypeInfo { get; } public NamespaceDefinition Namespace { get; private set; } public TypeDefinition Type { get; private set; } public MetadataDefinition(MetadataDefinitionKind kind, string name, ParameterTypeInfo receiverTypeInfo = default) : this() { Kind = kind; Name = name; ReceiverTypeInfo = receiverTypeInfo; } public static MetadataDefinition Create( MetadataReader reader, NamespaceDefinitionHandle namespaceHandle) { var definition = reader.GetNamespaceDefinition(namespaceHandle); return new MetadataDefinition( MetadataDefinitionKind.Namespace, reader.GetString(definition.Name)) { Namespace = definition }; } public static MetadataDefinition Create( MetadataReader reader, TypeDefinition definition) { var typeName = GetMetadataNameWithoutBackticks(reader, definition.Name); return new MetadataDefinition(MetadataDefinitionKind.Type, typeName) { Type = definition }; } } } }
// Licensed to the .NET Foundation under one or more 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 System.Reflection; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Serialization; using Microsoft.CodeAnalysis.Storage; using Microsoft.CodeAnalysis.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.FindSymbols { internal partial class SymbolTreeInfo { private static string GetMetadataNameWithoutBackticks(MetadataReader reader, StringHandle name) { var blobReader = reader.GetBlobReader(name); var backtickIndex = blobReader.IndexOf((byte)'`'); if (backtickIndex == -1) { return reader.GetString(name); } unsafe { return MetadataStringDecoder.DefaultUTF8.GetString( blobReader.CurrentPointer, backtickIndex); } } public static MetadataId GetMetadataIdNoThrow(PortableExecutableReference reference) { try { return reference.GetMetadataId(); } catch (Exception e) when (e is BadImageFormatException || e is IOException) { return null; } } private static Metadata GetMetadataNoThrow(PortableExecutableReference reference) { try { return reference.GetMetadata(); } catch (Exception e) when (e is BadImageFormatException || e is IOException) { return null; } } public static ValueTask<SymbolTreeInfo> GetInfoForMetadataReferenceAsync( Solution solution, PortableExecutableReference reference, bool loadOnly, CancellationToken cancellationToken) { var checksum = GetMetadataChecksum(solution, reference, cancellationToken); return GetInfoForMetadataReferenceAsync( solution, reference, checksum, loadOnly, cancellationToken); } /// <summary> /// Produces a <see cref="SymbolTreeInfo"/> for a given <see cref="PortableExecutableReference"/>. /// Note: will never return null; /// </summary> [PerformanceSensitive("https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1224834", OftenCompletesSynchronously = true)] public static async ValueTask<SymbolTreeInfo> GetInfoForMetadataReferenceAsync( Solution solution, PortableExecutableReference reference, Checksum checksum, bool loadOnly, CancellationToken cancellationToken) { var metadataId = GetMetadataIdNoThrow(reference); if (metadataId == null) return CreateEmpty(checksum); if (s_metadataIdToInfo.TryGetValue(metadataId, out var infoTask)) { var info = await infoTask.GetValueAsync(cancellationToken).ConfigureAwait(false); if (info.Checksum == checksum) return info; } var metadata = GetMetadataNoThrow(reference); if (metadata == null) return CreateEmpty(checksum); // If the data isn't in the table, and the client only wants the data if already loaded, then bail out as we // have no results to give. The data will eventually populate in memory due to // SymbolTreeInfoIncrementalAnalyzer eventually getting around to loading it. if (loadOnly) return null; var database = solution.Options.GetPersistentStorageDatabase(); return await GetInfoForMetadataReferenceSlowAsync( solution.Workspace.Services, SolutionKey.ToSolutionKey(solution), reference, checksum, database, metadata, cancellationToken).ConfigureAwait(false); } private static async Task<SymbolTreeInfo> GetInfoForMetadataReferenceSlowAsync( HostWorkspaceServices services, SolutionKey solutionKey, PortableExecutableReference reference, Checksum checksum, StorageDatabase database, Metadata metadata, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); // Important: this captured async lazy may live a long time *without* computing the final results. As such, // it is important that it note capture any large state. For example, it should not hold onto a Solution // instance. var asyncLazy = s_metadataIdToInfo.GetValue( metadata.Id, id => new AsyncLazy<SymbolTreeInfo>( c => TryCreateMetadataSymbolTreeInfoAsync(services, solutionKey, reference, checksum, database, c), cacheResult: true)); return await asyncLazy.GetValueAsync(cancellationToken).ConfigureAwait(false); } [PerformanceSensitive("https://github.com/dotnet/roslyn/issues/33131", AllowCaptures = false)] public static Checksum GetMetadataChecksum( Solution solution, PortableExecutableReference reference, CancellationToken cancellationToken) { // We can reuse the index for any given reference as long as it hasn't changed. // So our checksum is just the checksum for the PEReference itself. // First see if the value is already in the cache, to avoid an allocation if possible. if (ChecksumCache.TryGetValue(reference, out var cached)) { return cached; } // Break things up to the fast path above and this slow path where we allocate a closure. return GetMetadataChecksumSlow(solution, reference, cancellationToken); } private static Checksum GetMetadataChecksumSlow(Solution solution, PortableExecutableReference reference, CancellationToken cancellationToken) { return ChecksumCache.GetOrCreate(reference, _ => { var serializer = solution.Workspace.Services.GetService<ISerializerService>(); var checksum = serializer.CreateChecksum(reference, cancellationToken); // Include serialization format version in our checksum. That way if the // version ever changes, all persisted data won't match the current checksum // we expect, and we'll recompute things. return Checksum.Create(checksum, SerializationFormatChecksum); }); } private static Task<SymbolTreeInfo> TryCreateMetadataSymbolTreeInfoAsync( HostWorkspaceServices services, SolutionKey solutionKey, PortableExecutableReference reference, Checksum checksum, StorageDatabase database, CancellationToken cancellationToken) { var filePath = reference.FilePath; var result = TryLoadOrCreateAsync( services, solutionKey, checksum, database, loadOnly: false, createAsync: () => CreateMetadataSymbolTreeInfoAsync(services, solutionKey, checksum, database, reference), keySuffix: "_Metadata_" + filePath, tryReadObject: reader => TryReadSymbolTreeInfo(reader, checksum, nodes => GetSpellCheckerAsync(services, solutionKey, checksum, database, filePath, nodes)), cancellationToken: cancellationToken); Contract.ThrowIfNull(result); return result; } private static Task<SymbolTreeInfo> CreateMetadataSymbolTreeInfoAsync( HostWorkspaceServices services, SolutionKey solutionKey, Checksum checksum, StorageDatabase database, PortableExecutableReference reference) { var creator = new MetadataInfoCreator(services, solutionKey, checksum, database, reference); return Task.FromResult(creator.Create()); } private struct MetadataInfoCreator : IDisposable { private static readonly Predicate<string> s_isNotNullOrEmpty = s => !string.IsNullOrEmpty(s); private static readonly ObjectPool<List<string>> s_stringListPool = SharedPools.Default<List<string>>(); private readonly HostWorkspaceServices _services; private readonly SolutionKey _solutionKey; private readonly Checksum _checksum; private readonly StorageDatabase _database; private readonly PortableExecutableReference _reference; private readonly OrderPreservingMultiDictionary<string, string> _inheritanceMap; private readonly OrderPreservingMultiDictionary<MetadataNode, MetadataNode> _parentToChildren; private readonly MetadataNode _rootNode; // The metadata reader for the current metadata in the PEReference. private MetadataReader _metadataReader; // The set of type definitions we've read out of the current metadata reader. private readonly List<MetadataDefinition> _allTypeDefinitions; // Map from node represents extension method to list of possible parameter type info. // We can have more than one if there's multiple methods with same name but different receiver type. // e.g. // // public static bool AnotherExtensionMethod1(this int x); // public static bool AnotherExtensionMethod1(this bool x); // private readonly MultiDictionary<MetadataNode, ParameterTypeInfo> _extensionMethodToParameterTypeInfo; private bool _containsExtensionsMethod; public MetadataInfoCreator( HostWorkspaceServices services, SolutionKey solutionKey, Checksum checksum, StorageDatabase database, PortableExecutableReference reference) { _services = services; _solutionKey = solutionKey; _checksum = checksum; _database = database; _reference = reference; _metadataReader = null; _allTypeDefinitions = new List<MetadataDefinition>(); _containsExtensionsMethod = false; _inheritanceMap = OrderPreservingMultiDictionary<string, string>.GetInstance(); _parentToChildren = OrderPreservingMultiDictionary<MetadataNode, MetadataNode>.GetInstance(); _extensionMethodToParameterTypeInfo = new MultiDictionary<MetadataNode, ParameterTypeInfo>(); _rootNode = MetadataNode.Allocate(name: ""); } private static ImmutableArray<ModuleMetadata> GetModuleMetadata(Metadata metadata) { try { if (metadata is AssemblyMetadata assembly) { return assembly.GetModules(); } else if (metadata is ModuleMetadata module) { return ImmutableArray.Create(module); } } catch (BadImageFormatException) { // Trying to get the modules of an assembly can throw. For example, if // there is an invalid public-key defined for the assembly. See: // https://devdiv.visualstudio.com/DevDiv/_workitems?id=234447 } return ImmutableArray<ModuleMetadata>.Empty; } internal SymbolTreeInfo Create() { foreach (var moduleMetadata in GetModuleMetadata(GetMetadataNoThrow(_reference))) { try { _metadataReader = moduleMetadata.GetMetadataReader(); // First, walk all the symbols from metadata, populating the parentToChilren // map accordingly. GenerateMetadataNodes(); // Now, once we populated the initial map, go and get all the inheritance // information for all the types in the metadata. This may refer to // types that we haven't seen yet. We'll add those types to the parentToChildren // map accordingly. PopulateInheritanceMap(); // Clear the set of type definitions we read out of this piece of metadata. _allTypeDefinitions.Clear(); } catch (BadImageFormatException) { // any operation off metadata can throw BadImageFormatException continue; } } var extensionMethodsMap = new MultiDictionary<string, ExtensionMethodInfo>(); var unsortedNodes = GenerateUnsortedNodes(extensionMethodsMap); return CreateSymbolTreeInfo( _services, _solutionKey, _checksum, _database, _reference.FilePath, unsortedNodes, _inheritanceMap, extensionMethodsMap); } public void Dispose() { // Return all the metadata nodes back to the pool so that they can be // used for the next PEReference we read. foreach (var (_, children) in _parentToChildren) { foreach (var child in children) MetadataNode.Free(child); } MetadataNode.Free(_rootNode); _parentToChildren.Free(); _inheritanceMap.Free(); } private void GenerateMetadataNodes() { var globalNamespace = _metadataReader.GetNamespaceDefinitionRoot(); var definitionMap = OrderPreservingMultiDictionary<string, MetadataDefinition>.GetInstance(); try { LookupMetadataDefinitions(globalNamespace, definitionMap); foreach (var (name, definitions) in definitionMap) GenerateMetadataNodes(_rootNode, name, definitions); } finally { definitionMap.Free(); } } private void GenerateMetadataNodes( MetadataNode parentNode, string nodeName, OrderPreservingMultiDictionary<string, MetadataDefinition>.ValueSet definitionsWithSameName) { if (!UnicodeCharacterUtilities.IsValidIdentifier(nodeName)) { return; } var childNode = MetadataNode.Allocate(nodeName); _parentToChildren.Add(parentNode, childNode); // Add all child members var definitionMap = OrderPreservingMultiDictionary<string, MetadataDefinition>.GetInstance(); try { foreach (var definition in definitionsWithSameName) { if (definition.Kind == MetadataDefinitionKind.Member) { // We need to support having multiple methods with same name but different receiver type. _extensionMethodToParameterTypeInfo.Add(childNode, definition.ReceiverTypeInfo); } LookupMetadataDefinitions(definition, definitionMap); } foreach (var (name, definitions) in definitionMap) GenerateMetadataNodes(childNode, name, definitions); } finally { definitionMap.Free(); } } private void LookupMetadataDefinitions( MetadataDefinition definition, OrderPreservingMultiDictionary<string, MetadataDefinition> definitionMap) { switch (definition.Kind) { case MetadataDefinitionKind.Namespace: LookupMetadataDefinitions(definition.Namespace, definitionMap); break; case MetadataDefinitionKind.Type: LookupMetadataDefinitions(definition.Type, definitionMap); break; } } private void LookupMetadataDefinitions( TypeDefinition typeDefinition, OrderPreservingMultiDictionary<string, MetadataDefinition> definitionMap) { // Only bother looking for extension methods in static types. // Note this check means we would ignore extension methods declared in assemblies // compiled from VB code, since a module in VB is compiled into class with // "sealed" attribute but not "abstract". // Although this can be addressed by checking custom attributes, // we believe this is not a common scenario to warrant potential perf impact. if ((typeDefinition.Attributes & TypeAttributes.Abstract) != 0 && (typeDefinition.Attributes & TypeAttributes.Sealed) != 0) { foreach (var child in typeDefinition.GetMethods()) { var method = _metadataReader.GetMethodDefinition(child); if ((method.Attributes & MethodAttributes.SpecialName) != 0 || (method.Attributes & MethodAttributes.RTSpecialName) != 0) { continue; } // SymbolTreeInfo is only searched for types and extension methods. // So we don't want to pull in all methods here. As a simple approximation // we just pull in methods that have attributes on them. if ((method.Attributes & MethodAttributes.MemberAccessMask) == MethodAttributes.Public && (method.Attributes & MethodAttributes.Static) != 0 && method.GetParameters().Count > 0 && method.GetCustomAttributes().Count > 0) { // Decode method signature to get the receiver type name (i.e. type name for the first parameter) var blob = _metadataReader.GetBlobReader(method.Signature); var decoder = new SignatureDecoder<ParameterTypeInfo, object>(ParameterTypeInfoProvider.Instance, _metadataReader, genericContext: null); var signature = decoder.DecodeMethodSignature(ref blob); // It'd be good if we don't need to go through all parameters and make unnecessary allocations. // However, this is not possible with meatadata reader API right now (although it's possible by copying code from meatadata reader implementaion) if (signature.ParameterTypes.Length > 0) { _containsExtensionsMethod = true; var firstParameterTypeInfo = signature.ParameterTypes[0]; var definition = new MetadataDefinition(MetadataDefinitionKind.Member, _metadataReader.GetString(method.Name), firstParameterTypeInfo); definitionMap.Add(definition.Name, definition); } } } } foreach (var child in typeDefinition.GetNestedTypes()) { var type = _metadataReader.GetTypeDefinition(child); // We don't include internals from metadata assemblies. It's less likely that // a project would have IVT to it and so it helps us save on memory. It also // means we can avoid loading lots and lots of obfuscated code in the case the // dll was obfuscated. if (IsPublic(type.Attributes)) { var definition = MetadataDefinition.Create(_metadataReader, type); definitionMap.Add(definition.Name, definition); _allTypeDefinitions.Add(definition); } } } private void LookupMetadataDefinitions( NamespaceDefinition namespaceDefinition, OrderPreservingMultiDictionary<string, MetadataDefinition> definitionMap) { foreach (var child in namespaceDefinition.NamespaceDefinitions) { var definition = MetadataDefinition.Create(_metadataReader, child); definitionMap.Add(definition.Name, definition); } foreach (var child in namespaceDefinition.TypeDefinitions) { var typeDefinition = _metadataReader.GetTypeDefinition(child); if (IsPublic(typeDefinition.Attributes)) { var definition = MetadataDefinition.Create(_metadataReader, typeDefinition); definitionMap.Add(definition.Name, definition); _allTypeDefinitions.Add(definition); } } } private static bool IsPublic(TypeAttributes attributes) { var masked = attributes & TypeAttributes.VisibilityMask; return masked == TypeAttributes.Public || masked == TypeAttributes.NestedPublic; } private void PopulateInheritanceMap() { foreach (var typeDefinition in _allTypeDefinitions) { Debug.Assert(typeDefinition.Kind == MetadataDefinitionKind.Type); PopulateInheritance(typeDefinition); } } private void PopulateInheritance(MetadataDefinition metadataTypeDefinition) { var derivedTypeDefinition = metadataTypeDefinition.Type; var interfaceImplHandles = derivedTypeDefinition.GetInterfaceImplementations(); if (derivedTypeDefinition.BaseType.IsNil && interfaceImplHandles.Count == 0) { return; } var derivedTypeSimpleName = metadataTypeDefinition.Name; PopulateInheritance(derivedTypeSimpleName, derivedTypeDefinition.BaseType); foreach (var interfaceImplHandle in interfaceImplHandles) { if (!interfaceImplHandle.IsNil) { var interfaceImpl = _metadataReader.GetInterfaceImplementation(interfaceImplHandle); PopulateInheritance(derivedTypeSimpleName, interfaceImpl.Interface); } } } private void PopulateInheritance( string derivedTypeSimpleName, EntityHandle baseTypeOrInterfaceHandle) { if (baseTypeOrInterfaceHandle.IsNil) { return; } var baseTypeNameParts = s_stringListPool.Allocate(); try { AddBaseTypeNameParts(baseTypeOrInterfaceHandle, baseTypeNameParts); if (baseTypeNameParts.Count > 0 && baseTypeNameParts.TrueForAll(s_isNotNullOrEmpty)) { var lastPart = baseTypeNameParts.Last(); if (!_inheritanceMap.Contains(lastPart, derivedTypeSimpleName)) { _inheritanceMap.Add(baseTypeNameParts.Last(), derivedTypeSimpleName); } // The parent/child map may not know about this base-type yet (for example, // if the base type is a reference to a type outside of this assembly). // Add the base type to our map so we'll be able to resolve it later if // requested. EnsureParentsAndChildren(baseTypeNameParts); } } finally { s_stringListPool.ClearAndFree(baseTypeNameParts); } } private void AddBaseTypeNameParts( EntityHandle baseTypeOrInterfaceHandle, List<string> simpleNames) { var typeDefOrRefHandle = GetTypeDefOrRefHandle(baseTypeOrInterfaceHandle); if (typeDefOrRefHandle.Kind == HandleKind.TypeDefinition) { AddTypeDefinitionNameParts((TypeDefinitionHandle)typeDefOrRefHandle, simpleNames); } else if (typeDefOrRefHandle.Kind == HandleKind.TypeReference) { AddTypeReferenceNameParts((TypeReferenceHandle)typeDefOrRefHandle, simpleNames); } } private void AddTypeDefinitionNameParts( TypeDefinitionHandle handle, List<string> simpleNames) { var typeDefinition = _metadataReader.GetTypeDefinition(handle); var declaringType = typeDefinition.GetDeclaringType(); if (declaringType.IsNil) { // Not a nested type, just add the containing namespace. AddNamespaceParts(typeDefinition.NamespaceDefinition, simpleNames); } else { // We're a nested type, recurse and add the type we're declared in. // It will handle adding the namespace properly. AddTypeDefinitionNameParts(declaringType, simpleNames); } // Now add the simple name of the type itself. simpleNames.Add(GetMetadataNameWithoutBackticks(_metadataReader, typeDefinition.Name)); } private void AddNamespaceParts( StringHandle namespaceHandle, List<string> simpleNames) { var blobReader = _metadataReader.GetBlobReader(namespaceHandle); while (true) { var dotIndex = blobReader.IndexOf((byte)'.'); unsafe { // Note: we won't get any string sharing as we're just using the // default string decoded. However, that's ok. We only produce // these strings when we first read metadata. Then we create and // persist our own index. In the future when we read in that index // there's no way for us to share strings between us and the // compiler at that point. if (dotIndex == -1) { simpleNames.Add(MetadataStringDecoder.DefaultUTF8.GetString( blobReader.CurrentPointer, blobReader.RemainingBytes)); return; } else { simpleNames.Add(MetadataStringDecoder.DefaultUTF8.GetString( blobReader.CurrentPointer, dotIndex)); blobReader.Offset += dotIndex + 1; } } } } private void AddNamespaceParts( NamespaceDefinitionHandle namespaceHandle, List<string> simpleNames) { if (namespaceHandle.IsNil) { return; } var namespaceDefinition = _metadataReader.GetNamespaceDefinition(namespaceHandle); AddNamespaceParts(namespaceDefinition.Parent, simpleNames); simpleNames.Add(_metadataReader.GetString(namespaceDefinition.Name)); } private void AddTypeReferenceNameParts(TypeReferenceHandle handle, List<string> simpleNames) { var typeReference = _metadataReader.GetTypeReference(handle); AddNamespaceParts(typeReference.Namespace, simpleNames); simpleNames.Add(GetMetadataNameWithoutBackticks(_metadataReader, typeReference.Name)); } private EntityHandle GetTypeDefOrRefHandle(EntityHandle baseTypeOrInterfaceHandle) { switch (baseTypeOrInterfaceHandle.Kind) { case HandleKind.TypeDefinition: case HandleKind.TypeReference: return baseTypeOrInterfaceHandle; case HandleKind.TypeSpecification: return FirstEntityHandleProvider.Instance.GetTypeFromSpecification( _metadataReader, (TypeSpecificationHandle)baseTypeOrInterfaceHandle); default: return default; } } private void EnsureParentsAndChildren(List<string> simpleNames) { var currentNode = _rootNode; foreach (var simpleName in simpleNames) { var childNode = GetOrCreateChildNode(currentNode, simpleName); currentNode = childNode; } } private MetadataNode GetOrCreateChildNode( MetadataNode currentNode, string simpleName) { if (_parentToChildren.TryGetValue(currentNode, static (childNode, simpleName) => childNode.Name == simpleName, simpleName, out var childNode)) { // Found an existing child node. Just return that and all // future parts off of it. return childNode; } // Couldn't find a child node with this name. Make a new node for // it and return that for all future parts to be added to. var newChildNode = MetadataNode.Allocate(simpleName); _parentToChildren.Add(currentNode, newChildNode); return newChildNode; } private ImmutableArray<BuilderNode> GenerateUnsortedNodes(MultiDictionary<string, ExtensionMethodInfo> receiverTypeNameToMethodMap) { var unsortedNodes = ArrayBuilder<BuilderNode>.GetInstance(); unsortedNodes.Add(BuilderNode.RootNode); AddUnsortedNodes(unsortedNodes, receiverTypeNameToMethodMap, parentNode: _rootNode, parentIndex: 0, fullyQualifiedContainerName: _containsExtensionsMethod ? "" : null); return unsortedNodes.ToImmutableAndFree(); } private void AddUnsortedNodes(ArrayBuilder<BuilderNode> unsortedNodes, MultiDictionary<string, ExtensionMethodInfo> receiverTypeNameToMethodMap, MetadataNode parentNode, int parentIndex, string fullyQualifiedContainerName) { foreach (var child in _parentToChildren[parentNode]) { var childNode = new BuilderNode(child.Name, parentIndex, _extensionMethodToParameterTypeInfo[child]); var childIndex = unsortedNodes.Count; unsortedNodes.Add(childNode); if (fullyQualifiedContainerName != null) { foreach (var parameterTypeInfo in _extensionMethodToParameterTypeInfo[child]) { // We do not differentiate array of different kinds for simplicity. // e.g. int[], int[][], int[,], etc. are all represented as int[] in the index. // similar for complex receiver types, "[]" means it's an array type, "" otherwise. var parameterTypeName = (parameterTypeInfo.IsComplexType, parameterTypeInfo.IsArray) switch { (true, true) => Extensions.ComplexArrayReceiverTypeName, // complex array type, e.g. "T[,]" (true, false) => Extensions.ComplexReceiverTypeName, // complex non-array type, e.g. "T" (false, true) => parameterTypeInfo.Name + Extensions.ArrayReceiverTypeNameSuffix, // simple array type, e.g. "int[][,]" (false, false) => parameterTypeInfo.Name // simple non-array type, e.g. "int" }; receiverTypeNameToMethodMap.Add(parameterTypeName, new ExtensionMethodInfo(fullyQualifiedContainerName, child.Name)); } } AddUnsortedNodes(unsortedNodes, receiverTypeNameToMethodMap, child, childIndex, Concat(fullyQualifiedContainerName, child.Name)); } static string Concat(string containerName, string name) { if (containerName == null) { return null; } if (containerName.Length == 0) { return name; } return containerName + "." + name; } } } private class MetadataNode { public string Name { get; private set; } private static readonly ObjectPool<MetadataNode> s_pool = SharedPools.Default<MetadataNode>(); public static MetadataNode Allocate(string name) { var node = s_pool.Allocate(); Debug.Assert(node.Name == null); node.Name = name; return node; } public static void Free(MetadataNode node) { Debug.Assert(node.Name != null); node.Name = null; s_pool.Free(node); } } private enum MetadataDefinitionKind { Namespace, Type, Member, } private struct MetadataDefinition { public string Name { get; } public MetadataDefinitionKind Kind { get; } /// <summary> /// Only applies to member kind. Represents the type info of the first parameter. /// </summary> public ParameterTypeInfo ReceiverTypeInfo { get; } public NamespaceDefinition Namespace { get; private set; } public TypeDefinition Type { get; private set; } public MetadataDefinition(MetadataDefinitionKind kind, string name, ParameterTypeInfo receiverTypeInfo = default) : this() { Kind = kind; Name = name; ReceiverTypeInfo = receiverTypeInfo; } public static MetadataDefinition Create( MetadataReader reader, NamespaceDefinitionHandle namespaceHandle) { var definition = reader.GetNamespaceDefinition(namespaceHandle); return new MetadataDefinition( MetadataDefinitionKind.Namespace, reader.GetString(definition.Name)) { Namespace = definition }; } public static MetadataDefinition Create( MetadataReader reader, TypeDefinition definition) { var typeName = GetMetadataNameWithoutBackticks(reader, definition.Name); return new MetadataDefinition(MetadataDefinitionKind.Type, typeName) { Type = definition }; } } } }
1
dotnet/roslyn
56,433
Only allow Contract.ThrowIfNull() to be called on nullable types
We had some places we were calling it on bools.
jasonmalinowski
"2021-09-16T01:20:43Z"
"2021-09-16T18:44:11Z"
736fc1b5e6e2847689c0154b3e5f23ea99dd56af
6d0f4e3f972ceb561b04574e7f957a4ff458e272
Only allow Contract.ThrowIfNull() to be called on nullable types. We had some places we were calling it on bools.
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/Contract.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.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; namespace Roslyn.Utilities { internal static class Contract { // Guidance on inlining: // ThrowXxx methods are used heavily across the code base. // Inline their implementation of condition checking but don't inline the code that is only executed on failure. // This approach makes the common path efficient (both execution time and code size) // while keeping the rarely executed code in a separate method. /// <summary> /// Throws a non-accessible exception if the provided value is null. This method executes in /// all builds /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void ThrowIfNull<T>([NotNull] T value, [CallerLineNumber] int lineNumber = 0) { if (value is null) { Fail("Unexpected null", lineNumber); } } /// <summary> /// Throws a non-accessible exception if the provided value is null. This method executes in /// all builds /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void ThrowIfNull<T>([NotNull] T value, string message, [CallerLineNumber] int lineNumber = 0) { if (value is null) { Fail(message, lineNumber); } } /// <summary> /// Throws a non-accessible exception if the provided value is false. This method executes /// in all builds /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void ThrowIfFalse([DoesNotReturnIf(parameterValue: false)] bool condition, [CallerLineNumber] int lineNumber = 0) { if (!condition) { Fail("Unexpected false", lineNumber); } } /// <summary> /// Throws a non-accessible exception if the provided value is false. This method executes /// in all builds /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void ThrowIfFalse([DoesNotReturnIf(parameterValue: false)] bool condition, string message, [CallerLineNumber] int lineNumber = 0) { if (!condition) { Fail(message, lineNumber); } } /// <summary> /// Throws a non-accessible exception if the provided value is true. This method executes in /// all builds. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void ThrowIfTrue([DoesNotReturnIf(parameterValue: true)] bool condition, [CallerLineNumber] int lineNumber = 0) { if (condition) { Fail("Unexpected true", lineNumber); } } /// <summary> /// Throws a non-accessible exception if the provided value is true. This method executes in /// all builds. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void ThrowIfTrue([DoesNotReturnIf(parameterValue: true)] bool condition, string message, [CallerLineNumber] int lineNumber = 0) { if (condition) { Fail(message, lineNumber); } } [DebuggerHidden] [DoesNotReturn] [MethodImpl(MethodImplOptions.NoInlining)] public static void Fail(string message = "Unexpected", [CallerLineNumber] int lineNumber = 0) => throw new InvalidOperationException($"{message} - line {lineNumber}"); } }
// Licensed to the .NET Foundation under one or more 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.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; namespace Roslyn.Utilities { internal static class Contract { // Guidance on inlining: // ThrowXxx methods are used heavily across the code base. // Inline their implementation of condition checking but don't inline the code that is only executed on failure. // This approach makes the common path efficient (both execution time and code size) // while keeping the rarely executed code in a separate method. /// <summary> /// Throws a non-accessible exception if the provided value is null. This method executes in /// all builds /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void ThrowIfNull<T>([NotNull] T value, [CallerLineNumber] int lineNumber = 0) where T : class? { if (value is null) { Fail("Unexpected null", lineNumber); } } /// <summary> /// Throws a non-accessible exception if the provided value is null. This method executes in /// all builds /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void ThrowIfNull<T>([NotNull] T? value, [CallerLineNumber] int lineNumber = 0) where T : struct { if (value is null) { Fail("Unexpected null", lineNumber); } } /// <summary> /// Throws a non-accessible exception if the provided value is null. This method executes in /// all builds /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void ThrowIfNull<T>([NotNull] T value, string message, [CallerLineNumber] int lineNumber = 0) { if (value is null) { Fail(message, lineNumber); } } /// <summary> /// Throws a non-accessible exception if the provided value is false. This method executes /// in all builds /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void ThrowIfFalse([DoesNotReturnIf(parameterValue: false)] bool condition, [CallerLineNumber] int lineNumber = 0) { if (!condition) { Fail("Unexpected false", lineNumber); } } /// <summary> /// Throws a non-accessible exception if the provided value is false. This method executes /// in all builds /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void ThrowIfFalse([DoesNotReturnIf(parameterValue: false)] bool condition, string message, [CallerLineNumber] int lineNumber = 0) { if (!condition) { Fail(message, lineNumber); } } /// <summary> /// Throws a non-accessible exception if the provided value is true. This method executes in /// all builds. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void ThrowIfTrue([DoesNotReturnIf(parameterValue: true)] bool condition, [CallerLineNumber] int lineNumber = 0) { if (condition) { Fail("Unexpected true", lineNumber); } } /// <summary> /// Throws a non-accessible exception if the provided value is true. This method executes in /// all builds. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void ThrowIfTrue([DoesNotReturnIf(parameterValue: true)] bool condition, string message, [CallerLineNumber] int lineNumber = 0) { if (condition) { Fail(message, lineNumber); } } [DebuggerHidden] [DoesNotReturn] [MethodImpl(MethodImplOptions.NoInlining)] public static void Fail(string message = "Unexpected", [CallerLineNumber] int lineNumber = 0) => throw new InvalidOperationException($"{message} - line {lineNumber}"); } }
1
dotnet/roslyn
56,433
Only allow Contract.ThrowIfNull() to be called on nullable types
We had some places we were calling it on bools.
jasonmalinowski
"2021-09-16T01:20:43Z"
"2021-09-16T18:44:11Z"
736fc1b5e6e2847689c0154b3e5f23ea99dd56af
6d0f4e3f972ceb561b04574e7f957a4ff458e272
Only allow Contract.ThrowIfNull() to be called on nullable types. We had some places we were calling it on bools.
./src/Analyzers/Core/Analyzers/MatchFolderAndNamespace/MatchFolderAndNamespaceConstants.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.Analyzers.MatchFolderAndNamespace { internal static class MatchFolderAndNamespaceConstants { public const string RootNamespaceOption = "build_property.RootNamespace"; public const string ProjectDirOption = "build_property.ProjectDir"; public const string TargetNamespace = "TargetNamespace"; } }
// Licensed to the .NET Foundation under one or more 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.Analyzers.MatchFolderAndNamespace { internal static class MatchFolderAndNamespaceConstants { public const string RootNamespaceOption = "build_property.RootNamespace"; public const string ProjectDirOption = "build_property.ProjectDir"; public const string TargetNamespace = "TargetNamespace"; } }
-1
dotnet/roslyn
56,433
Only allow Contract.ThrowIfNull() to be called on nullable types
We had some places we were calling it on bools.
jasonmalinowski
"2021-09-16T01:20:43Z"
"2021-09-16T18:44:11Z"
736fc1b5e6e2847689c0154b3e5f23ea99dd56af
6d0f4e3f972ceb561b04574e7f957a4ff458e272
Only allow Contract.ThrowIfNull() to be called on nullable types. We had some places we were calling it on bools.
./src/Compilers/Core/Portable/SourceGeneration/Nodes/IIncrementalGeneratorNode.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.Threading; namespace Microsoft.CodeAnalysis { /// <summary> /// Represents a node in the execution pipeline of an incremental generator /// </summary> /// <typeparam name="T">The type of value this step operates on</typeparam> internal interface IIncrementalGeneratorNode<T> { NodeStateTable<T> UpdateStateTable(DriverStateTable.Builder graphState, NodeStateTable<T> previousTable, CancellationToken cancellationToken); IIncrementalGeneratorNode<T> WithComparer(IEqualityComparer<T> comparer); void RegisterOutput(IIncrementalGeneratorOutputNode output); } }
// Licensed to the .NET Foundation under one or more 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.Threading; namespace Microsoft.CodeAnalysis { /// <summary> /// Represents a node in the execution pipeline of an incremental generator /// </summary> /// <typeparam name="T">The type of value this step operates on</typeparam> internal interface IIncrementalGeneratorNode<T> { NodeStateTable<T> UpdateStateTable(DriverStateTable.Builder graphState, NodeStateTable<T> previousTable, CancellationToken cancellationToken); IIncrementalGeneratorNode<T> WithComparer(IEqualityComparer<T> comparer); void RegisterOutput(IIncrementalGeneratorOutputNode output); } }
-1
dotnet/roslyn
56,433
Only allow Contract.ThrowIfNull() to be called on nullable types
We had some places we were calling it on bools.
jasonmalinowski
"2021-09-16T01:20:43Z"
"2021-09-16T18:44:11Z"
736fc1b5e6e2847689c0154b3e5f23ea99dd56af
6d0f4e3f972ceb561b04574e7f957a4ff458e272
Only allow Contract.ThrowIfNull() to be called on nullable types. We had some places we were calling it on bools.
./src/Workspaces/Core/Portable/Workspace/Solution/AnalyzerConfigDocument.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 { public sealed class AnalyzerConfigDocument : TextDocument { internal AnalyzerConfigDocument(Project project, AnalyzerConfigDocumentState state) : base(project, state, TextDocumentKind.AnalyzerConfigDocument) { } } }
// Licensed to the .NET Foundation under one or more 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 { public sealed class AnalyzerConfigDocument : TextDocument { internal AnalyzerConfigDocument(Project project, AnalyzerConfigDocumentState state) : base(project, state, TextDocumentKind.AnalyzerConfigDocument) { } } }
-1
dotnet/roslyn
56,433
Only allow Contract.ThrowIfNull() to be called on nullable types
We had some places we were calling it on bools.
jasonmalinowski
"2021-09-16T01:20:43Z"
"2021-09-16T18:44:11Z"
736fc1b5e6e2847689c0154b3e5f23ea99dd56af
6d0f4e3f972ceb561b04574e7f957a4ff458e272
Only allow Contract.ThrowIfNull() to be called on nullable types. We had some places we were calling it on bools.
./src/Compilers/CSharp/Portable/Symbols/RefKindExtensions.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.Diagnostics; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal static partial class RefKindExtensions { public static bool IsManagedReference(this RefKind refKind) { Debug.Assert(refKind <= RefKind.RefReadOnly); return refKind != RefKind.None; } public static RefKind GetRefKind(this SyntaxKind syntaxKind) { switch (syntaxKind) { case SyntaxKind.RefKeyword: return RefKind.Ref; case SyntaxKind.OutKeyword: return RefKind.Out; case SyntaxKind.InKeyword: return RefKind.In; case SyntaxKind.None: return RefKind.None; default: throw ExceptionUtilities.UnexpectedValue(syntaxKind); } } public static bool IsWritableReference(this RefKind refKind) { switch (refKind) { case RefKind.Ref: case RefKind.Out: return true; case RefKind.None: case RefKind.In: return false; default: throw ExceptionUtilities.UnexpectedValue(refKind); } } } }
// Licensed to the .NET Foundation under one or more 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.Diagnostics; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal static partial class RefKindExtensions { public static bool IsManagedReference(this RefKind refKind) { Debug.Assert(refKind <= RefKind.RefReadOnly); return refKind != RefKind.None; } public static RefKind GetRefKind(this SyntaxKind syntaxKind) { switch (syntaxKind) { case SyntaxKind.RefKeyword: return RefKind.Ref; case SyntaxKind.OutKeyword: return RefKind.Out; case SyntaxKind.InKeyword: return RefKind.In; case SyntaxKind.None: return RefKind.None; default: throw ExceptionUtilities.UnexpectedValue(syntaxKind); } } public static bool IsWritableReference(this RefKind refKind) { switch (refKind) { case RefKind.Ref: case RefKind.Out: return true; case RefKind.None: case RefKind.In: return false; default: throw ExceptionUtilities.UnexpectedValue(refKind); } } } }
-1
dotnet/roslyn
56,433
Only allow Contract.ThrowIfNull() to be called on nullable types
We had some places we were calling it on bools.
jasonmalinowski
"2021-09-16T01:20:43Z"
"2021-09-16T18:44:11Z"
736fc1b5e6e2847689c0154b3e5f23ea99dd56af
6d0f4e3f972ceb561b04574e7f957a4ff458e272
Only allow Contract.ThrowIfNull() to be called on nullable types. We had some places we were calling it on bools.
./src/Compilers/CSharp/Portable/Symbols/Attributes/PEAttributeData.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.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Reflection.Metadata; using System.Threading; namespace Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE { /// <summary> /// Represents a PE custom attribute /// </summary> internal sealed class PEAttributeData : CSharpAttributeData { private readonly MetadataDecoder _decoder; private readonly CustomAttributeHandle _handle; private NamedTypeSymbol? _lazyAttributeClass = ErrorTypeSymbol.UnknownResultType; // Indicates uninitialized. private MethodSymbol? _lazyAttributeConstructor; private ImmutableArray<TypedConstant> _lazyConstructorArguments; private ImmutableArray<KeyValuePair<string, TypedConstant>> _lazyNamedArguments; private ThreeState _lazyHasErrors = ThreeState.Unknown; internal PEAttributeData(PEModuleSymbol moduleSymbol, CustomAttributeHandle handle) { _decoder = new MetadataDecoder(moduleSymbol); _handle = handle; } public override NamedTypeSymbol? AttributeClass { get { EnsureClassAndConstructorSymbolsAreLoaded(); return _lazyAttributeClass; } } public override MethodSymbol? AttributeConstructor { get { EnsureClassAndConstructorSymbolsAreLoaded(); return _lazyAttributeConstructor; } } public override SyntaxReference? ApplicationSyntaxReference { get { return null; } } protected internal override ImmutableArray<TypedConstant> CommonConstructorArguments { get { EnsureAttributeArgumentsAreLoaded(); return _lazyConstructorArguments; } } protected internal override ImmutableArray<KeyValuePair<string, TypedConstant>> CommonNamedArguments { get { EnsureAttributeArgumentsAreLoaded(); return _lazyNamedArguments; } } private void EnsureClassAndConstructorSymbolsAreLoaded() { #pragma warning disable 0252 if ((object?)_lazyAttributeClass == ErrorTypeSymbol.UnknownResultType) { TypeSymbol? attributeClass; MethodSymbol? attributeConstructor; if (!_decoder.GetCustomAttribute(_handle, out attributeClass, out attributeConstructor)) { // TODO: should we create CSErrorTypeSymbol for attribute class?? _lazyHasErrors = ThreeState.True; } else if ((object)attributeClass == null || attributeClass.IsErrorType() || (object)attributeConstructor == null) { _lazyHasErrors = ThreeState.True; } Interlocked.CompareExchange(ref _lazyAttributeConstructor, attributeConstructor, null); Interlocked.CompareExchange(ref _lazyAttributeClass, (NamedTypeSymbol?)attributeClass, ErrorTypeSymbol.UnknownResultType); // Serves as a flag, so do it last. } #pragma warning restore 0252 } private void EnsureAttributeArgumentsAreLoaded() { if (_lazyConstructorArguments.IsDefault || _lazyNamedArguments.IsDefault) { TypedConstant[]? lazyConstructorArguments = null; KeyValuePair<string, TypedConstant>[]? lazyNamedArguments = null; if (!_decoder.GetCustomAttribute(_handle, out lazyConstructorArguments, out lazyNamedArguments)) { _lazyHasErrors = ThreeState.True; } Debug.Assert(lazyConstructorArguments != null && lazyNamedArguments != null); ImmutableInterlocked.InterlockedInitialize(ref _lazyConstructorArguments, ImmutableArray.Create<TypedConstant>(lazyConstructorArguments)); ImmutableInterlocked.InterlockedInitialize(ref _lazyNamedArguments, ImmutableArray.Create<KeyValuePair<string, TypedConstant>>(lazyNamedArguments)); } } /// <summary> /// Matches an attribute by metadata namespace, metadata type name. Does not load the type symbol for /// the attribute. /// </summary> /// <param name="namespaceName"></param> /// <param name="typeName"></param> /// <returns>True if the attribute data matches.</returns> internal override bool IsTargetAttribute(string namespaceName, string typeName) { // Matching an attribute by name should not load the attribute class. return _decoder.IsTargetAttribute(_handle, namespaceName, typeName); } /// <summary> /// Matches an attribute by metadata namespace, metadata type name and metadata signature. Does not load the /// type symbol for the attribute. /// </summary> /// <param name="targetSymbol">Target symbol.</param> /// <param name="description">Attribute to match.</param> /// <returns> /// An index of the target constructor signature in /// signatures array, -1 if /// this is not the target attribute. /// </returns> internal override int GetTargetAttributeSignatureIndex(Symbol targetSymbol, AttributeDescription description) { // Matching an attribute by name should not load the attribute class. return _decoder.GetTargetAttributeSignatureIndex(_handle, description); } [MemberNotNullWhen(true, nameof(AttributeClass), nameof(AttributeConstructor))] internal override bool HasErrors { get { if (_lazyHasErrors == ThreeState.Unknown) { EnsureClassAndConstructorSymbolsAreLoaded(); EnsureAttributeArgumentsAreLoaded(); if (_lazyHasErrors == ThreeState.Unknown) { _lazyHasErrors = ThreeState.False; } } return _lazyHasErrors.Value(); } } } }
// Licensed to the .NET Foundation under one or more 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.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Reflection.Metadata; using System.Threading; namespace Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE { /// <summary> /// Represents a PE custom attribute /// </summary> internal sealed class PEAttributeData : CSharpAttributeData { private readonly MetadataDecoder _decoder; private readonly CustomAttributeHandle _handle; private NamedTypeSymbol? _lazyAttributeClass = ErrorTypeSymbol.UnknownResultType; // Indicates uninitialized. private MethodSymbol? _lazyAttributeConstructor; private ImmutableArray<TypedConstant> _lazyConstructorArguments; private ImmutableArray<KeyValuePair<string, TypedConstant>> _lazyNamedArguments; private ThreeState _lazyHasErrors = ThreeState.Unknown; internal PEAttributeData(PEModuleSymbol moduleSymbol, CustomAttributeHandle handle) { _decoder = new MetadataDecoder(moduleSymbol); _handle = handle; } public override NamedTypeSymbol? AttributeClass { get { EnsureClassAndConstructorSymbolsAreLoaded(); return _lazyAttributeClass; } } public override MethodSymbol? AttributeConstructor { get { EnsureClassAndConstructorSymbolsAreLoaded(); return _lazyAttributeConstructor; } } public override SyntaxReference? ApplicationSyntaxReference { get { return null; } } protected internal override ImmutableArray<TypedConstant> CommonConstructorArguments { get { EnsureAttributeArgumentsAreLoaded(); return _lazyConstructorArguments; } } protected internal override ImmutableArray<KeyValuePair<string, TypedConstant>> CommonNamedArguments { get { EnsureAttributeArgumentsAreLoaded(); return _lazyNamedArguments; } } private void EnsureClassAndConstructorSymbolsAreLoaded() { #pragma warning disable 0252 if ((object?)_lazyAttributeClass == ErrorTypeSymbol.UnknownResultType) { TypeSymbol? attributeClass; MethodSymbol? attributeConstructor; if (!_decoder.GetCustomAttribute(_handle, out attributeClass, out attributeConstructor)) { // TODO: should we create CSErrorTypeSymbol for attribute class?? _lazyHasErrors = ThreeState.True; } else if ((object)attributeClass == null || attributeClass.IsErrorType() || (object)attributeConstructor == null) { _lazyHasErrors = ThreeState.True; } Interlocked.CompareExchange(ref _lazyAttributeConstructor, attributeConstructor, null); Interlocked.CompareExchange(ref _lazyAttributeClass, (NamedTypeSymbol?)attributeClass, ErrorTypeSymbol.UnknownResultType); // Serves as a flag, so do it last. } #pragma warning restore 0252 } private void EnsureAttributeArgumentsAreLoaded() { if (_lazyConstructorArguments.IsDefault || _lazyNamedArguments.IsDefault) { TypedConstant[]? lazyConstructorArguments = null; KeyValuePair<string, TypedConstant>[]? lazyNamedArguments = null; if (!_decoder.GetCustomAttribute(_handle, out lazyConstructorArguments, out lazyNamedArguments)) { _lazyHasErrors = ThreeState.True; } Debug.Assert(lazyConstructorArguments != null && lazyNamedArguments != null); ImmutableInterlocked.InterlockedInitialize(ref _lazyConstructorArguments, ImmutableArray.Create<TypedConstant>(lazyConstructorArguments)); ImmutableInterlocked.InterlockedInitialize(ref _lazyNamedArguments, ImmutableArray.Create<KeyValuePair<string, TypedConstant>>(lazyNamedArguments)); } } /// <summary> /// Matches an attribute by metadata namespace, metadata type name. Does not load the type symbol for /// the attribute. /// </summary> /// <param name="namespaceName"></param> /// <param name="typeName"></param> /// <returns>True if the attribute data matches.</returns> internal override bool IsTargetAttribute(string namespaceName, string typeName) { // Matching an attribute by name should not load the attribute class. return _decoder.IsTargetAttribute(_handle, namespaceName, typeName); } /// <summary> /// Matches an attribute by metadata namespace, metadata type name and metadata signature. Does not load the /// type symbol for the attribute. /// </summary> /// <param name="targetSymbol">Target symbol.</param> /// <param name="description">Attribute to match.</param> /// <returns> /// An index of the target constructor signature in /// signatures array, -1 if /// this is not the target attribute. /// </returns> internal override int GetTargetAttributeSignatureIndex(Symbol targetSymbol, AttributeDescription description) { // Matching an attribute by name should not load the attribute class. return _decoder.GetTargetAttributeSignatureIndex(_handle, description); } [MemberNotNullWhen(true, nameof(AttributeClass), nameof(AttributeConstructor))] internal override bool HasErrors { get { if (_lazyHasErrors == ThreeState.Unknown) { EnsureClassAndConstructorSymbolsAreLoaded(); EnsureAttributeArgumentsAreLoaded(); if (_lazyHasErrors == ThreeState.Unknown) { _lazyHasErrors = ThreeState.False; } } return _lazyHasErrors.Value(); } } } }
-1
dotnet/roslyn
56,433
Only allow Contract.ThrowIfNull() to be called on nullable types
We had some places we were calling it on bools.
jasonmalinowski
"2021-09-16T01:20:43Z"
"2021-09-16T18:44:11Z"
736fc1b5e6e2847689c0154b3e5f23ea99dd56af
6d0f4e3f972ceb561b04574e7f957a4ff458e272
Only allow Contract.ThrowIfNull() to be called on nullable types. We had some places we were calling it on bools.
./src/EditorFeatures/CSharpTest/PullMemberUp/CSharpPullMemberUpTests.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.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CSharp.CodeRefactorings.PullMemberUp; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; using System.Collections.Immutable; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeRefactorings.PullMemberUp.Dialog; using System.Collections.Generic; using Microsoft.CodeAnalysis.Test.Utilities.PullMemberUp; using Roslyn.Test.Utilities; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.Editing; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.PullMemberUp { public class CSharpPullMemberUpTests : AbstractCSharpCodeActionTest { protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters) => new CSharpPullMemberUpCodeRefactoringProvider((IPullMemberUpOptionsService)parameters.fixProviderData); protected override ImmutableArray<CodeAction> MassageActions(ImmutableArray<CodeAction> actions) => FlattenActions(actions); #region Quick Action private async Task TestQuickActionNotProvidedAsync( string initialMarkup, TestParameters parameters = default) { using var workspace = CreateWorkspaceFromOptions(initialMarkup, parameters); var (actions, _) = await GetCodeActionsAsync(workspace, parameters); if (actions.Length == 1) { // The dialog shows up, not quick action Assert.Equal(actions.First().Title, FeaturesResources.Pull_members_up_to_base_type); } else if (actions.Length > 1) { Assert.True(false, "Pull Members Up is provided via quick action"); } else { Assert.True(true); } } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestNoRefactoringProvidedWhenPullFieldInInterfaceViaQuickAction() { var testText = @" namespace PushUpTest { public interface ITestInterface { } public class TestClass : ITestInterface { public int yo[||]u = 10086; } }"; await TestQuickActionNotProvidedAsync(testText); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestNoRefactoringProvidedWhenMethodDeclarationAlreadyExistsInInterfaceViaQuickAction() { var methodTest = @" namespace PushUpTest { public interface ITestInterface { void TestMethod(); } public class TestClass : ITestInterface { public void TestM[||]ethod() { System.Console.WriteLine(""Hello World""); } } }"; await TestQuickActionNotProvidedAsync(methodTest); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestNoRefactoringProvidedWhenPropertyDeclarationAlreadyExistsInInterfaceViaQuickAction() { var propertyTest1 = @" using System; namespace PushUpTest { interface IInterface { int TestProperty { get; } } public class TestClass : IInterface { public int TestPr[||]operty { get; private set; } } }"; await TestQuickActionNotProvidedAsync(propertyTest1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestNoRefactoringProvidedWhenEventDeclarationAlreadyExistsToInterfaceViaQuickAction() { var eventTest = @" using System; namespace PushUpTest { interface IInterface { event EventHandler Event2; } public class TestClass : IInterface { public event EventHandler Event1, Eve[||]nt2, Event3; } }"; await TestQuickActionNotProvidedAsync(eventTest); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestNoRefactoringProvidedInNestedTypesViaQuickAction() { var input = @" namespace PushUpTest { public interface ITestInterface { void Foobar(); } public class TestClass : ITestInterface { public class N[||]estedClass { } } }"; await TestQuickActionNotProvidedAsync(input); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullMethodUpToInterfaceViaQuickAction() { var testText = @" using System; namespace PushUpTest { interface IInterface { } public class TestClass : IInterface { public void TestM[||]ethod() { System.Console.WriteLine(""Hello World""); } } }"; var expected = @" using System; namespace PushUpTest { interface IInterface { void TestMethod(); } public class TestClass : IInterface { public void TestMethod() { System.Console.WriteLine(""Hello World""); } } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullAbstractMethodToInterfaceViaQuickAction() { var testText = @" namespace PushUpTest { public interface IInterface { } public abstract class TestClass : IInterface { public abstract void TestMeth[||]od(); } }"; var expected = @" namespace PushUpTest { public interface IInterface { void TestMethod(); } public abstract class TestClass : IInterface { public abstract void TestMethod(); } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullGenericsUpToInterfaceViaQuickAction() { var testText = @" using System; namespace PushUpTest { public interface IInterface { } public class TestClass : IInterface { public void TestMeth[||]od<T>() where T : IDisposable { } } }"; var expected = @" using System; namespace PushUpTest { public interface IInterface { void TestMethod<T>() where T : IDisposable; } public class TestClass : IInterface { public void TestMeth[||]od<T>() where T : IDisposable { } } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullSingleEventToInterfaceViaQuickAction() { var testText = @" using System; namespace PushUpTest { interface IInterface { } public class TestClass : IInterface { public event EventHandler Eve[||]nt1 { add { System.Console.Writeline(""This is add""); } remove { System.Console.Writeline(""This is remove""); } } } }"; var expected = @" using System; namespace PushUpTest { interface IInterface { event EventHandler Event1; } public class TestClass : IInterface { public event EventHandler Event1 { add { System.Console.Writeline(""This is add""); } remove { System.Console.Writeline(""This is remove""); } } } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullOneEventFromMultipleEventsToInterfaceViaQuickAction() { var testText = @" using System; namespace PushUpTest { interface IInterface { } public class TestClass : IInterface { public event EventHandler Event1, Eve[||]nt2, Event3; } }"; var expected = @" using System; namespace PushUpTest { interface IInterface { event EventHandler Event2; } public class TestClass : IInterface { public event EventHandler Event1, Event2, Event3; } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullPublicEventWithAccessorsToInterfaceViaQuickAction() { var testText = @" using System; namespace PushUpTest { interface IInterface { } public class TestClass : IInterface { public event EventHandler Eve[||]nt2 { add { System.Console.Writeln(""This is add in event1""); } remove { System.Console.Writeln(""This is remove in event2""); } } } }"; var expected = @" using System; namespace PushUpTest { interface IInterface { event EventHandler Event2; } public class TestClass : IInterface { public event EventHandler Event2 { add { System.Console.Writeln(""This is add in event1""); } remove { System.Console.Writeln(""This is remove in event2""); } } } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullPropertyWithPrivateSetterToInterfaceViaQuickAction() { var testText = @" using System; namespace PushUpTest { interface IInterface { } public class TestClass : IInterface { public int TestPr[||]operty { get; private set; } } }"; var expected = @" using System; namespace PushUpTest { interface IInterface { int TestProperty { get; } } public class TestClass : IInterface { public int TestProperty { get; private set; } } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullPropertyWithPrivateGetterToInterfaceViaQuickAction() { var testText = @" using System; namespace PushUpTest { interface IInterface { } public class TestClass : IInterface { public int TestProperty[||]{ private get; set; } } }"; var expected = @" using System; namespace PushUpTest { interface IInterface { int TestProperty { set; } } public class TestClass : IInterface { public int TestProperty{ private get; set; } } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullMemberFromInterfaceToInterfaceViaQuickAction() { var testText = @" using System; namespace PushUpTest { interface IInterface { } interface FooInterface : IInterface { int TestPr[||]operty { set; } } }"; var expected = @" using System; namespace PushUpTest { interface IInterface { int TestProperty { set; } } interface FooInterface : IInterface { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullIndexerWithOnlySetterToInterfaceViaQuickAction() { var testText = @" using System; namespace PushUpTest { interface IInterface { } public class TestClass : IInterface { private int j; public int th[||]is[int i] { set => j = value; } } }"; var expected = @" using System; namespace PushUpTest { interface IInterface { int this[int i] { set; } } public class TestClass : IInterface { private int j; public int this[int i] { set => j = value; } } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullIndexerWithOnlyGetterToInterfaceViaQuickAction() { var testText = @" using System; namespace PushUpTest { interface IInterface { } public class TestClass : IInterface { private int j; public int th[||]is[int i] { get => j = value; } } }"; var expected = @" using System; namespace PushUpTest { interface IInterface { int this[int i] { get; } } public class TestClass : IInterface { private int j; public int this[int i] { get => j = value; } } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullPropertyToInterfaceWithAddUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public interface IBase { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : IBase { public Uri En[||]dpoint { get; set; } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; public interface IBase { Uri Endpoint { get; set; } } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : IBase { public Uri Endpoint { get; set; } } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToInterfaceWithoutAddUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public interface IBase { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : IBase { public bool Test[||]Method() { var endpoint1 = new Uri(""http://localhost""); var endpoint2 = new Uri(""http://localhost""); return endpoint1.Equals(endpoint2); } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public interface IBase { bool TestMethod(); } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : IBase { public bool Test[||]Method() { var endpoint1 = new Uri(""http://localhost""); var endpoint2 = new Uri(""http://localhost""); return endpoint1.Equals(endpoint2); } } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodWithNewReturnTypeToInterfaceWithAddUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public interface IBase { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : IBase { public Uri Test[||]Method() { return new Uri(""http://localhost""); } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; public interface IBase { Uri TestMethod(); } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : IBase { public Uri TestMethod() { return new Uri(""http://localhost""); } } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodWithNewParamTypeToInterfaceWithAddUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public interface IBase { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : IBase { public bool Test[||]Method(Uri endpoint) { var localHost = new Uri(""http://localhost""); return endpoint.Equals(localhost); } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; public interface IBase { bool TestMethod(Uri endpoint); } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : IBase { public bool TestMethod(Uri endpoint) { var localHost = new Uri(""http://localhost""); return endpoint.Equals(localhost); } } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullEventToInterfaceWithAddUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public interface IBase { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : IBase { public event EventHandler Test[||]Event { add { Console.WriteLine(""adding event...""); } remove { Console.WriteLine(""removing event...""); } } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; public interface IBase { event EventHandler TestEvent; } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : IBase { public event EventHandler TestEvent { add { Console.WriteLine(""adding event...""); } remove { Console.WriteLine(""removing event...""); } } } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullPropertyToClassWithAddUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public class Base { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { public Uri En[||]dpoint { get; set; } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using System; public class Base { public Uri Endpoint { get; set; } } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullPropertyToClassWithAddUsingsViaQuickAction2() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">public class Base { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { public Uri En[||]dpoint { get; set; } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using System; public class Base { public Uri Endpoint { get; set; } } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullPropertyToClassWithoutDuplicatingUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; public class Base { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { public Uri En[||]dpoint { get; set; } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; public class Base { public Uri Endpoint { get; set; } } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullPropertyWithNewBodyTypeToClassWithAddUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public class Base { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { public bool Test[||]Property { get { var endpoint1 = new Uri(""http://localhost""); var endpoint2 = new Uri(""http://localhost""); return endpoint1.Equals(endpoint2); } } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using System; public class Base { public bool TestProperty { get { var endpoint1 = new Uri(""http://localhost""); var endpoint2 = new Uri(""http://localhost""); return endpoint1.Equals(endpoint2); } } } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodWithNewNonDeclaredBodyTypeToClassWithAddUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public class Base { } </Document> <Document FilePath = ""File2.cs""> using System.Linq; public class Derived : Base { public int Test[||]Method() { return Enumerable.Range(0, 5).Sum(); } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using System.Linq; public class Base { public int Test[||]Method() { return Enumerable.Range(0, 5).Sum(); } } </Document> <Document FilePath = ""File2.cs""> using System.Linq; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithOverlappingUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; using System.Threading.Tasks; public class Base { public Uri Endpoint{ get; set; } public async Task&lt;int&gt; Get5Async() { return 5; } } </Document> <Document FilePath = ""File2.cs""> using System.Linq; using System.Threading.Tasks; public class Derived : Base { public async Task&lt;int&gt; Test[||]Method() { return Enumerable.Range(0, 5).Sum(); } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; using System.Linq; using System.Threading.Tasks; public class Base { public Uri Endpoint{ get; set; } public async Task&lt;int&gt; Get5Async() { return 5; } public async Task&lt;int&gt; Test[||]Method() { return Enumerable.Range(0, 5).Sum(); } } </Document> <Document FilePath = ""File2.cs""> using System.Linq; using System.Threading.Tasks; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithUnnecessaryFirstUsingViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System.Threading.Tasks; public class Base { public async Task&lt;int&gt; Get5Async() { return 5; } } </Document> <Document FilePath = ""File2.cs""> using System; using System.Linq; using System.Threading.Tasks; public class Derived : Base { public async Task&lt;int&gt; Test[||]Method() { return Enumerable.Range(0, 5).Sum(); } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using System.Linq; using System.Threading.Tasks; public class Base { public async Task&lt;int&gt; Get5Async() { return 5; } public async Task&lt;int&gt; Test[||]Method() { return Enumerable.Range(0, 5).Sum(); } } </Document> <Document FilePath = ""File2.cs""> using System; using System.Linq; using System.Threading.Tasks; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithUnusedBaseUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; using System.Threading.Tasks; public class Base { public Uri Endpoint{ get; set; } } </Document> <Document FilePath = ""File2.cs""> using System.Linq; public class Derived : Base { public int Test[||]Method() { return Enumerable.Range(0, 5).Sum(); } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; using System.Linq; using System.Threading.Tasks; public class Base { public Uri Endpoint{ get; set; } public int TestMethod() { return Enumerable.Range(0, 5).Sum(); } } </Document> <Document FilePath = ""File2.cs""> using System.Linq; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithRetainCommentsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> // blah blah public class Base { } </Document> <Document FilePath = ""File2.cs""> using System.Linq; public class Derived : Base { public int Test[||]Method() { return 5; } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> // blah blah public class Base { public int TestMethod() { return 5; } } </Document> <Document FilePath = ""File2.cs""> using System.Linq; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithRetainPreImportCommentsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> // blah blah using System.Linq; public class Base { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { public Uri End[||]point { get; set; } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> // blah blah using System; using System.Linq; public class Base { public Uri Endpoint { get; set; } } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithRetainPostImportCommentsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System.Linq; // blah blah public class Base { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { public Uri End[||]point { get; set; } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; using System.Linq; // blah blah public class Base { public Uri Endpoint { get; set; } } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithLambdaUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public class Base { } </Document> <Document FilePath = ""File2.cs""> using System; using System.Linq; public class Derived : Base { public int Test[||]Method() { return Enumerable.Range(0, 5). Select((n) => new Uri(""http://"" + n)). Count((uri) => uri != null); } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using System; using System.Linq; public class Base { public int TestMethod() { return Enumerable.Range(0, 5). Select((n) => new Uri(""http://"" + n)). Count((uri) => uri != null); } } </Document> <Document FilePath = ""File2.cs""> using System; using System.Linq; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithUnusedUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; public class Base { public Uri Endpoint{ get; set; } } </Document> <Document FilePath = ""File2.cs""> using System.Linq; using System.Threading.Tasks; public class Derived : Base { public int Test[||]Method() { return Enumerable.Range(0, 5).Sum(); } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; using System.Linq; public class Base { public Uri Endpoint{ get; set; } public int TestMethod() { return Enumerable.Range(0, 5).Sum(); } } </Document> <Document FilePath = ""File2.cs""> using System.Linq; using System.Threading.Tasks; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassKeepSystemFirstViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace TestNs1 { using System; public class Base { public Uri Endpoint{ get; set; } } } </Document> <Document FilePath = ""File2.cs""> namespace A_TestNs2 { using TestNs1; public class Derived : Base { public Foo Test[||]Method() { return null; } } public class Foo { } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace TestNs1 { using System; using A_TestNs2; public class Base { public Uri Endpoint{ get; set; } public Foo TestMethod() { return null; } } } </Document> <Document FilePath = ""File2.cs""> namespace A_TestNs2 { using TestNs1; public class Derived : Base { } public class Foo { } } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassKeepSystemFirstViaQuickAction2() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace TestNs1 { public class Base { } } </Document> <Document FilePath = ""File2.cs""> namespace A_TestNs2 { using System; using TestNs1; public class Derived : Base { public Foo Test[||]Method() { var uri = new Uri(""http://localhost""); return null; } } public class Foo { } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using System; using A_TestNs2; namespace TestNs1 { public class Base { public Foo TestMethod() { var uri = new Uri(""http://localhost""); return null; } } } </Document> <Document FilePath = ""File2.cs""> namespace A_TestNs2 { using System; using TestNs1; public class Derived : Base { } public class Foo { } } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithExtensionViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace TestNs1 { public class Base { } public class Foo { } } </Document> <Document FilePath = ""File2.cs""> namespace TestNs2 { using TestNs1; public class Derived : Base { public int Test[||]Method() { var foo = new Foo(); return foo.FooBar(); } } public static class FooExtensions { public static int FooBar(this Foo foo) { return 5; } } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using TestNs2; namespace TestNs1 { public class Base { public int TestMethod() { var foo = new Foo(); return foo.FooBar(); } } public class Foo { } } </Document> <Document FilePath = ""File2.cs""> namespace TestNs2 { using TestNs1; public class Derived : Base { } public static class FooExtensions { public static int FooBar(this Foo foo) { return 5; } } } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithExtensionViaQuickAction2() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace TestNs1 { public class Base { } } </Document> <Document FilePath = ""File2.cs""> using TestNs1; using TestNs3; using TestNs4; namespace TestNs2 { public class Derived : Base { public int Test[||]Method() { var foo = new Foo(); return foo.FooBar(); } } } </Document> <Document FilePath = ""File3.cs""> namespace TestNs3 { public class Foo { } } </Document> <Document FilePath = ""File4.cs""> using TestNs3; namespace TestNs4 { public static class FooExtensions { public static int FooBar(this Foo foo) { return 5; } } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using TestNs3; using TestNs4; namespace TestNs1 { public class Base { public int TestMethod() { var foo = new Foo(); return foo.FooBar(); } } } </Document> <Document FilePath = ""File2.cs""> using TestNs1; using TestNs3; using TestNs4; namespace TestNs2 { public class Derived : Base { } } </Document> <Document FilePath = ""File3.cs""> namespace TestNs3 { public class Foo { } } </Document> <Document FilePath = ""File4.cs""> using TestNs3; namespace TestNs4 { public static class FooExtensions { public static int FooBar(this Foo foo) { return 5; } } } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithAliasUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; public class Base { public Uri Endpoint{ get; set; } } </Document> <Document FilePath = ""File2.cs""> using Enumer = System.Linq.Enumerable; using Sys = System; public class Derived : Base { public void Test[||]Method() { Sys.Console.WriteLine(Enumer.Range(0, 5).Sum()); } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; using Enumer = System.Linq.Enumerable; using Sys = System; public class Base { public Uri Endpoint{ get; set; } public void TestMethod() { Sys.Console.WriteLine(Enumer.Range(0, 5).Sum()); } } </Document> <Document FilePath = ""File2.cs""> using Enumer = System.Linq.Enumerable; using Sys = System; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullPropertyToClassWithBaseAliasUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using Enumer = System.Linq.Enumerable; public class Base { public void TestMethod() { System.Console.WriteLine(Enumer.Range(0, 5).Sum()); } } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { public Uri End[||]point{ get; set; } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; using Enumer = System.Linq.Enumerable; public class Base { public Uri Endpoint{ get; set; } public void TestMethod() { System.Console.WriteLine(Enumer.Range(0, 5).Sum()); } } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithMultipleNamespacedUsingsViaQuickAction() { var testText = @" namespace TestNs1 { using System; public class Base { public Uri Endpoint{ get; set; } } } namespace TestNs2 { using System.Linq; using TestNs1; public class Derived : Base { public int Test[||]Method() { return Enumerable.Range(0, 5).Sum(); } } } "; var expected = @" namespace TestNs1 { using System; using System.Linq; public class Base { public Uri Endpoint{ get; set; } public int TestMethod() { return Enumerable.Range(0, 5).Sum(); } } } namespace TestNs2 { using System.Linq; using TestNs1; public class Derived : Base { } } "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithNestedNamespacedUsingsViaQuickAction() { var testText = @" namespace TestNs1 { namespace InnerNs1 { using System; public class Base { public Uri Endpoint { get; set; } } } } namespace TestNs2 { namespace InnerNs2 { using System.Linq; using TestNs1.InnerNs1; public class Derived : Base { public int Test[||]Method() { return Foo.Bar(Enumerable.Range(0, 5).Sum()); } } public class Foo { public static int Bar(int num) { return num + 1; } } } } "; var expected = @" namespace TestNs1 { namespace InnerNs1 { using System; using System.Linq; using TestNs2.InnerNs2; public class Base { public Uri Endpoint { get; set; } public int TestMethod() { return Foo.Bar(Enumerable.Range(0, 5).Sum()); } } } } namespace TestNs2 { namespace InnerNs2 { using System.Linq; using TestNs1.InnerNs1; public class Derived : Base { } public class Foo { public static int Bar(int num) { return num + 1; } } } } "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithNewNamespaceUsingViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace A.B { class Base { } } </Document> <Document FilePath = ""File2.cs""> namespace X.Y { class Derived : A.B.Base { public Other Get[||]Other() => null; } class Other { } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using X.Y; namespace A.B { class Base { public Other GetOther() => null; } } </Document> <Document FilePath = ""File2.cs""> namespace X.Y { class Derived : A.B.Base { } class Other { } } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithFileNamespaceUsingViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace A.B; class Base { } </Document> <Document FilePath = ""File2.cs""> namespace X.Y; class Derived : A.B.Base { public Other Get[||]Other() => null; } class Other { } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using X.Y; namespace A.B; class Base { public Other GetOther() => null; } </Document> <Document FilePath = ""File2.cs""> namespace X.Y; class Derived : A.B.Base { } class Other { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithUnusedNamespaceUsingViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace A.B { class Base { } } </Document> <Document FilePath = ""File2.cs""> namespace X.Y { class Derived : A.B.Base { public int Get[||]Five() => 5; } class Other { } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace A.B { class Base { public int GetFive() => 5; } } </Document> <Document FilePath = ""File2.cs""> namespace X.Y { class Derived : A.B.Base { } class Other { } } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithMultipleNamespacesAndCommentsViaQuickAction() { var testText = @" // comment 1 namespace TestNs1 { // comment 2 // comment 3 public class Base { } } namespace TestNs2 { // comment 4 using System.Linq; using TestNs1; public class Derived : Base { public int Test[||]Method() { return 5; } } } "; var expected = @" // comment 1 namespace TestNs1 { // comment 2 // comment 3 public class Base { public int TestMethod() { return 5; } } } namespace TestNs2 { // comment 4 using System.Linq; using TestNs1; public class Derived : Base { } } "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithMultipleNamespacedUsingsAndCommentsViaQuickAction() { var testText = @" // comment 1 namespace TestNs1 { // comment 2 using System; // comment 3 public class Base { } } namespace TestNs2 { // comment 4 using System.Linq; using TestNs1; public class Derived : Base { public int Test[||]Method() { return Enumerable.Range(0, 5).Sum(); } } } "; var expected = @" // comment 1 namespace TestNs1 { // comment 2 using System; using System.Linq; // comment 3 public class Base { public int TestMethod() { return Enumerable.Range(0, 5).Sum(); } } } namespace TestNs2 { // comment 4 using System.Linq; using TestNs1; public class Derived : Base { } } "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithNamespacedUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace ClassLibrary1 { using System; public class Base { public Uri Endpoint{ get; set; } } } </Document> <Document FilePath = ""File2.cs""> namespace ClassLibrary1 { using System.Linq; public class Derived : Base { public int Test[||]Method() { return Enumerable.Range(0, 5).Sum(); } } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace ClassLibrary1 { using System; using System.Linq; public class Base { public Uri Endpoint{ get; set; } public int Test[||]Method() { return Enumerable.Range(0, 5).Sum(); } } } </Document> <Document FilePath = ""File2.cs""> namespace ClassLibrary1 { using System.Linq; public class Derived : Base { } } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithDuplicateNamespacedUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace ClassLibrary1 { using System; public class Base { public Uri Endpoint{ get; set; } } } </Document> <Document FilePath = ""File2.cs""> using System.Linq; namespace ClassLibrary1 { using System.Linq; public class Derived : Base { public int Test[||]Method() { return Enumerable.Range(0, 5).Sum(); } } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace ClassLibrary1 { using System; using System.Linq; public class Base { public Uri Endpoint{ get; set; } public int Test[||]Method() { return Enumerable.Range(0, 5).Sum(); } } } </Document> <Document FilePath = ""File2.cs""> using System.Linq; namespace ClassLibrary1 { using System.Linq; public class Derived : Base { } } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodWithNewReturnTypeToClassWithAddUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public class Base { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { public Uri En[||]dpoint() { return new Uri(""http://localhost""); } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using System; public class Base { public Uri Endpoint() { return new Uri(""http://localhost""); } } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodWithNewParamTypeToClassWithAddUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public class Base { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { public bool Test[||]Method(Uri endpoint) { var localHost = new Uri(""http://localhost""); return endpoint.Equals(localhost); } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using System; public class Base { public bool TestMethod(Uri endpoint) { var localHost = new Uri(""http://localhost""); return endpoint.Equals(localhost); } } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodWithNewBodyTypeToClassWithAddUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public class Base { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { public bool Test[||]Method() { var endpoint1 = new Uri(""http://localhost""); var endpoint2 = new Uri(""http://localhost""); return endpoint1.Equals(endpoint2); } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using System; public class Base { public bool TestMethod() { var endpoint1 = new Uri(""http://localhost""); var endpoint2 = new Uri(""http://localhost""); return endpoint1.Equals(endpoint2); } } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullEventToClassWithAddUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public class Base { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { public event EventHandler Test[||]Event { add { Console.WriteLine(""adding event...""); } remove { Console.WriteLine(""removing event...""); } } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using System; public class Base { public event EventHandler Test[||]Event { add { Console.WriteLine(""adding event...""); } remove { Console.WriteLine(""removing event...""); } } } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullFieldToClassWithAddUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public class Base { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { public var en[||]dpoint = new Uri(""http://localhost""); } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using System; public class Base { public var endpoint = new Uri(""http://localhost""); } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullFieldToClassNoConstructorWithAddUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public class Base { } </Document> <Document FilePath = ""File2.cs""> using System.Linq; public class Derived : Base { public var ran[||]ge = Enumerable.Range(0, 5); } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using System.Linq; public class Base { public var range = Enumerable.Range(0, 5); } </Document> <Document FilePath = ""File2.cs""> using System.Linq; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestNoRefactoringProvidedWhenPullOverrideMethodUpToClassViaQuickAction() { var methodTest = @" namespace PushUpTest { public class Base { public virtual void TestMethod() => System.Console.WriteLine(""foo bar bar foo""); } public class TestClass : Base { public override void TestMeth[||]od() { System.Console.WriteLine(""Hello World""); } } }"; await TestQuickActionNotProvidedAsync(methodTest); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestNoRefactoringProvidedWhenPullOverridePropertyUpToClassViaQuickAction() { var propertyTest = @" using System; namespace PushUpTest { public class Base { public virtual int TestProperty { get => 111; private set; } } public class TestClass : Base { public override int TestPr[||]operty { get; private set; } } }"; await TestQuickActionNotProvidedAsync(propertyTest); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestNoRefactoringProvidedWhenPullOverrideEventUpToClassViaQuickAction() { var eventTest = @" using System; namespace PushUpTest { public class Base2 { protected virtual event EventHandler Event3 { add { System.Console.WriteLine(""Hello""); } remove { System.Console.WriteLine(""World""); } }; } public class TestClass2 : Base2 { protected override event EventHandler E[||]vent3 { add { System.Console.WriteLine(""foo""); } remove { System.Console.WriteLine(""bar""); } }; } }"; await TestQuickActionNotProvidedAsync(eventTest); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestNoRefactoringProvidedWhenPullSameNameFieldUpToClassViaQuickAction() { // Fields share the same name will be thought as 'override', since it will cause error // if two same name fields exist in one class var fieldTest = @" namespace PushUpTest { public class Base { public int you = -100000; } public class TestClass : Base { public int y[||]ou = 10086; } }"; await TestQuickActionNotProvidedAsync(fieldTest); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullMethodToOrdinaryClassViaQuickAction() { var testText = @" namespace PushUpTest { public class Base { } public class TestClass : Base { public void TestMeth[||]od() { System.Console.WriteLine(""Hello World""); } } }"; var expected = @" namespace PushUpTest { public class Base { public void TestMethod() { System.Console.WriteLine(""Hello World""); } } public class TestClass : Base { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullOneFieldsToClassViaQuickAction() { var testText = @" namespace PushUpTest { public class Base { } public class TestClass : Base { public int you[||]= 10086; } }"; var expected = @" namespace PushUpTest { public class Base { public int you = 10086; } public class TestClass : Base { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullGenericsUpToClassViaQuickAction() { var testText = @" using System; namespace PushUpTest { public class BaseClass { } public class TestClass : BaseClass { public void TestMeth[||]od<T>() where T : IDisposable { } } }"; var expected = @" using System; namespace PushUpTest { public class BaseClass { public void TestMethod<T>() where T : IDisposable { } } public class TestClass : BaseClass { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullOneFieldFromMultipleFieldsToClassViaQuickAction() { var testText = @" namespace PushUpTest { public class Base { } public class TestClass : Base { public int you, a[||]nd, someone = 10086; } }"; var expected = @" namespace PushUpTest { public class Base { public int and; } public class TestClass : Base { public int you, someone = 10086; } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullMiddleFieldWithValueToClassViaQuickAction() { var testText = @" namespace PushUpTest { public class Base { } public class TestClass : Base { public int you, a[||]nd = 4000, someone = 10086; } }"; var expected = @" namespace PushUpTest { public class Base { public int and = 4000; } public class TestClass : Base { public int you, someone = 10086; } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullOneEventFromMultipleToClassViaQuickAction() { var testText = @" using System; namespace PushUpTest { public class Base2 { } public class Testclass2 : Base2 { private static event EventHandler Event1, Eve[||]nt3, Event4; } }"; var expected = @" using System; namespace PushUpTest { public class Base2 { private static event EventHandler Event3; } public class Testclass2 : Base2 { private static event EventHandler Event1, Event4; } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullEventToClassViaQuickAction() { var testText = @" using System; namespace PushUpTest { public class Base2 { } public class TestClass2 : Base2 { private static event EventHandler Eve[||]nt3; } }"; var expected = @" using System; namespace PushUpTest { public class Base2 { private static event EventHandler Event3; } public class TestClass2 : Base2 { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullEventWithBodyToClassViaQuickAction() { var testText = @" using System; namespace PushUpTest { public class Base2 { } public class TestClass2 : Base2 { private static event EventHandler Eve[||]nt3 { add { System.Console.Writeln(""Hello""); } remove { System.Console.Writeln(""World""); } }; } }"; var expected = @" using System; namespace PushUpTest { public class Base2 { private static event EventHandler Event3 { add { System.Console.Writeln(""Hello""); } remove { System.Console.Writeln(""World""); } }; } public class TestClass2 : Base2 { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullPropertyToClassViaQuickAction() { var testText = @" using System; namespace PushUpTest { public class Base { } public class TestClass : Base { public int TestPr[||]operty { get; private set; } } }"; var expected = @" using System; namespace PushUpTest { public class Base { public int TestProperty { get; private set; } } public class TestClass : Base { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullIndexerToClassViaQuickAction() { var testText = @" namespace PushUpTest { public class Base { } public class TestClass : Base { private int j; public int th[||]is[int i] { get => j; set => j = value; } } }"; var expected = @" namespace PushUpTest { public class Base { public int this[int i] { get => j; set => j = value; } } public class TestClass : Base { private int j; } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullMethodUpAcrossProjectViaQuickAction() { var testText = @" <Workspace> <Project Language=""C#"" AssemblyName=""CSAssembly1"" CommonReferences=""true""> <ProjectReference>CSAssembly2</ProjectReference> <Document> using Destination; public class TestClass : IInterface { public int Bar[||]Bar() { return 12345; } } </Document> </Project> <Project Language=""C#"" AssemblyName=""CSAssembly2"" CommonReferences=""true""> <Document> namespace Destination { public interface IInterface { } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""CSAssembly1"" CommonReferences=""true""> <ProjectReference>CSAssembly2</ProjectReference> <Document> using Destination; public class TestClass : IInterface { public int Bar[||]Bar() { return 12345; } } </Document> </Project> <Project Language=""C#"" AssemblyName=""CSAssembly2"" CommonReferences=""true""> <Document> namespace Destination { public interface IInterface { int BarBar(); } } </Document> </Project> </Workspace>"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullPropertyUpAcrossProjectViaQuickAction() { var testText = @" <Workspace> <Project Language=""C#"" AssemblyName=""CSAssembly1"" CommonReferences=""true""> <ProjectReference>CSAssembly2</ProjectReference> <Document> using Destination; public class TestClass : IInterface { public int F[||]oo { get; set; } } </Document> </Project> <Project Language=""C#"" AssemblyName=""CSAssembly2"" CommonReferences=""true""> <Document> namespace Destination { public interface IInterface { } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""CSAssembly1"" CommonReferences=""true""> <ProjectReference>CSAssembly2</ProjectReference> <Document> using Destination; public class TestClass : IInterface { public int Foo { get; set; } } </Document> </Project> <Project Language=""C#"" AssemblyName=""CSAssembly2"" CommonReferences=""true""> <Document> namespace Destination { public interface IInterface { int Foo { get; set; } } } </Document> </Project> </Workspace>"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullFieldUpAcrossProjectViaQuickAction() { var testText = @" <Workspace> <Project Language=""C#"" AssemblyName=""CSAssembly1"" CommonReferences=""true""> <ProjectReference>CSAssembly2</ProjectReference> <Document> using Destination; public class TestClass : BaseClass { private int i, j, [||]k = 10; } </Document> </Project> <Project Language=""C#"" AssemblyName=""CSAssembly2"" CommonReferences=""true""> <Document> namespace Destination { public class BaseClass { } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""CSAssembly1"" CommonReferences=""true""> <ProjectReference>CSAssembly2</ProjectReference> <Document> using Destination; public class TestClass : BaseClass { private int i, j; } </Document> </Project> <Project Language=""C#"" AssemblyName=""CSAssembly2"" CommonReferences=""true""> <Document> namespace Destination { public class BaseClass { private int k = 10; } } </Document> </Project> </Workspace>"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullMethodUpToVBClassViaQuickAction() { // Moving member from C# to Visual Basic is not supported currently since the FindMostRelevantDeclarationAsync method in // AbstractCodeGenerationService will return null. var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""CSAssembly"" CommonReferences=""true""> <ProjectReference>VBAssembly</ProjectReference> <Document> using VBAssembly; public class TestClass : VBClass { public int Bar[||]bar() { return 12345; } } </Document> </Project> <Project Language=""Visual Basic"" AssemblyName=""VBAssembly"" CommonReferences=""true""> <Document> Public Class VBClass End Class </Document> </Project> </Workspace>"; await TestQuickActionNotProvidedAsync(input); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullMethodUpToVBInterfaceViaQuickAction() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""CSAssembly"" CommonReferences=""true""> <ProjectReference>VBAssembly</ProjectReference> <Document> public class TestClass : VBInterface { public int Bar[||]bar() { return 12345; } } </Document> </Project> <Project Language=""Visual Basic"" AssemblyName=""VBAssembly"" CommonReferences=""true""> <Document> Public Interface VBInterface End Interface </Document> </Project> </Workspace> "; await TestQuickActionNotProvidedAsync(input); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullFieldUpToVBClassViaQuickAction() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""CSAssembly"" CommonReferences=""true""> <ProjectReference>VBAssembly</ProjectReference> <Document> using VBAssembly; public class TestClass : VBClass { public int fo[||]obar = 0; } </Document> </Project> <Project Language=""Visual Basic"" AssemblyName=""VBAssembly"" CommonReferences=""true""> <Document> Public Class VBClass End Class </Document> </Project> </Workspace>"; await TestQuickActionNotProvidedAsync(input); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullPropertyUpToVBClassViaQuickAction() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""CSAssembly"" CommonReferences=""true""> <ProjectReference>VBAssembly</ProjectReference> <Document> using VBAssembly; public class TestClass : VBClass { public int foo[||]bar { get; set; } }</Document> </Project> <Project Language=""Visual Basic"" AssemblyName=""VBAssembly"" CommonReferences=""true""> <Document> Public Class VBClass End Class </Document> </Project> </Workspace> "; await TestQuickActionNotProvidedAsync(input); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullPropertyUpToVBInterfaceViaQuickAction() { var input = @"<Workspace> <Project Language=""C#"" AssemblyName=""CSAssembly"" CommonReferences=""true""> <ProjectReference>VBAssembly</ProjectReference> <Document> using VBAssembly; public class TestClass : VBInterface { public int foo[||]bar { get; set; } } </Document> </Project> <Project Language = ""Visual Basic"" AssemblyName=""VBAssembly"" CommonReferences=""true""> <Document> Public Interface VBInterface End Interface </Document> </Project> </Workspace>"; await TestQuickActionNotProvidedAsync(input); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullEventUpToVBClassViaQuickAction() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""CSAssembly"" CommonReferences=""true""> <ProjectReference>VBAssembly</ProjectReference> <Document> using VBAssembly; public class TestClass : VBClass { public event EventHandler BarEve[||]nt; } </Document> </Project> <Project Language=""Visual Basic"" AssemblyName=""VBAssembly"" CommonReferences=""true""> <Document> Public Class VBClass End Class </Document> </Project> </Workspace>"; await TestQuickActionNotProvidedAsync(input); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullEventUpToVBInterfaceViaQuickAction() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""CSAssembly"" CommonReferences=""true""> <ProjectReference>VBAssembly</ProjectReference> <Document> using VBAssembly; public class TestClass : VBInterface { public event EventHandler BarEve[||]nt; } </Document> </Project> <Project Language=""Visual Basic"" AssemblyName=""VBAssembly"" CommonReferences=""true""> <Document> Public Interface VBInterface End Interface </Document> </Project> </Workspace>"; await TestQuickActionNotProvidedAsync(input); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(55746, "https://github.com/dotnet/roslyn/issues/55746")] public async Task TestPullMethodWithToClassWithAddUsingsInsideNamespaceViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace N { public class Base { } } </Document> <Document FilePath = ""File2.cs""> using System; namespace N { public class Derived : Base { public Uri En[||]dpoint() { return new Uri(""http://localhost""); } } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace N { using System; public class Base { public Uri Endpoint() { return new Uri(""http://localhost""); } } } </Document> <Document FilePath = ""File2.cs""> using System; namespace N { public class Derived : Base { } } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync( testText, expected, options: Option(CSharpCodeStyleOptions.PreferredUsingDirectivePlacement, CodeAnalysis.AddImports.AddImportPlacement.InsideNamespace, CodeStyle.NotificationOption2.Silent)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(55746, "https://github.com/dotnet/roslyn/issues/55746")] public async Task TestPullMethodWithToClassWithAddUsingsSystemUsingsLastViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace N1 { public class Base { } } </Document> <Document FilePath = ""File2.cs""> using System; using N2; namespace N1 { public class Derived : Base { public Goo Ge[||]tGoo() { return new Goo(String.Empty); } } } namespace N2 { public class Goo { public Goo(String s) { } } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using N2; using System; namespace N1 { public class Base { public Goo GetGoo() { return new Goo(String.Empty); } } } </Document> <Document FilePath = ""File2.cs""> using System; using N2; namespace N1 { public class Derived : Base { } } namespace N2 { public class Goo { public Goo(String s) { } } } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync( testText, expected, options: new(GetLanguage()) { { GenerationOptions.PlaceSystemNamespaceFirst, false }, }); } #endregion Quick Action #region Dialog internal Task TestWithPullMemberDialogAsync( string initialMarkUp, string expectedResult, IEnumerable<(string name, bool makeAbstract)> selection = null, string destinationName = null, int index = 0, TestParameters parameters = default) { var service = new TestPullMemberUpService(selection, destinationName); return TestInRegularAndScript1Async( initialMarkUp, expectedResult, index, parameters.WithFixProviderData(service)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullPartialMethodUpToInterfaceViaDialog() { var testText = @" using System; namespace PushUpTest { partial interface IInterface { } public partial class TestClass : IInterface { partial void Bar[||]Bar() } public partial class TestClass { partial void BarBar() {} } partial interface IInterface { } }"; var expected = @" using System; namespace PushUpTest { partial interface IInterface { void BarBar(); } public partial class TestClass : IInterface { void BarBar() } public partial class TestClass { partial void BarBar() {} } partial interface IInterface { } }"; await TestWithPullMemberDialogAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullExtendedPartialMethodUpToInterfaceViaDialog() { var testText = @" using System; namespace PushUpTest { partial interface IInterface { } public partial class TestClass : IInterface { public partial void Bar[||]Bar() } public partial class TestClass { public partial void BarBar() {} } partial interface IInterface { } }"; var expected = @" using System; namespace PushUpTest { partial interface IInterface { void BarBar(); } public partial class TestClass : IInterface { public partial void BarBar() } public partial class TestClass { public partial void BarBar() {} } partial interface IInterface { } }"; await TestWithPullMemberDialogAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullMultipleNonPublicMethodsToInterfaceViaDialog() { var testText = @" using System; namespace PushUpTest { interface IInterface { } public class TestClass : IInterface { public void TestMethod() { System.Console.WriteLine(""Hello World""); } protected void F[||]oo(int i) { // do awesome things } private static string Bar(string x) {} } }"; var expected = @" using System; namespace PushUpTest { interface IInterface { string Bar(string x); void Foo(int i); void TestMethod(); } public class TestClass : IInterface { public void TestMethod() { System.Console.WriteLine(""Hello World""); } public void Foo(int i) { // do awesome things } public string Bar(string x) {} } }"; await TestWithPullMemberDialogAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullMultipleNonPublicEventsToInterface() { var testText = @" using System; namespace PushUpTest { interface IInterface { } public class TestClass : IInterface { private event EventHandler Event1, Eve[||]nt2, Event3; } }"; var expected = @" using System; namespace PushUpTest { interface IInterface { event EventHandler Event1; event EventHandler Event2; event EventHandler Event3; } public class TestClass : IInterface { public event EventHandler Event1; public event EventHandler Event2; public event EventHandler Event3; } }"; await TestWithPullMemberDialogAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullMethodToInnerInterfaceViaDialog() { var testText = @" using System; namespace PushUpTest { public class TestClass : TestClass.IInterface { private void Bar[||]Bar() { } interface IInterface { } } }"; var expected = @" using System; namespace PushUpTest { public class TestClass : TestClass.IInterface { public void BarBar() { } interface IInterface { void BarBar(); } } }"; await TestWithPullMemberDialogAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullDifferentMembersFromClassToPartialInterfaceViaDialog() { var testText = @" using System; namespace PushUpTest { partial interface IInterface { } public class TestClass : IInterface { public int th[||]is[int i] { get => j = value; } private static void BarBar() {} protected static event EventHandler event1, event2; internal static int Foo { get; set; } } partial interface IInterface { } }"; var expected = @" using System; namespace PushUpTest { partial interface IInterface { int this[int i] { get; } int Foo { get; set; } event EventHandler event1; event EventHandler event2; void BarBar(); } public class TestClass : IInterface { public int this[int i] { get => j = value; } public void BarBar() {} public event EventHandler event1; public event EventHandler event2; public int Foo { get; set; } } partial interface IInterface { } }"; await TestWithPullMemberDialogAsync(testText, expected, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullAsyncMethod() { var testText = @" using System.Threading.Tasks; internal interface IPullUp { } internal class PullUp : IPullUp { internal async Task PullU[||]pAsync() { await Task.Delay(1000); } }"; var expectedText = @" using System.Threading.Tasks; internal interface IPullUp { Task PullUpAsync(); } internal class PullUp : IPullUp { public async Task PullUpAsync() { await Task.Delay(1000); } }"; await TestWithPullMemberDialogAsync(testText, expectedText); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullMethodWithAbstractOptionToClassViaDialog() { var testText = @" namespace PushUpTest { public class Base { } public class TestClass : Base { public void TestMeth[||]od() { System.Console.WriteLine(""Hello World""); } } }"; var expected = @" namespace PushUpTest { public abstract class Base { public abstract void TestMethod(); } public class TestClass : Base { public override void TestMeth[||]od() { System.Console.WriteLine(""Hello World""); } } }"; await TestWithPullMemberDialogAsync(testText, expected, new (string, bool)[] { ("TestMethod", true) }, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullAbstractMethodToClassViaDialog() { var testText = @" namespace PushUpTest { public class Base { } public abstract class TestClass : Base { public abstract void TestMeth[||]od(); } }"; var expected = @" namespace PushUpTest { public abstract class Base { public abstract void TestMethod(); } public abstract class TestClass : Base { } }"; await TestWithPullMemberDialogAsync(testText, expected, new (string, bool)[] { ("TestMethod", true) }, index: 0); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullMultipleEventsToClassViaDialog() { var testText = @" using System; namespace PushUpTest { public class Base2 { } public class Testclass2 : Base2 { private static event EventHandler Event1, Eve[||]nt3, Event4; } }"; var expected = @" using System; namespace PushUpTest { public class Base2 { private static event EventHandler Event1; private static event EventHandler Event3; private static event EventHandler Event4; } public class Testclass2 : Base2 { } }"; await TestWithPullMemberDialogAsync(testText, expected, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullMultipleAbstractEventsToInterfaceViaDialog() { var testText = @" using System; namespace PushUpTest { public interface ITest { } public abstract class Testclass2 : ITest { protected abstract event EventHandler Event1, Eve[||]nt3, Event4; } }"; var expected = @" using System; namespace PushUpTest { public interface ITest { event EventHandler Event1; event EventHandler Event3; event EventHandler Event4; } public abstract class Testclass2 : ITest { public abstract event EventHandler Event1; public abstract event EventHandler Event3; public abstract event EventHandler Event4; } }"; await TestWithPullMemberDialogAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullAbstractEventToClassViaDialog() { var testText = @" using System; namespace PushUpTest { public class Base2 { } public abstract class Testclass2 : Base2 { private static abstract event EventHandler Event1, Eve[||]nt3, Event4; } }"; var expected = @" using System; namespace PushUpTest { public abstract class Base2 { private static abstract event EventHandler Event3; } public abstract class Testclass2 : Base2 { private static abstract event EventHandler Event1, Event4; } }"; await TestWithPullMemberDialogAsync(testText, expected, new (string, bool)[] { ("Event3", false) }); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullNonPublicEventToInterfaceViaDialog() { var testText = @" using System; namespace PushUpTest { public interface ITest { } public class Testclass2 : ITest { private event EventHandler Eve[||]nt3; } }"; var expected = @" using System; namespace PushUpTest { public interface ITest { event EventHandler Event3; } public class Testclass2 : ITest { public event EventHandler Event3; } }"; await TestWithPullMemberDialogAsync(testText, expected, new (string, bool)[] { ("Event3", false) }); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullSingleNonPublicEventToInterfaceViaDialog() { var testText = @" using System; namespace PushUpTest { public interface ITest { } public abstract class TestClass2 : ITest { protected event EventHandler Eve[||]nt3; } }"; var expected = @" using System; namespace PushUpTest { public interface ITest { event EventHandler Event3; } public abstract class TestClass2 : ITest { public event EventHandler Event3; } }"; await TestWithPullMemberDialogAsync(testText, expected, new (string, bool)[] { ("Event3", false) }); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullNonPublicEventWithAddAndRemoveMethodToInterfaceViaDialog() { var testText = @" using System; namespace PushUpTest { interface IInterface { } public class TestClass : IInterface { private event EventHandler Eve[||]nt1 { add { System.Console.Writeline(""This is add""); } remove { System.Console.Writeline(""This is remove""); } } } }"; var expected = @" using System; namespace PushUpTest { interface IInterface { event EventHandler Event1; } public class TestClass : IInterface { public event EventHandler Event1 { add { System.Console.Writeline(""This is add""); } remove { System.Console.Writeline(""This is remove""); } } } }"; await TestWithPullMemberDialogAsync(testText, expected, new (string, bool)[] { ("Event1", false) }); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullFieldsToClassViaDialog() { var testText = @" using System; namespace PushUpTest { public class Base2 { } public class Testclass2 : Base2 { public int i, [||]j = 10, k = 100; } }"; var expected = @" using System; namespace PushUpTest { public class Base2 { public int i; public int j = 10; public int k = 100; } public class Testclass2 : Base2 { } }"; await TestWithPullMemberDialogAsync(testText, expected, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullNonPublicPropertyWithArrowToInterfaceViaDialog() { var testText = @" using System; namespace PushUpTest { public interface ITest { } public class Testclass2 : ITest { private double Test[||]Property => 2.717; } }"; var expected = @" using System; namespace PushUpTest { public interface ITest { double TestProperty { get; } } public class Testclass2 : ITest { public readonly double TestProperty => 2.717; } }"; await TestWithPullMemberDialogAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullNonPublicPropertyToInterfaceViaDialog() { var testText = @" using System; namespace PushUpTest { public interface ITest { } public class Testclass2 : ITest { private double Test[||]Property { get; set; } } }"; var expected = @" using System; namespace PushUpTest { public interface ITest { double TestProperty { get; set; } } public class Testclass2 : ITest { public double TestProperty { get; set; } } }"; await TestWithPullMemberDialogAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullNonPublicPropertyWithSingleAccessorToInterfaceViaDialog() { var testText = @" using System; namespace PushUpTest { public interface ITest { } public class Testclass2 : ITest { private static double Test[||]Property { set; } } }"; var expected = @" using System; namespace PushUpTest { public interface ITest { double TestProperty { set; } } public class Testclass2 : ITest { public double Test[||]Property { set; } } }"; await TestWithPullMemberDialogAsync(testText, expected); } [WorkItem(34268, "https://github.com/dotnet/roslyn/issues/34268")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullPropertyToAbstractClassViaDialogWithMakeAbstractOption() { var testText = @" abstract class B { } class D : B { int [||]X => 7; }"; var expected = @" abstract class B { private abstract int X { get; } } class D : B { override int X => 7; }"; await TestWithPullMemberDialogAsync(testText, expected, selection: new[] { ("X", true) }, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullEventUpToAbstractClassViaDialogWithMakeAbstractOption() { var testText = @" using System; namespace PushUpTest { public class Base2 { } public class Testclass2 : Base2 { private event EventHandler Event1, Eve[||]nt3, Event4; } }"; var expected = @" using System; namespace PushUpTest { public abstract class Base2 { private abstract event EventHandler Event3; } public class Testclass2 : Base2 { private event EventHandler Event1, Eve[||]nt3, Event4; } }"; await TestWithPullMemberDialogAsync(testText, expected, selection: new[] { ("Event3", true) }, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullEventWithAddAndRemoveMethodToClassViaDialogWithMakeAbstractOption() { var testText = @" using System; namespace PushUpTest { public class BaseClass { } public class TestClass : BaseClass { public event EventHandler Eve[||]nt1 { add { System.Console.Writeline(""This is add""); } remove { System.Console.Writeline(""This is remove""); } } } }"; var expected = @" using System; namespace PushUpTest { public abstract class BaseClass { public abstract event EventHandler Event1; } public class TestClass : BaseClass { public override event EventHandler Event1 { add { System.Console.Writeline(""This is add""); } remove { System.Console.Writeline(""This is remove""); } } } }"; await TestWithPullMemberDialogAsync(testText, expected, new (string, bool)[] { ("Event1", true) }, index: 1); } #endregion Dialog #region Selections and caret position [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestArgsIsPartOfHeader() { var testText = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } class Test2Attribute : Attribute { } public class A { } public class B : A { [Test] [Test2] void C([||]) { } } }"; var expected = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } class Test2Attribute : Attribute { } public class A { [Test] [Test2] void C() { } } public class B : A { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestRefactoringCaretBeforeAttributes() { var testText = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } class Test2Attribute : Attribute { } public class A { } public class B : A { [||][Test] [Test2] void C() { } } }"; var expected = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } class Test2Attribute : Attribute { } public class A { [Test] [Test2] void C() { } } public class B : A { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestMissingRefactoringCaretBetweenAttributes() { var testText = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } class Test2Attribute : Attribute { } public class A { } public class B : A { [Test] [||][Test2] void C() { } } }"; await TestQuickActionNotProvidedAsync(testText); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestRefactoringSelectionWithAttributes1() { var testText = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } public class A { } public class B : A { [Test] [|void C() { }|] } }"; var expected = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } public class A { [Test] void C() { } } public class B : A { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestRefactoringSelectionWithAttributes2() { var testText = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } public class A { } public class B : A { [|[Test] void C() { }|] } }"; var expected = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } public class A { [Test] void C() { } } public class B : A { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestRefactoringSelectionWithAttributes3() { var testText = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } public class A { } public class B : A { [Test][| void C() { } |] } }"; var expected = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } public class A { [Test] void C() { } } public class B : A { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestMissingRefactoringInAttributeList() { var testText = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } public class A { } public class B : A { [[||]Test] void C() { } } }"; await TestQuickActionNotProvidedAsync(testText); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestMissingRefactoringSelectionAttributeList() { var testText = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } class Test2Attribute : Attribute { } public class A { } public class B : A { [|[Test] [Test2]|] void C() { } } }"; await TestQuickActionNotProvidedAsync(testText); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestMissingRefactoringCaretInAttributeList() { var testText = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } class Test2Attribute : Attribute { } public class A { } public class B : A { [[||]Test] [Test2] void C() { } } }"; await TestQuickActionNotProvidedAsync(testText); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestMissingRefactoringCaretBetweenAttributeLists() { var testText = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } class Test2Attribute : Attribute { } public class A { } public class B : A { [Test] [||][Test2] void C() { } } }"; await TestQuickActionNotProvidedAsync(testText); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestMissingRefactoringSelectionAttributeList2() { var testText = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } class Test2Attribute : Attribute { } public class A { } public class B : A { [|[Test]|] [Test2] void C() { } } }"; await TestQuickActionNotProvidedAsync(testText); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestMissingRefactoringSelectAttributeList() { var testText = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } public class A { } public class B : A { [|[Test]|] void C() { } } }"; await TestQuickActionNotProvidedAsync(testText); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestRefactoringCaretLocAfterAttributes1() { var testText = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } public class A { } public class B : A { [Test] [||]void C() { } } }"; var expected = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } public class A { [Test] void C() { } } public class B : A { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestRefactoringCaretLocAfterAttributes2() { var testText = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } class Test2Attribute : Attribute { } public class A { } public class B : A { [Test] // Comment1 [Test2] // Comment2 [||]void C() { } } }"; var expected = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } class Test2Attribute : Attribute { } public class A { [Test] // Comment1 [Test2] // Comment2 void C() { } } public class B : A { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestRefactoringCaretLoc1() { var testText = @" namespace PushUpTest { public class A { } public class B : A { [||]void C() { } } }"; var expected = @" namespace PushUpTest { public class A { void C() { } } public class B : A { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestRefactoringSelection() { var testText = @" namespace PushUpTest { public class A { } public class B : A { [|void C() { }|] } }"; var expected = @" namespace PushUpTest { public class A { void C() { } } public class B : A { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestRefactoringSelectionComments() { var testText = @" namespace PushUpTest { public class A { } public class B : A { [| // Comment1 void C() { }|] } }"; var expected = @" namespace PushUpTest { public class A { // Comment1 void C() { } } public class B : A { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestRefactoringSelectionComments2() { var testText = @" namespace PushUpTest { public class A { } public class B : A { [|/// <summary> /// Test /// </summary> void C() { }|] } }"; var expected = @" namespace PushUpTest { public class A { /// <summary> /// Test /// </summary> void C() { } } public class B : A { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestRefactoringSelectionComments3() { var testText = @" namespace PushUpTest { public class A { } public class B : A { /// <summary> [|/// Test /// </summary> void C() { }|] } }"; var expected = @" namespace PushUpTest { public class A { /// <summary> /// Test /// </summary> void C() { } } public class B : A { } }"; await TestInRegularAndScriptAsync(testText, expected); } #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.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CSharp.CodeRefactorings.PullMemberUp; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; using System.Collections.Immutable; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeRefactorings.PullMemberUp.Dialog; using System.Collections.Generic; using Microsoft.CodeAnalysis.Test.Utilities.PullMemberUp; using Roslyn.Test.Utilities; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.Editing; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.PullMemberUp { public class CSharpPullMemberUpTests : AbstractCSharpCodeActionTest { protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters) => new CSharpPullMemberUpCodeRefactoringProvider((IPullMemberUpOptionsService)parameters.fixProviderData); protected override ImmutableArray<CodeAction> MassageActions(ImmutableArray<CodeAction> actions) => FlattenActions(actions); #region Quick Action private async Task TestQuickActionNotProvidedAsync( string initialMarkup, TestParameters parameters = default) { using var workspace = CreateWorkspaceFromOptions(initialMarkup, parameters); var (actions, _) = await GetCodeActionsAsync(workspace, parameters); if (actions.Length == 1) { // The dialog shows up, not quick action Assert.Equal(actions.First().Title, FeaturesResources.Pull_members_up_to_base_type); } else if (actions.Length > 1) { Assert.True(false, "Pull Members Up is provided via quick action"); } else { Assert.True(true); } } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestNoRefactoringProvidedWhenPullFieldInInterfaceViaQuickAction() { var testText = @" namespace PushUpTest { public interface ITestInterface { } public class TestClass : ITestInterface { public int yo[||]u = 10086; } }"; await TestQuickActionNotProvidedAsync(testText); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestNoRefactoringProvidedWhenMethodDeclarationAlreadyExistsInInterfaceViaQuickAction() { var methodTest = @" namespace PushUpTest { public interface ITestInterface { void TestMethod(); } public class TestClass : ITestInterface { public void TestM[||]ethod() { System.Console.WriteLine(""Hello World""); } } }"; await TestQuickActionNotProvidedAsync(methodTest); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestNoRefactoringProvidedWhenPropertyDeclarationAlreadyExistsInInterfaceViaQuickAction() { var propertyTest1 = @" using System; namespace PushUpTest { interface IInterface { int TestProperty { get; } } public class TestClass : IInterface { public int TestPr[||]operty { get; private set; } } }"; await TestQuickActionNotProvidedAsync(propertyTest1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestNoRefactoringProvidedWhenEventDeclarationAlreadyExistsToInterfaceViaQuickAction() { var eventTest = @" using System; namespace PushUpTest { interface IInterface { event EventHandler Event2; } public class TestClass : IInterface { public event EventHandler Event1, Eve[||]nt2, Event3; } }"; await TestQuickActionNotProvidedAsync(eventTest); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestNoRefactoringProvidedInNestedTypesViaQuickAction() { var input = @" namespace PushUpTest { public interface ITestInterface { void Foobar(); } public class TestClass : ITestInterface { public class N[||]estedClass { } } }"; await TestQuickActionNotProvidedAsync(input); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullMethodUpToInterfaceViaQuickAction() { var testText = @" using System; namespace PushUpTest { interface IInterface { } public class TestClass : IInterface { public void TestM[||]ethod() { System.Console.WriteLine(""Hello World""); } } }"; var expected = @" using System; namespace PushUpTest { interface IInterface { void TestMethod(); } public class TestClass : IInterface { public void TestMethod() { System.Console.WriteLine(""Hello World""); } } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullAbstractMethodToInterfaceViaQuickAction() { var testText = @" namespace PushUpTest { public interface IInterface { } public abstract class TestClass : IInterface { public abstract void TestMeth[||]od(); } }"; var expected = @" namespace PushUpTest { public interface IInterface { void TestMethod(); } public abstract class TestClass : IInterface { public abstract void TestMethod(); } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullGenericsUpToInterfaceViaQuickAction() { var testText = @" using System; namespace PushUpTest { public interface IInterface { } public class TestClass : IInterface { public void TestMeth[||]od<T>() where T : IDisposable { } } }"; var expected = @" using System; namespace PushUpTest { public interface IInterface { void TestMethod<T>() where T : IDisposable; } public class TestClass : IInterface { public void TestMeth[||]od<T>() where T : IDisposable { } } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullSingleEventToInterfaceViaQuickAction() { var testText = @" using System; namespace PushUpTest { interface IInterface { } public class TestClass : IInterface { public event EventHandler Eve[||]nt1 { add { System.Console.Writeline(""This is add""); } remove { System.Console.Writeline(""This is remove""); } } } }"; var expected = @" using System; namespace PushUpTest { interface IInterface { event EventHandler Event1; } public class TestClass : IInterface { public event EventHandler Event1 { add { System.Console.Writeline(""This is add""); } remove { System.Console.Writeline(""This is remove""); } } } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullOneEventFromMultipleEventsToInterfaceViaQuickAction() { var testText = @" using System; namespace PushUpTest { interface IInterface { } public class TestClass : IInterface { public event EventHandler Event1, Eve[||]nt2, Event3; } }"; var expected = @" using System; namespace PushUpTest { interface IInterface { event EventHandler Event2; } public class TestClass : IInterface { public event EventHandler Event1, Event2, Event3; } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullPublicEventWithAccessorsToInterfaceViaQuickAction() { var testText = @" using System; namespace PushUpTest { interface IInterface { } public class TestClass : IInterface { public event EventHandler Eve[||]nt2 { add { System.Console.Writeln(""This is add in event1""); } remove { System.Console.Writeln(""This is remove in event2""); } } } }"; var expected = @" using System; namespace PushUpTest { interface IInterface { event EventHandler Event2; } public class TestClass : IInterface { public event EventHandler Event2 { add { System.Console.Writeln(""This is add in event1""); } remove { System.Console.Writeln(""This is remove in event2""); } } } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullPropertyWithPrivateSetterToInterfaceViaQuickAction() { var testText = @" using System; namespace PushUpTest { interface IInterface { } public class TestClass : IInterface { public int TestPr[||]operty { get; private set; } } }"; var expected = @" using System; namespace PushUpTest { interface IInterface { int TestProperty { get; } } public class TestClass : IInterface { public int TestProperty { get; private set; } } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullPropertyWithPrivateGetterToInterfaceViaQuickAction() { var testText = @" using System; namespace PushUpTest { interface IInterface { } public class TestClass : IInterface { public int TestProperty[||]{ private get; set; } } }"; var expected = @" using System; namespace PushUpTest { interface IInterface { int TestProperty { set; } } public class TestClass : IInterface { public int TestProperty{ private get; set; } } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullMemberFromInterfaceToInterfaceViaQuickAction() { var testText = @" using System; namespace PushUpTest { interface IInterface { } interface FooInterface : IInterface { int TestPr[||]operty { set; } } }"; var expected = @" using System; namespace PushUpTest { interface IInterface { int TestProperty { set; } } interface FooInterface : IInterface { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullIndexerWithOnlySetterToInterfaceViaQuickAction() { var testText = @" using System; namespace PushUpTest { interface IInterface { } public class TestClass : IInterface { private int j; public int th[||]is[int i] { set => j = value; } } }"; var expected = @" using System; namespace PushUpTest { interface IInterface { int this[int i] { set; } } public class TestClass : IInterface { private int j; public int this[int i] { set => j = value; } } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullIndexerWithOnlyGetterToInterfaceViaQuickAction() { var testText = @" using System; namespace PushUpTest { interface IInterface { } public class TestClass : IInterface { private int j; public int th[||]is[int i] { get => j = value; } } }"; var expected = @" using System; namespace PushUpTest { interface IInterface { int this[int i] { get; } } public class TestClass : IInterface { private int j; public int this[int i] { get => j = value; } } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullPropertyToInterfaceWithAddUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public interface IBase { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : IBase { public Uri En[||]dpoint { get; set; } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; public interface IBase { Uri Endpoint { get; set; } } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : IBase { public Uri Endpoint { get; set; } } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToInterfaceWithoutAddUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public interface IBase { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : IBase { public bool Test[||]Method() { var endpoint1 = new Uri(""http://localhost""); var endpoint2 = new Uri(""http://localhost""); return endpoint1.Equals(endpoint2); } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public interface IBase { bool TestMethod(); } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : IBase { public bool Test[||]Method() { var endpoint1 = new Uri(""http://localhost""); var endpoint2 = new Uri(""http://localhost""); return endpoint1.Equals(endpoint2); } } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodWithNewReturnTypeToInterfaceWithAddUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public interface IBase { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : IBase { public Uri Test[||]Method() { return new Uri(""http://localhost""); } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; public interface IBase { Uri TestMethod(); } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : IBase { public Uri TestMethod() { return new Uri(""http://localhost""); } } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodWithNewParamTypeToInterfaceWithAddUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public interface IBase { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : IBase { public bool Test[||]Method(Uri endpoint) { var localHost = new Uri(""http://localhost""); return endpoint.Equals(localhost); } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; public interface IBase { bool TestMethod(Uri endpoint); } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : IBase { public bool TestMethod(Uri endpoint) { var localHost = new Uri(""http://localhost""); return endpoint.Equals(localhost); } } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullEventToInterfaceWithAddUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public interface IBase { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : IBase { public event EventHandler Test[||]Event { add { Console.WriteLine(""adding event...""); } remove { Console.WriteLine(""removing event...""); } } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; public interface IBase { event EventHandler TestEvent; } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : IBase { public event EventHandler TestEvent { add { Console.WriteLine(""adding event...""); } remove { Console.WriteLine(""removing event...""); } } } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullPropertyToClassWithAddUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public class Base { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { public Uri En[||]dpoint { get; set; } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using System; public class Base { public Uri Endpoint { get; set; } } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullPropertyToClassWithAddUsingsViaQuickAction2() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">public class Base { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { public Uri En[||]dpoint { get; set; } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using System; public class Base { public Uri Endpoint { get; set; } } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullPropertyToClassWithoutDuplicatingUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; public class Base { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { public Uri En[||]dpoint { get; set; } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; public class Base { public Uri Endpoint { get; set; } } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullPropertyWithNewBodyTypeToClassWithAddUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public class Base { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { public bool Test[||]Property { get { var endpoint1 = new Uri(""http://localhost""); var endpoint2 = new Uri(""http://localhost""); return endpoint1.Equals(endpoint2); } } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using System; public class Base { public bool TestProperty { get { var endpoint1 = new Uri(""http://localhost""); var endpoint2 = new Uri(""http://localhost""); return endpoint1.Equals(endpoint2); } } } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodWithNewNonDeclaredBodyTypeToClassWithAddUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public class Base { } </Document> <Document FilePath = ""File2.cs""> using System.Linq; public class Derived : Base { public int Test[||]Method() { return Enumerable.Range(0, 5).Sum(); } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using System.Linq; public class Base { public int Test[||]Method() { return Enumerable.Range(0, 5).Sum(); } } </Document> <Document FilePath = ""File2.cs""> using System.Linq; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithOverlappingUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; using System.Threading.Tasks; public class Base { public Uri Endpoint{ get; set; } public async Task&lt;int&gt; Get5Async() { return 5; } } </Document> <Document FilePath = ""File2.cs""> using System.Linq; using System.Threading.Tasks; public class Derived : Base { public async Task&lt;int&gt; Test[||]Method() { return Enumerable.Range(0, 5).Sum(); } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; using System.Linq; using System.Threading.Tasks; public class Base { public Uri Endpoint{ get; set; } public async Task&lt;int&gt; Get5Async() { return 5; } public async Task&lt;int&gt; Test[||]Method() { return Enumerable.Range(0, 5).Sum(); } } </Document> <Document FilePath = ""File2.cs""> using System.Linq; using System.Threading.Tasks; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithUnnecessaryFirstUsingViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System.Threading.Tasks; public class Base { public async Task&lt;int&gt; Get5Async() { return 5; } } </Document> <Document FilePath = ""File2.cs""> using System; using System.Linq; using System.Threading.Tasks; public class Derived : Base { public async Task&lt;int&gt; Test[||]Method() { return Enumerable.Range(0, 5).Sum(); } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using System.Linq; using System.Threading.Tasks; public class Base { public async Task&lt;int&gt; Get5Async() { return 5; } public async Task&lt;int&gt; Test[||]Method() { return Enumerable.Range(0, 5).Sum(); } } </Document> <Document FilePath = ""File2.cs""> using System; using System.Linq; using System.Threading.Tasks; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithUnusedBaseUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; using System.Threading.Tasks; public class Base { public Uri Endpoint{ get; set; } } </Document> <Document FilePath = ""File2.cs""> using System.Linq; public class Derived : Base { public int Test[||]Method() { return Enumerable.Range(0, 5).Sum(); } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; using System.Linq; using System.Threading.Tasks; public class Base { public Uri Endpoint{ get; set; } public int TestMethod() { return Enumerable.Range(0, 5).Sum(); } } </Document> <Document FilePath = ""File2.cs""> using System.Linq; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithRetainCommentsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> // blah blah public class Base { } </Document> <Document FilePath = ""File2.cs""> using System.Linq; public class Derived : Base { public int Test[||]Method() { return 5; } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> // blah blah public class Base { public int TestMethod() { return 5; } } </Document> <Document FilePath = ""File2.cs""> using System.Linq; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithRetainPreImportCommentsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> // blah blah using System.Linq; public class Base { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { public Uri End[||]point { get; set; } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> // blah blah using System; using System.Linq; public class Base { public Uri Endpoint { get; set; } } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithRetainPostImportCommentsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System.Linq; // blah blah public class Base { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { public Uri End[||]point { get; set; } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; using System.Linq; // blah blah public class Base { public Uri Endpoint { get; set; } } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithLambdaUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public class Base { } </Document> <Document FilePath = ""File2.cs""> using System; using System.Linq; public class Derived : Base { public int Test[||]Method() { return Enumerable.Range(0, 5). Select((n) => new Uri(""http://"" + n)). Count((uri) => uri != null); } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using System; using System.Linq; public class Base { public int TestMethod() { return Enumerable.Range(0, 5). Select((n) => new Uri(""http://"" + n)). Count((uri) => uri != null); } } </Document> <Document FilePath = ""File2.cs""> using System; using System.Linq; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithUnusedUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; public class Base { public Uri Endpoint{ get; set; } } </Document> <Document FilePath = ""File2.cs""> using System.Linq; using System.Threading.Tasks; public class Derived : Base { public int Test[||]Method() { return Enumerable.Range(0, 5).Sum(); } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; using System.Linq; public class Base { public Uri Endpoint{ get; set; } public int TestMethod() { return Enumerable.Range(0, 5).Sum(); } } </Document> <Document FilePath = ""File2.cs""> using System.Linq; using System.Threading.Tasks; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassKeepSystemFirstViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace TestNs1 { using System; public class Base { public Uri Endpoint{ get; set; } } } </Document> <Document FilePath = ""File2.cs""> namespace A_TestNs2 { using TestNs1; public class Derived : Base { public Foo Test[||]Method() { return null; } } public class Foo { } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace TestNs1 { using System; using A_TestNs2; public class Base { public Uri Endpoint{ get; set; } public Foo TestMethod() { return null; } } } </Document> <Document FilePath = ""File2.cs""> namespace A_TestNs2 { using TestNs1; public class Derived : Base { } public class Foo { } } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassKeepSystemFirstViaQuickAction2() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace TestNs1 { public class Base { } } </Document> <Document FilePath = ""File2.cs""> namespace A_TestNs2 { using System; using TestNs1; public class Derived : Base { public Foo Test[||]Method() { var uri = new Uri(""http://localhost""); return null; } } public class Foo { } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using System; using A_TestNs2; namespace TestNs1 { public class Base { public Foo TestMethod() { var uri = new Uri(""http://localhost""); return null; } } } </Document> <Document FilePath = ""File2.cs""> namespace A_TestNs2 { using System; using TestNs1; public class Derived : Base { } public class Foo { } } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithExtensionViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace TestNs1 { public class Base { } public class Foo { } } </Document> <Document FilePath = ""File2.cs""> namespace TestNs2 { using TestNs1; public class Derived : Base { public int Test[||]Method() { var foo = new Foo(); return foo.FooBar(); } } public static class FooExtensions { public static int FooBar(this Foo foo) { return 5; } } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using TestNs2; namespace TestNs1 { public class Base { public int TestMethod() { var foo = new Foo(); return foo.FooBar(); } } public class Foo { } } </Document> <Document FilePath = ""File2.cs""> namespace TestNs2 { using TestNs1; public class Derived : Base { } public static class FooExtensions { public static int FooBar(this Foo foo) { return 5; } } } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithExtensionViaQuickAction2() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace TestNs1 { public class Base { } } </Document> <Document FilePath = ""File2.cs""> using TestNs1; using TestNs3; using TestNs4; namespace TestNs2 { public class Derived : Base { public int Test[||]Method() { var foo = new Foo(); return foo.FooBar(); } } } </Document> <Document FilePath = ""File3.cs""> namespace TestNs3 { public class Foo { } } </Document> <Document FilePath = ""File4.cs""> using TestNs3; namespace TestNs4 { public static class FooExtensions { public static int FooBar(this Foo foo) { return 5; } } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using TestNs3; using TestNs4; namespace TestNs1 { public class Base { public int TestMethod() { var foo = new Foo(); return foo.FooBar(); } } } </Document> <Document FilePath = ""File2.cs""> using TestNs1; using TestNs3; using TestNs4; namespace TestNs2 { public class Derived : Base { } } </Document> <Document FilePath = ""File3.cs""> namespace TestNs3 { public class Foo { } } </Document> <Document FilePath = ""File4.cs""> using TestNs3; namespace TestNs4 { public static class FooExtensions { public static int FooBar(this Foo foo) { return 5; } } } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithAliasUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; public class Base { public Uri Endpoint{ get; set; } } </Document> <Document FilePath = ""File2.cs""> using Enumer = System.Linq.Enumerable; using Sys = System; public class Derived : Base { public void Test[||]Method() { Sys.Console.WriteLine(Enumer.Range(0, 5).Sum()); } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; using Enumer = System.Linq.Enumerable; using Sys = System; public class Base { public Uri Endpoint{ get; set; } public void TestMethod() { Sys.Console.WriteLine(Enumer.Range(0, 5).Sum()); } } </Document> <Document FilePath = ""File2.cs""> using Enumer = System.Linq.Enumerable; using Sys = System; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullPropertyToClassWithBaseAliasUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using Enumer = System.Linq.Enumerable; public class Base { public void TestMethod() { System.Console.WriteLine(Enumer.Range(0, 5).Sum()); } } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { public Uri End[||]point{ get; set; } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; using Enumer = System.Linq.Enumerable; public class Base { public Uri Endpoint{ get; set; } public void TestMethod() { System.Console.WriteLine(Enumer.Range(0, 5).Sum()); } } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithMultipleNamespacedUsingsViaQuickAction() { var testText = @" namespace TestNs1 { using System; public class Base { public Uri Endpoint{ get; set; } } } namespace TestNs2 { using System.Linq; using TestNs1; public class Derived : Base { public int Test[||]Method() { return Enumerable.Range(0, 5).Sum(); } } } "; var expected = @" namespace TestNs1 { using System; using System.Linq; public class Base { public Uri Endpoint{ get; set; } public int TestMethod() { return Enumerable.Range(0, 5).Sum(); } } } namespace TestNs2 { using System.Linq; using TestNs1; public class Derived : Base { } } "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithNestedNamespacedUsingsViaQuickAction() { var testText = @" namespace TestNs1 { namespace InnerNs1 { using System; public class Base { public Uri Endpoint { get; set; } } } } namespace TestNs2 { namespace InnerNs2 { using System.Linq; using TestNs1.InnerNs1; public class Derived : Base { public int Test[||]Method() { return Foo.Bar(Enumerable.Range(0, 5).Sum()); } } public class Foo { public static int Bar(int num) { return num + 1; } } } } "; var expected = @" namespace TestNs1 { namespace InnerNs1 { using System; using System.Linq; using TestNs2.InnerNs2; public class Base { public Uri Endpoint { get; set; } public int TestMethod() { return Foo.Bar(Enumerable.Range(0, 5).Sum()); } } } } namespace TestNs2 { namespace InnerNs2 { using System.Linq; using TestNs1.InnerNs1; public class Derived : Base { } public class Foo { public static int Bar(int num) { return num + 1; } } } } "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithNewNamespaceUsingViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace A.B { class Base { } } </Document> <Document FilePath = ""File2.cs""> namespace X.Y { class Derived : A.B.Base { public Other Get[||]Other() => null; } class Other { } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using X.Y; namespace A.B { class Base { public Other GetOther() => null; } } </Document> <Document FilePath = ""File2.cs""> namespace X.Y { class Derived : A.B.Base { } class Other { } } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithFileNamespaceUsingViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace A.B; class Base { } </Document> <Document FilePath = ""File2.cs""> namespace X.Y; class Derived : A.B.Base { public Other Get[||]Other() => null; } class Other { } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using X.Y; namespace A.B; class Base { public Other GetOther() => null; } </Document> <Document FilePath = ""File2.cs""> namespace X.Y; class Derived : A.B.Base { } class Other { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithUnusedNamespaceUsingViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace A.B { class Base { } } </Document> <Document FilePath = ""File2.cs""> namespace X.Y { class Derived : A.B.Base { public int Get[||]Five() => 5; } class Other { } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace A.B { class Base { public int GetFive() => 5; } } </Document> <Document FilePath = ""File2.cs""> namespace X.Y { class Derived : A.B.Base { } class Other { } } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithMultipleNamespacesAndCommentsViaQuickAction() { var testText = @" // comment 1 namespace TestNs1 { // comment 2 // comment 3 public class Base { } } namespace TestNs2 { // comment 4 using System.Linq; using TestNs1; public class Derived : Base { public int Test[||]Method() { return 5; } } } "; var expected = @" // comment 1 namespace TestNs1 { // comment 2 // comment 3 public class Base { public int TestMethod() { return 5; } } } namespace TestNs2 { // comment 4 using System.Linq; using TestNs1; public class Derived : Base { } } "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithMultipleNamespacedUsingsAndCommentsViaQuickAction() { var testText = @" // comment 1 namespace TestNs1 { // comment 2 using System; // comment 3 public class Base { } } namespace TestNs2 { // comment 4 using System.Linq; using TestNs1; public class Derived : Base { public int Test[||]Method() { return Enumerable.Range(0, 5).Sum(); } } } "; var expected = @" // comment 1 namespace TestNs1 { // comment 2 using System; using System.Linq; // comment 3 public class Base { public int TestMethod() { return Enumerable.Range(0, 5).Sum(); } } } namespace TestNs2 { // comment 4 using System.Linq; using TestNs1; public class Derived : Base { } } "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithNamespacedUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace ClassLibrary1 { using System; public class Base { public Uri Endpoint{ get; set; } } } </Document> <Document FilePath = ""File2.cs""> namespace ClassLibrary1 { using System.Linq; public class Derived : Base { public int Test[||]Method() { return Enumerable.Range(0, 5).Sum(); } } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace ClassLibrary1 { using System; using System.Linq; public class Base { public Uri Endpoint{ get; set; } public int Test[||]Method() { return Enumerable.Range(0, 5).Sum(); } } } </Document> <Document FilePath = ""File2.cs""> namespace ClassLibrary1 { using System.Linq; public class Derived : Base { } } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithDuplicateNamespacedUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace ClassLibrary1 { using System; public class Base { public Uri Endpoint{ get; set; } } } </Document> <Document FilePath = ""File2.cs""> using System.Linq; namespace ClassLibrary1 { using System.Linq; public class Derived : Base { public int Test[||]Method() { return Enumerable.Range(0, 5).Sum(); } } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace ClassLibrary1 { using System; using System.Linq; public class Base { public Uri Endpoint{ get; set; } public int Test[||]Method() { return Enumerable.Range(0, 5).Sum(); } } } </Document> <Document FilePath = ""File2.cs""> using System.Linq; namespace ClassLibrary1 { using System.Linq; public class Derived : Base { } } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodWithNewReturnTypeToClassWithAddUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public class Base { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { public Uri En[||]dpoint() { return new Uri(""http://localhost""); } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using System; public class Base { public Uri Endpoint() { return new Uri(""http://localhost""); } } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodWithNewParamTypeToClassWithAddUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public class Base { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { public bool Test[||]Method(Uri endpoint) { var localHost = new Uri(""http://localhost""); return endpoint.Equals(localhost); } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using System; public class Base { public bool TestMethod(Uri endpoint) { var localHost = new Uri(""http://localhost""); return endpoint.Equals(localhost); } } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodWithNewBodyTypeToClassWithAddUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public class Base { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { public bool Test[||]Method() { var endpoint1 = new Uri(""http://localhost""); var endpoint2 = new Uri(""http://localhost""); return endpoint1.Equals(endpoint2); } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using System; public class Base { public bool TestMethod() { var endpoint1 = new Uri(""http://localhost""); var endpoint2 = new Uri(""http://localhost""); return endpoint1.Equals(endpoint2); } } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullEventToClassWithAddUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public class Base { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { public event EventHandler Test[||]Event { add { Console.WriteLine(""adding event...""); } remove { Console.WriteLine(""removing event...""); } } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using System; public class Base { public event EventHandler Test[||]Event { add { Console.WriteLine(""adding event...""); } remove { Console.WriteLine(""removing event...""); } } } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullFieldToClassWithAddUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public class Base { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { public var en[||]dpoint = new Uri(""http://localhost""); } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using System; public class Base { public var endpoint = new Uri(""http://localhost""); } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullFieldToClassNoConstructorWithAddUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public class Base { } </Document> <Document FilePath = ""File2.cs""> using System.Linq; public class Derived : Base { public var ran[||]ge = Enumerable.Range(0, 5); } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using System.Linq; public class Base { public var range = Enumerable.Range(0, 5); } </Document> <Document FilePath = ""File2.cs""> using System.Linq; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestNoRefactoringProvidedWhenPullOverrideMethodUpToClassViaQuickAction() { var methodTest = @" namespace PushUpTest { public class Base { public virtual void TestMethod() => System.Console.WriteLine(""foo bar bar foo""); } public class TestClass : Base { public override void TestMeth[||]od() { System.Console.WriteLine(""Hello World""); } } }"; await TestQuickActionNotProvidedAsync(methodTest); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestNoRefactoringProvidedWhenPullOverridePropertyUpToClassViaQuickAction() { var propertyTest = @" using System; namespace PushUpTest { public class Base { public virtual int TestProperty { get => 111; private set; } } public class TestClass : Base { public override int TestPr[||]operty { get; private set; } } }"; await TestQuickActionNotProvidedAsync(propertyTest); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestNoRefactoringProvidedWhenPullOverrideEventUpToClassViaQuickAction() { var eventTest = @" using System; namespace PushUpTest { public class Base2 { protected virtual event EventHandler Event3 { add { System.Console.WriteLine(""Hello""); } remove { System.Console.WriteLine(""World""); } }; } public class TestClass2 : Base2 { protected override event EventHandler E[||]vent3 { add { System.Console.WriteLine(""foo""); } remove { System.Console.WriteLine(""bar""); } }; } }"; await TestQuickActionNotProvidedAsync(eventTest); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestNoRefactoringProvidedWhenPullSameNameFieldUpToClassViaQuickAction() { // Fields share the same name will be thought as 'override', since it will cause error // if two same name fields exist in one class var fieldTest = @" namespace PushUpTest { public class Base { public int you = -100000; } public class TestClass : Base { public int y[||]ou = 10086; } }"; await TestQuickActionNotProvidedAsync(fieldTest); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullMethodToOrdinaryClassViaQuickAction() { var testText = @" namespace PushUpTest { public class Base { } public class TestClass : Base { public void TestMeth[||]od() { System.Console.WriteLine(""Hello World""); } } }"; var expected = @" namespace PushUpTest { public class Base { public void TestMethod() { System.Console.WriteLine(""Hello World""); } } public class TestClass : Base { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullOneFieldsToClassViaQuickAction() { var testText = @" namespace PushUpTest { public class Base { } public class TestClass : Base { public int you[||]= 10086; } }"; var expected = @" namespace PushUpTest { public class Base { public int you = 10086; } public class TestClass : Base { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullGenericsUpToClassViaQuickAction() { var testText = @" using System; namespace PushUpTest { public class BaseClass { } public class TestClass : BaseClass { public void TestMeth[||]od<T>() where T : IDisposable { } } }"; var expected = @" using System; namespace PushUpTest { public class BaseClass { public void TestMethod<T>() where T : IDisposable { } } public class TestClass : BaseClass { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullOneFieldFromMultipleFieldsToClassViaQuickAction() { var testText = @" namespace PushUpTest { public class Base { } public class TestClass : Base { public int you, a[||]nd, someone = 10086; } }"; var expected = @" namespace PushUpTest { public class Base { public int and; } public class TestClass : Base { public int you, someone = 10086; } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullMiddleFieldWithValueToClassViaQuickAction() { var testText = @" namespace PushUpTest { public class Base { } public class TestClass : Base { public int you, a[||]nd = 4000, someone = 10086; } }"; var expected = @" namespace PushUpTest { public class Base { public int and = 4000; } public class TestClass : Base { public int you, someone = 10086; } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullOneEventFromMultipleToClassViaQuickAction() { var testText = @" using System; namespace PushUpTest { public class Base2 { } public class Testclass2 : Base2 { private static event EventHandler Event1, Eve[||]nt3, Event4; } }"; var expected = @" using System; namespace PushUpTest { public class Base2 { private static event EventHandler Event3; } public class Testclass2 : Base2 { private static event EventHandler Event1, Event4; } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullEventToClassViaQuickAction() { var testText = @" using System; namespace PushUpTest { public class Base2 { } public class TestClass2 : Base2 { private static event EventHandler Eve[||]nt3; } }"; var expected = @" using System; namespace PushUpTest { public class Base2 { private static event EventHandler Event3; } public class TestClass2 : Base2 { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullEventWithBodyToClassViaQuickAction() { var testText = @" using System; namespace PushUpTest { public class Base2 { } public class TestClass2 : Base2 { private static event EventHandler Eve[||]nt3 { add { System.Console.Writeln(""Hello""); } remove { System.Console.Writeln(""World""); } }; } }"; var expected = @" using System; namespace PushUpTest { public class Base2 { private static event EventHandler Event3 { add { System.Console.Writeln(""Hello""); } remove { System.Console.Writeln(""World""); } }; } public class TestClass2 : Base2 { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullPropertyToClassViaQuickAction() { var testText = @" using System; namespace PushUpTest { public class Base { } public class TestClass : Base { public int TestPr[||]operty { get; private set; } } }"; var expected = @" using System; namespace PushUpTest { public class Base { public int TestProperty { get; private set; } } public class TestClass : Base { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullIndexerToClassViaQuickAction() { var testText = @" namespace PushUpTest { public class Base { } public class TestClass : Base { private int j; public int th[||]is[int i] { get => j; set => j = value; } } }"; var expected = @" namespace PushUpTest { public class Base { public int this[int i] { get => j; set => j = value; } } public class TestClass : Base { private int j; } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullMethodUpAcrossProjectViaQuickAction() { var testText = @" <Workspace> <Project Language=""C#"" AssemblyName=""CSAssembly1"" CommonReferences=""true""> <ProjectReference>CSAssembly2</ProjectReference> <Document> using Destination; public class TestClass : IInterface { public int Bar[||]Bar() { return 12345; } } </Document> </Project> <Project Language=""C#"" AssemblyName=""CSAssembly2"" CommonReferences=""true""> <Document> namespace Destination { public interface IInterface { } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""CSAssembly1"" CommonReferences=""true""> <ProjectReference>CSAssembly2</ProjectReference> <Document> using Destination; public class TestClass : IInterface { public int Bar[||]Bar() { return 12345; } } </Document> </Project> <Project Language=""C#"" AssemblyName=""CSAssembly2"" CommonReferences=""true""> <Document> namespace Destination { public interface IInterface { int BarBar(); } } </Document> </Project> </Workspace>"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullPropertyUpAcrossProjectViaQuickAction() { var testText = @" <Workspace> <Project Language=""C#"" AssemblyName=""CSAssembly1"" CommonReferences=""true""> <ProjectReference>CSAssembly2</ProjectReference> <Document> using Destination; public class TestClass : IInterface { public int F[||]oo { get; set; } } </Document> </Project> <Project Language=""C#"" AssemblyName=""CSAssembly2"" CommonReferences=""true""> <Document> namespace Destination { public interface IInterface { } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""CSAssembly1"" CommonReferences=""true""> <ProjectReference>CSAssembly2</ProjectReference> <Document> using Destination; public class TestClass : IInterface { public int Foo { get; set; } } </Document> </Project> <Project Language=""C#"" AssemblyName=""CSAssembly2"" CommonReferences=""true""> <Document> namespace Destination { public interface IInterface { int Foo { get; set; } } } </Document> </Project> </Workspace>"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullFieldUpAcrossProjectViaQuickAction() { var testText = @" <Workspace> <Project Language=""C#"" AssemblyName=""CSAssembly1"" CommonReferences=""true""> <ProjectReference>CSAssembly2</ProjectReference> <Document> using Destination; public class TestClass : BaseClass { private int i, j, [||]k = 10; } </Document> </Project> <Project Language=""C#"" AssemblyName=""CSAssembly2"" CommonReferences=""true""> <Document> namespace Destination { public class BaseClass { } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""CSAssembly1"" CommonReferences=""true""> <ProjectReference>CSAssembly2</ProjectReference> <Document> using Destination; public class TestClass : BaseClass { private int i, j; } </Document> </Project> <Project Language=""C#"" AssemblyName=""CSAssembly2"" CommonReferences=""true""> <Document> namespace Destination { public class BaseClass { private int k = 10; } } </Document> </Project> </Workspace>"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullMethodUpToVBClassViaQuickAction() { // Moving member from C# to Visual Basic is not supported currently since the FindMostRelevantDeclarationAsync method in // AbstractCodeGenerationService will return null. var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""CSAssembly"" CommonReferences=""true""> <ProjectReference>VBAssembly</ProjectReference> <Document> using VBAssembly; public class TestClass : VBClass { public int Bar[||]bar() { return 12345; } } </Document> </Project> <Project Language=""Visual Basic"" AssemblyName=""VBAssembly"" CommonReferences=""true""> <Document> Public Class VBClass End Class </Document> </Project> </Workspace>"; await TestQuickActionNotProvidedAsync(input); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullMethodUpToVBInterfaceViaQuickAction() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""CSAssembly"" CommonReferences=""true""> <ProjectReference>VBAssembly</ProjectReference> <Document> public class TestClass : VBInterface { public int Bar[||]bar() { return 12345; } } </Document> </Project> <Project Language=""Visual Basic"" AssemblyName=""VBAssembly"" CommonReferences=""true""> <Document> Public Interface VBInterface End Interface </Document> </Project> </Workspace> "; await TestQuickActionNotProvidedAsync(input); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullFieldUpToVBClassViaQuickAction() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""CSAssembly"" CommonReferences=""true""> <ProjectReference>VBAssembly</ProjectReference> <Document> using VBAssembly; public class TestClass : VBClass { public int fo[||]obar = 0; } </Document> </Project> <Project Language=""Visual Basic"" AssemblyName=""VBAssembly"" CommonReferences=""true""> <Document> Public Class VBClass End Class </Document> </Project> </Workspace>"; await TestQuickActionNotProvidedAsync(input); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullPropertyUpToVBClassViaQuickAction() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""CSAssembly"" CommonReferences=""true""> <ProjectReference>VBAssembly</ProjectReference> <Document> using VBAssembly; public class TestClass : VBClass { public int foo[||]bar { get; set; } }</Document> </Project> <Project Language=""Visual Basic"" AssemblyName=""VBAssembly"" CommonReferences=""true""> <Document> Public Class VBClass End Class </Document> </Project> </Workspace> "; await TestQuickActionNotProvidedAsync(input); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullPropertyUpToVBInterfaceViaQuickAction() { var input = @"<Workspace> <Project Language=""C#"" AssemblyName=""CSAssembly"" CommonReferences=""true""> <ProjectReference>VBAssembly</ProjectReference> <Document> using VBAssembly; public class TestClass : VBInterface { public int foo[||]bar { get; set; } } </Document> </Project> <Project Language = ""Visual Basic"" AssemblyName=""VBAssembly"" CommonReferences=""true""> <Document> Public Interface VBInterface End Interface </Document> </Project> </Workspace>"; await TestQuickActionNotProvidedAsync(input); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullEventUpToVBClassViaQuickAction() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""CSAssembly"" CommonReferences=""true""> <ProjectReference>VBAssembly</ProjectReference> <Document> using VBAssembly; public class TestClass : VBClass { public event EventHandler BarEve[||]nt; } </Document> </Project> <Project Language=""Visual Basic"" AssemblyName=""VBAssembly"" CommonReferences=""true""> <Document> Public Class VBClass End Class </Document> </Project> </Workspace>"; await TestQuickActionNotProvidedAsync(input); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullEventUpToVBInterfaceViaQuickAction() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""CSAssembly"" CommonReferences=""true""> <ProjectReference>VBAssembly</ProjectReference> <Document> using VBAssembly; public class TestClass : VBInterface { public event EventHandler BarEve[||]nt; } </Document> </Project> <Project Language=""Visual Basic"" AssemblyName=""VBAssembly"" CommonReferences=""true""> <Document> Public Interface VBInterface End Interface </Document> </Project> </Workspace>"; await TestQuickActionNotProvidedAsync(input); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(55746, "https://github.com/dotnet/roslyn/issues/55746")] public async Task TestPullMethodWithToClassWithAddUsingsInsideNamespaceViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace N { public class Base { } } </Document> <Document FilePath = ""File2.cs""> using System; namespace N { public class Derived : Base { public Uri En[||]dpoint() { return new Uri(""http://localhost""); } } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace N { using System; public class Base { public Uri Endpoint() { return new Uri(""http://localhost""); } } } </Document> <Document FilePath = ""File2.cs""> using System; namespace N { public class Derived : Base { } } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync( testText, expected, options: Option(CSharpCodeStyleOptions.PreferredUsingDirectivePlacement, CodeAnalysis.AddImports.AddImportPlacement.InsideNamespace, CodeStyle.NotificationOption2.Silent)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(55746, "https://github.com/dotnet/roslyn/issues/55746")] public async Task TestPullMethodWithToClassWithAddUsingsSystemUsingsLastViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace N1 { public class Base { } } </Document> <Document FilePath = ""File2.cs""> using System; using N2; namespace N1 { public class Derived : Base { public Goo Ge[||]tGoo() { return new Goo(String.Empty); } } } namespace N2 { public class Goo { public Goo(String s) { } } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using N2; using System; namespace N1 { public class Base { public Goo GetGoo() { return new Goo(String.Empty); } } } </Document> <Document FilePath = ""File2.cs""> using System; using N2; namespace N1 { public class Derived : Base { } } namespace N2 { public class Goo { public Goo(String s) { } } } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync( testText, expected, options: new(GetLanguage()) { { GenerationOptions.PlaceSystemNamespaceFirst, false }, }); } #endregion Quick Action #region Dialog internal Task TestWithPullMemberDialogAsync( string initialMarkUp, string expectedResult, IEnumerable<(string name, bool makeAbstract)> selection = null, string destinationName = null, int index = 0, TestParameters parameters = default) { var service = new TestPullMemberUpService(selection, destinationName); return TestInRegularAndScript1Async( initialMarkUp, expectedResult, index, parameters.WithFixProviderData(service)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullPartialMethodUpToInterfaceViaDialog() { var testText = @" using System; namespace PushUpTest { partial interface IInterface { } public partial class TestClass : IInterface { partial void Bar[||]Bar() } public partial class TestClass { partial void BarBar() {} } partial interface IInterface { } }"; var expected = @" using System; namespace PushUpTest { partial interface IInterface { void BarBar(); } public partial class TestClass : IInterface { void BarBar() } public partial class TestClass { partial void BarBar() {} } partial interface IInterface { } }"; await TestWithPullMemberDialogAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullExtendedPartialMethodUpToInterfaceViaDialog() { var testText = @" using System; namespace PushUpTest { partial interface IInterface { } public partial class TestClass : IInterface { public partial void Bar[||]Bar() } public partial class TestClass { public partial void BarBar() {} } partial interface IInterface { } }"; var expected = @" using System; namespace PushUpTest { partial interface IInterface { void BarBar(); } public partial class TestClass : IInterface { public partial void BarBar() } public partial class TestClass { public partial void BarBar() {} } partial interface IInterface { } }"; await TestWithPullMemberDialogAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullMultipleNonPublicMethodsToInterfaceViaDialog() { var testText = @" using System; namespace PushUpTest { interface IInterface { } public class TestClass : IInterface { public void TestMethod() { System.Console.WriteLine(""Hello World""); } protected void F[||]oo(int i) { // do awesome things } private static string Bar(string x) {} } }"; var expected = @" using System; namespace PushUpTest { interface IInterface { string Bar(string x); void Foo(int i); void TestMethod(); } public class TestClass : IInterface { public void TestMethod() { System.Console.WriteLine(""Hello World""); } public void Foo(int i) { // do awesome things } public string Bar(string x) {} } }"; await TestWithPullMemberDialogAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullMultipleNonPublicEventsToInterface() { var testText = @" using System; namespace PushUpTest { interface IInterface { } public class TestClass : IInterface { private event EventHandler Event1, Eve[||]nt2, Event3; } }"; var expected = @" using System; namespace PushUpTest { interface IInterface { event EventHandler Event1; event EventHandler Event2; event EventHandler Event3; } public class TestClass : IInterface { public event EventHandler Event1; public event EventHandler Event2; public event EventHandler Event3; } }"; await TestWithPullMemberDialogAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullMethodToInnerInterfaceViaDialog() { var testText = @" using System; namespace PushUpTest { public class TestClass : TestClass.IInterface { private void Bar[||]Bar() { } interface IInterface { } } }"; var expected = @" using System; namespace PushUpTest { public class TestClass : TestClass.IInterface { public void BarBar() { } interface IInterface { void BarBar(); } } }"; await TestWithPullMemberDialogAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullDifferentMembersFromClassToPartialInterfaceViaDialog() { var testText = @" using System; namespace PushUpTest { partial interface IInterface { } public class TestClass : IInterface { public int th[||]is[int i] { get => j = value; } private static void BarBar() {} protected static event EventHandler event1, event2; internal static int Foo { get; set; } } partial interface IInterface { } }"; var expected = @" using System; namespace PushUpTest { partial interface IInterface { int this[int i] { get; } int Foo { get; set; } event EventHandler event1; event EventHandler event2; void BarBar(); } public class TestClass : IInterface { public int this[int i] { get => j = value; } public void BarBar() {} public event EventHandler event1; public event EventHandler event2; public int Foo { get; set; } } partial interface IInterface { } }"; await TestWithPullMemberDialogAsync(testText, expected, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullAsyncMethod() { var testText = @" using System.Threading.Tasks; internal interface IPullUp { } internal class PullUp : IPullUp { internal async Task PullU[||]pAsync() { await Task.Delay(1000); } }"; var expectedText = @" using System.Threading.Tasks; internal interface IPullUp { Task PullUpAsync(); } internal class PullUp : IPullUp { public async Task PullUpAsync() { await Task.Delay(1000); } }"; await TestWithPullMemberDialogAsync(testText, expectedText); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullMethodWithAbstractOptionToClassViaDialog() { var testText = @" namespace PushUpTest { public class Base { } public class TestClass : Base { public void TestMeth[||]od() { System.Console.WriteLine(""Hello World""); } } }"; var expected = @" namespace PushUpTest { public abstract class Base { public abstract void TestMethod(); } public class TestClass : Base { public override void TestMeth[||]od() { System.Console.WriteLine(""Hello World""); } } }"; await TestWithPullMemberDialogAsync(testText, expected, new (string, bool)[] { ("TestMethod", true) }, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullAbstractMethodToClassViaDialog() { var testText = @" namespace PushUpTest { public class Base { } public abstract class TestClass : Base { public abstract void TestMeth[||]od(); } }"; var expected = @" namespace PushUpTest { public abstract class Base { public abstract void TestMethod(); } public abstract class TestClass : Base { } }"; await TestWithPullMemberDialogAsync(testText, expected, new (string, bool)[] { ("TestMethod", true) }, index: 0); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullMultipleEventsToClassViaDialog() { var testText = @" using System; namespace PushUpTest { public class Base2 { } public class Testclass2 : Base2 { private static event EventHandler Event1, Eve[||]nt3, Event4; } }"; var expected = @" using System; namespace PushUpTest { public class Base2 { private static event EventHandler Event1; private static event EventHandler Event3; private static event EventHandler Event4; } public class Testclass2 : Base2 { } }"; await TestWithPullMemberDialogAsync(testText, expected, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullMultipleAbstractEventsToInterfaceViaDialog() { var testText = @" using System; namespace PushUpTest { public interface ITest { } public abstract class Testclass2 : ITest { protected abstract event EventHandler Event1, Eve[||]nt3, Event4; } }"; var expected = @" using System; namespace PushUpTest { public interface ITest { event EventHandler Event1; event EventHandler Event3; event EventHandler Event4; } public abstract class Testclass2 : ITest { public abstract event EventHandler Event1; public abstract event EventHandler Event3; public abstract event EventHandler Event4; } }"; await TestWithPullMemberDialogAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullAbstractEventToClassViaDialog() { var testText = @" using System; namespace PushUpTest { public class Base2 { } public abstract class Testclass2 : Base2 { private static abstract event EventHandler Event1, Eve[||]nt3, Event4; } }"; var expected = @" using System; namespace PushUpTest { public abstract class Base2 { private static abstract event EventHandler Event3; } public abstract class Testclass2 : Base2 { private static abstract event EventHandler Event1, Event4; } }"; await TestWithPullMemberDialogAsync(testText, expected, new (string, bool)[] { ("Event3", false) }); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullNonPublicEventToInterfaceViaDialog() { var testText = @" using System; namespace PushUpTest { public interface ITest { } public class Testclass2 : ITest { private event EventHandler Eve[||]nt3; } }"; var expected = @" using System; namespace PushUpTest { public interface ITest { event EventHandler Event3; } public class Testclass2 : ITest { public event EventHandler Event3; } }"; await TestWithPullMemberDialogAsync(testText, expected, new (string, bool)[] { ("Event3", false) }); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullSingleNonPublicEventToInterfaceViaDialog() { var testText = @" using System; namespace PushUpTest { public interface ITest { } public abstract class TestClass2 : ITest { protected event EventHandler Eve[||]nt3; } }"; var expected = @" using System; namespace PushUpTest { public interface ITest { event EventHandler Event3; } public abstract class TestClass2 : ITest { public event EventHandler Event3; } }"; await TestWithPullMemberDialogAsync(testText, expected, new (string, bool)[] { ("Event3", false) }); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullNonPublicEventWithAddAndRemoveMethodToInterfaceViaDialog() { var testText = @" using System; namespace PushUpTest { interface IInterface { } public class TestClass : IInterface { private event EventHandler Eve[||]nt1 { add { System.Console.Writeline(""This is add""); } remove { System.Console.Writeline(""This is remove""); } } } }"; var expected = @" using System; namespace PushUpTest { interface IInterface { event EventHandler Event1; } public class TestClass : IInterface { public event EventHandler Event1 { add { System.Console.Writeline(""This is add""); } remove { System.Console.Writeline(""This is remove""); } } } }"; await TestWithPullMemberDialogAsync(testText, expected, new (string, bool)[] { ("Event1", false) }); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullFieldsToClassViaDialog() { var testText = @" using System; namespace PushUpTest { public class Base2 { } public class Testclass2 : Base2 { public int i, [||]j = 10, k = 100; } }"; var expected = @" using System; namespace PushUpTest { public class Base2 { public int i; public int j = 10; public int k = 100; } public class Testclass2 : Base2 { } }"; await TestWithPullMemberDialogAsync(testText, expected, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullNonPublicPropertyWithArrowToInterfaceViaDialog() { var testText = @" using System; namespace PushUpTest { public interface ITest { } public class Testclass2 : ITest { private double Test[||]Property => 2.717; } }"; var expected = @" using System; namespace PushUpTest { public interface ITest { double TestProperty { get; } } public class Testclass2 : ITest { public readonly double TestProperty => 2.717; } }"; await TestWithPullMemberDialogAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullNonPublicPropertyToInterfaceViaDialog() { var testText = @" using System; namespace PushUpTest { public interface ITest { } public class Testclass2 : ITest { private double Test[||]Property { get; set; } } }"; var expected = @" using System; namespace PushUpTest { public interface ITest { double TestProperty { get; set; } } public class Testclass2 : ITest { public double TestProperty { get; set; } } }"; await TestWithPullMemberDialogAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullNonPublicPropertyWithSingleAccessorToInterfaceViaDialog() { var testText = @" using System; namespace PushUpTest { public interface ITest { } public class Testclass2 : ITest { private static double Test[||]Property { set; } } }"; var expected = @" using System; namespace PushUpTest { public interface ITest { double TestProperty { set; } } public class Testclass2 : ITest { public double Test[||]Property { set; } } }"; await TestWithPullMemberDialogAsync(testText, expected); } [WorkItem(34268, "https://github.com/dotnet/roslyn/issues/34268")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullPropertyToAbstractClassViaDialogWithMakeAbstractOption() { var testText = @" abstract class B { } class D : B { int [||]X => 7; }"; var expected = @" abstract class B { private abstract int X { get; } } class D : B { override int X => 7; }"; await TestWithPullMemberDialogAsync(testText, expected, selection: new[] { ("X", true) }, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullEventUpToAbstractClassViaDialogWithMakeAbstractOption() { var testText = @" using System; namespace PushUpTest { public class Base2 { } public class Testclass2 : Base2 { private event EventHandler Event1, Eve[||]nt3, Event4; } }"; var expected = @" using System; namespace PushUpTest { public abstract class Base2 { private abstract event EventHandler Event3; } public class Testclass2 : Base2 { private event EventHandler Event1, Eve[||]nt3, Event4; } }"; await TestWithPullMemberDialogAsync(testText, expected, selection: new[] { ("Event3", true) }, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullEventWithAddAndRemoveMethodToClassViaDialogWithMakeAbstractOption() { var testText = @" using System; namespace PushUpTest { public class BaseClass { } public class TestClass : BaseClass { public event EventHandler Eve[||]nt1 { add { System.Console.Writeline(""This is add""); } remove { System.Console.Writeline(""This is remove""); } } } }"; var expected = @" using System; namespace PushUpTest { public abstract class BaseClass { public abstract event EventHandler Event1; } public class TestClass : BaseClass { public override event EventHandler Event1 { add { System.Console.Writeline(""This is add""); } remove { System.Console.Writeline(""This is remove""); } } } }"; await TestWithPullMemberDialogAsync(testText, expected, new (string, bool)[] { ("Event1", true) }, index: 1); } #endregion Dialog #region Selections and caret position [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestArgsIsPartOfHeader() { var testText = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } class Test2Attribute : Attribute { } public class A { } public class B : A { [Test] [Test2] void C([||]) { } } }"; var expected = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } class Test2Attribute : Attribute { } public class A { [Test] [Test2] void C() { } } public class B : A { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestRefactoringCaretBeforeAttributes() { var testText = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } class Test2Attribute : Attribute { } public class A { } public class B : A { [||][Test] [Test2] void C() { } } }"; var expected = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } class Test2Attribute : Attribute { } public class A { [Test] [Test2] void C() { } } public class B : A { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestMissingRefactoringCaretBetweenAttributes() { var testText = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } class Test2Attribute : Attribute { } public class A { } public class B : A { [Test] [||][Test2] void C() { } } }"; await TestQuickActionNotProvidedAsync(testText); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestRefactoringSelectionWithAttributes1() { var testText = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } public class A { } public class B : A { [Test] [|void C() { }|] } }"; var expected = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } public class A { [Test] void C() { } } public class B : A { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestRefactoringSelectionWithAttributes2() { var testText = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } public class A { } public class B : A { [|[Test] void C() { }|] } }"; var expected = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } public class A { [Test] void C() { } } public class B : A { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestRefactoringSelectionWithAttributes3() { var testText = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } public class A { } public class B : A { [Test][| void C() { } |] } }"; var expected = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } public class A { [Test] void C() { } } public class B : A { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestMissingRefactoringInAttributeList() { var testText = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } public class A { } public class B : A { [[||]Test] void C() { } } }"; await TestQuickActionNotProvidedAsync(testText); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestMissingRefactoringSelectionAttributeList() { var testText = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } class Test2Attribute : Attribute { } public class A { } public class B : A { [|[Test] [Test2]|] void C() { } } }"; await TestQuickActionNotProvidedAsync(testText); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestMissingRefactoringCaretInAttributeList() { var testText = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } class Test2Attribute : Attribute { } public class A { } public class B : A { [[||]Test] [Test2] void C() { } } }"; await TestQuickActionNotProvidedAsync(testText); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestMissingRefactoringCaretBetweenAttributeLists() { var testText = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } class Test2Attribute : Attribute { } public class A { } public class B : A { [Test] [||][Test2] void C() { } } }"; await TestQuickActionNotProvidedAsync(testText); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestMissingRefactoringSelectionAttributeList2() { var testText = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } class Test2Attribute : Attribute { } public class A { } public class B : A { [|[Test]|] [Test2] void C() { } } }"; await TestQuickActionNotProvidedAsync(testText); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestMissingRefactoringSelectAttributeList() { var testText = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } public class A { } public class B : A { [|[Test]|] void C() { } } }"; await TestQuickActionNotProvidedAsync(testText); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestRefactoringCaretLocAfterAttributes1() { var testText = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } public class A { } public class B : A { [Test] [||]void C() { } } }"; var expected = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } public class A { [Test] void C() { } } public class B : A { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestRefactoringCaretLocAfterAttributes2() { var testText = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } class Test2Attribute : Attribute { } public class A { } public class B : A { [Test] // Comment1 [Test2] // Comment2 [||]void C() { } } }"; var expected = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } class Test2Attribute : Attribute { } public class A { [Test] // Comment1 [Test2] // Comment2 void C() { } } public class B : A { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestRefactoringCaretLoc1() { var testText = @" namespace PushUpTest { public class A { } public class B : A { [||]void C() { } } }"; var expected = @" namespace PushUpTest { public class A { void C() { } } public class B : A { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestRefactoringSelection() { var testText = @" namespace PushUpTest { public class A { } public class B : A { [|void C() { }|] } }"; var expected = @" namespace PushUpTest { public class A { void C() { } } public class B : A { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestRefactoringSelectionComments() { var testText = @" namespace PushUpTest { public class A { } public class B : A { [| // Comment1 void C() { }|] } }"; var expected = @" namespace PushUpTest { public class A { // Comment1 void C() { } } public class B : A { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestRefactoringSelectionComments2() { var testText = @" namespace PushUpTest { public class A { } public class B : A { [|/// <summary> /// Test /// </summary> void C() { }|] } }"; var expected = @" namespace PushUpTest { public class A { /// <summary> /// Test /// </summary> void C() { } } public class B : A { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestRefactoringSelectionComments3() { var testText = @" namespace PushUpTest { public class A { } public class B : A { /// <summary> [|/// Test /// </summary> void C() { }|] } }"; var expected = @" namespace PushUpTest { public class A { /// <summary> /// Test /// </summary> void C() { } } public class B : A { } }"; await TestInRegularAndScriptAsync(testText, expected); } #endregion } }
-1
dotnet/roslyn
56,433
Only allow Contract.ThrowIfNull() to be called on nullable types
We had some places we were calling it on bools.
jasonmalinowski
"2021-09-16T01:20:43Z"
"2021-09-16T18:44:11Z"
736fc1b5e6e2847689c0154b3e5f23ea99dd56af
6d0f4e3f972ceb561b04574e7f957a4ff458e272
Only allow Contract.ThrowIfNull() to be called on nullable types. We had some places we were calling it on bools.
./src/Workspaces/Core/Portable/Shared/Extensions/SemanticModelExtensions.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.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using Humanizer; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Shared.Extensions { internal static partial class SemanticModelExtensions { public static SemanticMap GetSemanticMap(this SemanticModel semanticModel, SyntaxNode node, CancellationToken cancellationToken) => SemanticMap.From(semanticModel, node, cancellationToken); /// <summary> /// Fetches the ITypeSymbol that should be used if we were generating a parameter or local that would accept <paramref name="expression"/>. If /// expression is a type, that's returned; otherwise this will see if it's something like a method group and then choose an appropriate delegate. /// </summary> public static ITypeSymbol GetType( this SemanticModel semanticModel, SyntaxNode expression, CancellationToken cancellationToken) { var typeInfo = semanticModel.GetTypeInfo(expression, cancellationToken); if (typeInfo.Type != null) { return typeInfo.Type; } var symbolInfo = semanticModel.GetSymbolInfo(expression, cancellationToken); return symbolInfo.GetAnySymbol().ConvertToType(semanticModel.Compilation); } private static ISymbol? MapSymbol(ISymbol symbol, ITypeSymbol? type) { if (symbol.IsConstructor() && symbol.ContainingType.IsAnonymousType) { return symbol.ContainingType; } if (symbol.IsThisParameter()) { // Map references to this/base to the actual type that those correspond to. return type; } if (symbol.IsFunctionValue() && symbol.ContainingSymbol is IMethodSymbol method) { if (method?.AssociatedSymbol != null) { return method.AssociatedSymbol; } else { return method; } } // see if we can map the built-in language operator to a real method on the containing // type of the symbol. built-in operators can happen when querying the semantic model // for operators. However, we would prefer to just use the real operator on the type // if it has one. if (symbol is IMethodSymbol methodSymbol && methodSymbol.MethodKind == MethodKind.BuiltinOperator && methodSymbol.ContainingType is ITypeSymbol containingType) { var comparer = SymbolEquivalenceComparer.Instance.ParameterEquivalenceComparer; // Note: this will find the real method vs the built-in. That's because the // built-in is synthesized operator that isn't actually in the list of members of // its 'ContainingType'. var mapped = containingType.GetMembers(methodSymbol.Name) .OfType<IMethodSymbol>() .FirstOrDefault(s => s.Parameters.SequenceEqual(methodSymbol.Parameters, comparer)); symbol = mapped ?? symbol; } return symbol; } public static TokenSemanticInfo GetSemanticInfo( this SemanticModel semanticModel, SyntaxToken token, Workspace workspace, CancellationToken cancellationToken) { var languageServices = workspace.Services.GetLanguageServices(token.Language); var syntaxFacts = languageServices.GetRequiredService<ISyntaxFactsService>(); if (!syntaxFacts.IsBindableToken(token)) { return TokenSemanticInfo.Empty; } var semanticFacts = languageServices.GetRequiredService<ISemanticFactsService>(); IAliasSymbol? aliasSymbol; ITypeSymbol? type; ITypeSymbol? convertedType; ISymbol? declaredSymbol; ImmutableArray<ISymbol?> allSymbols; var overriddingIdentifier = syntaxFacts.GetDeclarationIdentifierIfOverride(token); if (overriddingIdentifier.HasValue) { // on an "override" token, we'll find the overridden symbol aliasSymbol = null; var overriddingSymbol = semanticFacts.GetDeclaredSymbol(semanticModel, overriddingIdentifier.Value, cancellationToken); var overriddenSymbol = overriddingSymbol.GetOverriddenMember(); // on an "override" token, the overridden symbol is the only part of TokenSemanticInfo used by callers, so type doesn't matter type = null; convertedType = null; declaredSymbol = null; allSymbols = overriddenSymbol is null ? ImmutableArray<ISymbol?>.Empty : ImmutableArray.Create<ISymbol?>(overriddenSymbol); } else { aliasSymbol = semanticModel.GetAliasInfo(token.Parent!, cancellationToken); var bindableParent = syntaxFacts.TryGetBindableParent(token); var typeInfo = bindableParent != null ? semanticModel.GetTypeInfo(bindableParent, cancellationToken) : default; type = typeInfo.Type; convertedType = typeInfo.ConvertedType; declaredSymbol = MapSymbol(semanticFacts.GetDeclaredSymbol(semanticModel, token, cancellationToken), type); var skipSymbolInfoLookup = declaredSymbol.IsKind(SymbolKind.RangeVariable); allSymbols = skipSymbolInfoLookup ? ImmutableArray<ISymbol?>.Empty : semanticFacts .GetBestOrAllSymbols(semanticModel, bindableParent, token, cancellationToken) .WhereAsArray(s => !s.Equals(declaredSymbol)) .SelectAsArray(s => MapSymbol(s, type)); } // NOTE(cyrusn): This is a workaround to how the semantic model binds and returns // information for VB event handlers. Namely, if you have: // // Event X]() // Sub Goo() // Dim y = New $$XEventHandler(AddressOf bar) // End Sub // // Only GetTypeInfo will return any information for XEventHandler. So, in this // case, we upgrade the type to be the symbol we return. if (type != null && allSymbols.Length == 0) { if (type.Kind == SymbolKind.NamedType) { var namedType = (INamedTypeSymbol)type; if (namedType.TypeKind == TypeKind.Delegate || namedType.AssociatedSymbol != null) { allSymbols = ImmutableArray.Create<ISymbol?>(type); type = null; } } } if (allSymbols.Length == 0 && syntaxFacts.IsQueryKeyword(token)) { type = null; convertedType = null; } return new TokenSemanticInfo(declaredSymbol, aliasSymbol, allSymbols, type, convertedType, token.Span); } public static string GenerateNameFromType(this SemanticModel semanticModel, ITypeSymbol type, ISyntaxFacts syntaxFacts, bool capitalize) { var pluralize = semanticModel.ShouldPluralize(type); var typeArguments = type.GetAllTypeArguments(); // We may be able to use the type's arguments to generate a name if we're working with an enumerable type. if (pluralize && TryGeneratePluralizedNameFromTypeArgument(syntaxFacts, typeArguments, capitalize, out var typeArgumentParameterName)) { return typeArgumentParameterName; } // If there's no type argument and we have an array type, we should pluralize, e.g. using 'frogs' for 'new Frog[]' instead of 'frog' if (type.TypeKind == TypeKind.Array && typeArguments.IsEmpty) { return type.CreateParameterName(capitalize).Pluralize(); } // Otherwise assume no pluralization, e.g. using 'immutableArray', 'list', etc. instead of their // plural forms return type.CreateParameterName(capitalize); } private static bool ShouldPluralize(this SemanticModel semanticModel, ITypeSymbol type) { if (type == null) return false; // string implements IEnumerable<char>, so we need to specifically exclude it. if (type.SpecialType == SpecialType.System_String) return false; var enumerableType = semanticModel.Compilation.IEnumerableOfTType(); return type.AllInterfaces.Any(i => i.OriginalDefinition.Equals(enumerableType)); } private static bool TryGeneratePluralizedNameFromTypeArgument( ISyntaxFacts syntaxFacts, ImmutableArray<ITypeSymbol> typeArguments, bool capitalize, [NotNullWhen(true)] out string? parameterName) { // We only consider generating a name if there's one type argument. // This logic can potentially be expanded upon in the future. if (typeArguments.Length == 1) { // We only want the last part of the type, i.e. we don't want namespaces. var typeArgument = typeArguments.Single().ToDisplayParts().Last().ToString(); if (syntaxFacts.IsValidIdentifier(typeArgument)) { typeArgument = typeArgument.Pluralize(); parameterName = capitalize ? typeArgument.ToPascalCase() : typeArgument.ToCamelCase(); return true; } } parameterName = 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. using System; using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using Humanizer; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Shared.Extensions { internal static partial class SemanticModelExtensions { public static SemanticMap GetSemanticMap(this SemanticModel semanticModel, SyntaxNode node, CancellationToken cancellationToken) => SemanticMap.From(semanticModel, node, cancellationToken); /// <summary> /// Fetches the ITypeSymbol that should be used if we were generating a parameter or local that would accept <paramref name="expression"/>. If /// expression is a type, that's returned; otherwise this will see if it's something like a method group and then choose an appropriate delegate. /// </summary> public static ITypeSymbol GetType( this SemanticModel semanticModel, SyntaxNode expression, CancellationToken cancellationToken) { var typeInfo = semanticModel.GetTypeInfo(expression, cancellationToken); if (typeInfo.Type != null) { return typeInfo.Type; } var symbolInfo = semanticModel.GetSymbolInfo(expression, cancellationToken); return symbolInfo.GetAnySymbol().ConvertToType(semanticModel.Compilation); } private static ISymbol? MapSymbol(ISymbol symbol, ITypeSymbol? type) { if (symbol.IsConstructor() && symbol.ContainingType.IsAnonymousType) { return symbol.ContainingType; } if (symbol.IsThisParameter()) { // Map references to this/base to the actual type that those correspond to. return type; } if (symbol.IsFunctionValue() && symbol.ContainingSymbol is IMethodSymbol method) { if (method?.AssociatedSymbol != null) { return method.AssociatedSymbol; } else { return method; } } // see if we can map the built-in language operator to a real method on the containing // type of the symbol. built-in operators can happen when querying the semantic model // for operators. However, we would prefer to just use the real operator on the type // if it has one. if (symbol is IMethodSymbol methodSymbol && methodSymbol.MethodKind == MethodKind.BuiltinOperator && methodSymbol.ContainingType is ITypeSymbol containingType) { var comparer = SymbolEquivalenceComparer.Instance.ParameterEquivalenceComparer; // Note: this will find the real method vs the built-in. That's because the // built-in is synthesized operator that isn't actually in the list of members of // its 'ContainingType'. var mapped = containingType.GetMembers(methodSymbol.Name) .OfType<IMethodSymbol>() .FirstOrDefault(s => s.Parameters.SequenceEqual(methodSymbol.Parameters, comparer)); symbol = mapped ?? symbol; } return symbol; } public static TokenSemanticInfo GetSemanticInfo( this SemanticModel semanticModel, SyntaxToken token, Workspace workspace, CancellationToken cancellationToken) { var languageServices = workspace.Services.GetLanguageServices(token.Language); var syntaxFacts = languageServices.GetRequiredService<ISyntaxFactsService>(); if (!syntaxFacts.IsBindableToken(token)) { return TokenSemanticInfo.Empty; } var semanticFacts = languageServices.GetRequiredService<ISemanticFactsService>(); IAliasSymbol? aliasSymbol; ITypeSymbol? type; ITypeSymbol? convertedType; ISymbol? declaredSymbol; ImmutableArray<ISymbol?> allSymbols; var overriddingIdentifier = syntaxFacts.GetDeclarationIdentifierIfOverride(token); if (overriddingIdentifier.HasValue) { // on an "override" token, we'll find the overridden symbol aliasSymbol = null; var overriddingSymbol = semanticFacts.GetDeclaredSymbol(semanticModel, overriddingIdentifier.Value, cancellationToken); var overriddenSymbol = overriddingSymbol.GetOverriddenMember(); // on an "override" token, the overridden symbol is the only part of TokenSemanticInfo used by callers, so type doesn't matter type = null; convertedType = null; declaredSymbol = null; allSymbols = overriddenSymbol is null ? ImmutableArray<ISymbol?>.Empty : ImmutableArray.Create<ISymbol?>(overriddenSymbol); } else { aliasSymbol = semanticModel.GetAliasInfo(token.Parent!, cancellationToken); var bindableParent = syntaxFacts.TryGetBindableParent(token); var typeInfo = bindableParent != null ? semanticModel.GetTypeInfo(bindableParent, cancellationToken) : default; type = typeInfo.Type; convertedType = typeInfo.ConvertedType; declaredSymbol = MapSymbol(semanticFacts.GetDeclaredSymbol(semanticModel, token, cancellationToken), type); var skipSymbolInfoLookup = declaredSymbol.IsKind(SymbolKind.RangeVariable); allSymbols = skipSymbolInfoLookup ? ImmutableArray<ISymbol?>.Empty : semanticFacts .GetBestOrAllSymbols(semanticModel, bindableParent, token, cancellationToken) .WhereAsArray(s => !s.Equals(declaredSymbol)) .SelectAsArray(s => MapSymbol(s, type)); } // NOTE(cyrusn): This is a workaround to how the semantic model binds and returns // information for VB event handlers. Namely, if you have: // // Event X]() // Sub Goo() // Dim y = New $$XEventHandler(AddressOf bar) // End Sub // // Only GetTypeInfo will return any information for XEventHandler. So, in this // case, we upgrade the type to be the symbol we return. if (type != null && allSymbols.Length == 0) { if (type.Kind == SymbolKind.NamedType) { var namedType = (INamedTypeSymbol)type; if (namedType.TypeKind == TypeKind.Delegate || namedType.AssociatedSymbol != null) { allSymbols = ImmutableArray.Create<ISymbol?>(type); type = null; } } } if (allSymbols.Length == 0 && syntaxFacts.IsQueryKeyword(token)) { type = null; convertedType = null; } return new TokenSemanticInfo(declaredSymbol, aliasSymbol, allSymbols, type, convertedType, token.Span); } public static string GenerateNameFromType(this SemanticModel semanticModel, ITypeSymbol type, ISyntaxFacts syntaxFacts, bool capitalize) { var pluralize = semanticModel.ShouldPluralize(type); var typeArguments = type.GetAllTypeArguments(); // We may be able to use the type's arguments to generate a name if we're working with an enumerable type. if (pluralize && TryGeneratePluralizedNameFromTypeArgument(syntaxFacts, typeArguments, capitalize, out var typeArgumentParameterName)) { return typeArgumentParameterName; } // If there's no type argument and we have an array type, we should pluralize, e.g. using 'frogs' for 'new Frog[]' instead of 'frog' if (type.TypeKind == TypeKind.Array && typeArguments.IsEmpty) { return type.CreateParameterName(capitalize).Pluralize(); } // Otherwise assume no pluralization, e.g. using 'immutableArray', 'list', etc. instead of their // plural forms return type.CreateParameterName(capitalize); } private static bool ShouldPluralize(this SemanticModel semanticModel, ITypeSymbol type) { if (type == null) return false; // string implements IEnumerable<char>, so we need to specifically exclude it. if (type.SpecialType == SpecialType.System_String) return false; var enumerableType = semanticModel.Compilation.IEnumerableOfTType(); return type.AllInterfaces.Any(i => i.OriginalDefinition.Equals(enumerableType)); } private static bool TryGeneratePluralizedNameFromTypeArgument( ISyntaxFacts syntaxFacts, ImmutableArray<ITypeSymbol> typeArguments, bool capitalize, [NotNullWhen(true)] out string? parameterName) { // We only consider generating a name if there's one type argument. // This logic can potentially be expanded upon in the future. if (typeArguments.Length == 1) { // We only want the last part of the type, i.e. we don't want namespaces. var typeArgument = typeArguments.Single().ToDisplayParts().Last().ToString(); if (syntaxFacts.IsValidIdentifier(typeArgument)) { typeArgument = typeArgument.Pluralize(); parameterName = capitalize ? typeArgument.ToPascalCase() : typeArgument.ToCamelCase(); return true; } } parameterName = null; return false; } } }
-1
dotnet/roslyn
56,433
Only allow Contract.ThrowIfNull() to be called on nullable types
We had some places we were calling it on bools.
jasonmalinowski
"2021-09-16T01:20:43Z"
"2021-09-16T18:44:11Z"
736fc1b5e6e2847689c0154b3e5f23ea99dd56af
6d0f4e3f972ceb561b04574e7f957a4ff458e272
Only allow Contract.ThrowIfNull() to be called on nullable types. We had some places we were calling it on bools.
./src/Tools/Source/RunTests/Logger.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.Text; using System.Threading.Tasks; namespace RunTests { internal static class Logger { private static readonly List<string> s_lines = new List<string>(); private static bool s_hasErrors; internal static bool HasErrors => s_hasErrors; internal static void LogError(Exception ex, string line) { lock (s_lines) { s_hasErrors = true; s_lines.Add($"Error {ex.Message}: {line}"); s_lines.Add(ex.StackTrace ?? ""); } } internal static void Log(string message, Exception ex) { lock (s_lines) { s_lines.Add(message); s_lines.Add(ex.Message); s_lines.Add(ex.StackTrace ?? ""); } } internal static void Log(Exception ex) { lock (s_lines) { s_lines.Add(ex.Message); s_lines.Add(ex.StackTrace ?? ""); } } internal static void Log(string line) { lock (s_lines) { s_lines.Add(line); } } internal static void Clear() { lock (s_lines) { s_lines.Clear(); } } internal static void WriteTo(TextWriter textWriter) { lock (s_lines) { foreach (var line in s_lines) { textWriter.WriteLine(line); } } } } }
// Licensed to the .NET Foundation under one or more 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.Text; using System.Threading.Tasks; namespace RunTests { internal static class Logger { private static readonly List<string> s_lines = new List<string>(); private static bool s_hasErrors; internal static bool HasErrors => s_hasErrors; internal static void LogError(Exception ex, string line) { lock (s_lines) { s_hasErrors = true; s_lines.Add($"Error {ex.Message}: {line}"); s_lines.Add(ex.StackTrace ?? ""); } } internal static void Log(string message, Exception ex) { lock (s_lines) { s_lines.Add(message); s_lines.Add(ex.Message); s_lines.Add(ex.StackTrace ?? ""); } } internal static void Log(Exception ex) { lock (s_lines) { s_lines.Add(ex.Message); s_lines.Add(ex.StackTrace ?? ""); } } internal static void Log(string line) { lock (s_lines) { s_lines.Add(line); } } internal static void Clear() { lock (s_lines) { s_lines.Clear(); } } internal static void WriteTo(TextWriter textWriter) { lock (s_lines) { foreach (var line in s_lines) { textWriter.WriteLine(line); } } } } }
-1
dotnet/roslyn
56,433
Only allow Contract.ThrowIfNull() to be called on nullable types
We had some places we were calling it on bools.
jasonmalinowski
"2021-09-16T01:20:43Z"
"2021-09-16T18:44:11Z"
736fc1b5e6e2847689c0154b3e5f23ea99dd56af
6d0f4e3f972ceb561b04574e7f957a4ff458e272
Only allow Contract.ThrowIfNull() to be called on nullable types. We had some places we were calling it on bools.
./src/VisualStudio/Core/Def/Implementation/Interactive/IAbstractResetInteractiveCommand.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 Roslyn.VisualStudio.Services.Interactive { /// <summary> /// An interface that implements the execution of ResetInteractive. /// Implementation is defined separately from command declaration in order /// to avoid the need to load the dll. /// </summary> internal interface IResetInteractiveCommand { void ExecuteResetInteractive(); } }
// Licensed to the .NET Foundation under one or more 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 Roslyn.VisualStudio.Services.Interactive { /// <summary> /// An interface that implements the execution of ResetInteractive. /// Implementation is defined separately from command declaration in order /// to avoid the need to load the dll. /// </summary> internal interface IResetInteractiveCommand { void ExecuteResetInteractive(); } }
-1
dotnet/roslyn
56,433
Only allow Contract.ThrowIfNull() to be called on nullable types
We had some places we were calling it on bools.
jasonmalinowski
"2021-09-16T01:20:43Z"
"2021-09-16T18:44:11Z"
736fc1b5e6e2847689c0154b3e5f23ea99dd56af
6d0f4e3f972ceb561b04574e7f957a4ff458e272
Only allow Contract.ThrowIfNull() to be called on nullable types. We had some places we were calling it on bools.
./src/Workspaces/Core/Portable/Classification/SyntaxClassification/EmbeddedLanguagesClassifier.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.Linq; using System.Threading; using Microsoft.CodeAnalysis.EmbeddedLanguages.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.Classification.Classifiers { internal class EmbeddedLanguagesClassifier : AbstractSyntaxClassifier { private readonly IEmbeddedLanguagesProvider _languagesProvider; public override ImmutableArray<int> SyntaxTokenKinds { get; } public EmbeddedLanguagesClassifier(IEmbeddedLanguagesProvider languagesProvider) { _languagesProvider = languagesProvider; SyntaxTokenKinds = languagesProvider.Languages.Where(p => p.Classifier != null) .SelectMany(p => p.Classifier.SyntaxTokenKinds) .Distinct() .ToImmutableArray(); } public override void AddClassifications(Workspace workspace, SyntaxToken token, SemanticModel semanticModel, ArrayBuilder<ClassifiedSpan> result, CancellationToken cancellationToken) { foreach (var language in _languagesProvider.Languages) { var classifier = language.Classifier; if (classifier != null) { var count = result.Count; classifier.AddClassifications(workspace, token, semanticModel, result, cancellationToken); if (result.Count != count) { // This classifier added values. No need to check the other ones. return; } } } } } }
// Licensed to the .NET Foundation under one or more 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.Linq; using System.Threading; using Microsoft.CodeAnalysis.EmbeddedLanguages.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.Classification.Classifiers { internal class EmbeddedLanguagesClassifier : AbstractSyntaxClassifier { private readonly IEmbeddedLanguagesProvider _languagesProvider; public override ImmutableArray<int> SyntaxTokenKinds { get; } public EmbeddedLanguagesClassifier(IEmbeddedLanguagesProvider languagesProvider) { _languagesProvider = languagesProvider; SyntaxTokenKinds = languagesProvider.Languages.Where(p => p.Classifier != null) .SelectMany(p => p.Classifier.SyntaxTokenKinds) .Distinct() .ToImmutableArray(); } public override void AddClassifications(Workspace workspace, SyntaxToken token, SemanticModel semanticModel, ArrayBuilder<ClassifiedSpan> result, CancellationToken cancellationToken) { foreach (var language in _languagesProvider.Languages) { var classifier = language.Classifier; if (classifier != null) { var count = result.Count; classifier.AddClassifications(workspace, token, semanticModel, result, cancellationToken); if (result.Count != count) { // This classifier added values. No need to check the other ones. return; } } } } } }
-1
dotnet/roslyn
56,433
Only allow Contract.ThrowIfNull() to be called on nullable types
We had some places we were calling it on bools.
jasonmalinowski
"2021-09-16T01:20:43Z"
"2021-09-16T18:44:11Z"
736fc1b5e6e2847689c0154b3e5f23ea99dd56af
6d0f4e3f972ceb561b04574e7f957a4ff458e272
Only allow Contract.ThrowIfNull() to be called on nullable types. We had some places we were calling it on bools.
./src/Compilers/CSharp/Test/Syntax/Parsing/NullableParsingTests.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.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class NullableParsingTests : ParsingTests { public NullableParsingTests(ITestOutputHelper output) : base(output) { } [WorkItem(23272, "https://github.com/dotnet/roslyn/issues/23272")] [Fact] public void PartialAccessibilityAndNullableArray() { // Note: the typo `privat` is necessary for https://github.com/dotnet/roslyn/issues/23272. UsingTree( @"class C { privat C[]? F; }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.FieldDeclaration); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "privat"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.BracketedArgumentList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Argument); { N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } } N(SyntaxKind.CloseBracketToken); } } } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.IncompleteMember); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "F"); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [WorkItem(24482, "https://github.com/dotnet/roslyn/issues/24482")] [Fact] public void NullableArray_Cast_01() { UsingExpression("(object[]?)null"); N(SyntaxKind.CastExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.NullableType); { N(SyntaxKind.ArrayType); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.ObjectKeyword); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.QuestionToken); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.NullLiteralExpression); { N(SyntaxKind.NullKeyword); } } EOF(); } [WorkItem(24482, "https://github.com/dotnet/roslyn/issues/24482")] [Fact] public void NullableArray_Cast_02() { UsingExpression("(object[]??)null", // (1,1): error CS1073: Unexpected token 'null' // (object[]??)null Diagnostic(ErrorCode.ERR_UnexpectedToken, "(object[]??)").WithArguments("null").WithLocation(1, 1), // (1,2): error CS1525: Invalid expression term 'object' // (object[]??)null Diagnostic(ErrorCode.ERR_InvalidExprTerm, "object").WithArguments("object").WithLocation(1, 2), // (1,9): error CS0443: Syntax error; value expected // (object[]??)null Diagnostic(ErrorCode.ERR_ValueExpected, "]").WithLocation(1, 9), // (1,12): error CS1525: Invalid expression term ')' // (object[]??)null Diagnostic(ErrorCode.ERR_InvalidExprTerm, ")").WithArguments(")").WithLocation(1, 12)); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CoalesceExpression); { N(SyntaxKind.ElementAccessExpression); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.ObjectKeyword); } N(SyntaxKind.BracketedArgumentList); { N(SyntaxKind.OpenBracketToken); M(SyntaxKind.Argument); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.QuestionQuestionToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.CloseParenToken); } EOF(); } [WorkItem(24482, "https://github.com/dotnet/roslyn/issues/24482")] [Fact] public void NullableArray_Cast_03() { UsingExpression("(object[?])null", // (1,1): error CS1073: Unexpected token 'null' // (object[?])null Diagnostic(ErrorCode.ERR_UnexpectedToken, "(object[?])").WithArguments("null").WithLocation(1, 1), // (1,2): error CS1525: Invalid expression term 'object' // (object[?])null Diagnostic(ErrorCode.ERR_InvalidExprTerm, "object").WithArguments("object").WithLocation(1, 2), // (1,9): error CS1001: Identifier expected // (object[?])null Diagnostic(ErrorCode.ERR_IdentifierExpected, "?").WithLocation(1, 9)); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.ElementAccessExpression); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.ObjectKeyword); } N(SyntaxKind.BracketedArgumentList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.CloseParenToken); } EOF(); } [WorkItem(24482, "https://github.com/dotnet/roslyn/issues/24482")] [Fact] public void NullableArray_Cast_04() { UsingExpression("(object?[]?[])null"); N(SyntaxKind.CastExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.ArrayType); { N(SyntaxKind.NullableType); { N(SyntaxKind.ArrayType); { N(SyntaxKind.NullableType); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.ObjectKeyword); } N(SyntaxKind.QuestionToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.QuestionToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.CloseParenToken); N(SyntaxKind.NullLiteralExpression); { N(SyntaxKind.NullKeyword); } } EOF(); } [WorkItem(24482, "https://github.com/dotnet/roslyn/issues/24482")] [Fact] public void NullableArray_Cast_05() { UsingExpression("(object[][]?[]?)null"); N(SyntaxKind.CastExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.NullableType); { N(SyntaxKind.ArrayType); { N(SyntaxKind.NullableType); { N(SyntaxKind.ArrayType); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.ObjectKeyword); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.QuestionToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.QuestionToken); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.NullLiteralExpression); { N(SyntaxKind.NullKeyword); } } EOF(); } [Fact] public void ConditionalOperator_NotNullableType() { UsingExpression("x is T ? y : z"); N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } } N(SyntaxKind.QuestionToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "y"); } N(SyntaxKind.ColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "z"); } } EOF(); } [Fact] public void ConditionalOperator_NullableType() { UsingExpression("x is T ? ? y : z"); N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); } } N(SyntaxKind.QuestionToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "y"); } N(SyntaxKind.ColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "z"); } } EOF(); } [Fact] public void ConditionalOperator_NotNullableArray() { UsingExpression("x is T[] ? y : z"); N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ArrayType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } } N(SyntaxKind.QuestionToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "y"); } N(SyntaxKind.ColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "z"); } } EOF(); } [Fact] public void ConditionalOperator_NullableArray() { UsingExpression("x is T[] ? ? y : z"); N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.NullableType); { N(SyntaxKind.ArrayType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.QuestionToken); } } N(SyntaxKind.QuestionToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "y"); } N(SyntaxKind.ColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "z"); } } EOF(); } [Fact] public void NullCoalescingOperator_NotNullableType() { UsingExpression("x as T?? y"); N(SyntaxKind.CoalesceExpression); { N(SyntaxKind.AsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.AsKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } } N(SyntaxKind.QuestionQuestionToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "y"); } } EOF(); } [Fact] public void NullCoalescingOperator_NullableType() { UsingExpression("x as T? ?? y"); N(SyntaxKind.CoalesceExpression); { N(SyntaxKind.AsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.AsKeyword); N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); } } N(SyntaxKind.QuestionQuestionToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "y"); } } EOF(); } [Fact] public void NullCoalescingOperator_NullableType_Invalid() { UsingExpression("x as T??? y", // (1,9): error CS1525: Invalid expression term '?' // x as T??? y Diagnostic(ErrorCode.ERR_InvalidExprTerm, "?").WithArguments("?").WithLocation(1, 9), // (1,12): error CS1003: Syntax error, ':' expected // x as T??? y Diagnostic(ErrorCode.ERR_SyntaxError, "").WithArguments(":", "").WithLocation(1, 12), // (1,12): error CS1733: Expected expression // x as T??? y Diagnostic(ErrorCode.ERR_ExpressionExpected, "").WithLocation(1, 12)); N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.CoalesceExpression); { N(SyntaxKind.AsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.AsKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } } N(SyntaxKind.QuestionQuestionToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.QuestionToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "y"); } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } EOF(); } [Fact] public void NullCoalescingOperator_NotNullableArray() { UsingExpression("x as T[] ?? y"); N(SyntaxKind.CoalesceExpression); { N(SyntaxKind.AsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.AsKeyword); N(SyntaxKind.ArrayType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } } N(SyntaxKind.QuestionQuestionToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "y"); } } EOF(); } [Fact] public void NullCoalescingOperator_NullableArray() { UsingExpression("x as T[] ? ?? y"); N(SyntaxKind.CoalesceExpression); { N(SyntaxKind.AsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.AsKeyword); N(SyntaxKind.NullableType); { N(SyntaxKind.ArrayType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.QuestionToken); } } N(SyntaxKind.QuestionQuestionToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "y"); } } EOF(); } [Fact] public void DeclarationPattern_NullableType() { UsingStatement("switch (e) { case T? t: break; }", // (1,25): error CS1525: Invalid expression term 'break' // switch (e) { case T? t: break; } Diagnostic(ErrorCode.ERR_InvalidExprTerm, "break").WithArguments("break").WithLocation(1, 25), // (1,25): error CS1003: Syntax error, ':' expected // switch (e) { case T? t: break; } Diagnostic(ErrorCode.ERR_SyntaxError, "break").WithArguments(":", "break").WithLocation(1, 25)); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "t"); } N(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void DeclarationPattern_NullableArray() { UsingStatement("switch (e) { case T[]? t: break; }", options: TestOptions.Regular8, // (1,19): error CS8400: Feature 'type pattern' is not available in C# 8.0. Please use language version 9.0 or greater. // switch (e) { case T[]? t: break; } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "T[]").WithArguments("type pattern", "9.0").WithLocation(1, 19), // (1,22): error CS1003: Syntax error, ':' expected // switch (e) { case T[]? t: break; } Diagnostic(ErrorCode.ERR_SyntaxError, "?").WithArguments(":", "?").WithLocation(1, 22), // (1,22): error CS1513: } expected // switch (e) { case T[]? t: break; } Diagnostic(ErrorCode.ERR_RbraceExpected, "?").WithLocation(1, 22)); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.TypePattern); { N(SyntaxKind.ArrayType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } } M(SyntaxKind.ColonToken); } N(SyntaxKind.LabeledStatement); { N(SyntaxKind.IdentifierToken, "t"); N(SyntaxKind.ColonToken); N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void DeclarationPattern_ArrayOfNullableType() { UsingStatement("switch (e) { case T?[] t: break; }"); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.ArrayType); { N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "t"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void DeclarationPattern_NullableArrayOfArray() { UsingStatement("switch (e) { case T[]?[] t: break; }"); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.ArrayType); { N(SyntaxKind.NullableType); { N(SyntaxKind.ArrayType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.QuestionToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "t"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void NullableArray_TypeArgument() { UsingExpression("F<A[]?, object[]?>()"); N(SyntaxKind.InvocationExpression); { N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "F"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.NullableType); { N(SyntaxKind.ArrayType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.QuestionToken); } N(SyntaxKind.CommaToken); N(SyntaxKind.NullableType); { N(SyntaxKind.ArrayType); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.ObjectKeyword); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.QuestionToken); } N(SyntaxKind.GreaterThanToken); } } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } } EOF(); } [Fact] public void NullableArray_TupleType() { UsingStatement("(object[]?, A[]?) t;"); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.NullableType); { N(SyntaxKind.ArrayType); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.ObjectKeyword); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.QuestionToken); } } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.NullableType); { N(SyntaxKind.ArrayType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.QuestionToken); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "t"); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void NullableArray_Using() { UsingStatement("using (A[]? a = b) { }"); N(SyntaxKind.UsingStatement); { N(SyntaxKind.UsingKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.NullableType); { N(SyntaxKind.ArrayType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.QuestionToken); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "a"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } } } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void NullableArray_Query() { UsingExpression("from A[]? a in b select a"); N(SyntaxKind.QueryExpression); { N(SyntaxKind.FromClause); { N(SyntaxKind.FromKeyword); N(SyntaxKind.NullableType); { N(SyntaxKind.ArrayType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.QuestionToken); } N(SyntaxKind.IdentifierToken, "a"); N(SyntaxKind.InKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } N(SyntaxKind.QueryBody); { N(SyntaxKind.SelectClause); { N(SyntaxKind.SelectKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } } } } EOF(); } [Fact] public void NullableArray_ExplicitlyTypedLambda() { UsingExpression("F((object[]? a) => a)"); N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "F"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.ParenthesizedLambdaExpression); { N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.NullableType); { N(SyntaxKind.ArrayType); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.ObjectKeyword); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.QuestionToken); } N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } } } N(SyntaxKind.CloseParenToken); } } EOF(); } [Fact] public void NullableArray_PartialMember() { UsingTree( @"class C { partial A[]? F(); }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PartialKeyword); N(SyntaxKind.NullableType); { N(SyntaxKind.ArrayType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.QuestionToken); } N(SyntaxKind.IdentifierToken, "F"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void CreateNullableArray_01() { UsingExpression("new object[,][]?", // (1,17): error CS1733: Expected expression // new object[,][]? Diagnostic(ErrorCode.ERR_ExpressionExpected, "").WithLocation(1, 17), // (1,17): error CS1003: Syntax error, ':' expected // new object[,][]? Diagnostic(ErrorCode.ERR_SyntaxError, "").WithArguments(":", "").WithLocation(1, 17), // (1,17): error CS1733: Expected expression // new object[,][]? Diagnostic(ErrorCode.ERR_ExpressionExpected, "").WithLocation(1, 17) ); N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.ArrayCreationExpression); { N(SyntaxKind.NewKeyword); N(SyntaxKind.ArrayType); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.ObjectKeyword); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CommaToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } } N(SyntaxKind.QuestionToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } EOF(); } [Fact] public void CreateNullableArray_02() { UsingExpression("new object[,][]? { 1, 2 }"); N(SyntaxKind.ObjectCreationExpression); { N(SyntaxKind.NewKeyword); N(SyntaxKind.NullableType); { N(SyntaxKind.ArrayType); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.ObjectKeyword); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CommaToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.QuestionToken); } N(SyntaxKind.CollectionInitializerExpression); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } N(SyntaxKind.CommaToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void CreateNullableArray_03() { UsingExpression("new object[1,2]?[3]?[4]"); N(SyntaxKind.ArrayCreationExpression); { N(SyntaxKind.NewKeyword); N(SyntaxKind.ArrayType); { N(SyntaxKind.NullableType); { N(SyntaxKind.ArrayType); { N(SyntaxKind.NullableType); { N(SyntaxKind.ArrayType); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.ObjectKeyword); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } N(SyntaxKind.CommaToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.QuestionToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.QuestionToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } N(SyntaxKind.CloseBracketToken); } } } EOF(); } [Fact] public void CreateNullableArray_04() { UsingExpression("new object[,]?[]?[]"); N(SyntaxKind.ArrayCreationExpression); { N(SyntaxKind.NewKeyword); N(SyntaxKind.ArrayType); { N(SyntaxKind.NullableType); { N(SyntaxKind.ArrayType); { N(SyntaxKind.NullableType); { N(SyntaxKind.ArrayType); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.ObjectKeyword); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CommaToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.QuestionToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.QuestionToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } } EOF(); } [Fact] public void CreateNullableArray_05() { UsingExpression("new object[1,2]?[3]?[]"); N(SyntaxKind.ArrayCreationExpression); { N(SyntaxKind.NewKeyword); N(SyntaxKind.ArrayType); { N(SyntaxKind.NullableType); { N(SyntaxKind.ArrayType); { N(SyntaxKind.NullableType); { N(SyntaxKind.ArrayType); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.ObjectKeyword); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } N(SyntaxKind.CommaToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.QuestionToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.QuestionToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } } EOF(); } [Fact] public void CreateNullableArray_06() { UsingExpression("new object[]"); N(SyntaxKind.ArrayCreationExpression); { N(SyntaxKind.NewKeyword); N(SyntaxKind.ArrayType); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.ObjectKeyword); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } } EOF(); } [Fact] public void CreateNullableArray_07() { UsingExpression("new object[1]?[2,3]?[]"); N(SyntaxKind.ArrayCreationExpression); { N(SyntaxKind.NewKeyword); N(SyntaxKind.ArrayType); { N(SyntaxKind.NullableType); { N(SyntaxKind.ArrayType); { N(SyntaxKind.NullableType); { N(SyntaxKind.ArrayType); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.ObjectKeyword); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.QuestionToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } N(SyntaxKind.CommaToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.QuestionToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } } EOF(); } } }
// Licensed to the .NET Foundation under one or more 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.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class NullableParsingTests : ParsingTests { public NullableParsingTests(ITestOutputHelper output) : base(output) { } [WorkItem(23272, "https://github.com/dotnet/roslyn/issues/23272")] [Fact] public void PartialAccessibilityAndNullableArray() { // Note: the typo `privat` is necessary for https://github.com/dotnet/roslyn/issues/23272. UsingTree( @"class C { privat C[]? F; }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.FieldDeclaration); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "privat"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.BracketedArgumentList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Argument); { N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } } N(SyntaxKind.CloseBracketToken); } } } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.IncompleteMember); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "F"); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [WorkItem(24482, "https://github.com/dotnet/roslyn/issues/24482")] [Fact] public void NullableArray_Cast_01() { UsingExpression("(object[]?)null"); N(SyntaxKind.CastExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.NullableType); { N(SyntaxKind.ArrayType); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.ObjectKeyword); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.QuestionToken); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.NullLiteralExpression); { N(SyntaxKind.NullKeyword); } } EOF(); } [WorkItem(24482, "https://github.com/dotnet/roslyn/issues/24482")] [Fact] public void NullableArray_Cast_02() { UsingExpression("(object[]??)null", // (1,1): error CS1073: Unexpected token 'null' // (object[]??)null Diagnostic(ErrorCode.ERR_UnexpectedToken, "(object[]??)").WithArguments("null").WithLocation(1, 1), // (1,2): error CS1525: Invalid expression term 'object' // (object[]??)null Diagnostic(ErrorCode.ERR_InvalidExprTerm, "object").WithArguments("object").WithLocation(1, 2), // (1,9): error CS0443: Syntax error; value expected // (object[]??)null Diagnostic(ErrorCode.ERR_ValueExpected, "]").WithLocation(1, 9), // (1,12): error CS1525: Invalid expression term ')' // (object[]??)null Diagnostic(ErrorCode.ERR_InvalidExprTerm, ")").WithArguments(")").WithLocation(1, 12)); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CoalesceExpression); { N(SyntaxKind.ElementAccessExpression); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.ObjectKeyword); } N(SyntaxKind.BracketedArgumentList); { N(SyntaxKind.OpenBracketToken); M(SyntaxKind.Argument); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.QuestionQuestionToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.CloseParenToken); } EOF(); } [WorkItem(24482, "https://github.com/dotnet/roslyn/issues/24482")] [Fact] public void NullableArray_Cast_03() { UsingExpression("(object[?])null", // (1,1): error CS1073: Unexpected token 'null' // (object[?])null Diagnostic(ErrorCode.ERR_UnexpectedToken, "(object[?])").WithArguments("null").WithLocation(1, 1), // (1,2): error CS1525: Invalid expression term 'object' // (object[?])null Diagnostic(ErrorCode.ERR_InvalidExprTerm, "object").WithArguments("object").WithLocation(1, 2), // (1,9): error CS1001: Identifier expected // (object[?])null Diagnostic(ErrorCode.ERR_IdentifierExpected, "?").WithLocation(1, 9)); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.ElementAccessExpression); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.ObjectKeyword); } N(SyntaxKind.BracketedArgumentList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.CloseParenToken); } EOF(); } [WorkItem(24482, "https://github.com/dotnet/roslyn/issues/24482")] [Fact] public void NullableArray_Cast_04() { UsingExpression("(object?[]?[])null"); N(SyntaxKind.CastExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.ArrayType); { N(SyntaxKind.NullableType); { N(SyntaxKind.ArrayType); { N(SyntaxKind.NullableType); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.ObjectKeyword); } N(SyntaxKind.QuestionToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.QuestionToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.CloseParenToken); N(SyntaxKind.NullLiteralExpression); { N(SyntaxKind.NullKeyword); } } EOF(); } [WorkItem(24482, "https://github.com/dotnet/roslyn/issues/24482")] [Fact] public void NullableArray_Cast_05() { UsingExpression("(object[][]?[]?)null"); N(SyntaxKind.CastExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.NullableType); { N(SyntaxKind.ArrayType); { N(SyntaxKind.NullableType); { N(SyntaxKind.ArrayType); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.ObjectKeyword); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.QuestionToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.QuestionToken); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.NullLiteralExpression); { N(SyntaxKind.NullKeyword); } } EOF(); } [Fact] public void ConditionalOperator_NotNullableType() { UsingExpression("x is T ? y : z"); N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } } N(SyntaxKind.QuestionToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "y"); } N(SyntaxKind.ColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "z"); } } EOF(); } [Fact] public void ConditionalOperator_NullableType() { UsingExpression("x is T ? ? y : z"); N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); } } N(SyntaxKind.QuestionToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "y"); } N(SyntaxKind.ColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "z"); } } EOF(); } [Fact] public void ConditionalOperator_NotNullableArray() { UsingExpression("x is T[] ? y : z"); N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ArrayType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } } N(SyntaxKind.QuestionToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "y"); } N(SyntaxKind.ColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "z"); } } EOF(); } [Fact] public void ConditionalOperator_NullableArray() { UsingExpression("x is T[] ? ? y : z"); N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.NullableType); { N(SyntaxKind.ArrayType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.QuestionToken); } } N(SyntaxKind.QuestionToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "y"); } N(SyntaxKind.ColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "z"); } } EOF(); } [Fact] public void NullCoalescingOperator_NotNullableType() { UsingExpression("x as T?? y"); N(SyntaxKind.CoalesceExpression); { N(SyntaxKind.AsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.AsKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } } N(SyntaxKind.QuestionQuestionToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "y"); } } EOF(); } [Fact] public void NullCoalescingOperator_NullableType() { UsingExpression("x as T? ?? y"); N(SyntaxKind.CoalesceExpression); { N(SyntaxKind.AsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.AsKeyword); N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); } } N(SyntaxKind.QuestionQuestionToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "y"); } } EOF(); } [Fact] public void NullCoalescingOperator_NullableType_Invalid() { UsingExpression("x as T??? y", // (1,9): error CS1525: Invalid expression term '?' // x as T??? y Diagnostic(ErrorCode.ERR_InvalidExprTerm, "?").WithArguments("?").WithLocation(1, 9), // (1,12): error CS1003: Syntax error, ':' expected // x as T??? y Diagnostic(ErrorCode.ERR_SyntaxError, "").WithArguments(":", "").WithLocation(1, 12), // (1,12): error CS1733: Expected expression // x as T??? y Diagnostic(ErrorCode.ERR_ExpressionExpected, "").WithLocation(1, 12)); N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.CoalesceExpression); { N(SyntaxKind.AsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.AsKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } } N(SyntaxKind.QuestionQuestionToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.QuestionToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "y"); } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } EOF(); } [Fact] public void NullCoalescingOperator_NotNullableArray() { UsingExpression("x as T[] ?? y"); N(SyntaxKind.CoalesceExpression); { N(SyntaxKind.AsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.AsKeyword); N(SyntaxKind.ArrayType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } } N(SyntaxKind.QuestionQuestionToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "y"); } } EOF(); } [Fact] public void NullCoalescingOperator_NullableArray() { UsingExpression("x as T[] ? ?? y"); N(SyntaxKind.CoalesceExpression); { N(SyntaxKind.AsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.AsKeyword); N(SyntaxKind.NullableType); { N(SyntaxKind.ArrayType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.QuestionToken); } } N(SyntaxKind.QuestionQuestionToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "y"); } } EOF(); } [Fact] public void DeclarationPattern_NullableType() { UsingStatement("switch (e) { case T? t: break; }", // (1,25): error CS1525: Invalid expression term 'break' // switch (e) { case T? t: break; } Diagnostic(ErrorCode.ERR_InvalidExprTerm, "break").WithArguments("break").WithLocation(1, 25), // (1,25): error CS1003: Syntax error, ':' expected // switch (e) { case T? t: break; } Diagnostic(ErrorCode.ERR_SyntaxError, "break").WithArguments(":", "break").WithLocation(1, 25)); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "t"); } N(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void DeclarationPattern_NullableArray() { UsingStatement("switch (e) { case T[]? t: break; }", options: TestOptions.Regular8, // (1,19): error CS8400: Feature 'type pattern' is not available in C# 8.0. Please use language version 9.0 or greater. // switch (e) { case T[]? t: break; } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "T[]").WithArguments("type pattern", "9.0").WithLocation(1, 19), // (1,22): error CS1003: Syntax error, ':' expected // switch (e) { case T[]? t: break; } Diagnostic(ErrorCode.ERR_SyntaxError, "?").WithArguments(":", "?").WithLocation(1, 22), // (1,22): error CS1513: } expected // switch (e) { case T[]? t: break; } Diagnostic(ErrorCode.ERR_RbraceExpected, "?").WithLocation(1, 22)); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.TypePattern); { N(SyntaxKind.ArrayType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } } M(SyntaxKind.ColonToken); } N(SyntaxKind.LabeledStatement); { N(SyntaxKind.IdentifierToken, "t"); N(SyntaxKind.ColonToken); N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void DeclarationPattern_ArrayOfNullableType() { UsingStatement("switch (e) { case T?[] t: break; }"); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.ArrayType); { N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "t"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void DeclarationPattern_NullableArrayOfArray() { UsingStatement("switch (e) { case T[]?[] t: break; }"); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.ArrayType); { N(SyntaxKind.NullableType); { N(SyntaxKind.ArrayType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.QuestionToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "t"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void NullableArray_TypeArgument() { UsingExpression("F<A[]?, object[]?>()"); N(SyntaxKind.InvocationExpression); { N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "F"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.NullableType); { N(SyntaxKind.ArrayType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.QuestionToken); } N(SyntaxKind.CommaToken); N(SyntaxKind.NullableType); { N(SyntaxKind.ArrayType); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.ObjectKeyword); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.QuestionToken); } N(SyntaxKind.GreaterThanToken); } } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } } EOF(); } [Fact] public void NullableArray_TupleType() { UsingStatement("(object[]?, A[]?) t;"); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.NullableType); { N(SyntaxKind.ArrayType); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.ObjectKeyword); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.QuestionToken); } } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.NullableType); { N(SyntaxKind.ArrayType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.QuestionToken); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "t"); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void NullableArray_Using() { UsingStatement("using (A[]? a = b) { }"); N(SyntaxKind.UsingStatement); { N(SyntaxKind.UsingKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.NullableType); { N(SyntaxKind.ArrayType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.QuestionToken); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "a"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } } } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void NullableArray_Query() { UsingExpression("from A[]? a in b select a"); N(SyntaxKind.QueryExpression); { N(SyntaxKind.FromClause); { N(SyntaxKind.FromKeyword); N(SyntaxKind.NullableType); { N(SyntaxKind.ArrayType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.QuestionToken); } N(SyntaxKind.IdentifierToken, "a"); N(SyntaxKind.InKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } N(SyntaxKind.QueryBody); { N(SyntaxKind.SelectClause); { N(SyntaxKind.SelectKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } } } } EOF(); } [Fact] public void NullableArray_ExplicitlyTypedLambda() { UsingExpression("F((object[]? a) => a)"); N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "F"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.ParenthesizedLambdaExpression); { N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.NullableType); { N(SyntaxKind.ArrayType); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.ObjectKeyword); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.QuestionToken); } N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } } } N(SyntaxKind.CloseParenToken); } } EOF(); } [Fact] public void NullableArray_PartialMember() { UsingTree( @"class C { partial A[]? F(); }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PartialKeyword); N(SyntaxKind.NullableType); { N(SyntaxKind.ArrayType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.QuestionToken); } N(SyntaxKind.IdentifierToken, "F"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void CreateNullableArray_01() { UsingExpression("new object[,][]?", // (1,17): error CS1733: Expected expression // new object[,][]? Diagnostic(ErrorCode.ERR_ExpressionExpected, "").WithLocation(1, 17), // (1,17): error CS1003: Syntax error, ':' expected // new object[,][]? Diagnostic(ErrorCode.ERR_SyntaxError, "").WithArguments(":", "").WithLocation(1, 17), // (1,17): error CS1733: Expected expression // new object[,][]? Diagnostic(ErrorCode.ERR_ExpressionExpected, "").WithLocation(1, 17) ); N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.ArrayCreationExpression); { N(SyntaxKind.NewKeyword); N(SyntaxKind.ArrayType); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.ObjectKeyword); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CommaToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } } N(SyntaxKind.QuestionToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } EOF(); } [Fact] public void CreateNullableArray_02() { UsingExpression("new object[,][]? { 1, 2 }"); N(SyntaxKind.ObjectCreationExpression); { N(SyntaxKind.NewKeyword); N(SyntaxKind.NullableType); { N(SyntaxKind.ArrayType); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.ObjectKeyword); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CommaToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.QuestionToken); } N(SyntaxKind.CollectionInitializerExpression); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } N(SyntaxKind.CommaToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void CreateNullableArray_03() { UsingExpression("new object[1,2]?[3]?[4]"); N(SyntaxKind.ArrayCreationExpression); { N(SyntaxKind.NewKeyword); N(SyntaxKind.ArrayType); { N(SyntaxKind.NullableType); { N(SyntaxKind.ArrayType); { N(SyntaxKind.NullableType); { N(SyntaxKind.ArrayType); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.ObjectKeyword); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } N(SyntaxKind.CommaToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.QuestionToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.QuestionToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } N(SyntaxKind.CloseBracketToken); } } } EOF(); } [Fact] public void CreateNullableArray_04() { UsingExpression("new object[,]?[]?[]"); N(SyntaxKind.ArrayCreationExpression); { N(SyntaxKind.NewKeyword); N(SyntaxKind.ArrayType); { N(SyntaxKind.NullableType); { N(SyntaxKind.ArrayType); { N(SyntaxKind.NullableType); { N(SyntaxKind.ArrayType); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.ObjectKeyword); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CommaToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.QuestionToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.QuestionToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } } EOF(); } [Fact] public void CreateNullableArray_05() { UsingExpression("new object[1,2]?[3]?[]"); N(SyntaxKind.ArrayCreationExpression); { N(SyntaxKind.NewKeyword); N(SyntaxKind.ArrayType); { N(SyntaxKind.NullableType); { N(SyntaxKind.ArrayType); { N(SyntaxKind.NullableType); { N(SyntaxKind.ArrayType); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.ObjectKeyword); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } N(SyntaxKind.CommaToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.QuestionToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.QuestionToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } } EOF(); } [Fact] public void CreateNullableArray_06() { UsingExpression("new object[]"); N(SyntaxKind.ArrayCreationExpression); { N(SyntaxKind.NewKeyword); N(SyntaxKind.ArrayType); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.ObjectKeyword); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } } EOF(); } [Fact] public void CreateNullableArray_07() { UsingExpression("new object[1]?[2,3]?[]"); N(SyntaxKind.ArrayCreationExpression); { N(SyntaxKind.NewKeyword); N(SyntaxKind.ArrayType); { N(SyntaxKind.NullableType); { N(SyntaxKind.ArrayType); { N(SyntaxKind.NullableType); { N(SyntaxKind.ArrayType); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.ObjectKeyword); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.QuestionToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } N(SyntaxKind.CommaToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.QuestionToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } } EOF(); } } }
-1
dotnet/roslyn
56,433
Only allow Contract.ThrowIfNull() to be called on nullable types
We had some places we were calling it on bools.
jasonmalinowski
"2021-09-16T01:20:43Z"
"2021-09-16T18:44:11Z"
736fc1b5e6e2847689c0154b3e5f23ea99dd56af
6d0f4e3f972ceb561b04574e7f957a4ff458e272
Only allow Contract.ThrowIfNull() to be called on nullable types. We had some places we were calling it on bools.
./src/Features/Core/Portable/ValueTracking/ValueTrackedItem.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.Linq; using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Classification; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ValueTracking { internal class ValueTrackedItem { public SymbolKey SymbolKey { get; } public ValueTrackedItem? Parent { get; } public DocumentId DocumentId { get; } public TextSpan Span { get; } public ImmutableArray<ClassifiedSpan> ClassifiedSpans { get; } public SourceText SourceText { get; } public Glyph Glyph { get; } private ValueTrackedItem( SymbolKey symbolKey, SourceText sourceText, ImmutableArray<ClassifiedSpan> classifiedSpans, TextSpan textSpan, DocumentId documentId, Glyph glyph, ValueTrackedItem? parent = null) { SymbolKey = symbolKey; Parent = parent; Glyph = glyph; Span = textSpan; ClassifiedSpans = classifiedSpans; SourceText = sourceText; DocumentId = documentId; } public override string ToString() { var subText = SourceText.GetSubText(Span); return subText.ToString(); } public static Task<ValueTrackedItem?> TryCreateAsync(Solution solution, Location location, ISymbol symbol, ValueTrackedItem? parent = null, CancellationToken cancellationToken = default) { Contract.ThrowIfNull(location.SourceTree); var document = solution.GetRequiredDocument(location.SourceTree); return TryCreateAsync(document, location.SourceSpan, symbol, parent, cancellationToken); } public static async Task<ValueTrackedItem?> TryCreateAsync(Document document, TextSpan textSpan, ISymbol symbol, ValueTrackedItem? parent = null, CancellationToken cancellationToken = default) { var excerptService = document.Services.GetService<IDocumentExcerptService>(); SourceText? sourceText = null; ImmutableArray<ClassifiedSpan> classifiedSpans = default; if (excerptService != null) { var result = await excerptService.TryExcerptAsync(document, textSpan, ExcerptMode.SingleLine, cancellationToken).ConfigureAwait(false); if (result.HasValue) { var value = result.Value; sourceText = value.Content; } } if (sourceText is null) { var documentSpan = await ClassifiedSpansAndHighlightSpanFactory.GetClassifiedDocumentSpanAsync(document, textSpan, cancellationToken).ConfigureAwait(false); var classificationResult = await ClassifiedSpansAndHighlightSpanFactory.ClassifyAsync(documentSpan, cancellationToken).ConfigureAwait(false); classifiedSpans = classificationResult.ClassifiedSpans; var syntaxTree = await document.GetRequiredSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); sourceText = await syntaxTree.GetTextAsync(cancellationToken).ConfigureAwait(false); } return new ValueTrackedItem( SymbolKey.Create(symbol, cancellationToken), sourceText, classifiedSpans, textSpan, document.Id, symbol.GetGlyph(), parent: parent); } } }
// Licensed to the .NET Foundation under one or more 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.Linq; using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Classification; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ValueTracking { internal class ValueTrackedItem { public SymbolKey SymbolKey { get; } public ValueTrackedItem? Parent { get; } public DocumentId DocumentId { get; } public TextSpan Span { get; } public ImmutableArray<ClassifiedSpan> ClassifiedSpans { get; } public SourceText SourceText { get; } public Glyph Glyph { get; } private ValueTrackedItem( SymbolKey symbolKey, SourceText sourceText, ImmutableArray<ClassifiedSpan> classifiedSpans, TextSpan textSpan, DocumentId documentId, Glyph glyph, ValueTrackedItem? parent = null) { SymbolKey = symbolKey; Parent = parent; Glyph = glyph; Span = textSpan; ClassifiedSpans = classifiedSpans; SourceText = sourceText; DocumentId = documentId; } public override string ToString() { var subText = SourceText.GetSubText(Span); return subText.ToString(); } public static Task<ValueTrackedItem?> TryCreateAsync(Solution solution, Location location, ISymbol symbol, ValueTrackedItem? parent = null, CancellationToken cancellationToken = default) { Contract.ThrowIfNull(location.SourceTree); var document = solution.GetRequiredDocument(location.SourceTree); return TryCreateAsync(document, location.SourceSpan, symbol, parent, cancellationToken); } public static async Task<ValueTrackedItem?> TryCreateAsync(Document document, TextSpan textSpan, ISymbol symbol, ValueTrackedItem? parent = null, CancellationToken cancellationToken = default) { var excerptService = document.Services.GetService<IDocumentExcerptService>(); SourceText? sourceText = null; ImmutableArray<ClassifiedSpan> classifiedSpans = default; if (excerptService != null) { var result = await excerptService.TryExcerptAsync(document, textSpan, ExcerptMode.SingleLine, cancellationToken).ConfigureAwait(false); if (result.HasValue) { var value = result.Value; sourceText = value.Content; } } if (sourceText is null) { var documentSpan = await ClassifiedSpansAndHighlightSpanFactory.GetClassifiedDocumentSpanAsync(document, textSpan, cancellationToken).ConfigureAwait(false); var classificationResult = await ClassifiedSpansAndHighlightSpanFactory.ClassifyAsync(documentSpan, cancellationToken).ConfigureAwait(false); classifiedSpans = classificationResult.ClassifiedSpans; var syntaxTree = await document.GetRequiredSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); sourceText = await syntaxTree.GetTextAsync(cancellationToken).ConfigureAwait(false); } return new ValueTrackedItem( SymbolKey.Create(symbol, cancellationToken), sourceText, classifiedSpans, textSpan, document.Id, symbol.GetGlyph(), parent: parent); } } }
-1
dotnet/roslyn
56,433
Only allow Contract.ThrowIfNull() to be called on nullable types
We had some places we were calling it on bools.
jasonmalinowski
"2021-09-16T01:20:43Z"
"2021-09-16T18:44:11Z"
736fc1b5e6e2847689c0154b3e5f23ea99dd56af
6d0f4e3f972ceb561b04574e7f957a4ff458e272
Only allow Contract.ThrowIfNull() to be called on nullable types. We had some places we were calling it on bools.
./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/LanguageServices/CSharpSyntaxFactsService.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.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; using Microsoft.CodeAnalysis.CSharp.LanguageServices; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp { internal sealed partial class CSharpSyntaxFactsServiceFactory { private sealed class CSharpSyntaxFactsService : CSharpSyntaxFacts, ISyntaxFactsService { internal static new readonly CSharpSyntaxFactsService Instance = new(); public bool IsInInactiveRegion(SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { if (syntaxTree == null) { return false; } return syntaxTree.IsInInactiveRegion(position, cancellationToken); } public bool IsInNonUserCode(SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { if (syntaxTree == null) { return false; } return syntaxTree.IsInNonUserCode(position, cancellationToken); } private static readonly SyntaxAnnotation s_annotation = new(); public void AddFirstMissingCloseBrace<TContextNode>( SyntaxNode root, TContextNode contextNode, out SyntaxNode newRoot, out TContextNode newContextNode) where TContextNode : SyntaxNode { newRoot = new AddFirstMissingCloseBraceRewriter(contextNode).Visit(root); newContextNode = (TContextNode)newRoot.GetAnnotatedNodes(s_annotation).Single(); } public bool IsPossibleTupleContext(SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken); return syntaxTree.IsPossibleTupleContext(token, position); } private class AddFirstMissingCloseBraceRewriter : CSharpSyntaxRewriter { private readonly SyntaxNode _contextNode; private bool _seenContextNode = false; private bool _addedFirstCloseCurly = false; public AddFirstMissingCloseBraceRewriter(SyntaxNode contextNode) => _contextNode = contextNode; public override SyntaxNode Visit(SyntaxNode node) { if (node == _contextNode) { _seenContextNode = true; // Annotate the context node so we can find it again in the new tree // after we've added the close curly. return node.WithAdditionalAnnotations(s_annotation); } // rewrite this node normally. var rewritten = base.Visit(node); if (rewritten == node) { return rewritten; } // This node changed. That means that something underneath us got // rewritten. (i.e. we added the annotation to the context node). Debug.Assert(_seenContextNode); // Ok, we're past the context node now. See if this is a node with // curlies. If so, if it has a missing close curly then add in the // missing curly. Also, even if it doesn't have missing curlies, // then still ask to format its close curly to make sure all the // curlies up the stack are properly formatted. var braces = rewritten.GetBraces(); if (braces.openBrace.Kind() == SyntaxKind.None && braces.closeBrace.Kind() == SyntaxKind.None) { // Not an item with braces. Just pass it up. return rewritten; } // See if the close brace is missing. If it's the first missing one // we're seeing then definitely add it. if (braces.closeBrace.IsMissing) { if (!_addedFirstCloseCurly) { var closeBrace = SyntaxFactory.Token(SyntaxKind.CloseBraceToken) .WithAdditionalAnnotations(Formatter.Annotation); rewritten = rewritten.ReplaceToken(braces.closeBrace, closeBrace); _addedFirstCloseCurly = true; } } else { // Ask for the close brace to be formatted so that all the braces // up the spine are in the right location. rewritten = rewritten.ReplaceToken(braces.closeBrace, braces.closeBrace.WithAdditionalAnnotations(Formatter.Annotation)); } return rewritten; } } public Task<ImmutableArray<SyntaxNode>> GetSelectedFieldsAndPropertiesAsync(SyntaxTree tree, TextSpan textSpan, bool allowPartialSelection, CancellationToken cancellationToken) => CSharpSelectedMembers.Instance.GetSelectedFieldsAndPropertiesAsync(tree, textSpan, allowPartialSelection, 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.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; using Microsoft.CodeAnalysis.CSharp.LanguageServices; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp { internal sealed partial class CSharpSyntaxFactsServiceFactory { private sealed class CSharpSyntaxFactsService : CSharpSyntaxFacts, ISyntaxFactsService { internal static new readonly CSharpSyntaxFactsService Instance = new(); public bool IsInInactiveRegion(SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { if (syntaxTree == null) { return false; } return syntaxTree.IsInInactiveRegion(position, cancellationToken); } public bool IsInNonUserCode(SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { if (syntaxTree == null) { return false; } return syntaxTree.IsInNonUserCode(position, cancellationToken); } private static readonly SyntaxAnnotation s_annotation = new(); public void AddFirstMissingCloseBrace<TContextNode>( SyntaxNode root, TContextNode contextNode, out SyntaxNode newRoot, out TContextNode newContextNode) where TContextNode : SyntaxNode { newRoot = new AddFirstMissingCloseBraceRewriter(contextNode).Visit(root); newContextNode = (TContextNode)newRoot.GetAnnotatedNodes(s_annotation).Single(); } public bool IsPossibleTupleContext(SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken); return syntaxTree.IsPossibleTupleContext(token, position); } private class AddFirstMissingCloseBraceRewriter : CSharpSyntaxRewriter { private readonly SyntaxNode _contextNode; private bool _seenContextNode = false; private bool _addedFirstCloseCurly = false; public AddFirstMissingCloseBraceRewriter(SyntaxNode contextNode) => _contextNode = contextNode; public override SyntaxNode Visit(SyntaxNode node) { if (node == _contextNode) { _seenContextNode = true; // Annotate the context node so we can find it again in the new tree // after we've added the close curly. return node.WithAdditionalAnnotations(s_annotation); } // rewrite this node normally. var rewritten = base.Visit(node); if (rewritten == node) { return rewritten; } // This node changed. That means that something underneath us got // rewritten. (i.e. we added the annotation to the context node). Debug.Assert(_seenContextNode); // Ok, we're past the context node now. See if this is a node with // curlies. If so, if it has a missing close curly then add in the // missing curly. Also, even if it doesn't have missing curlies, // then still ask to format its close curly to make sure all the // curlies up the stack are properly formatted. var braces = rewritten.GetBraces(); if (braces.openBrace.Kind() == SyntaxKind.None && braces.closeBrace.Kind() == SyntaxKind.None) { // Not an item with braces. Just pass it up. return rewritten; } // See if the close brace is missing. If it's the first missing one // we're seeing then definitely add it. if (braces.closeBrace.IsMissing) { if (!_addedFirstCloseCurly) { var closeBrace = SyntaxFactory.Token(SyntaxKind.CloseBraceToken) .WithAdditionalAnnotations(Formatter.Annotation); rewritten = rewritten.ReplaceToken(braces.closeBrace, closeBrace); _addedFirstCloseCurly = true; } } else { // Ask for the close brace to be formatted so that all the braces // up the spine are in the right location. rewritten = rewritten.ReplaceToken(braces.closeBrace, braces.closeBrace.WithAdditionalAnnotations(Formatter.Annotation)); } return rewritten; } } public Task<ImmutableArray<SyntaxNode>> GetSelectedFieldsAndPropertiesAsync(SyntaxTree tree, TextSpan textSpan, bool allowPartialSelection, CancellationToken cancellationToken) => CSharpSelectedMembers.Instance.GetSelectedFieldsAndPropertiesAsync(tree, textSpan, allowPartialSelection, cancellationToken); } } }
-1
dotnet/roslyn
56,433
Only allow Contract.ThrowIfNull() to be called on nullable types
We had some places we were calling it on bools.
jasonmalinowski
"2021-09-16T01:20:43Z"
"2021-09-16T18:44:11Z"
736fc1b5e6e2847689c0154b3e5f23ea99dd56af
6d0f4e3f972ceb561b04574e7f957a4ff458e272
Only allow Contract.ThrowIfNull() to be called on nullable types. We had some places we were calling it on bools.
./src/Compilers/Core/Portable/Diagnostic/SuppressionInfo.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.Diagnostics { /// <summary> /// Contains information about the source of diagnostic suppression. /// </summary> public sealed class SuppressionInfo { /// <summary> /// <see cref="Diagnostic.Id"/> of the suppressed diagnostic. /// </summary> public string Id { get; } /// <summary> /// If the diagnostic was suppressed by an attribute, then returns that attribute. /// Otherwise, returns null. /// </summary> public AttributeData? Attribute { get; } internal SuppressionInfo(string id, AttributeData? attribute) { Id = id; Attribute = attribute; } } }
// Licensed to the .NET Foundation under one or more 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.Diagnostics { /// <summary> /// Contains information about the source of diagnostic suppression. /// </summary> public sealed class SuppressionInfo { /// <summary> /// <see cref="Diagnostic.Id"/> of the suppressed diagnostic. /// </summary> public string Id { get; } /// <summary> /// If the diagnostic was suppressed by an attribute, then returns that attribute. /// Otherwise, returns null. /// </summary> public AttributeData? Attribute { get; } internal SuppressionInfo(string id, AttributeData? attribute) { Id = id; Attribute = attribute; } } }
-1
dotnet/roslyn
56,433
Only allow Contract.ThrowIfNull() to be called on nullable types
We had some places we were calling it on bools.
jasonmalinowski
"2021-09-16T01:20:43Z"
"2021-09-16T18:44:11Z"
736fc1b5e6e2847689c0154b3e5f23ea99dd56af
6d0f4e3f972ceb561b04574e7f957a4ff458e272
Only allow Contract.ThrowIfNull() to be called on nullable types. We had some places we were calling it on bools.
./src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_UsingStatement.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.Diagnostics; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Microsoft.CodeAnalysis.CSharp { internal sealed partial class LocalRewriter { /// <summary> /// Rewrite a using statement into a try finally statement. Four forms are possible: /// 1) using (expr) stmt /// 2) await using (expr) stmt /// 3) using (C c = expr) stmt /// 4) await using (C c = expr) stmt /// /// The first two are handled by RewriteExpressionUsingStatement and the latter two are handled by /// RewriteDeclarationUsingStatement (called in a loop, once for each local declared). /// /// For the async variants, `IAsyncDisposable` is used instead of `IDisposable` and we produce /// `... await expr.DisposeAsync() ...` instead of `... expr.Dispose() ...`. /// </summary> /// <remarks> /// It would be more in line with our usual pattern to rewrite using to try-finally /// in the ControlFlowRewriter, but if we don't do it here the BoundMultipleLocalDeclarations /// will be rewritten into a form that makes them harder to separate. /// </remarks> public override BoundNode VisitUsingStatement(BoundUsingStatement node) { BoundStatement? rewrittenBody = VisitStatement(node.Body); Debug.Assert(rewrittenBody is { }); BoundBlock tryBlock = rewrittenBody.Kind == BoundKind.Block ? (BoundBlock)rewrittenBody : BoundBlock.SynthesizedNoLocals(node.Syntax, rewrittenBody); if (node.ExpressionOpt != null) { return MakeExpressionUsingStatement(node, tryBlock); } else { Debug.Assert(node.DeclarationsOpt is { }); SyntaxToken awaitKeyword = node.Syntax.Kind() == SyntaxKind.UsingStatement ? ((UsingStatementSyntax)node.Syntax).AwaitKeyword : default; return MakeDeclarationUsingStatement(node.Syntax, tryBlock, node.Locals, node.DeclarationsOpt.LocalDeclarations, node.IDisposableConversion, node.PatternDisposeInfoOpt, node.AwaitOpt, awaitKeyword); } } private BoundStatement MakeDeclarationUsingStatement(SyntaxNode syntax, BoundBlock body, ImmutableArray<LocalSymbol> locals, ImmutableArray<BoundLocalDeclaration> declarations, Conversion iDisposableConversion, MethodArgumentInfo? patternDisposeInfo, BoundAwaitableInfo? awaitOpt, SyntaxToken awaitKeyword) { Debug.Assert(declarations != null); BoundBlock result = body; for (int i = declarations.Length - 1; i >= 0; i--) //NB: inner-to-outer = right-to-left { result = RewriteDeclarationUsingStatement(syntax, declarations[i], result, iDisposableConversion, awaitKeyword, awaitOpt, patternDisposeInfo); } // Declare all locals in a single, top-level block so that the scope is correct in the debugger // (Dev10 has them all come into scope at once, not per-declaration.) return new BoundBlock( syntax, locals, ImmutableArray.Create<BoundStatement>(result)); } /// <summary> /// Lower "[await] using var x = (expression)" to a try-finally block. /// </summary> private BoundStatement MakeLocalUsingDeclarationStatement(BoundUsingLocalDeclarations usingDeclarations, ImmutableArray<BoundStatement> statements) { LocalDeclarationStatementSyntax syntax = (LocalDeclarationStatementSyntax)usingDeclarations.Syntax; BoundBlock body = new BoundBlock(syntax, ImmutableArray<LocalSymbol>.Empty, statements); var usingStatement = MakeDeclarationUsingStatement(syntax, body, ImmutableArray<LocalSymbol>.Empty, usingDeclarations.LocalDeclarations, usingDeclarations.IDisposableConversion, usingDeclarations.PatternDisposeInfoOpt, awaitOpt: usingDeclarations.AwaitOpt, awaitKeyword: syntax.AwaitKeyword); return usingStatement; } /// <summary> /// Lower "using [await] (expression) statement" to a try-finally block. /// </summary> private BoundBlock MakeExpressionUsingStatement(BoundUsingStatement node, BoundBlock tryBlock) { Debug.Assert(node.ExpressionOpt != null); Debug.Assert(node.DeclarationsOpt == null); // See comments in BuildUsingTryFinally for the details of the lowering to try-finally. // // SPEC: A using statement of the form "using (expression) statement; " has the // SPEC: same three possible expansions [ as "using (ResourceType r = expression) statement; ] // SPEC: but in this case ResourceType is implicitly the compile-time type of the expression, // SPEC: and the resource variable is inaccessible to and invisible to the embedded statement. // // DELIBERATE SPEC VIOLATION: // // The spec quote above implies that the expression must have a type; in fact we allow // the expression to be null. // // If expr is the constant null then we can elide the whole thing and simply generate the statement. BoundExpression rewrittenExpression = VisitExpression(node.ExpressionOpt); if (rewrittenExpression.ConstantValue == ConstantValue.Null) { Debug.Assert(node.Locals.IsEmpty); // TODO: This might not be a valid assumption in presence of semicolon operator. return tryBlock; } // Otherwise, we lower "using(expression) statement;" as follows: // // * If the expression is of type dynamic then we lower as though the user had written // // using(IDisposable temp = (IDisposable)expression) statement; // // Note that we have to do the conversion early, not in the finally block, because // if the conversion fails at runtime with an exception then the exception must happen // before the statement runs. // // * Otherwise we lower as though the user had written // // using(ResourceType temp = expression) statement; // Debug.Assert(rewrittenExpression.Type is { }); TypeSymbol expressionType = rewrittenExpression.Type; SyntaxNode expressionSyntax = rewrittenExpression.Syntax; UsingStatementSyntax usingSyntax = (UsingStatementSyntax)node.Syntax; BoundAssignmentOperator tempAssignment; BoundLocal boundTemp; if (expressionType is null || expressionType.IsDynamic()) { // IDisposable temp = (IDisposable) expr; // or // IAsyncDisposable temp = (IAsyncDisposable) expr; TypeSymbol iDisposableType = node.AwaitOpt is null ? _compilation.GetSpecialType(SpecialType.System_IDisposable) : _compilation.GetWellKnownType(WellKnownType.System_IAsyncDisposable); _diagnostics.ReportUseSite(iDisposableType, usingSyntax); BoundExpression tempInit = MakeConversionNode( expressionSyntax, rewrittenExpression, Conversion.GetTrivialConversion(node.IDisposableConversion.Kind), iDisposableType, @checked: false, constantValueOpt: rewrittenExpression.ConstantValue); boundTemp = _factory.StoreToTemp(tempInit, out tempAssignment, kind: SynthesizedLocalKind.Using); } else { // ResourceType temp = expr; boundTemp = _factory.StoreToTemp(rewrittenExpression, out tempAssignment, syntaxOpt: usingSyntax, kind: SynthesizedLocalKind.Using); } BoundStatement expressionStatement = new BoundExpressionStatement(expressionSyntax, tempAssignment); if (this.Instrument) { expressionStatement = _instrumenter.InstrumentUsingTargetCapture(node, expressionStatement); } BoundStatement tryFinally = RewriteUsingStatementTryFinally(usingSyntax, tryBlock, boundTemp, usingSyntax.AwaitKeyword, node.AwaitOpt, node.PatternDisposeInfoOpt); // { ResourceType temp = expr; try { ... } finally { ... } } return new BoundBlock( syntax: usingSyntax, locals: node.Locals.Add(boundTemp.LocalSymbol), statements: ImmutableArray.Create<BoundStatement>(expressionStatement, tryFinally)); } /// <summary> /// Lower "using [await] (ResourceType resource = expression) statement" to a try-finally block. /// </summary> /// <remarks> /// Assumes that the local symbol will be declared (i.e. in the LocalsOpt array) of an enclosing block. /// Assumes that using statements with multiple locals have already been split up into multiple using statements. /// </remarks> private BoundBlock RewriteDeclarationUsingStatement( SyntaxNode usingSyntax, BoundLocalDeclaration localDeclaration, BoundBlock tryBlock, Conversion iDisposableConversion, SyntaxToken awaitKeywordOpt, BoundAwaitableInfo? awaitOpt, MethodArgumentInfo? patternDisposeInfo) { Debug.Assert(localDeclaration.InitializerOpt is { }); SyntaxNode declarationSyntax = localDeclaration.Syntax; LocalSymbol localSymbol = localDeclaration.LocalSymbol; TypeSymbol localType = localSymbol.Type; Debug.Assert((object)localType != null); //otherwise, there wouldn't be a conversion to IDisposable BoundLocal boundLocal = new BoundLocal(declarationSyntax, localSymbol, localDeclaration.InitializerOpt.ConstantValue, localType); BoundStatement? rewrittenDeclaration = VisitStatement(localDeclaration); Debug.Assert(rewrittenDeclaration is { }); // If we know that the expression is null, then we know that the null check in the finally block // will fail, and the Dispose call will never happen. That is, the finally block will have no effect. // Consequently, we can simply skip the whole try-finally construct and just create a block containing // the new declaration. if (boundLocal.ConstantValue == ConstantValue.Null) { //localSymbol will be declared by an enclosing block return BoundBlock.SynthesizedNoLocals(usingSyntax, rewrittenDeclaration, tryBlock); } if (localType.IsDynamic()) { TypeSymbol iDisposableType = awaitOpt is null ? _compilation.GetSpecialType(SpecialType.System_IDisposable) : _compilation.GetWellKnownType(WellKnownType.System_IAsyncDisposable); _diagnostics.ReportUseSite(iDisposableType, usingSyntax); BoundExpression tempInit = MakeConversionNode( declarationSyntax, boundLocal, iDisposableConversion, iDisposableType, @checked: false); BoundAssignmentOperator tempAssignment; BoundLocal boundTemp = _factory.StoreToTemp(tempInit, out tempAssignment, kind: SynthesizedLocalKind.Using); BoundStatement tryFinally = RewriteUsingStatementTryFinally(usingSyntax, tryBlock, boundTemp, awaitKeywordOpt, awaitOpt, patternDisposeInfo); return new BoundBlock( syntax: usingSyntax, locals: ImmutableArray.Create<LocalSymbol>(boundTemp.LocalSymbol), //localSymbol will be declared by an enclosing block statements: ImmutableArray.Create<BoundStatement>( rewrittenDeclaration, new BoundExpressionStatement(declarationSyntax, tempAssignment), tryFinally)); } else { BoundStatement tryFinally = RewriteUsingStatementTryFinally(usingSyntax, tryBlock, boundLocal, awaitKeywordOpt, awaitOpt, patternDisposeInfo); // localSymbol will be declared by an enclosing block return BoundBlock.SynthesizedNoLocals(usingSyntax, rewrittenDeclaration, tryFinally); } } private BoundStatement RewriteUsingStatementTryFinally( SyntaxNode syntax, BoundBlock tryBlock, BoundLocal local, SyntaxToken awaitKeywordOpt, BoundAwaitableInfo? awaitOpt, MethodArgumentInfo? patternDisposeInfo) { // SPEC: When ResourceType is a non-nullable value type, the expansion is: // SPEC: // SPEC: { // SPEC: ResourceType resource = expr; // SPEC: try { statement; } // SPEC: finally { ((IDisposable)resource).Dispose(); } // SPEC: } // SPEC: // SPEC: Otherwise, when Resource type is a nullable value type or // SPEC: a reference type other than dynamic, the expansion is: // SPEC: // SPEC: { // SPEC: ResourceType resource = expr; // SPEC: try { statement; } // SPEC: finally { if (resource != null) ((IDisposable)resource).Dispose(); } // SPEC: } // SPEC: // SPEC: Otherwise, when ResourceType is dynamic, the expansion is: // SPEC: { // SPEC: dynamic resource = expr; // SPEC: IDisposable d = (IDisposable)resource; // SPEC: try { statement; } // SPEC: finally { if (d != null) d.Dispose(); } // SPEC: } // SPEC: // SPEC: An implementation is permitted to implement a given using statement // SPEC: differently -- for example, for performance reasons -- as long as the // SPEC: behavior is consistent with the above expansion. // // In the case of using-await statement, we'll use "IAsyncDisposable" instead of "IDisposable", "await DisposeAsync()" instead of "Dispose()" // // And we do in fact generate the code slightly differently than precisely how it is // described above. // // First: if the type is a non-nullable value type then we do not do the // *boxing conversion* from the resource to IDisposable. Rather, we do // a *constrained virtual call* that elides the boxing if possible. // // Now, you might wonder if that is legal; isn't skipping the boxing producing // an observable difference? Because if the value type is mutable and the Dispose // mutates it, then skipping the boxing means that we are now mutating the original, // not the boxed copy. But this is never observable. Either (1) we have "using(R r = x){}" // and r is out of scope after the finally, so it is not possible to observe the mutation, // or (2) we have "using(x) {}". But that has the semantics of "using(R temp = x){}", // so again, we are not mutating x to begin with; we're always mutating a copy. Therefore // it doesn't matter if we skip making *a copy of the copy*. // // This is what the dev10 compiler does, and we do so as well. // // Second: if the type is a nullable value type then we can similarly elide the boxing. // We can generate // // { // ResourceType resource = expr; // try { statement; } // finally { if (resource.HasValue) resource.GetValueOrDefault().Dispose(); } // } // // Where again we do a constrained virtual call to Dispose, rather than boxing // the value to IDisposable. // // Note that this optimization is *not* what the native compiler does; in this case // the native compiler behavior is to test for HasValue, then *box* and convert // the boxed value to IDisposable. There's no need to do that. // // Third: if we have "using(x)" and x is dynamic then obviously we need not generate // "{ dynamic temp1 = x; IDisposable temp2 = (IDisposable) temp1; ... }". Rather, we elide // the completely unnecessary first temporary. Debug.Assert((awaitKeywordOpt == default) == (awaitOpt is null)); BoundExpression disposedExpression; bool isNullableValueType = local.Type.IsNullableType(); if (isNullableValueType) { MethodSymbol getValueOrDefault = UnsafeGetNullableMethod(syntax, local.Type, SpecialMember.System_Nullable_T_GetValueOrDefault); // local.GetValueOrDefault() disposedExpression = BoundCall.Synthesized(syntax, local, getValueOrDefault); } else { // local disposedExpression = local; } BoundExpression disposeCall = GenerateDisposeCall(syntax, disposedExpression, patternDisposeInfo, awaitOpt, awaitKeywordOpt); // local.Dispose(); or await variant BoundStatement disposeStatement = new BoundExpressionStatement(syntax, disposeCall); BoundExpression? ifCondition; if (isNullableValueType) { // local.HasValue ifCondition = MakeNullableHasValue(syntax, local); } else if (local.Type.IsValueType) { ifCondition = null; } else { // local != null ifCondition = MakeNullCheck(syntax, local, BinaryOperatorKind.NotEqual); } BoundStatement finallyStatement; if (ifCondition == null) { // local.Dispose(); or await variant finallyStatement = disposeStatement; } else { // if (local != null) local.Dispose(); // or // if (local.HasValue) local.GetValueOrDefault().Dispose(); // or // await variants finallyStatement = RewriteIfStatement( syntax: syntax, rewrittenCondition: ifCondition, rewrittenConsequence: disposeStatement, rewrittenAlternativeOpt: null, hasErrors: false); } // try { ... } finally { if (local != null) local.Dispose(); } // or // nullable or await variants BoundStatement tryFinally = new BoundTryStatement( syntax: syntax, tryBlock: tryBlock, catchBlocks: ImmutableArray<BoundCatchBlock>.Empty, finallyBlockOpt: BoundBlock.SynthesizedNoLocals(syntax, finallyStatement)); return tryFinally; } private BoundExpression GenerateDisposeCall( SyntaxNode syntax, BoundExpression disposedExpression, MethodArgumentInfo? disposeInfo, BoundAwaitableInfo? awaitOpt, SyntaxToken awaitKeyword) { Debug.Assert(awaitOpt is null || awaitKeyword != default); // If we don't have an explicit dispose method, try and get the special member for IDisposable/IAsyncDisposable MethodSymbol? disposeMethod = disposeInfo?.Method; if (disposeMethod is null) { if (awaitOpt is null) { // IDisposable.Dispose() Binder.TryGetSpecialTypeMember(_compilation, SpecialMember.System_IDisposable__Dispose, syntax, _diagnostics, out disposeMethod); } else { // IAsyncDisposable.DisposeAsync() TryGetWellKnownTypeMember<MethodSymbol>(syntax: null, WellKnownMember.System_IAsyncDisposable__DisposeAsync, out disposeMethod, location: awaitKeyword.GetLocation()); } } BoundExpression disposeCall; if (disposeMethod is null) { disposeCall = new BoundBadExpression(syntax, LookupResultKind.NotInvocable, ImmutableArray<Symbol?>.Empty, ImmutableArray.Create(disposedExpression), ErrorTypeSymbol.UnknownResultType); } else { if (disposeInfo is null) { // Generate the info for IDisposable.Dispose(). We know it has no arguments. disposeInfo = MethodArgumentInfo.CreateParameterlessMethod(disposeMethod); } disposeCall = MakeCallWithNoExplicitArgument(disposeInfo, syntax, disposedExpression); if (awaitOpt is object) { // await local.DisposeAsync() _sawAwaitInExceptionHandler = true; TypeSymbol awaitExpressionType = awaitOpt.GetResult?.ReturnType ?? _compilation.DynamicType; disposeCall = RewriteAwaitExpression(syntax, disposeCall, awaitOpt, awaitExpressionType, false); } } return disposeCall; } /// <summary> /// Synthesize a call `expression.Method()`, but with some extra smarts to handle extension methods, and to fill-in optional and params parameters. This call expects that the /// receiver parameter has already been visited. /// </summary> private BoundExpression MakeCallWithNoExplicitArgument(MethodArgumentInfo methodArgumentInfo, SyntaxNode syntax, BoundExpression? expression, bool assertParametersAreOptional = true) { MethodSymbol method = methodArgumentInfo.Method; #if DEBUG if (method.IsExtensionMethod) { Debug.Assert(expression == null); Debug.Assert(method.Parameters.AsSpan()[1..].All(assertParametersAreOptional, (p, assertOptional) => (p.IsOptional || p.IsParams || !assertOptional) && p.RefKind == RefKind.None)); Debug.Assert(method.ParameterRefKinds.IsDefaultOrEmpty || method.ParameterRefKinds[0] is RefKind.In or RefKind.None); } else { Debug.Assert(!assertParametersAreOptional || method.Parameters.All(p => p.IsOptional || p.IsParams)); Debug.Assert(method.ParameterRefKinds.IsDefaultOrEmpty); } Debug.Assert(methodArgumentInfo.Arguments.All(arg => arg is not BoundConversion { ConversionKind: ConversionKind.InterpolatedStringHandler })); #endif return MakeArgumentsAndCall( syntax, expression, method, methodArgumentInfo.Arguments, argumentRefKindsOpt: default, expanded: methodArgumentInfo.Expanded, invokedAsExtensionMethod: method.IsExtensionMethod, methodArgumentInfo.ArgsToParamsOpt, resultKind: LookupResultKind.Viable, type: method.ReturnType, temps: 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; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Microsoft.CodeAnalysis.CSharp { internal sealed partial class LocalRewriter { /// <summary> /// Rewrite a using statement into a try finally statement. Four forms are possible: /// 1) using (expr) stmt /// 2) await using (expr) stmt /// 3) using (C c = expr) stmt /// 4) await using (C c = expr) stmt /// /// The first two are handled by RewriteExpressionUsingStatement and the latter two are handled by /// RewriteDeclarationUsingStatement (called in a loop, once for each local declared). /// /// For the async variants, `IAsyncDisposable` is used instead of `IDisposable` and we produce /// `... await expr.DisposeAsync() ...` instead of `... expr.Dispose() ...`. /// </summary> /// <remarks> /// It would be more in line with our usual pattern to rewrite using to try-finally /// in the ControlFlowRewriter, but if we don't do it here the BoundMultipleLocalDeclarations /// will be rewritten into a form that makes them harder to separate. /// </remarks> public override BoundNode VisitUsingStatement(BoundUsingStatement node) { BoundStatement? rewrittenBody = VisitStatement(node.Body); Debug.Assert(rewrittenBody is { }); BoundBlock tryBlock = rewrittenBody.Kind == BoundKind.Block ? (BoundBlock)rewrittenBody : BoundBlock.SynthesizedNoLocals(node.Syntax, rewrittenBody); if (node.ExpressionOpt != null) { return MakeExpressionUsingStatement(node, tryBlock); } else { Debug.Assert(node.DeclarationsOpt is { }); SyntaxToken awaitKeyword = node.Syntax.Kind() == SyntaxKind.UsingStatement ? ((UsingStatementSyntax)node.Syntax).AwaitKeyword : default; return MakeDeclarationUsingStatement(node.Syntax, tryBlock, node.Locals, node.DeclarationsOpt.LocalDeclarations, node.IDisposableConversion, node.PatternDisposeInfoOpt, node.AwaitOpt, awaitKeyword); } } private BoundStatement MakeDeclarationUsingStatement(SyntaxNode syntax, BoundBlock body, ImmutableArray<LocalSymbol> locals, ImmutableArray<BoundLocalDeclaration> declarations, Conversion iDisposableConversion, MethodArgumentInfo? patternDisposeInfo, BoundAwaitableInfo? awaitOpt, SyntaxToken awaitKeyword) { Debug.Assert(declarations != null); BoundBlock result = body; for (int i = declarations.Length - 1; i >= 0; i--) //NB: inner-to-outer = right-to-left { result = RewriteDeclarationUsingStatement(syntax, declarations[i], result, iDisposableConversion, awaitKeyword, awaitOpt, patternDisposeInfo); } // Declare all locals in a single, top-level block so that the scope is correct in the debugger // (Dev10 has them all come into scope at once, not per-declaration.) return new BoundBlock( syntax, locals, ImmutableArray.Create<BoundStatement>(result)); } /// <summary> /// Lower "[await] using var x = (expression)" to a try-finally block. /// </summary> private BoundStatement MakeLocalUsingDeclarationStatement(BoundUsingLocalDeclarations usingDeclarations, ImmutableArray<BoundStatement> statements) { LocalDeclarationStatementSyntax syntax = (LocalDeclarationStatementSyntax)usingDeclarations.Syntax; BoundBlock body = new BoundBlock(syntax, ImmutableArray<LocalSymbol>.Empty, statements); var usingStatement = MakeDeclarationUsingStatement(syntax, body, ImmutableArray<LocalSymbol>.Empty, usingDeclarations.LocalDeclarations, usingDeclarations.IDisposableConversion, usingDeclarations.PatternDisposeInfoOpt, awaitOpt: usingDeclarations.AwaitOpt, awaitKeyword: syntax.AwaitKeyword); return usingStatement; } /// <summary> /// Lower "using [await] (expression) statement" to a try-finally block. /// </summary> private BoundBlock MakeExpressionUsingStatement(BoundUsingStatement node, BoundBlock tryBlock) { Debug.Assert(node.ExpressionOpt != null); Debug.Assert(node.DeclarationsOpt == null); // See comments in BuildUsingTryFinally for the details of the lowering to try-finally. // // SPEC: A using statement of the form "using (expression) statement; " has the // SPEC: same three possible expansions [ as "using (ResourceType r = expression) statement; ] // SPEC: but in this case ResourceType is implicitly the compile-time type of the expression, // SPEC: and the resource variable is inaccessible to and invisible to the embedded statement. // // DELIBERATE SPEC VIOLATION: // // The spec quote above implies that the expression must have a type; in fact we allow // the expression to be null. // // If expr is the constant null then we can elide the whole thing and simply generate the statement. BoundExpression rewrittenExpression = VisitExpression(node.ExpressionOpt); if (rewrittenExpression.ConstantValue == ConstantValue.Null) { Debug.Assert(node.Locals.IsEmpty); // TODO: This might not be a valid assumption in presence of semicolon operator. return tryBlock; } // Otherwise, we lower "using(expression) statement;" as follows: // // * If the expression is of type dynamic then we lower as though the user had written // // using(IDisposable temp = (IDisposable)expression) statement; // // Note that we have to do the conversion early, not in the finally block, because // if the conversion fails at runtime with an exception then the exception must happen // before the statement runs. // // * Otherwise we lower as though the user had written // // using(ResourceType temp = expression) statement; // Debug.Assert(rewrittenExpression.Type is { }); TypeSymbol expressionType = rewrittenExpression.Type; SyntaxNode expressionSyntax = rewrittenExpression.Syntax; UsingStatementSyntax usingSyntax = (UsingStatementSyntax)node.Syntax; BoundAssignmentOperator tempAssignment; BoundLocal boundTemp; if (expressionType is null || expressionType.IsDynamic()) { // IDisposable temp = (IDisposable) expr; // or // IAsyncDisposable temp = (IAsyncDisposable) expr; TypeSymbol iDisposableType = node.AwaitOpt is null ? _compilation.GetSpecialType(SpecialType.System_IDisposable) : _compilation.GetWellKnownType(WellKnownType.System_IAsyncDisposable); _diagnostics.ReportUseSite(iDisposableType, usingSyntax); BoundExpression tempInit = MakeConversionNode( expressionSyntax, rewrittenExpression, Conversion.GetTrivialConversion(node.IDisposableConversion.Kind), iDisposableType, @checked: false, constantValueOpt: rewrittenExpression.ConstantValue); boundTemp = _factory.StoreToTemp(tempInit, out tempAssignment, kind: SynthesizedLocalKind.Using); } else { // ResourceType temp = expr; boundTemp = _factory.StoreToTemp(rewrittenExpression, out tempAssignment, syntaxOpt: usingSyntax, kind: SynthesizedLocalKind.Using); } BoundStatement expressionStatement = new BoundExpressionStatement(expressionSyntax, tempAssignment); if (this.Instrument) { expressionStatement = _instrumenter.InstrumentUsingTargetCapture(node, expressionStatement); } BoundStatement tryFinally = RewriteUsingStatementTryFinally(usingSyntax, tryBlock, boundTemp, usingSyntax.AwaitKeyword, node.AwaitOpt, node.PatternDisposeInfoOpt); // { ResourceType temp = expr; try { ... } finally { ... } } return new BoundBlock( syntax: usingSyntax, locals: node.Locals.Add(boundTemp.LocalSymbol), statements: ImmutableArray.Create<BoundStatement>(expressionStatement, tryFinally)); } /// <summary> /// Lower "using [await] (ResourceType resource = expression) statement" to a try-finally block. /// </summary> /// <remarks> /// Assumes that the local symbol will be declared (i.e. in the LocalsOpt array) of an enclosing block. /// Assumes that using statements with multiple locals have already been split up into multiple using statements. /// </remarks> private BoundBlock RewriteDeclarationUsingStatement( SyntaxNode usingSyntax, BoundLocalDeclaration localDeclaration, BoundBlock tryBlock, Conversion iDisposableConversion, SyntaxToken awaitKeywordOpt, BoundAwaitableInfo? awaitOpt, MethodArgumentInfo? patternDisposeInfo) { Debug.Assert(localDeclaration.InitializerOpt is { }); SyntaxNode declarationSyntax = localDeclaration.Syntax; LocalSymbol localSymbol = localDeclaration.LocalSymbol; TypeSymbol localType = localSymbol.Type; Debug.Assert((object)localType != null); //otherwise, there wouldn't be a conversion to IDisposable BoundLocal boundLocal = new BoundLocal(declarationSyntax, localSymbol, localDeclaration.InitializerOpt.ConstantValue, localType); BoundStatement? rewrittenDeclaration = VisitStatement(localDeclaration); Debug.Assert(rewrittenDeclaration is { }); // If we know that the expression is null, then we know that the null check in the finally block // will fail, and the Dispose call will never happen. That is, the finally block will have no effect. // Consequently, we can simply skip the whole try-finally construct and just create a block containing // the new declaration. if (boundLocal.ConstantValue == ConstantValue.Null) { //localSymbol will be declared by an enclosing block return BoundBlock.SynthesizedNoLocals(usingSyntax, rewrittenDeclaration, tryBlock); } if (localType.IsDynamic()) { TypeSymbol iDisposableType = awaitOpt is null ? _compilation.GetSpecialType(SpecialType.System_IDisposable) : _compilation.GetWellKnownType(WellKnownType.System_IAsyncDisposable); _diagnostics.ReportUseSite(iDisposableType, usingSyntax); BoundExpression tempInit = MakeConversionNode( declarationSyntax, boundLocal, iDisposableConversion, iDisposableType, @checked: false); BoundAssignmentOperator tempAssignment; BoundLocal boundTemp = _factory.StoreToTemp(tempInit, out tempAssignment, kind: SynthesizedLocalKind.Using); BoundStatement tryFinally = RewriteUsingStatementTryFinally(usingSyntax, tryBlock, boundTemp, awaitKeywordOpt, awaitOpt, patternDisposeInfo); return new BoundBlock( syntax: usingSyntax, locals: ImmutableArray.Create<LocalSymbol>(boundTemp.LocalSymbol), //localSymbol will be declared by an enclosing block statements: ImmutableArray.Create<BoundStatement>( rewrittenDeclaration, new BoundExpressionStatement(declarationSyntax, tempAssignment), tryFinally)); } else { BoundStatement tryFinally = RewriteUsingStatementTryFinally(usingSyntax, tryBlock, boundLocal, awaitKeywordOpt, awaitOpt, patternDisposeInfo); // localSymbol will be declared by an enclosing block return BoundBlock.SynthesizedNoLocals(usingSyntax, rewrittenDeclaration, tryFinally); } } private BoundStatement RewriteUsingStatementTryFinally( SyntaxNode syntax, BoundBlock tryBlock, BoundLocal local, SyntaxToken awaitKeywordOpt, BoundAwaitableInfo? awaitOpt, MethodArgumentInfo? patternDisposeInfo) { // SPEC: When ResourceType is a non-nullable value type, the expansion is: // SPEC: // SPEC: { // SPEC: ResourceType resource = expr; // SPEC: try { statement; } // SPEC: finally { ((IDisposable)resource).Dispose(); } // SPEC: } // SPEC: // SPEC: Otherwise, when Resource type is a nullable value type or // SPEC: a reference type other than dynamic, the expansion is: // SPEC: // SPEC: { // SPEC: ResourceType resource = expr; // SPEC: try { statement; } // SPEC: finally { if (resource != null) ((IDisposable)resource).Dispose(); } // SPEC: } // SPEC: // SPEC: Otherwise, when ResourceType is dynamic, the expansion is: // SPEC: { // SPEC: dynamic resource = expr; // SPEC: IDisposable d = (IDisposable)resource; // SPEC: try { statement; } // SPEC: finally { if (d != null) d.Dispose(); } // SPEC: } // SPEC: // SPEC: An implementation is permitted to implement a given using statement // SPEC: differently -- for example, for performance reasons -- as long as the // SPEC: behavior is consistent with the above expansion. // // In the case of using-await statement, we'll use "IAsyncDisposable" instead of "IDisposable", "await DisposeAsync()" instead of "Dispose()" // // And we do in fact generate the code slightly differently than precisely how it is // described above. // // First: if the type is a non-nullable value type then we do not do the // *boxing conversion* from the resource to IDisposable. Rather, we do // a *constrained virtual call* that elides the boxing if possible. // // Now, you might wonder if that is legal; isn't skipping the boxing producing // an observable difference? Because if the value type is mutable and the Dispose // mutates it, then skipping the boxing means that we are now mutating the original, // not the boxed copy. But this is never observable. Either (1) we have "using(R r = x){}" // and r is out of scope after the finally, so it is not possible to observe the mutation, // or (2) we have "using(x) {}". But that has the semantics of "using(R temp = x){}", // so again, we are not mutating x to begin with; we're always mutating a copy. Therefore // it doesn't matter if we skip making *a copy of the copy*. // // This is what the dev10 compiler does, and we do so as well. // // Second: if the type is a nullable value type then we can similarly elide the boxing. // We can generate // // { // ResourceType resource = expr; // try { statement; } // finally { if (resource.HasValue) resource.GetValueOrDefault().Dispose(); } // } // // Where again we do a constrained virtual call to Dispose, rather than boxing // the value to IDisposable. // // Note that this optimization is *not* what the native compiler does; in this case // the native compiler behavior is to test for HasValue, then *box* and convert // the boxed value to IDisposable. There's no need to do that. // // Third: if we have "using(x)" and x is dynamic then obviously we need not generate // "{ dynamic temp1 = x; IDisposable temp2 = (IDisposable) temp1; ... }". Rather, we elide // the completely unnecessary first temporary. Debug.Assert((awaitKeywordOpt == default) == (awaitOpt is null)); BoundExpression disposedExpression; bool isNullableValueType = local.Type.IsNullableType(); if (isNullableValueType) { MethodSymbol getValueOrDefault = UnsafeGetNullableMethod(syntax, local.Type, SpecialMember.System_Nullable_T_GetValueOrDefault); // local.GetValueOrDefault() disposedExpression = BoundCall.Synthesized(syntax, local, getValueOrDefault); } else { // local disposedExpression = local; } BoundExpression disposeCall = GenerateDisposeCall(syntax, disposedExpression, patternDisposeInfo, awaitOpt, awaitKeywordOpt); // local.Dispose(); or await variant BoundStatement disposeStatement = new BoundExpressionStatement(syntax, disposeCall); BoundExpression? ifCondition; if (isNullableValueType) { // local.HasValue ifCondition = MakeNullableHasValue(syntax, local); } else if (local.Type.IsValueType) { ifCondition = null; } else { // local != null ifCondition = MakeNullCheck(syntax, local, BinaryOperatorKind.NotEqual); } BoundStatement finallyStatement; if (ifCondition == null) { // local.Dispose(); or await variant finallyStatement = disposeStatement; } else { // if (local != null) local.Dispose(); // or // if (local.HasValue) local.GetValueOrDefault().Dispose(); // or // await variants finallyStatement = RewriteIfStatement( syntax: syntax, rewrittenCondition: ifCondition, rewrittenConsequence: disposeStatement, rewrittenAlternativeOpt: null, hasErrors: false); } // try { ... } finally { if (local != null) local.Dispose(); } // or // nullable or await variants BoundStatement tryFinally = new BoundTryStatement( syntax: syntax, tryBlock: tryBlock, catchBlocks: ImmutableArray<BoundCatchBlock>.Empty, finallyBlockOpt: BoundBlock.SynthesizedNoLocals(syntax, finallyStatement)); return tryFinally; } private BoundExpression GenerateDisposeCall( SyntaxNode syntax, BoundExpression disposedExpression, MethodArgumentInfo? disposeInfo, BoundAwaitableInfo? awaitOpt, SyntaxToken awaitKeyword) { Debug.Assert(awaitOpt is null || awaitKeyword != default); // If we don't have an explicit dispose method, try and get the special member for IDisposable/IAsyncDisposable MethodSymbol? disposeMethod = disposeInfo?.Method; if (disposeMethod is null) { if (awaitOpt is null) { // IDisposable.Dispose() Binder.TryGetSpecialTypeMember(_compilation, SpecialMember.System_IDisposable__Dispose, syntax, _diagnostics, out disposeMethod); } else { // IAsyncDisposable.DisposeAsync() TryGetWellKnownTypeMember<MethodSymbol>(syntax: null, WellKnownMember.System_IAsyncDisposable__DisposeAsync, out disposeMethod, location: awaitKeyword.GetLocation()); } } BoundExpression disposeCall; if (disposeMethod is null) { disposeCall = new BoundBadExpression(syntax, LookupResultKind.NotInvocable, ImmutableArray<Symbol?>.Empty, ImmutableArray.Create(disposedExpression), ErrorTypeSymbol.UnknownResultType); } else { if (disposeInfo is null) { // Generate the info for IDisposable.Dispose(). We know it has no arguments. disposeInfo = MethodArgumentInfo.CreateParameterlessMethod(disposeMethod); } disposeCall = MakeCallWithNoExplicitArgument(disposeInfo, syntax, disposedExpression); if (awaitOpt is object) { // await local.DisposeAsync() _sawAwaitInExceptionHandler = true; TypeSymbol awaitExpressionType = awaitOpt.GetResult?.ReturnType ?? _compilation.DynamicType; disposeCall = RewriteAwaitExpression(syntax, disposeCall, awaitOpt, awaitExpressionType, false); } } return disposeCall; } /// <summary> /// Synthesize a call `expression.Method()`, but with some extra smarts to handle extension methods, and to fill-in optional and params parameters. This call expects that the /// receiver parameter has already been visited. /// </summary> private BoundExpression MakeCallWithNoExplicitArgument(MethodArgumentInfo methodArgumentInfo, SyntaxNode syntax, BoundExpression? expression, bool assertParametersAreOptional = true) { MethodSymbol method = methodArgumentInfo.Method; #if DEBUG if (method.IsExtensionMethod) { Debug.Assert(expression == null); Debug.Assert(method.Parameters.AsSpan()[1..].All(assertParametersAreOptional, (p, assertOptional) => (p.IsOptional || p.IsParams || !assertOptional) && p.RefKind == RefKind.None)); Debug.Assert(method.ParameterRefKinds.IsDefaultOrEmpty || method.ParameterRefKinds[0] is RefKind.In or RefKind.None); } else { Debug.Assert(!assertParametersAreOptional || method.Parameters.All(p => p.IsOptional || p.IsParams)); Debug.Assert(method.ParameterRefKinds.IsDefaultOrEmpty); } Debug.Assert(methodArgumentInfo.Arguments.All(arg => arg is not BoundConversion { ConversionKind: ConversionKind.InterpolatedStringHandler })); #endif return MakeArgumentsAndCall( syntax, expression, method, methodArgumentInfo.Arguments, argumentRefKindsOpt: default, expanded: methodArgumentInfo.Expanded, invokedAsExtensionMethod: method.IsExtensionMethod, methodArgumentInfo.ArgsToParamsOpt, resultKind: LookupResultKind.Viable, type: method.ReturnType, temps: null); } } }
-1
dotnet/roslyn
56,433
Only allow Contract.ThrowIfNull() to be called on nullable types
We had some places we were calling it on bools.
jasonmalinowski
"2021-09-16T01:20:43Z"
"2021-09-16T18:44:11Z"
736fc1b5e6e2847689c0154b3e5f23ea99dd56af
6d0f4e3f972ceb561b04574e7f957a4ff458e272
Only allow Contract.ThrowIfNull() to be called on nullable types. We had some places we were calling it on bools.
./src/Compilers/CSharp/Test/Emit/Emit/EditAndContinue/EditAndContinueTest.GenerationVerifier.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.Linq; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using Roslyn.Test.Utilities; using static Microsoft.CodeAnalysis.CSharp.EditAndContinue.UnitTests.EditAndContinueTestBase; namespace Microsoft.CodeAnalysis.CSharp.EditAndContinue.UnitTests { internal partial class EditAndContinueTest { internal sealed class GenerationVerifier { private readonly int _ordinal; private readonly MetadataReader _metadataReader; private readonly IEnumerable<MetadataReader> _readers; public GenerationVerifier(int ordinal, MetadataReader metadataReader, IEnumerable<MetadataReader> readers) { _ordinal = ordinal; _metadataReader = metadataReader; _readers = readers; } private string GetAssertMessage(string message) { var ordinalDescription = _ordinal == 0 ? "initial baseline" : $"generation {_ordinal}"; return $"Failure in {ordinalDescription}: {message}"; } internal void VerifyTypeDefNames(params string[] expected) { var actual = _readers.GetStrings(_metadataReader.GetTypeDefNames()); AssertEx.Equal(expected, actual, message: GetAssertMessage("TypeDefs don't match")); } internal void VerifyMethodDefNames(params string[] expected) { var actual = _readers.GetStrings(_metadataReader.GetMethodDefNames()); AssertEx.Equal(expected, actual, message: GetAssertMessage("MethodDefs don't match")); } internal void VerifyMemberRefNames(params string[] expected) { var actual = _readers.GetStrings(_metadataReader.GetMemberRefNames()); AssertEx.Equal(expected, actual, message: GetAssertMessage("MemberRefs don't match")); } internal void VerifyFieldDefNames(params string[] expected) { var actual = _readers.GetStrings(_metadataReader.GetFieldDefNames()); AssertEx.Equal(expected, actual, message: GetAssertMessage("FieldDefs don't match")); } internal void VerifyPropertyDefNames(params string[] expected) { var actual = _readers.GetStrings(_metadataReader.GetPropertyDefNames()); AssertEx.Equal(expected, actual, message: GetAssertMessage("PropertyDefs don't match")); } internal void VerifyTableSize(TableIndex table, int expected) { AssertEx.AreEqual(expected, _metadataReader.GetTableRowCount(table), message: GetAssertMessage($"{table} table size doesnt't match")); } internal void VerifyEncLog(IEnumerable<EditAndContinueLogEntry> expected) { AssertEx.Equal(expected, _metadataReader.GetEditAndContinueLogEntries(), itemInspector: EncLogRowToString, message: GetAssertMessage("EncLog doesn't match")); } internal void VerifyEncMap(IEnumerable<EntityHandle> expected) { AssertEx.Equal(expected, _metadataReader.GetEditAndContinueMapEntries(), itemInspector: EncMapRowToString, message: GetAssertMessage("EncMap doesn't match")); } internal void VerifyEncLogDefinitions(IEnumerable<EditAndContinueLogEntry> expected) { AssertEx.Equal(expected, _metadataReader.GetEditAndContinueLogEntries().Where(e => IsDefinition(e.Handle.Kind)), itemInspector: EncLogRowToString, message: GetAssertMessage("EncLog definitions don't match")); } internal void VerifyEncMapDefinitions(IEnumerable<EntityHandle> expected) { AssertEx.Equal(expected, _metadataReader.GetEditAndContinueMapEntries().Where(e => IsDefinition(e.Kind)), itemInspector: EncMapRowToString, message: GetAssertMessage("EncMap definitions don't match")); } internal void VerifyCustomAttributes(IEnumerable<CustomAttributeRow> expected) { AssertEx.Equal(expected, _metadataReader.GetCustomAttributeRows(), itemInspector: AttributeRowToString); } } } }
// Licensed to the .NET Foundation under one or more 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.Linq; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using Roslyn.Test.Utilities; using static Microsoft.CodeAnalysis.CSharp.EditAndContinue.UnitTests.EditAndContinueTestBase; namespace Microsoft.CodeAnalysis.CSharp.EditAndContinue.UnitTests { internal partial class EditAndContinueTest { internal sealed class GenerationVerifier { private readonly int _ordinal; private readonly MetadataReader _metadataReader; private readonly IEnumerable<MetadataReader> _readers; public GenerationVerifier(int ordinal, MetadataReader metadataReader, IEnumerable<MetadataReader> readers) { _ordinal = ordinal; _metadataReader = metadataReader; _readers = readers; } private string GetAssertMessage(string message) { var ordinalDescription = _ordinal == 0 ? "initial baseline" : $"generation {_ordinal}"; return $"Failure in {ordinalDescription}: {message}"; } internal void VerifyTypeDefNames(params string[] expected) { var actual = _readers.GetStrings(_metadataReader.GetTypeDefNames()); AssertEx.Equal(expected, actual, message: GetAssertMessage("TypeDefs don't match")); } internal void VerifyMethodDefNames(params string[] expected) { var actual = _readers.GetStrings(_metadataReader.GetMethodDefNames()); AssertEx.Equal(expected, actual, message: GetAssertMessage("MethodDefs don't match")); } internal void VerifyMemberRefNames(params string[] expected) { var actual = _readers.GetStrings(_metadataReader.GetMemberRefNames()); AssertEx.Equal(expected, actual, message: GetAssertMessage("MemberRefs don't match")); } internal void VerifyFieldDefNames(params string[] expected) { var actual = _readers.GetStrings(_metadataReader.GetFieldDefNames()); AssertEx.Equal(expected, actual, message: GetAssertMessage("FieldDefs don't match")); } internal void VerifyPropertyDefNames(params string[] expected) { var actual = _readers.GetStrings(_metadataReader.GetPropertyDefNames()); AssertEx.Equal(expected, actual, message: GetAssertMessage("PropertyDefs don't match")); } internal void VerifyTableSize(TableIndex table, int expected) { AssertEx.AreEqual(expected, _metadataReader.GetTableRowCount(table), message: GetAssertMessage($"{table} table size doesnt't match")); } internal void VerifyEncLog(IEnumerable<EditAndContinueLogEntry> expected) { AssertEx.Equal(expected, _metadataReader.GetEditAndContinueLogEntries(), itemInspector: EncLogRowToString, message: GetAssertMessage("EncLog doesn't match")); } internal void VerifyEncMap(IEnumerable<EntityHandle> expected) { AssertEx.Equal(expected, _metadataReader.GetEditAndContinueMapEntries(), itemInspector: EncMapRowToString, message: GetAssertMessage("EncMap doesn't match")); } internal void VerifyEncLogDefinitions(IEnumerable<EditAndContinueLogEntry> expected) { AssertEx.Equal(expected, _metadataReader.GetEditAndContinueLogEntries().Where(e => IsDefinition(e.Handle.Kind)), itemInspector: EncLogRowToString, message: GetAssertMessage("EncLog definitions don't match")); } internal void VerifyEncMapDefinitions(IEnumerable<EntityHandle> expected) { AssertEx.Equal(expected, _metadataReader.GetEditAndContinueMapEntries().Where(e => IsDefinition(e.Kind)), itemInspector: EncMapRowToString, message: GetAssertMessage("EncMap definitions don't match")); } internal void VerifyCustomAttributes(IEnumerable<CustomAttributeRow> expected) { AssertEx.Equal(expected, _metadataReader.GetCustomAttributeRows(), itemInspector: AttributeRowToString); } } } }
-1
dotnet/roslyn
56,433
Only allow Contract.ThrowIfNull() to be called on nullable types
We had some places we were calling it on bools.
jasonmalinowski
"2021-09-16T01:20:43Z"
"2021-09-16T18:44:11Z"
736fc1b5e6e2847689c0154b3e5f23ea99dd56af
6d0f4e3f972ceb561b04574e7f957a4ff458e272
Only allow Contract.ThrowIfNull() to be called on nullable types. We had some places we were calling it on bools.
./src/Compilers/Core/Portable/OutputKind.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.Text; using System; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// Specifies output assembly kinds generated by compiler. /// </summary> public enum OutputKind { /// <summary> /// An .exe with an entry point and a console. /// </summary> ConsoleApplication = 0, /// <summary> /// An .exe with an entry point but no console. /// </summary> WindowsApplication = 1, /// <summary> /// A .dll file. /// </summary> DynamicallyLinkedLibrary = 2, /// <summary> /// A .netmodule file. /// </summary> NetModule = 3, /// <summary> /// A .winmdobj file. /// </summary> WindowsRuntimeMetadata = 4, /// <summary> /// An .exe that can run in an app container. /// </summary> /// <remarks> /// Equivalent to a WindowsApplication, but with an extra bit set in the Portable Executable file /// so that the application can only be run in an app container. /// Also known as a "Windows Store app". /// </remarks> WindowsRuntimeApplication = 5, } internal static partial class EnumBounds { internal static bool IsValid(this OutputKind value) { return value >= OutputKind.ConsoleApplication && value <= OutputKind.WindowsRuntimeApplication; } internal static string GetDefaultExtension(this OutputKind kind) { switch (kind) { case OutputKind.ConsoleApplication: case OutputKind.WindowsApplication: case OutputKind.WindowsRuntimeApplication: return ".exe"; case OutputKind.DynamicallyLinkedLibrary: return ".dll"; case OutputKind.NetModule: return ".netmodule"; case OutputKind.WindowsRuntimeMetadata: return ".winmdobj"; default: return ".dll"; } } internal static bool IsApplication(this OutputKind kind) { switch (kind) { case OutputKind.ConsoleApplication: case OutputKind.WindowsApplication: case OutputKind.WindowsRuntimeApplication: return true; case OutputKind.DynamicallyLinkedLibrary: case OutputKind.NetModule: case OutputKind.WindowsRuntimeMetadata: return false; default: return false; } } internal static bool IsNetModule(this OutputKind kind) { return kind == OutputKind.NetModule; } internal static bool IsWindowsRuntime(this OutputKind kind) { return kind == OutputKind.WindowsRuntimeMetadata; } } }
// Licensed to the .NET Foundation under one or more 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.Text; using System; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// Specifies output assembly kinds generated by compiler. /// </summary> public enum OutputKind { /// <summary> /// An .exe with an entry point and a console. /// </summary> ConsoleApplication = 0, /// <summary> /// An .exe with an entry point but no console. /// </summary> WindowsApplication = 1, /// <summary> /// A .dll file. /// </summary> DynamicallyLinkedLibrary = 2, /// <summary> /// A .netmodule file. /// </summary> NetModule = 3, /// <summary> /// A .winmdobj file. /// </summary> WindowsRuntimeMetadata = 4, /// <summary> /// An .exe that can run in an app container. /// </summary> /// <remarks> /// Equivalent to a WindowsApplication, but with an extra bit set in the Portable Executable file /// so that the application can only be run in an app container. /// Also known as a "Windows Store app". /// </remarks> WindowsRuntimeApplication = 5, } internal static partial class EnumBounds { internal static bool IsValid(this OutputKind value) { return value >= OutputKind.ConsoleApplication && value <= OutputKind.WindowsRuntimeApplication; } internal static string GetDefaultExtension(this OutputKind kind) { switch (kind) { case OutputKind.ConsoleApplication: case OutputKind.WindowsApplication: case OutputKind.WindowsRuntimeApplication: return ".exe"; case OutputKind.DynamicallyLinkedLibrary: return ".dll"; case OutputKind.NetModule: return ".netmodule"; case OutputKind.WindowsRuntimeMetadata: return ".winmdobj"; default: return ".dll"; } } internal static bool IsApplication(this OutputKind kind) { switch (kind) { case OutputKind.ConsoleApplication: case OutputKind.WindowsApplication: case OutputKind.WindowsRuntimeApplication: return true; case OutputKind.DynamicallyLinkedLibrary: case OutputKind.NetModule: case OutputKind.WindowsRuntimeMetadata: return false; default: return false; } } internal static bool IsNetModule(this OutputKind kind) { return kind == OutputKind.NetModule; } internal static bool IsWindowsRuntime(this OutputKind kind) { return kind == OutputKind.WindowsRuntimeMetadata; } } }
-1
dotnet/roslyn
56,433
Only allow Contract.ThrowIfNull() to be called on nullable types
We had some places we were calling it on bools.
jasonmalinowski
"2021-09-16T01:20:43Z"
"2021-09-16T18:44:11Z"
736fc1b5e6e2847689c0154b3e5f23ea99dd56af
6d0f4e3f972ceb561b04574e7f957a4ff458e272
Only allow Contract.ThrowIfNull() to be called on nullable types. We had some places we were calling it on bools.
./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/Extensions/ITypeSymbolExtensions.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.CodeAnalysis; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Shared.Lightup; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Simplification; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Extensions { internal static partial class ITypeSymbolExtensions { public static ExpressionSyntax GenerateExpressionSyntax( this ITypeSymbol typeSymbol) { return typeSymbol.Accept(ExpressionSyntaxGeneratorVisitor.Instance)!.WithAdditionalAnnotations(Simplifier.Annotation); } public static NameSyntax GenerateNameSyntax( this INamespaceOrTypeSymbol symbol, bool allowVar = true) { return (NameSyntax)GenerateTypeSyntax(symbol, nameSyntax: true, allowVar: allowVar); } public static TypeSyntax GenerateTypeSyntax( this INamespaceOrTypeSymbol symbol, bool allowVar = true) { return GenerateTypeSyntax(symbol, nameSyntax: false, allowVar: allowVar); } private static TypeSyntax GenerateTypeSyntax( INamespaceOrTypeSymbol symbol, bool nameSyntax, bool allowVar = true) { var type = symbol as ITypeSymbol; if (type != null && type.ContainsAnonymousType()) { // something with an anonymous type can only be represented with 'var', regardless // of what the user's preferences might be. return SyntaxFactory.IdentifierName("var"); } var syntax = symbol.Accept(TypeSyntaxGeneratorVisitor.Create(nameSyntax))! .WithAdditionalAnnotations(Simplifier.Annotation); if (!allowVar) { syntax = syntax.WithAdditionalAnnotations(DoNotAllowVarAnnotation.Annotation); } if (type != null && type.IsReferenceType) { var additionalAnnotation = type.NullableAnnotation switch { NullableAnnotation.None => NullableSyntaxAnnotationEx.Oblivious, NullableAnnotation.Annotated => NullableSyntaxAnnotationEx.AnnotatedOrNotAnnotated, NullableAnnotation.NotAnnotated => NullableSyntaxAnnotationEx.AnnotatedOrNotAnnotated, _ => throw ExceptionUtilities.UnexpectedValue(type.NullableAnnotation), }; if (additionalAnnotation is object) { syntax = syntax.WithAdditionalAnnotations(additionalAnnotation); } } return syntax; } public static TypeSyntax GenerateRefTypeSyntax( this INamespaceOrTypeSymbol symbol) { var underlyingType = GenerateTypeSyntax(symbol) .WithPrependedLeadingTrivia(SyntaxFactory.ElasticMarker) .WithAdditionalAnnotations(Simplifier.Annotation); var refKeyword = SyntaxFactory.Token(SyntaxKind.RefKeyword); return SyntaxFactory.RefType(refKeyword, underlyingType); } public static TypeSyntax GenerateRefReadOnlyTypeSyntax( this INamespaceOrTypeSymbol symbol) { var underlyingType = GenerateTypeSyntax(symbol) .WithPrependedLeadingTrivia(SyntaxFactory.ElasticMarker) .WithAdditionalAnnotations(Simplifier.Annotation); var refKeyword = SyntaxFactory.Token(SyntaxKind.RefKeyword); var readOnlyKeyword = SyntaxFactory.Token(SyntaxKind.ReadOnlyKeyword); return SyntaxFactory.RefType(refKeyword, readOnlyKeyword, underlyingType); } public static bool ContainingTypesOrSelfHasUnsafeKeyword(this ITypeSymbol containingType) { do { foreach (var reference in containingType.DeclaringSyntaxReferences) { if (reference.GetSyntax().ChildTokens().Any(t => t.IsKind(SyntaxKind.UnsafeKeyword))) { return true; } } containingType = containingType.ContainingType; } while (containingType != null); return false; } public static async Task<ISymbol?> FindApplicableAliasAsync(this ITypeSymbol type, int position, SemanticModel semanticModel, CancellationToken cancellationToken) { try { if (semanticModel.IsSpeculativeSemanticModel) { position = semanticModel.OriginalPositionForSpeculation; semanticModel = semanticModel.ParentModel; } var root = await semanticModel.SyntaxTree.GetRootAsync(cancellationToken).ConfigureAwait(false); var applicableUsings = GetApplicableUsings(position, (CompilationUnitSyntax)root); foreach (var applicableUsing in applicableUsings) { var alias = semanticModel.GetOriginalSemanticModel().GetDeclaredSymbol(applicableUsing, cancellationToken); if (alias != null && Equals(alias.Target, type)) { return alias; } } return null; } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } private static IEnumerable<UsingDirectiveSyntax> GetApplicableUsings(int position, SyntaxNode root) { var namespaceUsings = root.FindToken(position).Parent!.GetAncestors<BaseNamespaceDeclarationSyntax>().SelectMany(n => n.Usings); var allUsings = root is CompilationUnitSyntax compilationUnit ? compilationUnit.Usings.Concat(namespaceUsings) : namespaceUsings; return allUsings.Where(u => u.Alias != null); } public static bool IsIntrinsicType(this ITypeSymbol typeSymbol) { switch (typeSymbol.SpecialType) { case SpecialType.System_Boolean: case SpecialType.System_Char: case SpecialType.System_SByte: case SpecialType.System_Int16: case SpecialType.System_Int32: case SpecialType.System_Int64: case SpecialType.System_Byte: case SpecialType.System_UInt16: case SpecialType.System_UInt32: case SpecialType.System_UInt64: case SpecialType.System_Single: case SpecialType.System_Double: // NOTE: VB treats System.DateTime as an intrinsic, while C# does not, see "predeftype.h" //case SpecialType.System_DateTime: case SpecialType.System_Decimal: return true; default: return false; } } public static bool TryGetRecordPrimaryConstructor(this INamedTypeSymbol typeSymbol, [NotNullWhen(true)] out IMethodSymbol? primaryConstructor) { if (typeSymbol.IsRecord) { Debug.Assert(typeSymbol.GetParameters().IsDefaultOrEmpty, "If GetParameters extension handles record, we can remove the handling here."); // A bit hacky to determine the parameters of primary constructor associated with a given record. // Simplifying is tracked by: https://github.com/dotnet/roslyn/issues/53092. // Note: When the issue is handled, we can remove the logic here and handle things in GetParameters extension. BUT // if GetParameters extension method gets updated to handle records, we need to test EVERY usage // of the extension method and make sure the change is applicable to all these usages. primaryConstructor = typeSymbol.InstanceConstructors.FirstOrDefault( c => c.DeclaringSyntaxReferences.FirstOrDefault()?.GetSyntax() is RecordDeclarationSyntax); return primaryConstructor is not null; } primaryConstructor = 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. using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Shared.Lightup; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Simplification; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Extensions { internal static partial class ITypeSymbolExtensions { public static ExpressionSyntax GenerateExpressionSyntax( this ITypeSymbol typeSymbol) { return typeSymbol.Accept(ExpressionSyntaxGeneratorVisitor.Instance)!.WithAdditionalAnnotations(Simplifier.Annotation); } public static NameSyntax GenerateNameSyntax( this INamespaceOrTypeSymbol symbol, bool allowVar = true) { return (NameSyntax)GenerateTypeSyntax(symbol, nameSyntax: true, allowVar: allowVar); } public static TypeSyntax GenerateTypeSyntax( this INamespaceOrTypeSymbol symbol, bool allowVar = true) { return GenerateTypeSyntax(symbol, nameSyntax: false, allowVar: allowVar); } private static TypeSyntax GenerateTypeSyntax( INamespaceOrTypeSymbol symbol, bool nameSyntax, bool allowVar = true) { var type = symbol as ITypeSymbol; if (type != null && type.ContainsAnonymousType()) { // something with an anonymous type can only be represented with 'var', regardless // of what the user's preferences might be. return SyntaxFactory.IdentifierName("var"); } var syntax = symbol.Accept(TypeSyntaxGeneratorVisitor.Create(nameSyntax))! .WithAdditionalAnnotations(Simplifier.Annotation); if (!allowVar) { syntax = syntax.WithAdditionalAnnotations(DoNotAllowVarAnnotation.Annotation); } if (type != null && type.IsReferenceType) { var additionalAnnotation = type.NullableAnnotation switch { NullableAnnotation.None => NullableSyntaxAnnotationEx.Oblivious, NullableAnnotation.Annotated => NullableSyntaxAnnotationEx.AnnotatedOrNotAnnotated, NullableAnnotation.NotAnnotated => NullableSyntaxAnnotationEx.AnnotatedOrNotAnnotated, _ => throw ExceptionUtilities.UnexpectedValue(type.NullableAnnotation), }; if (additionalAnnotation is object) { syntax = syntax.WithAdditionalAnnotations(additionalAnnotation); } } return syntax; } public static TypeSyntax GenerateRefTypeSyntax( this INamespaceOrTypeSymbol symbol) { var underlyingType = GenerateTypeSyntax(symbol) .WithPrependedLeadingTrivia(SyntaxFactory.ElasticMarker) .WithAdditionalAnnotations(Simplifier.Annotation); var refKeyword = SyntaxFactory.Token(SyntaxKind.RefKeyword); return SyntaxFactory.RefType(refKeyword, underlyingType); } public static TypeSyntax GenerateRefReadOnlyTypeSyntax( this INamespaceOrTypeSymbol symbol) { var underlyingType = GenerateTypeSyntax(symbol) .WithPrependedLeadingTrivia(SyntaxFactory.ElasticMarker) .WithAdditionalAnnotations(Simplifier.Annotation); var refKeyword = SyntaxFactory.Token(SyntaxKind.RefKeyword); var readOnlyKeyword = SyntaxFactory.Token(SyntaxKind.ReadOnlyKeyword); return SyntaxFactory.RefType(refKeyword, readOnlyKeyword, underlyingType); } public static bool ContainingTypesOrSelfHasUnsafeKeyword(this ITypeSymbol containingType) { do { foreach (var reference in containingType.DeclaringSyntaxReferences) { if (reference.GetSyntax().ChildTokens().Any(t => t.IsKind(SyntaxKind.UnsafeKeyword))) { return true; } } containingType = containingType.ContainingType; } while (containingType != null); return false; } public static async Task<ISymbol?> FindApplicableAliasAsync(this ITypeSymbol type, int position, SemanticModel semanticModel, CancellationToken cancellationToken) { try { if (semanticModel.IsSpeculativeSemanticModel) { position = semanticModel.OriginalPositionForSpeculation; semanticModel = semanticModel.ParentModel; } var root = await semanticModel.SyntaxTree.GetRootAsync(cancellationToken).ConfigureAwait(false); var applicableUsings = GetApplicableUsings(position, (CompilationUnitSyntax)root); foreach (var applicableUsing in applicableUsings) { var alias = semanticModel.GetOriginalSemanticModel().GetDeclaredSymbol(applicableUsing, cancellationToken); if (alias != null && Equals(alias.Target, type)) { return alias; } } return null; } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } private static IEnumerable<UsingDirectiveSyntax> GetApplicableUsings(int position, SyntaxNode root) { var namespaceUsings = root.FindToken(position).Parent!.GetAncestors<BaseNamespaceDeclarationSyntax>().SelectMany(n => n.Usings); var allUsings = root is CompilationUnitSyntax compilationUnit ? compilationUnit.Usings.Concat(namespaceUsings) : namespaceUsings; return allUsings.Where(u => u.Alias != null); } public static bool IsIntrinsicType(this ITypeSymbol typeSymbol) { switch (typeSymbol.SpecialType) { case SpecialType.System_Boolean: case SpecialType.System_Char: case SpecialType.System_SByte: case SpecialType.System_Int16: case SpecialType.System_Int32: case SpecialType.System_Int64: case SpecialType.System_Byte: case SpecialType.System_UInt16: case SpecialType.System_UInt32: case SpecialType.System_UInt64: case SpecialType.System_Single: case SpecialType.System_Double: // NOTE: VB treats System.DateTime as an intrinsic, while C# does not, see "predeftype.h" //case SpecialType.System_DateTime: case SpecialType.System_Decimal: return true; default: return false; } } public static bool TryGetRecordPrimaryConstructor(this INamedTypeSymbol typeSymbol, [NotNullWhen(true)] out IMethodSymbol? primaryConstructor) { if (typeSymbol.IsRecord) { Debug.Assert(typeSymbol.GetParameters().IsDefaultOrEmpty, "If GetParameters extension handles record, we can remove the handling here."); // A bit hacky to determine the parameters of primary constructor associated with a given record. // Simplifying is tracked by: https://github.com/dotnet/roslyn/issues/53092. // Note: When the issue is handled, we can remove the logic here and handle things in GetParameters extension. BUT // if GetParameters extension method gets updated to handle records, we need to test EVERY usage // of the extension method and make sure the change is applicable to all these usages. primaryConstructor = typeSymbol.InstanceConstructors.FirstOrDefault( c => c.DeclaringSyntaxReferences.FirstOrDefault()?.GetSyntax() is RecordDeclarationSyntax); return primaryConstructor is not null; } primaryConstructor = null; return false; } } }
-1
dotnet/roslyn
56,433
Only allow Contract.ThrowIfNull() to be called on nullable types
We had some places we were calling it on bools.
jasonmalinowski
"2021-09-16T01:20:43Z"
"2021-09-16T18:44:11Z"
736fc1b5e6e2847689c0154b3e5f23ea99dd56af
6d0f4e3f972ceb561b04574e7f957a4ff458e272
Only allow Contract.ThrowIfNull() to be called on nullable types. We had some places we were calling it on bools.
./src/Workspaces/CoreTest/FindAllDeclarationsTests.TestSolutionsAndProject.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 Microsoft.CodeAnalysis.Remote; using Microsoft.CodeAnalysis.Remote.Testing; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.UnitTests { public partial class FindAllDeclarationsTests { private readonly ITestOutputHelper _logger; public FindAllDeclarationsTests(ITestOutputHelper logger) { _logger = logger; } private static void Verify(string searchTerm, bool respectCase, SolutionKind workspaceKind, IEnumerable<ISymbol> declarations, params string[] expectedResults) { var actualResultCount = declarations.Count(); var expectedResultCount = expectedResults.Length; Assert.True(expectedResultCount == actualResultCount, string.Format("Search term '{0}' expected '{1}' results, found '{2}. Ignore case was set to '{3}', Workspace {4} was used", searchTerm, expectedResultCount, actualResultCount, respectCase, Enum.GetName(typeof(SolutionKind), workspaceKind))); if (actualResultCount > 0) { VerifyResults(declarations, expectedResults); } } private static void Verify(SolutionKind workspaceKind, IEnumerable<ISymbol> declarations, params string[] expectedResults) { var actualResultCount = declarations.Count(); var expectedResultCount = expectedResults.Length; Assert.True(expectedResultCount == actualResultCount, string.Format("Expected '{0}' results, found '{1}. Workspace {2} was used", expectedResultCount, actualResultCount, Enum.GetName(typeof(SolutionKind), workspaceKind))); if (actualResultCount > 0) { VerifyResults(declarations, expectedResults); } } private static void VerifyResults(IEnumerable<ISymbol> declarations, string[] expectedResults) { declarations = declarations.OrderBy(d => d.ToString()); expectedResults = expectedResults.OrderBy(r => r).ToArray(); for (var i = 0; i < expectedResults.Length; i++) { var actualResult = declarations.ElementAt(i).ToString(); var expectedResult = expectedResults[i]; Assert.True( string.Equals(actualResult, expectedResult, StringComparison.Ordinal), string.Format("Expected result to be {0} was {1}", expectedResult, actualResult)); } } private Workspace CreateWorkspace(TestHost testHost = TestHost.InProcess) { var composition = FeaturesTestCompositions.Features.WithTestHostParts(testHost); var workspace = new AdhocWorkspace(composition.GetHostServices()); if (testHost == TestHost.OutOfProcess) { var remoteHostProvider = (InProcRemoteHostClientProvider)workspace.Services.GetRequiredService<IRemoteHostClientProvider>(); remoteHostProvider.TraceListener = new XunitTraceListener(_logger); } return workspace; } private Workspace CreateWorkspaceWithSingleProjectSolution(TestHost testHost, string[] sourceTexts, out Solution solution) { var pid = ProjectId.CreateNewId(); var workspace = CreateWorkspace(testHost); solution = workspace.CurrentSolution .AddProject(pid, "TestCases", "TestCases", LanguageNames.CSharp) .AddMetadataReference(pid, MscorlibRef); for (var i = 0; i < sourceTexts.Length; i++) { var did = DocumentId.CreateNewId(pid); solution = solution.AddDocument(did, "goo" + i + ".cs", SourceText.From(sourceTexts[i])); } return workspace; } private Workspace CreateWorkspaceWithMultipleProjectSolution(TestHost testHost, string[] sourceTexts, out Solution solution) { var workspace = CreateWorkspace(testHost); solution = workspace.CurrentSolution; for (var i = 0; i < sourceTexts.Length; i++) { var pid = ProjectId.CreateNewId(); var did = DocumentId.CreateNewId(pid); solution = solution .AddProject(pid, "TestCases" + i, "TestCases" + i, LanguageNames.CSharp) .AddMetadataReference(pid, MscorlibRef); solution = solution.AddDocument(did, "goo" + i + ".cs", SourceText.From(sourceTexts[i])); } return workspace; } private Workspace CreateWorkspaceWithSolution(SolutionKind solutionKind, out Solution solution, TestHost testHost = TestHost.InProcess) => solutionKind switch { SolutionKind.SingleClass => CreateWorkspaceWithSingleProjectSolution(testHost, new[] { SingleClass }, out solution), SolutionKind.SingleClassWithSingleMethod => CreateWorkspaceWithSingleProjectSolution(testHost, new[] { SingleClassWithSingleMethod }, out solution), SolutionKind.SingleClassWithSingleProperty => CreateWorkspaceWithSingleProjectSolution(testHost, new[] { SingleClassWithSingleProperty }, out solution), SolutionKind.SingleClassWithSingleField => CreateWorkspaceWithSingleProjectSolution(testHost, new[] { SingleClassWithSingleField }, out solution), SolutionKind.TwoProjectsEachWithASingleClassWithSingleMethod => CreateWorkspaceWithMultipleProjectSolution(testHost, new[] { SingleClassWithSingleMethod, SingleClassWithSingleMethod }, out solution), SolutionKind.TwoProjectsEachWithASingleClassWithSingleProperty => CreateWorkspaceWithMultipleProjectSolution(testHost, new[] { SingleClassWithSingleProperty, SingleClassWithSingleProperty }, out solution), SolutionKind.TwoProjectsEachWithASingleClassWithSingleField => CreateWorkspaceWithMultipleProjectSolution(testHost, new[] { SingleClassWithSingleField, SingleClassWithSingleField }, out solution), SolutionKind.NestedClass => CreateWorkspaceWithSingleProjectSolution(testHost, new[] { NestedClass }, out solution), SolutionKind.TwoNamespacesWithIdenticalClasses => CreateWorkspaceWithSingleProjectSolution(testHost, new[] { Namespace1, Namespace2 }, out solution), _ => throw ExceptionUtilities.UnexpectedValue(solutionKind), }; private Workspace CreateWorkspaceWithProject(SolutionKind solutionKind, out Project project, TestHost testHost = TestHost.InProcess) { var workspace = CreateWorkspaceWithSolution(solutionKind, out var solution, testHost); project = solution.Projects.First(); return workspace; } public enum SolutionKind { SingleClass, SingleClassWithSingleMethod, SingleClassWithSingleProperty, SingleClassWithSingleField, TwoProjectsEachWithASingleClassWithSingleMethod, TwoProjectsEachWithASingleClassWithSingleProperty, TwoProjectsEachWithASingleClassWithSingleField, NestedClass, TwoNamespacesWithIdenticalClasses } private const string SingleClass = @" using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TestCases { class TestCase { } } "; private const string SingleClassWithSingleMethod = @" using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TestCases { class TestCase { static void Test(string[] args) { } } } "; private const string SingleClassWithSingleProperty = @" using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TestCases { class TestCase { public int TestProperty{ get; set; } } } "; private const string SingleClassWithSingleField = @" using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TestCases { class TestCase { private int TestField = 0; } } "; private const string NestedClass = @" using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TestCases { class TestCase { class InnerTestCase { } } } "; private const string Namespace1 = @" using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TestCase1 { class TestCase { } } "; private const string Namespace2 = @" using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TestCase2 { class TestCase { } } "; } }
// Licensed to the .NET Foundation under one or more 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 Microsoft.CodeAnalysis.Remote; using Microsoft.CodeAnalysis.Remote.Testing; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.UnitTests { public partial class FindAllDeclarationsTests { private readonly ITestOutputHelper _logger; public FindAllDeclarationsTests(ITestOutputHelper logger) { _logger = logger; } private static void Verify(string searchTerm, bool respectCase, SolutionKind workspaceKind, IEnumerable<ISymbol> declarations, params string[] expectedResults) { var actualResultCount = declarations.Count(); var expectedResultCount = expectedResults.Length; Assert.True(expectedResultCount == actualResultCount, string.Format("Search term '{0}' expected '{1}' results, found '{2}. Ignore case was set to '{3}', Workspace {4} was used", searchTerm, expectedResultCount, actualResultCount, respectCase, Enum.GetName(typeof(SolutionKind), workspaceKind))); if (actualResultCount > 0) { VerifyResults(declarations, expectedResults); } } private static void Verify(SolutionKind workspaceKind, IEnumerable<ISymbol> declarations, params string[] expectedResults) { var actualResultCount = declarations.Count(); var expectedResultCount = expectedResults.Length; Assert.True(expectedResultCount == actualResultCount, string.Format("Expected '{0}' results, found '{1}. Workspace {2} was used", expectedResultCount, actualResultCount, Enum.GetName(typeof(SolutionKind), workspaceKind))); if (actualResultCount > 0) { VerifyResults(declarations, expectedResults); } } private static void VerifyResults(IEnumerable<ISymbol> declarations, string[] expectedResults) { declarations = declarations.OrderBy(d => d.ToString()); expectedResults = expectedResults.OrderBy(r => r).ToArray(); for (var i = 0; i < expectedResults.Length; i++) { var actualResult = declarations.ElementAt(i).ToString(); var expectedResult = expectedResults[i]; Assert.True( string.Equals(actualResult, expectedResult, StringComparison.Ordinal), string.Format("Expected result to be {0} was {1}", expectedResult, actualResult)); } } private Workspace CreateWorkspace(TestHost testHost = TestHost.InProcess) { var composition = FeaturesTestCompositions.Features.WithTestHostParts(testHost); var workspace = new AdhocWorkspace(composition.GetHostServices()); if (testHost == TestHost.OutOfProcess) { var remoteHostProvider = (InProcRemoteHostClientProvider)workspace.Services.GetRequiredService<IRemoteHostClientProvider>(); remoteHostProvider.TraceListener = new XunitTraceListener(_logger); } return workspace; } private Workspace CreateWorkspaceWithSingleProjectSolution(TestHost testHost, string[] sourceTexts, out Solution solution) { var pid = ProjectId.CreateNewId(); var workspace = CreateWorkspace(testHost); solution = workspace.CurrentSolution .AddProject(pid, "TestCases", "TestCases", LanguageNames.CSharp) .AddMetadataReference(pid, MscorlibRef); for (var i = 0; i < sourceTexts.Length; i++) { var did = DocumentId.CreateNewId(pid); solution = solution.AddDocument(did, "goo" + i + ".cs", SourceText.From(sourceTexts[i])); } return workspace; } private Workspace CreateWorkspaceWithMultipleProjectSolution(TestHost testHost, string[] sourceTexts, out Solution solution) { var workspace = CreateWorkspace(testHost); solution = workspace.CurrentSolution; for (var i = 0; i < sourceTexts.Length; i++) { var pid = ProjectId.CreateNewId(); var did = DocumentId.CreateNewId(pid); solution = solution .AddProject(pid, "TestCases" + i, "TestCases" + i, LanguageNames.CSharp) .AddMetadataReference(pid, MscorlibRef); solution = solution.AddDocument(did, "goo" + i + ".cs", SourceText.From(sourceTexts[i])); } return workspace; } private Workspace CreateWorkspaceWithSolution(SolutionKind solutionKind, out Solution solution, TestHost testHost = TestHost.InProcess) => solutionKind switch { SolutionKind.SingleClass => CreateWorkspaceWithSingleProjectSolution(testHost, new[] { SingleClass }, out solution), SolutionKind.SingleClassWithSingleMethod => CreateWorkspaceWithSingleProjectSolution(testHost, new[] { SingleClassWithSingleMethod }, out solution), SolutionKind.SingleClassWithSingleProperty => CreateWorkspaceWithSingleProjectSolution(testHost, new[] { SingleClassWithSingleProperty }, out solution), SolutionKind.SingleClassWithSingleField => CreateWorkspaceWithSingleProjectSolution(testHost, new[] { SingleClassWithSingleField }, out solution), SolutionKind.TwoProjectsEachWithASingleClassWithSingleMethod => CreateWorkspaceWithMultipleProjectSolution(testHost, new[] { SingleClassWithSingleMethod, SingleClassWithSingleMethod }, out solution), SolutionKind.TwoProjectsEachWithASingleClassWithSingleProperty => CreateWorkspaceWithMultipleProjectSolution(testHost, new[] { SingleClassWithSingleProperty, SingleClassWithSingleProperty }, out solution), SolutionKind.TwoProjectsEachWithASingleClassWithSingleField => CreateWorkspaceWithMultipleProjectSolution(testHost, new[] { SingleClassWithSingleField, SingleClassWithSingleField }, out solution), SolutionKind.NestedClass => CreateWorkspaceWithSingleProjectSolution(testHost, new[] { NestedClass }, out solution), SolutionKind.TwoNamespacesWithIdenticalClasses => CreateWorkspaceWithSingleProjectSolution(testHost, new[] { Namespace1, Namespace2 }, out solution), _ => throw ExceptionUtilities.UnexpectedValue(solutionKind), }; private Workspace CreateWorkspaceWithProject(SolutionKind solutionKind, out Project project, TestHost testHost = TestHost.InProcess) { var workspace = CreateWorkspaceWithSolution(solutionKind, out var solution, testHost); project = solution.Projects.First(); return workspace; } public enum SolutionKind { SingleClass, SingleClassWithSingleMethod, SingleClassWithSingleProperty, SingleClassWithSingleField, TwoProjectsEachWithASingleClassWithSingleMethod, TwoProjectsEachWithASingleClassWithSingleProperty, TwoProjectsEachWithASingleClassWithSingleField, NestedClass, TwoNamespacesWithIdenticalClasses } private const string SingleClass = @" using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TestCases { class TestCase { } } "; private const string SingleClassWithSingleMethod = @" using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TestCases { class TestCase { static void Test(string[] args) { } } } "; private const string SingleClassWithSingleProperty = @" using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TestCases { class TestCase { public int TestProperty{ get; set; } } } "; private const string SingleClassWithSingleField = @" using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TestCases { class TestCase { private int TestField = 0; } } "; private const string NestedClass = @" using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TestCases { class TestCase { class InnerTestCase { } } } "; private const string Namespace1 = @" using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TestCase1 { class TestCase { } } "; private const string Namespace2 = @" using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TestCase2 { class TestCase { } } "; } }
-1
dotnet/roslyn
56,433
Only allow Contract.ThrowIfNull() to be called on nullable types
We had some places we were calling it on bools.
jasonmalinowski
"2021-09-16T01:20:43Z"
"2021-09-16T18:44:11Z"
736fc1b5e6e2847689c0154b3e5f23ea99dd56af
6d0f4e3f972ceb561b04574e7f957a4ff458e272
Only allow Contract.ThrowIfNull() to be called on nullable types. We had some places we were calling it on bools.
./src/Workspaces/Remote/ServiceHub/Host/RemoteGlobalOperationNotificationService.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.Notification; namespace Microsoft.CodeAnalysis.Remote.Services { [ExportWorkspaceService(typeof(IGlobalOperationNotificationService), WorkspaceKind.RemoteWorkspace), Shared] internal sealed class RemoteGlobalOperationNotificationService : IGlobalOperationNotificationService { public event EventHandler? Started; public event EventHandler<GlobalOperationEventArgs>? Stopped; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public RemoteGlobalOperationNotificationService() { } public GlobalOperationRegistration Start(string operation) { // Currently not supported for anything on the remote side to start a global // operation. throw new NotSupportedException(); } public void OnStarted() => Started?.Invoke(this, EventArgs.Empty); public void OnStopped(ImmutableArray<string> operations) => Stopped?.Invoke(this, new GlobalOperationEventArgs(operations)); } }
// Licensed to the .NET Foundation under one or more 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.Notification; namespace Microsoft.CodeAnalysis.Remote.Services { [ExportWorkspaceService(typeof(IGlobalOperationNotificationService), WorkspaceKind.RemoteWorkspace), Shared] internal sealed class RemoteGlobalOperationNotificationService : IGlobalOperationNotificationService { public event EventHandler? Started; public event EventHandler<GlobalOperationEventArgs>? Stopped; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public RemoteGlobalOperationNotificationService() { } public GlobalOperationRegistration Start(string operation) { // Currently not supported for anything on the remote side to start a global // operation. throw new NotSupportedException(); } public void OnStarted() => Started?.Invoke(this, EventArgs.Empty); public void OnStopped(ImmutableArray<string> operations) => Stopped?.Invoke(this, new GlobalOperationEventArgs(operations)); } }
-1
dotnet/roslyn
56,433
Only allow Contract.ThrowIfNull() to be called on nullable types
We had some places we were calling it on bools.
jasonmalinowski
"2021-09-16T01:20:43Z"
"2021-09-16T18:44:11Z"
736fc1b5e6e2847689c0154b3e5f23ea99dd56af
6d0f4e3f972ceb561b04574e7f957a4ff458e272
Only allow Contract.ThrowIfNull() to be called on nullable types. We had some places we were calling it on bools.
./src/EditorFeatures/CSharpTest/Classification/TotalClassifierTests_Dynamic.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.Tasks; using Microsoft.CodeAnalysis.Remote.Testing; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using static Microsoft.CodeAnalysis.Editor.UnitTests.Classification.FormattedClassifications; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Classification { public partial class TotalClassifierTests { [Theory] [CombinatorialData] public async Task DynamicAsParamTypeAndDefault(TestHost testHost) { await TestInClassAsync(@"void M(dynamic d = default(dynamic", testHost, Keyword("void"), Method("M"), Punctuation.OpenParen, Keyword("dynamic"), Parameter("d"), Operators.Equals, Keyword("default"), Punctuation.OpenParen, Keyword("dynamic")); } [Theory] [CombinatorialData] public async Task DynamicExplicitConversion(TestHost testHost) { await TestInMethodAsync( @"dynamic d = (dynamic)a;", testHost, Keyword("dynamic"), Local("d"), Operators.Equals, Punctuation.OpenParen, Keyword("dynamic"), Punctuation.CloseParen, Identifier("a"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task DynamicMethodCall(TestHost testHost) { await TestInMethodAsync(@"dynamic.Equals(1, 1);", testHost, Identifier("dynamic"), Operators.Dot, Identifier("Equals"), Punctuation.OpenParen, Number("1"), Punctuation.Comma, Number("1"), Punctuation.CloseParen, Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task DynamicNullable(TestHost testHost) { await TestInMethodAsync(@"dynamic? a", testHost, Keyword("dynamic"), Operators.QuestionMark, Local("a")); } [Theory] [CombinatorialData] public async Task DynamicAsUsingAliasForClass(TestHost testHost) { await TestAsync( @"using dynamic = System.EventArgs;", testHost, Keyword("using"), Class("dynamic"), Operators.Equals, Namespace("System"), Operators.Dot, Class("EventArgs"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task DynamicAsUsingAliasForDelegate(TestHost testHost) { await TestAsync( @"using dynamic = System.Action;", testHost, Keyword("using"), Delegate("dynamic"), Operators.Equals, Namespace("System"), Operators.Dot, Delegate("Action"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task DynamicAsUsingAliasForStruct(TestHost testHost) { await TestAsync( @"using dynamic = System.DateTime;", testHost, Keyword("using"), Struct("dynamic"), Operators.Equals, Namespace("System"), Operators.Dot, Struct("DateTime"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task DynamicAsUsingAliasForEnum(TestHost testHost) { await TestAsync( @"using dynamic = System.DayOfWeek;", testHost, Keyword("using"), Enum("dynamic"), Operators.Equals, Namespace("System"), Operators.Dot, Enum("DayOfWeek"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task DynamicAsUsingAliasForInterface(TestHost testHost) { await TestAsync( @"using dynamic = System.IDisposable;", testHost, Keyword("using"), Interface("dynamic"), Operators.Equals, Namespace("System"), Operators.Dot, Interface("IDisposable"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task DynamicAsExternAlias(TestHost testHost) { await TestAsync( @"extern alias dynamic; class C { dynamic::Goo a; }", testHost, Keyword("extern"), Keyword("alias"), Namespace("dynamic"), Punctuation.Semicolon, Keyword("class"), Class("C"), Punctuation.OpenCurly, Namespace("dynamic"), Operators.ColonColon, Identifier("Goo"), Field("a"), Punctuation.Semicolon, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task DynamicAsDelegateType(TestHost testHost) { await TestAsync(@"delegate void dynamic()", testHost, Keyword("delegate"), Keyword("void"), Delegate("dynamic"), Punctuation.OpenParen, Punctuation.CloseParen); } [Theory] [CombinatorialData] public async Task DynamicAsDelegateReturnTypeAndParam(TestHost testHost) { await TestAsync(@"delegate dynamic MyDelegate (dynamic d)", testHost, Keyword("delegate"), Keyword("dynamic"), Delegate("MyDelegate"), Punctuation.OpenParen, Keyword("dynamic"), Parameter("d"), Punctuation.CloseParen); } [Theory] [CombinatorialData] public async Task DynamicAsDelegateLocalVariable(TestHost testHost) { await TestInMethodAsync( @"Func<string> f = delegate { int dynamic = 10; return dynamic.ToString(); };", testHost, Identifier("Func"), Punctuation.OpenAngle, Keyword("string"), Punctuation.CloseAngle, Local("f"), Operators.Equals, Keyword("delegate"), Punctuation.OpenCurly, Keyword("int"), Local("dynamic"), Operators.Equals, Number("10"), Punctuation.Semicolon, ControlKeyword("return"), Local("dynamic"), Operators.Dot, Method("ToString"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task DynamicAsGenericTypeName(TestHost testHost) { await TestAsync( @"partial class dynamic<T> { } class C { dynamic<int> d; }", testHost, Keyword("partial"), Keyword("class"), Class("dynamic"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("class"), Class("C"), Punctuation.OpenCurly, Class("dynamic"), Punctuation.OpenAngle, Keyword("int"), Punctuation.CloseAngle, Field("d"), Punctuation.Semicolon, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task DynamicAsGenericField(TestHost testHost) { await TestAsync( @"class A<T> { T dynamic; }", testHost, Keyword("class"), Class("A"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenCurly, TypeParameter("T"), Field("dynamic"), Punctuation.Semicolon, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task DynamicAsIndexerTypeAndParameter(TestHost testHost) { await TestInClassAsync(@"dynamic this[dynamic i]", testHost, Keyword("dynamic"), Keyword("this"), Punctuation.OpenBracket, Keyword("dynamic"), Parameter("i"), Punctuation.CloseBracket); } [Theory] [CombinatorialData] public async Task DynamicAsOperatorTypeAndParameter(TestHost testHost) { await TestInClassAsync(@"static dynamic operator +(dynamic d1)", testHost, Keyword("static"), Keyword("dynamic"), Keyword("operator"), Operators.Plus, Punctuation.OpenParen, Keyword("dynamic"), Parameter("d1"), Punctuation.CloseParen); } [Theory] [CombinatorialData] public async Task DynamicAsOperatorName(TestHost testHost) { await TestInClassAsync(@"static explicit operator dynamic(dynamic s)", testHost, Keyword("static"), Keyword("explicit"), Keyword("operator"), Keyword("dynamic"), Punctuation.OpenParen, Keyword("dynamic"), Parameter("s"), Punctuation.CloseParen); } [Theory] [CombinatorialData] public async Task DynamicAsPropertyTypeAndName(TestHost testHost) { await TestInClassAsync(@"dynamic dynamic { get; set; }", testHost, Keyword("dynamic"), Property("dynamic"), Punctuation.OpenCurly, Keyword("get"), Punctuation.Semicolon, Keyword("set"), Punctuation.Semicolon, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task DynamicAsEventName(TestHost testHost) { await TestInClassAsync(@"event Action dynamic", testHost, Keyword("event"), Identifier("Action"), Event("dynamic")); } [Theory] [CombinatorialData] public async Task DynamicAsLinqLocalVariable(TestHost testHost) { await TestInMethodAsync(@"var v = from dynamic in names", testHost, Keyword("var"), Local("v"), Operators.Equals, Keyword("from"), Identifier("dynamic"), Keyword("in"), Identifier("names")); } [Theory] [CombinatorialData] public async Task DynamicAsAnonymousTypePropertyName(TestHost testHost) { await TestInMethodAsync( @"var v = from dynamic in names select new { dynamic = dynamic };", testHost, Keyword("var"), Local("v"), Operators.Equals, Keyword("from"), Identifier("dynamic"), Keyword("in"), Identifier("names"), Keyword("select"), Keyword("new"), Punctuation.OpenCurly, Property("dynamic"), Operators.Equals, Identifier("dynamic"), Punctuation.CloseCurly, Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task DynamicAsArgumentToLambdaExpression(TestHost testHost) { await TestInMethodAsync( @"var p = names.Select(dynamic => dynamic.Length);", testHost, Keyword("var"), Local("p"), Operators.Equals, Identifier("names"), Operators.Dot, Identifier("Select"), Punctuation.OpenParen, Parameter("dynamic"), Operators.EqualsGreaterThan, Parameter("dynamic"), Operators.Dot, Identifier("Length"), Punctuation.CloseParen, Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task DynamicAsAnonymousMethodLocalVariable(TestHost testHost) { await TestInMethodAsync( @"D f = delegate { string dynamic = ""a""; return dynamic.Length; };", testHost, Identifier("D"), Local("f"), Operators.Equals, Keyword("delegate"), Punctuation.OpenCurly, Keyword("string"), Local("dynamic"), Operators.Equals, String(@"""a"""), Punctuation.Semicolon, ControlKeyword("return"), Local("dynamic"), Operators.Dot, Property("Length"), Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task DynamicAsMethodName(TestHost testHost) { await TestInClassAsync( @"dynamic dynamic() { }", testHost, Keyword("dynamic"), Method("dynamic"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task DynamicAsStaticMethodTypeAndParams(TestHost testHost) { await TestInClassAsync( @"static dynamic dynamic(params dynamic[] dynamic) { }", testHost, Keyword("static"), Keyword("dynamic"), Method("dynamic"), Static("dynamic"), Punctuation.OpenParen, Keyword("params"), Keyword("dynamic"), Punctuation.OpenBracket, Punctuation.CloseBracket, Parameter("dynamic"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task DynamicArraysInMethodSignature(TestHost testHost) { await TestInClassAsync( @"dynamic[] M(dynamic[] p, params dynamic[] pa) { }", testHost, Keyword("dynamic"), Punctuation.OpenBracket, Punctuation.CloseBracket, Method("M"), Punctuation.OpenParen, Keyword("dynamic"), Punctuation.OpenBracket, Punctuation.CloseBracket, Parameter("p"), Punctuation.Comma, Keyword("params"), Keyword("dynamic"), Punctuation.OpenBracket, Punctuation.CloseBracket, Parameter("pa"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task DynamicInPartialMethods(TestHost testHost) { await TestInClassAsync( @"partial void F(dynamic d); partial void F(dynamic d) { }", testHost, Keyword("partial"), Keyword("void"), Method("F"), Punctuation.OpenParen, Keyword("dynamic"), Parameter("d"), Punctuation.CloseParen, Punctuation.Semicolon, Keyword("partial"), Keyword("void"), Method("F"), Punctuation.OpenParen, Keyword("dynamic"), Parameter("d"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task DynamicRefAndOutParameters(TestHost testHost) { await TestInClassAsync( @"void F(ref dynamic r, out dynamic o) { }", testHost, Keyword("void"), Method("F"), Punctuation.OpenParen, Keyword("ref"), Keyword("dynamic"), Parameter("r"), Punctuation.Comma, Keyword("out"), Keyword("dynamic"), Parameter("o"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task DynamicInExtensionMethod(TestHost testHost) { await TestInClassAsync( @"dynamic F(this dynamic self, dynamic p) { }", testHost, Keyword("dynamic"), ExtensionMethod("F"), Punctuation.OpenParen, Keyword("this"), Keyword("dynamic"), Parameter("self"), Punctuation.Comma, Keyword("dynamic"), Parameter("p"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task DynamicAsBaseClass(TestHost testHost) { await TestAsync( @"class C : dynamic { }", testHost, Keyword("class"), Class("C"), Punctuation.Colon, Keyword("dynamic"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task DynamicAsGenericConstraint(TestHost testHost) { await TestAsync( @"class C<T> where T : dynamic { }", testHost, Keyword("class"), Class("C"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Keyword("where"), TypeParameter("T"), Punctuation.Colon, Keyword("dynamic"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task DynamicSizeOf(TestHost testHost) { await TestInClassAsync( @"unsafe int M() { return sizeof(dynamic); }", testHost, Keyword("unsafe"), Keyword("int"), Method("M"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, ControlKeyword("return"), Keyword("sizeof"), Punctuation.OpenParen, Keyword("dynamic"), Punctuation.CloseParen, Punctuation.Semicolon, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task DynamicTypeOf(TestHost testHost) { await TestInMethodAsync(@"typeof(dynamic)", testHost, Keyword("typeof"), Punctuation.OpenParen, Keyword("dynamic"), Punctuation.CloseParen); } [Theory] [WorkItem(44423, "https://github.com/dotnet/roslyn/issues/44423")] [CombinatorialData] public async Task DynamicAsArrayName(bool script, TestHost testHost) { var code = @"int[] dynamic = { 1 };"; var parseOptions = script ? Options.Script : null; await TestAsync( code, code, testHost, parseOptions, Keyword("int"), Punctuation.OpenBracket, Punctuation.CloseBracket, script ? Field("dynamic") : Local("dynamic"), Operators.Equals, Punctuation.OpenCurly, Number("1"), Punctuation.CloseCurly, Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task DynamicInForeach(TestHost testHost) { await TestInMethodAsync(@"foreach (dynamic dynamic in dynamic", testHost, ControlKeyword("foreach"), Punctuation.OpenParen, Keyword("dynamic"), Local("dynamic"), ControlKeyword("in"), Identifier("dynamic")); } [Theory] [CombinatorialData] public async Task DynamicInUsing(TestHost testHost) { await TestInMethodAsync(@"using(dynamic d", testHost, Keyword("using"), Punctuation.OpenParen, Keyword("dynamic"), Local("d")); } [Theory] [CombinatorialData] public async Task DynamicAsLocalVariableName(TestHost testHost) { await TestInMethodAsync( @"dynamic dynamic;", testHost, Keyword("dynamic"), Local("dynamic"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task DynamicAsNamespaceName(TestHost testHost) { await TestAsync( @"namespace dynamic { }", testHost, Keyword("namespace"), Namespace("dynamic"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task DynamicAsClassName(TestHost testHost) { await TestAsync( @"class dynamic { }", testHost, Keyword("class"), Class("dynamic"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task DynamicAsConstructorDeclarationName(TestHost testHost) { await TestAsync( @"class dynamic { dynamic() { } }", testHost, Keyword("class"), Class("dynamic"), Punctuation.OpenCurly, Class("dynamic"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task DynamicAsNamespaceAlias(TestHost testHost) { await TestInMethodAsync( @"dynamic.FileInfo file;", testHost, Identifier("dynamic"), Operators.Dot, Identifier("FileInfo"), Local("file"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task DynamicAsGotoLabel(TestHost testHost) { await TestInMethodAsync( @"dynamic: int i = 0; goto dynamic;", testHost, Label("dynamic"), Punctuation.Colon, Keyword("int"), Local("i"), Operators.Equals, Number("0"), Punctuation.Semicolon, ControlKeyword("goto"), Label("dynamic"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task DynamicAsEnumField(TestHost testHost) { await TestInMethodAsync( @"A a = A.dynamic;", testHost, Identifier("A"), Local("a"), Operators.Equals, Identifier("A"), Operators.Dot, Identifier("dynamic"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task DynamicAsEnumFieldDefinition(TestHost testHost) { await TestAsync( @"enum A { dynamic }", testHost, Keyword("enum"), Enum("A"), Punctuation.OpenCurly, EnumMember("dynamic"), Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task DynamicAsEnumType(TestHost testHost) { await TestAsync( @"enum dynamic { }", testHost, Keyword("enum"), Enum("dynamic"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task DynamicAsGenericTypeParameter(TestHost testHost) { await TestAsync( @"class C<dynamic, T> where dynamic : T { dynamic d; }", testHost, Keyword("class"), Class("C"), Punctuation.OpenAngle, TypeParameter("dynamic"), Punctuation.Comma, TypeParameter("T"), Punctuation.CloseAngle, Keyword("where"), TypeParameter("dynamic"), Punctuation.Colon, TypeParameter("T"), Punctuation.OpenCurly, TypeParameter("dynamic"), Field("d"), Punctuation.Semicolon, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task DynamicAsFieldType(TestHost testHost) { await TestInClassAsync(@"dynamic d", testHost, Keyword("dynamic"), Field("d")); } [Theory] [CombinatorialData] public async Task DynamicAsStaticFieldType(TestHost testHost) { await TestInClassAsync(@"static dynamic d", testHost, Keyword("static"), Keyword("dynamic"), Field("d"), Static("d")); } [Theory] [CombinatorialData] public async Task DynamicAsLocalVariableType(TestHost testHost) { await TestInMethodAsync(@"dynamic d", testHost, Keyword("dynamic"), Local("d")); } [Theory] [CombinatorialData] public async Task DynamicAsArrayLocalVariableType(TestHost testHost) { await TestInMethodAsync(@"dynamic[] d", testHost, Keyword("dynamic"), Punctuation.OpenBracket, Punctuation.CloseBracket, Local("d")); } [Theory] [CombinatorialData] public async Task DynamicAsLambdaParameterType(TestHost testHost) { await TestInMethodAsync( @"var q = a.Where((dynamic d) => d == dynamic);", testHost, Keyword("var"), Local("q"), Operators.Equals, Identifier("a"), Operators.Dot, Identifier("Where"), Punctuation.OpenParen, Punctuation.OpenParen, Keyword("dynamic"), Parameter("d"), Punctuation.CloseParen, Operators.EqualsGreaterThan, Parameter("d"), Operators.EqualsEquals, Identifier("dynamic"), Punctuation.CloseParen, Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task DynamicArray(TestHost testHost) { await TestInMethodAsync( @"dynamic d = new dynamic[5];", testHost, Keyword("dynamic"), Local("d"), Operators.Equals, Keyword("new"), Keyword("dynamic"), Punctuation.OpenBracket, Number("5"), Punctuation.CloseBracket, Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task DynamicConstructor(TestHost testHost) { await TestInMethodAsync( @"dynamic d = new dynamic();", testHost, Keyword("dynamic"), Local("d"), Operators.Equals, Keyword("new"), Keyword("dynamic"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task DynamicAfterIs(TestHost testHost) { await TestInMethodAsync(@"if (a is dynamic)", testHost, ControlKeyword("if"), Punctuation.OpenParen, Identifier("a"), Keyword("is"), Keyword("dynamic"), Punctuation.CloseParen); } [Theory] [CombinatorialData] public async Task DynamicAfterAs(TestHost testHost) { await TestInMethodAsync(@"a = a as dynamic", testHost, Identifier("a"), Operators.Equals, Identifier("a"), Keyword("as"), Keyword("dynamic")); } [Theory] [CombinatorialData] public async Task DynamicAsGenericTypeArgument(TestHost testHost) { await TestInMethodAsync( @"List<dynamic> l = new List<dynamic>();", testHost, Identifier("List"), Punctuation.OpenAngle, Keyword("dynamic"), Punctuation.CloseAngle, Local("l"), Operators.Equals, Keyword("new"), Identifier("List"), Punctuation.OpenAngle, Keyword("dynamic"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task DynamicAsSecondGenericTypeArgument(TestHost testHost) { await TestInMethodAsync( @"KVP<string, dynamic> kvp;", testHost, Identifier("KVP"), Punctuation.OpenAngle, Keyword("string"), Punctuation.Comma, Keyword("dynamic"), Punctuation.CloseAngle, Local("kvp"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task DynamicAsRegionLabel(TestHost testHost) { var code = @"#region dynamic #endregion"; await TestAsync(code, testHost, PPKeyword("#"), PPKeyword("region"), PPText("dynamic"), PPKeyword("#"), PPKeyword("endregion")); } [Theory] [CombinatorialData] public async Task DynamicAsInterfaceType(TestHost testHost) { await TestAsync( @"interface dynamic { }", testHost, Keyword("interface"), Interface("dynamic"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task DynamicAsStructType(TestHost testHost) { await TestAsync( @"struct dynamic { }", testHost, Keyword("struct"), Struct("dynamic"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task DynamicAsUndefinedGenericType(TestHost testHost) { await TestInMethodAsync( @"dynamic<int> d;", testHost, Identifier("dynamic"), Punctuation.OpenAngle, Keyword("int"), Punctuation.CloseAngle, Local("d"), Punctuation.Semicolon); } } }
// Licensed to the .NET Foundation under one or more 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.Tasks; using Microsoft.CodeAnalysis.Remote.Testing; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using static Microsoft.CodeAnalysis.Editor.UnitTests.Classification.FormattedClassifications; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Classification { public partial class TotalClassifierTests { [Theory] [CombinatorialData] public async Task DynamicAsParamTypeAndDefault(TestHost testHost) { await TestInClassAsync(@"void M(dynamic d = default(dynamic", testHost, Keyword("void"), Method("M"), Punctuation.OpenParen, Keyword("dynamic"), Parameter("d"), Operators.Equals, Keyword("default"), Punctuation.OpenParen, Keyword("dynamic")); } [Theory] [CombinatorialData] public async Task DynamicExplicitConversion(TestHost testHost) { await TestInMethodAsync( @"dynamic d = (dynamic)a;", testHost, Keyword("dynamic"), Local("d"), Operators.Equals, Punctuation.OpenParen, Keyword("dynamic"), Punctuation.CloseParen, Identifier("a"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task DynamicMethodCall(TestHost testHost) { await TestInMethodAsync(@"dynamic.Equals(1, 1);", testHost, Identifier("dynamic"), Operators.Dot, Identifier("Equals"), Punctuation.OpenParen, Number("1"), Punctuation.Comma, Number("1"), Punctuation.CloseParen, Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task DynamicNullable(TestHost testHost) { await TestInMethodAsync(@"dynamic? a", testHost, Keyword("dynamic"), Operators.QuestionMark, Local("a")); } [Theory] [CombinatorialData] public async Task DynamicAsUsingAliasForClass(TestHost testHost) { await TestAsync( @"using dynamic = System.EventArgs;", testHost, Keyword("using"), Class("dynamic"), Operators.Equals, Namespace("System"), Operators.Dot, Class("EventArgs"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task DynamicAsUsingAliasForDelegate(TestHost testHost) { await TestAsync( @"using dynamic = System.Action;", testHost, Keyword("using"), Delegate("dynamic"), Operators.Equals, Namespace("System"), Operators.Dot, Delegate("Action"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task DynamicAsUsingAliasForStruct(TestHost testHost) { await TestAsync( @"using dynamic = System.DateTime;", testHost, Keyword("using"), Struct("dynamic"), Operators.Equals, Namespace("System"), Operators.Dot, Struct("DateTime"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task DynamicAsUsingAliasForEnum(TestHost testHost) { await TestAsync( @"using dynamic = System.DayOfWeek;", testHost, Keyword("using"), Enum("dynamic"), Operators.Equals, Namespace("System"), Operators.Dot, Enum("DayOfWeek"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task DynamicAsUsingAliasForInterface(TestHost testHost) { await TestAsync( @"using dynamic = System.IDisposable;", testHost, Keyword("using"), Interface("dynamic"), Operators.Equals, Namespace("System"), Operators.Dot, Interface("IDisposable"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task DynamicAsExternAlias(TestHost testHost) { await TestAsync( @"extern alias dynamic; class C { dynamic::Goo a; }", testHost, Keyword("extern"), Keyword("alias"), Namespace("dynamic"), Punctuation.Semicolon, Keyword("class"), Class("C"), Punctuation.OpenCurly, Namespace("dynamic"), Operators.ColonColon, Identifier("Goo"), Field("a"), Punctuation.Semicolon, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task DynamicAsDelegateType(TestHost testHost) { await TestAsync(@"delegate void dynamic()", testHost, Keyword("delegate"), Keyword("void"), Delegate("dynamic"), Punctuation.OpenParen, Punctuation.CloseParen); } [Theory] [CombinatorialData] public async Task DynamicAsDelegateReturnTypeAndParam(TestHost testHost) { await TestAsync(@"delegate dynamic MyDelegate (dynamic d)", testHost, Keyword("delegate"), Keyword("dynamic"), Delegate("MyDelegate"), Punctuation.OpenParen, Keyword("dynamic"), Parameter("d"), Punctuation.CloseParen); } [Theory] [CombinatorialData] public async Task DynamicAsDelegateLocalVariable(TestHost testHost) { await TestInMethodAsync( @"Func<string> f = delegate { int dynamic = 10; return dynamic.ToString(); };", testHost, Identifier("Func"), Punctuation.OpenAngle, Keyword("string"), Punctuation.CloseAngle, Local("f"), Operators.Equals, Keyword("delegate"), Punctuation.OpenCurly, Keyword("int"), Local("dynamic"), Operators.Equals, Number("10"), Punctuation.Semicolon, ControlKeyword("return"), Local("dynamic"), Operators.Dot, Method("ToString"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task DynamicAsGenericTypeName(TestHost testHost) { await TestAsync( @"partial class dynamic<T> { } class C { dynamic<int> d; }", testHost, Keyword("partial"), Keyword("class"), Class("dynamic"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("class"), Class("C"), Punctuation.OpenCurly, Class("dynamic"), Punctuation.OpenAngle, Keyword("int"), Punctuation.CloseAngle, Field("d"), Punctuation.Semicolon, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task DynamicAsGenericField(TestHost testHost) { await TestAsync( @"class A<T> { T dynamic; }", testHost, Keyword("class"), Class("A"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenCurly, TypeParameter("T"), Field("dynamic"), Punctuation.Semicolon, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task DynamicAsIndexerTypeAndParameter(TestHost testHost) { await TestInClassAsync(@"dynamic this[dynamic i]", testHost, Keyword("dynamic"), Keyword("this"), Punctuation.OpenBracket, Keyword("dynamic"), Parameter("i"), Punctuation.CloseBracket); } [Theory] [CombinatorialData] public async Task DynamicAsOperatorTypeAndParameter(TestHost testHost) { await TestInClassAsync(@"static dynamic operator +(dynamic d1)", testHost, Keyword("static"), Keyword("dynamic"), Keyword("operator"), Operators.Plus, Punctuation.OpenParen, Keyword("dynamic"), Parameter("d1"), Punctuation.CloseParen); } [Theory] [CombinatorialData] public async Task DynamicAsOperatorName(TestHost testHost) { await TestInClassAsync(@"static explicit operator dynamic(dynamic s)", testHost, Keyword("static"), Keyword("explicit"), Keyword("operator"), Keyword("dynamic"), Punctuation.OpenParen, Keyword("dynamic"), Parameter("s"), Punctuation.CloseParen); } [Theory] [CombinatorialData] public async Task DynamicAsPropertyTypeAndName(TestHost testHost) { await TestInClassAsync(@"dynamic dynamic { get; set; }", testHost, Keyword("dynamic"), Property("dynamic"), Punctuation.OpenCurly, Keyword("get"), Punctuation.Semicolon, Keyword("set"), Punctuation.Semicolon, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task DynamicAsEventName(TestHost testHost) { await TestInClassAsync(@"event Action dynamic", testHost, Keyword("event"), Identifier("Action"), Event("dynamic")); } [Theory] [CombinatorialData] public async Task DynamicAsLinqLocalVariable(TestHost testHost) { await TestInMethodAsync(@"var v = from dynamic in names", testHost, Keyword("var"), Local("v"), Operators.Equals, Keyword("from"), Identifier("dynamic"), Keyword("in"), Identifier("names")); } [Theory] [CombinatorialData] public async Task DynamicAsAnonymousTypePropertyName(TestHost testHost) { await TestInMethodAsync( @"var v = from dynamic in names select new { dynamic = dynamic };", testHost, Keyword("var"), Local("v"), Operators.Equals, Keyword("from"), Identifier("dynamic"), Keyword("in"), Identifier("names"), Keyword("select"), Keyword("new"), Punctuation.OpenCurly, Property("dynamic"), Operators.Equals, Identifier("dynamic"), Punctuation.CloseCurly, Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task DynamicAsArgumentToLambdaExpression(TestHost testHost) { await TestInMethodAsync( @"var p = names.Select(dynamic => dynamic.Length);", testHost, Keyword("var"), Local("p"), Operators.Equals, Identifier("names"), Operators.Dot, Identifier("Select"), Punctuation.OpenParen, Parameter("dynamic"), Operators.EqualsGreaterThan, Parameter("dynamic"), Operators.Dot, Identifier("Length"), Punctuation.CloseParen, Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task DynamicAsAnonymousMethodLocalVariable(TestHost testHost) { await TestInMethodAsync( @"D f = delegate { string dynamic = ""a""; return dynamic.Length; };", testHost, Identifier("D"), Local("f"), Operators.Equals, Keyword("delegate"), Punctuation.OpenCurly, Keyword("string"), Local("dynamic"), Operators.Equals, String(@"""a"""), Punctuation.Semicolon, ControlKeyword("return"), Local("dynamic"), Operators.Dot, Property("Length"), Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task DynamicAsMethodName(TestHost testHost) { await TestInClassAsync( @"dynamic dynamic() { }", testHost, Keyword("dynamic"), Method("dynamic"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task DynamicAsStaticMethodTypeAndParams(TestHost testHost) { await TestInClassAsync( @"static dynamic dynamic(params dynamic[] dynamic) { }", testHost, Keyword("static"), Keyword("dynamic"), Method("dynamic"), Static("dynamic"), Punctuation.OpenParen, Keyword("params"), Keyword("dynamic"), Punctuation.OpenBracket, Punctuation.CloseBracket, Parameter("dynamic"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task DynamicArraysInMethodSignature(TestHost testHost) { await TestInClassAsync( @"dynamic[] M(dynamic[] p, params dynamic[] pa) { }", testHost, Keyword("dynamic"), Punctuation.OpenBracket, Punctuation.CloseBracket, Method("M"), Punctuation.OpenParen, Keyword("dynamic"), Punctuation.OpenBracket, Punctuation.CloseBracket, Parameter("p"), Punctuation.Comma, Keyword("params"), Keyword("dynamic"), Punctuation.OpenBracket, Punctuation.CloseBracket, Parameter("pa"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task DynamicInPartialMethods(TestHost testHost) { await TestInClassAsync( @"partial void F(dynamic d); partial void F(dynamic d) { }", testHost, Keyword("partial"), Keyword("void"), Method("F"), Punctuation.OpenParen, Keyword("dynamic"), Parameter("d"), Punctuation.CloseParen, Punctuation.Semicolon, Keyword("partial"), Keyword("void"), Method("F"), Punctuation.OpenParen, Keyword("dynamic"), Parameter("d"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task DynamicRefAndOutParameters(TestHost testHost) { await TestInClassAsync( @"void F(ref dynamic r, out dynamic o) { }", testHost, Keyword("void"), Method("F"), Punctuation.OpenParen, Keyword("ref"), Keyword("dynamic"), Parameter("r"), Punctuation.Comma, Keyword("out"), Keyword("dynamic"), Parameter("o"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task DynamicInExtensionMethod(TestHost testHost) { await TestInClassAsync( @"dynamic F(this dynamic self, dynamic p) { }", testHost, Keyword("dynamic"), ExtensionMethod("F"), Punctuation.OpenParen, Keyword("this"), Keyword("dynamic"), Parameter("self"), Punctuation.Comma, Keyword("dynamic"), Parameter("p"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task DynamicAsBaseClass(TestHost testHost) { await TestAsync( @"class C : dynamic { }", testHost, Keyword("class"), Class("C"), Punctuation.Colon, Keyword("dynamic"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task DynamicAsGenericConstraint(TestHost testHost) { await TestAsync( @"class C<T> where T : dynamic { }", testHost, Keyword("class"), Class("C"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Keyword("where"), TypeParameter("T"), Punctuation.Colon, Keyword("dynamic"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task DynamicSizeOf(TestHost testHost) { await TestInClassAsync( @"unsafe int M() { return sizeof(dynamic); }", testHost, Keyword("unsafe"), Keyword("int"), Method("M"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, ControlKeyword("return"), Keyword("sizeof"), Punctuation.OpenParen, Keyword("dynamic"), Punctuation.CloseParen, Punctuation.Semicolon, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task DynamicTypeOf(TestHost testHost) { await TestInMethodAsync(@"typeof(dynamic)", testHost, Keyword("typeof"), Punctuation.OpenParen, Keyword("dynamic"), Punctuation.CloseParen); } [Theory] [WorkItem(44423, "https://github.com/dotnet/roslyn/issues/44423")] [CombinatorialData] public async Task DynamicAsArrayName(bool script, TestHost testHost) { var code = @"int[] dynamic = { 1 };"; var parseOptions = script ? Options.Script : null; await TestAsync( code, code, testHost, parseOptions, Keyword("int"), Punctuation.OpenBracket, Punctuation.CloseBracket, script ? Field("dynamic") : Local("dynamic"), Operators.Equals, Punctuation.OpenCurly, Number("1"), Punctuation.CloseCurly, Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task DynamicInForeach(TestHost testHost) { await TestInMethodAsync(@"foreach (dynamic dynamic in dynamic", testHost, ControlKeyword("foreach"), Punctuation.OpenParen, Keyword("dynamic"), Local("dynamic"), ControlKeyword("in"), Identifier("dynamic")); } [Theory] [CombinatorialData] public async Task DynamicInUsing(TestHost testHost) { await TestInMethodAsync(@"using(dynamic d", testHost, Keyword("using"), Punctuation.OpenParen, Keyword("dynamic"), Local("d")); } [Theory] [CombinatorialData] public async Task DynamicAsLocalVariableName(TestHost testHost) { await TestInMethodAsync( @"dynamic dynamic;", testHost, Keyword("dynamic"), Local("dynamic"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task DynamicAsNamespaceName(TestHost testHost) { await TestAsync( @"namespace dynamic { }", testHost, Keyword("namespace"), Namespace("dynamic"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task DynamicAsClassName(TestHost testHost) { await TestAsync( @"class dynamic { }", testHost, Keyword("class"), Class("dynamic"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task DynamicAsConstructorDeclarationName(TestHost testHost) { await TestAsync( @"class dynamic { dynamic() { } }", testHost, Keyword("class"), Class("dynamic"), Punctuation.OpenCurly, Class("dynamic"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task DynamicAsNamespaceAlias(TestHost testHost) { await TestInMethodAsync( @"dynamic.FileInfo file;", testHost, Identifier("dynamic"), Operators.Dot, Identifier("FileInfo"), Local("file"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task DynamicAsGotoLabel(TestHost testHost) { await TestInMethodAsync( @"dynamic: int i = 0; goto dynamic;", testHost, Label("dynamic"), Punctuation.Colon, Keyword("int"), Local("i"), Operators.Equals, Number("0"), Punctuation.Semicolon, ControlKeyword("goto"), Label("dynamic"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task DynamicAsEnumField(TestHost testHost) { await TestInMethodAsync( @"A a = A.dynamic;", testHost, Identifier("A"), Local("a"), Operators.Equals, Identifier("A"), Operators.Dot, Identifier("dynamic"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task DynamicAsEnumFieldDefinition(TestHost testHost) { await TestAsync( @"enum A { dynamic }", testHost, Keyword("enum"), Enum("A"), Punctuation.OpenCurly, EnumMember("dynamic"), Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task DynamicAsEnumType(TestHost testHost) { await TestAsync( @"enum dynamic { }", testHost, Keyword("enum"), Enum("dynamic"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task DynamicAsGenericTypeParameter(TestHost testHost) { await TestAsync( @"class C<dynamic, T> where dynamic : T { dynamic d; }", testHost, Keyword("class"), Class("C"), Punctuation.OpenAngle, TypeParameter("dynamic"), Punctuation.Comma, TypeParameter("T"), Punctuation.CloseAngle, Keyword("where"), TypeParameter("dynamic"), Punctuation.Colon, TypeParameter("T"), Punctuation.OpenCurly, TypeParameter("dynamic"), Field("d"), Punctuation.Semicolon, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task DynamicAsFieldType(TestHost testHost) { await TestInClassAsync(@"dynamic d", testHost, Keyword("dynamic"), Field("d")); } [Theory] [CombinatorialData] public async Task DynamicAsStaticFieldType(TestHost testHost) { await TestInClassAsync(@"static dynamic d", testHost, Keyword("static"), Keyword("dynamic"), Field("d"), Static("d")); } [Theory] [CombinatorialData] public async Task DynamicAsLocalVariableType(TestHost testHost) { await TestInMethodAsync(@"dynamic d", testHost, Keyword("dynamic"), Local("d")); } [Theory] [CombinatorialData] public async Task DynamicAsArrayLocalVariableType(TestHost testHost) { await TestInMethodAsync(@"dynamic[] d", testHost, Keyword("dynamic"), Punctuation.OpenBracket, Punctuation.CloseBracket, Local("d")); } [Theory] [CombinatorialData] public async Task DynamicAsLambdaParameterType(TestHost testHost) { await TestInMethodAsync( @"var q = a.Where((dynamic d) => d == dynamic);", testHost, Keyword("var"), Local("q"), Operators.Equals, Identifier("a"), Operators.Dot, Identifier("Where"), Punctuation.OpenParen, Punctuation.OpenParen, Keyword("dynamic"), Parameter("d"), Punctuation.CloseParen, Operators.EqualsGreaterThan, Parameter("d"), Operators.EqualsEquals, Identifier("dynamic"), Punctuation.CloseParen, Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task DynamicArray(TestHost testHost) { await TestInMethodAsync( @"dynamic d = new dynamic[5];", testHost, Keyword("dynamic"), Local("d"), Operators.Equals, Keyword("new"), Keyword("dynamic"), Punctuation.OpenBracket, Number("5"), Punctuation.CloseBracket, Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task DynamicConstructor(TestHost testHost) { await TestInMethodAsync( @"dynamic d = new dynamic();", testHost, Keyword("dynamic"), Local("d"), Operators.Equals, Keyword("new"), Keyword("dynamic"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task DynamicAfterIs(TestHost testHost) { await TestInMethodAsync(@"if (a is dynamic)", testHost, ControlKeyword("if"), Punctuation.OpenParen, Identifier("a"), Keyword("is"), Keyword("dynamic"), Punctuation.CloseParen); } [Theory] [CombinatorialData] public async Task DynamicAfterAs(TestHost testHost) { await TestInMethodAsync(@"a = a as dynamic", testHost, Identifier("a"), Operators.Equals, Identifier("a"), Keyword("as"), Keyword("dynamic")); } [Theory] [CombinatorialData] public async Task DynamicAsGenericTypeArgument(TestHost testHost) { await TestInMethodAsync( @"List<dynamic> l = new List<dynamic>();", testHost, Identifier("List"), Punctuation.OpenAngle, Keyword("dynamic"), Punctuation.CloseAngle, Local("l"), Operators.Equals, Keyword("new"), Identifier("List"), Punctuation.OpenAngle, Keyword("dynamic"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task DynamicAsSecondGenericTypeArgument(TestHost testHost) { await TestInMethodAsync( @"KVP<string, dynamic> kvp;", testHost, Identifier("KVP"), Punctuation.OpenAngle, Keyword("string"), Punctuation.Comma, Keyword("dynamic"), Punctuation.CloseAngle, Local("kvp"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task DynamicAsRegionLabel(TestHost testHost) { var code = @"#region dynamic #endregion"; await TestAsync(code, testHost, PPKeyword("#"), PPKeyword("region"), PPText("dynamic"), PPKeyword("#"), PPKeyword("endregion")); } [Theory] [CombinatorialData] public async Task DynamicAsInterfaceType(TestHost testHost) { await TestAsync( @"interface dynamic { }", testHost, Keyword("interface"), Interface("dynamic"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task DynamicAsStructType(TestHost testHost) { await TestAsync( @"struct dynamic { }", testHost, Keyword("struct"), Struct("dynamic"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task DynamicAsUndefinedGenericType(TestHost testHost) { await TestInMethodAsync( @"dynamic<int> d;", testHost, Identifier("dynamic"), Punctuation.OpenAngle, Keyword("int"), Punctuation.CloseAngle, Local("d"), Punctuation.Semicolon); } } }
-1
dotnet/roslyn
56,433
Only allow Contract.ThrowIfNull() to be called on nullable types
We had some places we were calling it on bools.
jasonmalinowski
"2021-09-16T01:20:43Z"
"2021-09-16T18:44:11Z"
736fc1b5e6e2847689c0154b3e5f23ea99dd56af
6d0f4e3f972ceb561b04574e7f957a4ff458e272
Only allow Contract.ThrowIfNull() to be called on nullable types. We had some places we were calling it on bools.
./src/Compilers/CSharp/Portable/Binder/ConstantFieldsInProgress.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 Microsoft.CodeAnalysis.CSharp.Symbols; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// This is used while computing the values of constant fields. Since they can depend on each /// other, we need to keep track of which ones we are currently computing in order to avoid (and /// report) cycles. /// </summary> internal sealed class ConstantFieldsInProgress { private readonly SourceFieldSymbol _fieldOpt; private readonly HashSet<SourceFieldSymbolWithSyntaxReference> _dependencies; internal static readonly ConstantFieldsInProgress Empty = new ConstantFieldsInProgress(null, null); internal ConstantFieldsInProgress( SourceFieldSymbol fieldOpt, HashSet<SourceFieldSymbolWithSyntaxReference> dependencies) { _fieldOpt = fieldOpt; _dependencies = dependencies; } public bool IsEmpty { get { return (object)_fieldOpt == null; } } internal void AddDependency(SourceFieldSymbolWithSyntaxReference field) { _dependencies.Add(field); } } }
// Licensed to the .NET Foundation under one or more 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 Microsoft.CodeAnalysis.CSharp.Symbols; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// This is used while computing the values of constant fields. Since they can depend on each /// other, we need to keep track of which ones we are currently computing in order to avoid (and /// report) cycles. /// </summary> internal sealed class ConstantFieldsInProgress { private readonly SourceFieldSymbol _fieldOpt; private readonly HashSet<SourceFieldSymbolWithSyntaxReference> _dependencies; internal static readonly ConstantFieldsInProgress Empty = new ConstantFieldsInProgress(null, null); internal ConstantFieldsInProgress( SourceFieldSymbol fieldOpt, HashSet<SourceFieldSymbolWithSyntaxReference> dependencies) { _fieldOpt = fieldOpt; _dependencies = dependencies; } public bool IsEmpty { get { return (object)_fieldOpt == null; } } internal void AddDependency(SourceFieldSymbolWithSyntaxReference field) { _dependencies.Add(field); } } }
-1
dotnet/roslyn
56,433
Only allow Contract.ThrowIfNull() to be called on nullable types
We had some places we were calling it on bools.
jasonmalinowski
"2021-09-16T01:20:43Z"
"2021-09-16T18:44:11Z"
736fc1b5e6e2847689c0154b3e5f23ea99dd56af
6d0f4e3f972ceb561b04574e7f957a4ff458e272
Only allow Contract.ThrowIfNull() to be called on nullable types. We had some places we were calling it on bools.
./src/ExpressionEvaluator/Core/Test/ResultProvider/Debugger/Engine/DkmClrObjectFavoritesInfo.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 #region Assembly Microsoft.VisualStudio.Debugger.Engine, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a // References\Debugger\v2.0\Microsoft.VisualStudio.Debugger.Engine.dll #endregion using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; namespace Microsoft.VisualStudio.Debugger.Evaluation { public class DkmClrObjectFavoritesInfo { public DkmClrObjectFavoritesInfo(IList<string> favorites, string displayString = null, string simpleDisplayString = null) { Favorites = new ReadOnlyCollection<string>(favorites); DisplayString = displayString; SimpleDisplayString = simpleDisplayString; } public string DisplayString { get; } public string SimpleDisplayString { get; } public ReadOnlyCollection<string> Favorites { 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 #region Assembly Microsoft.VisualStudio.Debugger.Engine, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a // References\Debugger\v2.0\Microsoft.VisualStudio.Debugger.Engine.dll #endregion using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; namespace Microsoft.VisualStudio.Debugger.Evaluation { public class DkmClrObjectFavoritesInfo { public DkmClrObjectFavoritesInfo(IList<string> favorites, string displayString = null, string simpleDisplayString = null) { Favorites = new ReadOnlyCollection<string>(favorites); DisplayString = displayString; SimpleDisplayString = simpleDisplayString; } public string DisplayString { get; } public string SimpleDisplayString { get; } public ReadOnlyCollection<string> Favorites { get; } } }
-1
dotnet/roslyn
56,433
Only allow Contract.ThrowIfNull() to be called on nullable types
We had some places we were calling it on bools.
jasonmalinowski
"2021-09-16T01:20:43Z"
"2021-09-16T18:44:11Z"
736fc1b5e6e2847689c0154b3e5f23ea99dd56af
6d0f4e3f972ceb561b04574e7f957a4ff458e272
Only allow Contract.ThrowIfNull() to be called on nullable types. We had some places we were calling it on bools.
./src/Workspaces/Core/Portable/Shared/TestHooks/AsynchronousOperationListenerProvider.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.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.Composition; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Remote; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Shared.TestHooks { /// <summary> /// use <see cref="IAsynchronousOperationListenerProvider" /> in product code to get /// <see cref="IAsynchronousOperationListener" /> and use /// <see cref="AsynchronousOperationListenerProvider" /> in test to get waiter. /// </summary> [Shared] [Export(typeof(IAsynchronousOperationListenerProvider))] [Export(typeof(AsynchronousOperationListenerProvider))] internal sealed partial class AsynchronousOperationListenerProvider : IAsynchronousOperationListenerProvider { public static readonly IAsynchronousOperationListenerProvider NullProvider = new NullListenerProvider(); public static readonly IAsynchronousOperationListener NullListener = new NullOperationListener(); /// <summary> /// indicate whether asynchronous listener is enabled or not. /// it is tri-state since we want to retrieve this value, if never explicitly set, from environment variable /// and then cache it. /// we read value from environment variable (RoslynWaiterEnabled) because we want team, that doesn't have /// access to Roslyn code (InternalVisibleTo), can use this listener/waiter framework as well. /// those team can enable this without using <see cref="AsynchronousOperationListenerProvider.Enable(bool)" /> API /// </summary> public static bool? s_enabled = null; private readonly ConcurrentDictionary<string, AsynchronousOperationListener> _singletonListeners; private readonly Func<string, AsynchronousOperationListener> _createCallback; /// <summary> /// indicate whether <see cref="AsynchronousOperationListener.TrackActiveTokens"/> is enabled or not /// it is tri-state since we want to retrieve this value, if never explicitly set, from environment variable /// and then cache it. /// we read value from environment variable (RoslynWaiterDiagnosticTokenEnabled) because we want team, that doesn't have /// access to Roslyn code (InternalVisibleTo), can use this listener/waiter framework as well. /// those team can enable this without using <see cref="AsynchronousOperationListenerProvider.EnableDiagnosticTokens(bool)" /> API /// </summary> private bool? _enableDiagnosticTokens; /// <summary> /// Provides a default value for <see cref="_enableDiagnosticTokens"/>. /// </summary> private static bool? s_enableDiagnosticTokens; public static void Enable(bool enable) => Enable(enable, diagnostics: null); public static void Enable(bool enable, bool? diagnostics) { // right now, made it static so that one can enable it through reflection easy // but we can think of some other way s_enabled = enable; s_enableDiagnosticTokens = diagnostics; } [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public AsynchronousOperationListenerProvider() { _singletonListeners = new ConcurrentDictionary<string, AsynchronousOperationListener>(concurrencyLevel: 2, capacity: 20); _createCallback = name => new AsynchronousOperationListener(name, DiagnosticTokensEnabled); } public IAsynchronousOperationListener GetListener(string featureName) { if (!IsEnabled) { // if listener is not enabled. it always return null listener return NullListener; } return _singletonListeners.GetOrAdd(featureName, _createCallback); } /// <summary> /// Enable or disable TrackActiveTokens for test /// </summary> public void EnableDiagnosticTokens(bool enable) { _enableDiagnosticTokens = enable; _singletonListeners.Values.Do(l => l.TrackActiveTokens = enable); } /// <summary> /// Get Waiters for listeners for test /// </summary> public IAsynchronousOperationWaiter GetWaiter(string featureName) => (IAsynchronousOperationWaiter)GetListener(featureName); /// <summary> /// Wait for all of the <see cref="IAsynchronousOperationWaiter"/> instances to finish their /// work. /// </summary> /// <remarks> /// This is a very handy method for debugging hangs in the unit test. Set a break point in the /// loop, dig into the waiters and see all of the active <see cref="IAsyncToken"/> values /// representing the remaining work. /// </remarks> public async Task WaitAllAsync(Workspace? workspace, string[]? featureNames = null, Action? eventProcessingAction = null, TimeSpan? timeout = null) { var startTime = Stopwatch.StartNew(); var smallTimeout = TimeSpan.FromMilliseconds(10); RemoteHostClient? remoteHostClient = null; if (workspace?.Services.GetService<IRemoteHostClientProvider>() is { } remoteHostClientProvider) { remoteHostClient = await remoteHostClientProvider.TryGetRemoteHostClientAsync(CancellationToken.None).ConfigureAwait(false); } List<Task>? tasks = null; while (true) { var waiters = GetCandidateWaiters(featureNames); tasks = waiters.Select(x => x.ExpeditedWaitAsync()).Where(t => !t.IsCompleted).ToList(); if (remoteHostClient is not null) { var isCompleted = await remoteHostClient.TryInvokeAsync<IRemoteAsynchronousOperationListenerService, bool>( (service, cancellationToken) => service.IsCompletedAsync(featureNames.ToImmutableArrayOrEmpty(), cancellationToken), CancellationToken.None).ConfigureAwait(false); if (isCompleted.HasValue && !isCompleted.Value) { tasks.Add(remoteHostClient.TryInvokeAsync<IRemoteAsynchronousOperationListenerService>( (service, cancellationToken) => service.ExpeditedWaitAsync(featureNames.ToImmutableArrayOrEmpty(), cancellationToken), CancellationToken.None).AsTask()); } } if (tasks.Count == 0) { // no new pending tasks break; } do { // wait for all current tasks to be done for the time given if (Task.WaitAll(tasks.ToArray(), smallTimeout)) { // current set of tasks are done. // see whether there are new tasks added while we were waiting break; } // certain test requires some event queues to be processed // for waiter tasks to finish such as Dispatcher queue eventProcessingAction?.Invoke(); // in unit test where it uses fake foreground task scheduler such as StaTaskScheduler // we need to yield for the scheduler to run inlined tasks. If we are not processing events, we // switch to the thread pool for the continuations since the yield will only let operations at the // same or higher priority to execute prior to the continuation. var continueOnCapturedContext = eventProcessingAction is object; await Task.Delay(smallTimeout).ConfigureAwait(continueOnCapturedContext); if (startTime.Elapsed > timeout && timeout != Timeout.InfiniteTimeSpan) { throw new TimeoutException(); } } while (true); } foreach (var task in tasks) { if (task.Exception != null) { throw task.Exception; } } } public bool HasPendingWaiter(params string[] featureNames) { var waiters = GetCandidateWaiters(featureNames); return waiters.Any(w => w.HasPendingWork); } /// <summary> /// Get all saved DiagnosticAsyncToken to investigate tests failure easier /// </summary> public List<AsynchronousOperationListener.DiagnosticAsyncToken> GetTokens() => _singletonListeners.Values.Where(l => l.TrackActiveTokens).SelectMany(l => l.ActiveDiagnosticTokens).ToList(); internal static bool IsEnabled { get { if (!s_enabled.HasValue) { // if s_enabled has never been set, check environment variable to see whether it should be enabled. var enabled = Environment.GetEnvironmentVariable("RoslynWaiterEnabled"); s_enabled = string.Equals(enabled, "1", StringComparison.OrdinalIgnoreCase) || string.Equals(enabled, "True", StringComparison.OrdinalIgnoreCase); } return s_enabled.Value; } } internal bool DiagnosticTokensEnabled { get { if (!_enableDiagnosticTokens.HasValue) { if (s_enableDiagnosticTokens.HasValue) { _enableDiagnosticTokens = s_enableDiagnosticTokens; } else { // if _enableDiagnosticTokens has never been set, check environment variable to see whether it should be enabled. var enabled = Environment.GetEnvironmentVariable("RoslynWaiterDiagnosticTokenEnabled"); _enableDiagnosticTokens = string.Equals(enabled, "1", StringComparison.OrdinalIgnoreCase) || string.Equals(enabled, "True", StringComparison.OrdinalIgnoreCase); } } return _enableDiagnosticTokens.Value; } } private IEnumerable<IAsynchronousOperationWaiter> GetCandidateWaiters(string[]? featureNames) { if (featureNames == null || featureNames.Length == 0) { return _singletonListeners.Values.Cast<IAsynchronousOperationWaiter>(); } return _singletonListeners.Where(kv => featureNames.Contains(kv.Key)).Select(kv => (IAsynchronousOperationWaiter)kv.Value); } } }
// Licensed to the .NET Foundation under one or more 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.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.Composition; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Remote; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Shared.TestHooks { /// <summary> /// use <see cref="IAsynchronousOperationListenerProvider" /> in product code to get /// <see cref="IAsynchronousOperationListener" /> and use /// <see cref="AsynchronousOperationListenerProvider" /> in test to get waiter. /// </summary> [Shared] [Export(typeof(IAsynchronousOperationListenerProvider))] [Export(typeof(AsynchronousOperationListenerProvider))] internal sealed partial class AsynchronousOperationListenerProvider : IAsynchronousOperationListenerProvider { public static readonly IAsynchronousOperationListenerProvider NullProvider = new NullListenerProvider(); public static readonly IAsynchronousOperationListener NullListener = new NullOperationListener(); /// <summary> /// indicate whether asynchronous listener is enabled or not. /// it is tri-state since we want to retrieve this value, if never explicitly set, from environment variable /// and then cache it. /// we read value from environment variable (RoslynWaiterEnabled) because we want team, that doesn't have /// access to Roslyn code (InternalVisibleTo), can use this listener/waiter framework as well. /// those team can enable this without using <see cref="AsynchronousOperationListenerProvider.Enable(bool)" /> API /// </summary> public static bool? s_enabled = null; private readonly ConcurrentDictionary<string, AsynchronousOperationListener> _singletonListeners; private readonly Func<string, AsynchronousOperationListener> _createCallback; /// <summary> /// indicate whether <see cref="AsynchronousOperationListener.TrackActiveTokens"/> is enabled or not /// it is tri-state since we want to retrieve this value, if never explicitly set, from environment variable /// and then cache it. /// we read value from environment variable (RoslynWaiterDiagnosticTokenEnabled) because we want team, that doesn't have /// access to Roslyn code (InternalVisibleTo), can use this listener/waiter framework as well. /// those team can enable this without using <see cref="AsynchronousOperationListenerProvider.EnableDiagnosticTokens(bool)" /> API /// </summary> private bool? _enableDiagnosticTokens; /// <summary> /// Provides a default value for <see cref="_enableDiagnosticTokens"/>. /// </summary> private static bool? s_enableDiagnosticTokens; public static void Enable(bool enable) => Enable(enable, diagnostics: null); public static void Enable(bool enable, bool? diagnostics) { // right now, made it static so that one can enable it through reflection easy // but we can think of some other way s_enabled = enable; s_enableDiagnosticTokens = diagnostics; } [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public AsynchronousOperationListenerProvider() { _singletonListeners = new ConcurrentDictionary<string, AsynchronousOperationListener>(concurrencyLevel: 2, capacity: 20); _createCallback = name => new AsynchronousOperationListener(name, DiagnosticTokensEnabled); } public IAsynchronousOperationListener GetListener(string featureName) { if (!IsEnabled) { // if listener is not enabled. it always return null listener return NullListener; } return _singletonListeners.GetOrAdd(featureName, _createCallback); } /// <summary> /// Enable or disable TrackActiveTokens for test /// </summary> public void EnableDiagnosticTokens(bool enable) { _enableDiagnosticTokens = enable; _singletonListeners.Values.Do(l => l.TrackActiveTokens = enable); } /// <summary> /// Get Waiters for listeners for test /// </summary> public IAsynchronousOperationWaiter GetWaiter(string featureName) => (IAsynchronousOperationWaiter)GetListener(featureName); /// <summary> /// Wait for all of the <see cref="IAsynchronousOperationWaiter"/> instances to finish their /// work. /// </summary> /// <remarks> /// This is a very handy method for debugging hangs in the unit test. Set a break point in the /// loop, dig into the waiters and see all of the active <see cref="IAsyncToken"/> values /// representing the remaining work. /// </remarks> public async Task WaitAllAsync(Workspace? workspace, string[]? featureNames = null, Action? eventProcessingAction = null, TimeSpan? timeout = null) { var startTime = Stopwatch.StartNew(); var smallTimeout = TimeSpan.FromMilliseconds(10); RemoteHostClient? remoteHostClient = null; if (workspace?.Services.GetService<IRemoteHostClientProvider>() is { } remoteHostClientProvider) { remoteHostClient = await remoteHostClientProvider.TryGetRemoteHostClientAsync(CancellationToken.None).ConfigureAwait(false); } List<Task>? tasks = null; while (true) { var waiters = GetCandidateWaiters(featureNames); tasks = waiters.Select(x => x.ExpeditedWaitAsync()).Where(t => !t.IsCompleted).ToList(); if (remoteHostClient is not null) { var isCompleted = await remoteHostClient.TryInvokeAsync<IRemoteAsynchronousOperationListenerService, bool>( (service, cancellationToken) => service.IsCompletedAsync(featureNames.ToImmutableArrayOrEmpty(), cancellationToken), CancellationToken.None).ConfigureAwait(false); if (isCompleted.HasValue && !isCompleted.Value) { tasks.Add(remoteHostClient.TryInvokeAsync<IRemoteAsynchronousOperationListenerService>( (service, cancellationToken) => service.ExpeditedWaitAsync(featureNames.ToImmutableArrayOrEmpty(), cancellationToken), CancellationToken.None).AsTask()); } } if (tasks.Count == 0) { // no new pending tasks break; } do { // wait for all current tasks to be done for the time given if (Task.WaitAll(tasks.ToArray(), smallTimeout)) { // current set of tasks are done. // see whether there are new tasks added while we were waiting break; } // certain test requires some event queues to be processed // for waiter tasks to finish such as Dispatcher queue eventProcessingAction?.Invoke(); // in unit test where it uses fake foreground task scheduler such as StaTaskScheduler // we need to yield for the scheduler to run inlined tasks. If we are not processing events, we // switch to the thread pool for the continuations since the yield will only let operations at the // same or higher priority to execute prior to the continuation. var continueOnCapturedContext = eventProcessingAction is object; await Task.Delay(smallTimeout).ConfigureAwait(continueOnCapturedContext); if (startTime.Elapsed > timeout && timeout != Timeout.InfiniteTimeSpan) { throw new TimeoutException(); } } while (true); } foreach (var task in tasks) { if (task.Exception != null) { throw task.Exception; } } } public bool HasPendingWaiter(params string[] featureNames) { var waiters = GetCandidateWaiters(featureNames); return waiters.Any(w => w.HasPendingWork); } /// <summary> /// Get all saved DiagnosticAsyncToken to investigate tests failure easier /// </summary> public List<AsynchronousOperationListener.DiagnosticAsyncToken> GetTokens() => _singletonListeners.Values.Where(l => l.TrackActiveTokens).SelectMany(l => l.ActiveDiagnosticTokens).ToList(); internal static bool IsEnabled { get { if (!s_enabled.HasValue) { // if s_enabled has never been set, check environment variable to see whether it should be enabled. var enabled = Environment.GetEnvironmentVariable("RoslynWaiterEnabled"); s_enabled = string.Equals(enabled, "1", StringComparison.OrdinalIgnoreCase) || string.Equals(enabled, "True", StringComparison.OrdinalIgnoreCase); } return s_enabled.Value; } } internal bool DiagnosticTokensEnabled { get { if (!_enableDiagnosticTokens.HasValue) { if (s_enableDiagnosticTokens.HasValue) { _enableDiagnosticTokens = s_enableDiagnosticTokens; } else { // if _enableDiagnosticTokens has never been set, check environment variable to see whether it should be enabled. var enabled = Environment.GetEnvironmentVariable("RoslynWaiterDiagnosticTokenEnabled"); _enableDiagnosticTokens = string.Equals(enabled, "1", StringComparison.OrdinalIgnoreCase) || string.Equals(enabled, "True", StringComparison.OrdinalIgnoreCase); } } return _enableDiagnosticTokens.Value; } } private IEnumerable<IAsynchronousOperationWaiter> GetCandidateWaiters(string[]? featureNames) { if (featureNames == null || featureNames.Length == 0) { return _singletonListeners.Values.Cast<IAsynchronousOperationWaiter>(); } return _singletonListeners.Where(kv => featureNames.Contains(kv.Key)).Select(kv => (IAsynchronousOperationWaiter)kv.Value); } } }
-1
dotnet/roslyn
56,433
Only allow Contract.ThrowIfNull() to be called on nullable types
We had some places we were calling it on bools.
jasonmalinowski
"2021-09-16T01:20:43Z"
"2021-09-16T18:44:11Z"
736fc1b5e6e2847689c0154b3e5f23ea99dd56af
6d0f4e3f972ceb561b04574e7f957a4ff458e272
Only allow Contract.ThrowIfNull() to be called on nullable types. We had some places we were calling it on bools.
./src/Compilers/Core/Portable/DiagnosticAnalyzer/AnalysisState.StateKind.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 { internal partial class AnalysisState { /// <summary> /// State kind of per-analyzer <see cref="AnalyzerStateData"/> tracking an analyzer's partial analysis state. /// An analysis state object can be in one of the following states: /// 1. Completely unprocessed: <see cref="ReadyToProcess"/> /// 2. Currently being processed: <see cref="InProcess"/> /// 3. Partially processed by one or more older requests that was either completed or cancelled: <see cref="ReadyToProcess"/> /// 4. Fully processed: <see cref="FullyProcessed"/>. /// </summary> internal enum StateKind { /// <summary> /// Ready for processing. /// Indicates it is either completely unprocessed or partially processed by one or more older requests that was either completed or cancelled. /// </summary> ReadyToProcess, /// <summary> /// Currently being processed. /// </summary> InProcess, /// <summary> /// Fully processed. /// </summary> FullyProcessed, } } }
// Licensed to the .NET Foundation under one or more 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 { internal partial class AnalysisState { /// <summary> /// State kind of per-analyzer <see cref="AnalyzerStateData"/> tracking an analyzer's partial analysis state. /// An analysis state object can be in one of the following states: /// 1. Completely unprocessed: <see cref="ReadyToProcess"/> /// 2. Currently being processed: <see cref="InProcess"/> /// 3. Partially processed by one or more older requests that was either completed or cancelled: <see cref="ReadyToProcess"/> /// 4. Fully processed: <see cref="FullyProcessed"/>. /// </summary> internal enum StateKind { /// <summary> /// Ready for processing. /// Indicates it is either completely unprocessed or partially processed by one or more older requests that was either completed or cancelled. /// </summary> ReadyToProcess, /// <summary> /// Currently being processed. /// </summary> InProcess, /// <summary> /// Fully processed. /// </summary> FullyProcessed, } } }
-1
dotnet/roslyn
56,433
Only allow Contract.ThrowIfNull() to be called on nullable types
We had some places we were calling it on bools.
jasonmalinowski
"2021-09-16T01:20:43Z"
"2021-09-16T18:44:11Z"
736fc1b5e6e2847689c0154b3e5f23ea99dd56af
6d0f4e3f972ceb561b04574e7f957a4ff458e272
Only allow Contract.ThrowIfNull() to be called on nullable types. We had some places we were calling it on bools.
./src/Compilers/CSharp/Portable/Syntax/NamespaceDeclarationSyntax.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 partial class NamespaceDeclarationSyntax { internal new InternalSyntax.NamespaceDeclarationSyntax Green { get { return (InternalSyntax.NamespaceDeclarationSyntax)base.Green; } } public NamespaceDeclarationSyntax Update(SyntaxToken namespaceKeyword, NameSyntax name, SyntaxToken openBraceToken, SyntaxList<ExternAliasDirectiveSyntax> externs, SyntaxList<UsingDirectiveSyntax> usings, SyntaxList<MemberDeclarationSyntax> members, SyntaxToken closeBraceToken, SyntaxToken semicolonToken) => this.Update(this.AttributeLists, this.Modifiers, namespaceKeyword, name, openBraceToken, externs, usings, members, closeBraceToken, semicolonToken); } }
// Licensed to the .NET Foundation under one or more 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 partial class NamespaceDeclarationSyntax { internal new InternalSyntax.NamespaceDeclarationSyntax Green { get { return (InternalSyntax.NamespaceDeclarationSyntax)base.Green; } } public NamespaceDeclarationSyntax Update(SyntaxToken namespaceKeyword, NameSyntax name, SyntaxToken openBraceToken, SyntaxList<ExternAliasDirectiveSyntax> externs, SyntaxList<UsingDirectiveSyntax> usings, SyntaxList<MemberDeclarationSyntax> members, SyntaxToken closeBraceToken, SyntaxToken semicolonToken) => this.Update(this.AttributeLists, this.Modifiers, namespaceKeyword, name, openBraceToken, externs, usings, members, closeBraceToken, semicolonToken); } }
-1
dotnet/roslyn
56,433
Only allow Contract.ThrowIfNull() to be called on nullable types
We had some places we were calling it on bools.
jasonmalinowski
"2021-09-16T01:20:43Z"
"2021-09-16T18:44:11Z"
736fc1b5e6e2847689c0154b3e5f23ea99dd56af
6d0f4e3f972ceb561b04574e7f957a4ff458e272
Only allow Contract.ThrowIfNull() to be called on nullable types. We had some places we were calling it on bools.
./src/EditorFeatures/Core/Extensibility/SignatureHelp/SignatureHelpItemEventArgs.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 Microsoft.CodeAnalysis.SignatureHelp; namespace Microsoft.CodeAnalysis.Editor { internal class SignatureHelpItemEventArgs : EventArgs { public SignatureHelpItem SignatureHelpItem { get; } public SignatureHelpItemEventArgs(SignatureHelpItem signatureHelpItem) => this.SignatureHelpItem = signatureHelpItem; } }
// Licensed to the .NET Foundation under one or more 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 Microsoft.CodeAnalysis.SignatureHelp; namespace Microsoft.CodeAnalysis.Editor { internal class SignatureHelpItemEventArgs : EventArgs { public SignatureHelpItem SignatureHelpItem { get; } public SignatureHelpItemEventArgs(SignatureHelpItem signatureHelpItem) => this.SignatureHelpItem = signatureHelpItem; } }
-1
dotnet/roslyn
56,433
Only allow Contract.ThrowIfNull() to be called on nullable types
We had some places we were calling it on bools.
jasonmalinowski
"2021-09-16T01:20:43Z"
"2021-09-16T18:44:11Z"
736fc1b5e6e2847689c0154b3e5f23ea99dd56af
6d0f4e3f972ceb561b04574e7f957a4ff458e272
Only allow Contract.ThrowIfNull() to be called on nullable types. We had some places we were calling it on bools.
./src/Features/Core/Portable/GenerateMember/GenerateParameterizedMember/AbstractGenerateConversionService.State.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.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.GenerateMember.GenerateParameterizedMember { internal partial class AbstractGenerateConversionService<TService, TSimpleNameSyntax, TExpressionSyntax, TInvocationExpressionSyntax> { protected new class State : AbstractGenerateParameterizedMemberService<TService, TSimpleNameSyntax, TExpressionSyntax, TInvocationExpressionSyntax>.State { public static async Task<State> GenerateConversionStateAsync( TService service, SemanticDocument document, SyntaxNode interfaceNode, CancellationToken cancellationToken) { var state = new State(); if (!await state.TryInitializeConversionAsync(service, document, interfaceNode, cancellationToken).ConfigureAwait(false)) { return null; } return state; } private Task<bool> TryInitializeConversionAsync( TService service, SemanticDocument document, SyntaxNode node, CancellationToken cancellationToken) { if (service.IsImplicitConversionGeneration(node)) { if (!TryInitializeImplicitConversion(service, document, node, cancellationToken)) { return SpecializedTasks.False; } } else if (service.IsExplicitConversionGeneration(node)) { if (!TryInitializeExplicitConversion(service, document, node, cancellationToken)) { return SpecializedTasks.False; } } return TryFinishInitializingStateAsync(service, document, cancellationToken); } private bool TryInitializeExplicitConversion(TService service, SemanticDocument document, SyntaxNode node, CancellationToken cancellationToken) { MethodKind = MethodKind.Conversion; if (!service.TryInitializeExplicitConversionState( document, node, ClassInterfaceModuleStructTypes, cancellationToken, out var identifierToken, out var methodSymbol, out var typeToGenerateIn)) { return false; } ContainingType = document.SemanticModel.GetEnclosingNamedType(node.SpanStart, cancellationToken); if (ContainingType == null) { return false; } IdentifierToken = identifierToken; TypeToGenerateIn = typeToGenerateIn; SignatureInfo = new MethodSignatureInfo(document, this, methodSymbol); location = node.GetLocation(); MethodGenerationKind = MethodGenerationKind.ExplicitConversion; return true; } private bool TryInitializeImplicitConversion(TService service, SemanticDocument document, SyntaxNode node, CancellationToken cancellationToken) { MethodKind = MethodKind.Conversion; if (!service.TryInitializeImplicitConversionState( document, node, ClassInterfaceModuleStructTypes, cancellationToken, out var identifierToken, out var methodSymbol, out var typeToGenerateIn)) { return false; } ContainingType = document.SemanticModel.GetEnclosingNamedType(node.SpanStart, cancellationToken); if (ContainingType == null) { return false; } IdentifierToken = identifierToken; TypeToGenerateIn = typeToGenerateIn; SignatureInfo = new MethodSignatureInfo(document, this, methodSymbol); MethodGenerationKind = MethodGenerationKind.ImplicitConversion; return 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. #nullable disable using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.GenerateMember.GenerateParameterizedMember { internal partial class AbstractGenerateConversionService<TService, TSimpleNameSyntax, TExpressionSyntax, TInvocationExpressionSyntax> { protected new class State : AbstractGenerateParameterizedMemberService<TService, TSimpleNameSyntax, TExpressionSyntax, TInvocationExpressionSyntax>.State { public static async Task<State> GenerateConversionStateAsync( TService service, SemanticDocument document, SyntaxNode interfaceNode, CancellationToken cancellationToken) { var state = new State(); if (!await state.TryInitializeConversionAsync(service, document, interfaceNode, cancellationToken).ConfigureAwait(false)) { return null; } return state; } private Task<bool> TryInitializeConversionAsync( TService service, SemanticDocument document, SyntaxNode node, CancellationToken cancellationToken) { if (service.IsImplicitConversionGeneration(node)) { if (!TryInitializeImplicitConversion(service, document, node, cancellationToken)) { return SpecializedTasks.False; } } else if (service.IsExplicitConversionGeneration(node)) { if (!TryInitializeExplicitConversion(service, document, node, cancellationToken)) { return SpecializedTasks.False; } } return TryFinishInitializingStateAsync(service, document, cancellationToken); } private bool TryInitializeExplicitConversion(TService service, SemanticDocument document, SyntaxNode node, CancellationToken cancellationToken) { MethodKind = MethodKind.Conversion; if (!service.TryInitializeExplicitConversionState( document, node, ClassInterfaceModuleStructTypes, cancellationToken, out var identifierToken, out var methodSymbol, out var typeToGenerateIn)) { return false; } ContainingType = document.SemanticModel.GetEnclosingNamedType(node.SpanStart, cancellationToken); if (ContainingType == null) { return false; } IdentifierToken = identifierToken; TypeToGenerateIn = typeToGenerateIn; SignatureInfo = new MethodSignatureInfo(document, this, methodSymbol); location = node.GetLocation(); MethodGenerationKind = MethodGenerationKind.ExplicitConversion; return true; } private bool TryInitializeImplicitConversion(TService service, SemanticDocument document, SyntaxNode node, CancellationToken cancellationToken) { MethodKind = MethodKind.Conversion; if (!service.TryInitializeImplicitConversionState( document, node, ClassInterfaceModuleStructTypes, cancellationToken, out var identifierToken, out var methodSymbol, out var typeToGenerateIn)) { return false; } ContainingType = document.SemanticModel.GetEnclosingNamedType(node.SpanStart, cancellationToken); if (ContainingType == null) { return false; } IdentifierToken = identifierToken; TypeToGenerateIn = typeToGenerateIn; SignatureInfo = new MethodSignatureInfo(document, this, methodSymbol); MethodGenerationKind = MethodGenerationKind.ImplicitConversion; return true; } } } }
-1
dotnet/roslyn
56,433
Only allow Contract.ThrowIfNull() to be called on nullable types
We had some places we were calling it on bools.
jasonmalinowski
"2021-09-16T01:20:43Z"
"2021-09-16T18:44:11Z"
736fc1b5e6e2847689c0154b3e5f23ea99dd56af
6d0f4e3f972ceb561b04574e7f957a4ff458e272
Only allow Contract.ThrowIfNull() to be called on nullable types. We had some places we were calling it on bools.
./src/Compilers/Core/Portable/Emit/EditAndContinue/DefinitionMap.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.IO; using System.Linq; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.Symbols; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Emit { internal abstract class DefinitionMap { protected readonly struct MappedMethod { public readonly IMethodSymbolInternal PreviousMethod; public readonly Func<SyntaxNode, SyntaxNode?>? SyntaxMap; public MappedMethod(IMethodSymbolInternal previousMethod, Func<SyntaxNode, SyntaxNode?>? syntaxMap) { PreviousMethod = previousMethod; SyntaxMap = syntaxMap; } } protected readonly IReadOnlyDictionary<IMethodSymbolInternal, MappedMethod> mappedMethods; protected abstract SymbolMatcher MapToMetadataSymbolMatcher { get; } protected abstract SymbolMatcher MapToPreviousSymbolMatcher { get; } protected DefinitionMap(IEnumerable<SemanticEdit> edits) { Debug.Assert(edits != null); this.mappedMethods = GetMappedMethods(edits); } private IReadOnlyDictionary<IMethodSymbolInternal, MappedMethod> GetMappedMethods(IEnumerable<SemanticEdit> edits) { var mappedMethods = new Dictionary<IMethodSymbolInternal, MappedMethod>(); foreach (var edit in edits) { // We should always "preserve locals" of iterator and async methods since the state machine // might be active without MoveNext method being on stack. We don't enforce this requirement here, // since a method may be incorrectly marked by Iterator/AsyncStateMachine attribute by the user, // in which case we can't reliably figure out that it's an error in semantic edit set. // We should also "preserve locals" of any updated method containing lambdas. The goal is to // treat lambdas the same as method declarations. Lambdas declared in a method body that escape // the method (are assigned to a field, added to an event, e.g.) might be invoked after the method // is updated and when it no longer contains active statements. If we didn't map the lambdas of // the updated body to the original lambdas we would run the out-of-date lambda bodies, // which would not happen if the lambdas were named methods. // TODO (bug https://github.com/dotnet/roslyn/issues/2504) // Note that in some cases an Insert might also need to map syntax. For example, a new constructor added // to a class that has field/property initializers with lambdas. These lambdas get "copied" into the constructor // (assuming it doesn't have "this" constructor initializer) and thus their generated names need to be preserved. if (edit.Kind == SemanticEditKind.Update && edit.PreserveLocalVariables) { RoslynDebug.AssertNotNull(edit.NewSymbol); RoslynDebug.AssertNotNull(edit.OldSymbol); if (GetISymbolInternalOrNull(edit.NewSymbol) is IMethodSymbolInternal newMethod && GetISymbolInternalOrNull(edit.OldSymbol) is IMethodSymbolInternal oldMethod) { mappedMethods.Add(newMethod, new MappedMethod(oldMethod, edit.SyntaxMap)); } } } return mappedMethods; } protected abstract ISymbolInternal? GetISymbolInternalOrNull(ISymbol symbol); internal Cci.IDefinition? MapDefinition(Cci.IDefinition definition) { return MapToPreviousSymbolMatcher.MapDefinition(definition) ?? (MapToMetadataSymbolMatcher != MapToPreviousSymbolMatcher ? MapToMetadataSymbolMatcher.MapDefinition(definition) : null); } internal Cci.INamespace? MapNamespace(Cci.INamespace @namespace) { return MapToPreviousSymbolMatcher.MapNamespace(@namespace) ?? (MapToMetadataSymbolMatcher != MapToPreviousSymbolMatcher ? MapToMetadataSymbolMatcher.MapNamespace(@namespace) : null); } internal bool DefinitionExists(Cci.IDefinition definition) => MapDefinition(definition) is object; internal bool NamespaceExists(Cci.INamespace @namespace) => MapNamespace(@namespace) is object; internal abstract bool TryGetTypeHandle(Cci.ITypeDefinition def, out TypeDefinitionHandle handle); internal abstract bool TryGetEventHandle(Cci.IEventDefinition def, out EventDefinitionHandle handle); internal abstract bool TryGetFieldHandle(Cci.IFieldDefinition def, out FieldDefinitionHandle handle); internal abstract bool TryGetMethodHandle(Cci.IMethodDefinition def, out MethodDefinitionHandle handle); internal abstract bool TryGetPropertyHandle(Cci.IPropertyDefinition def, out PropertyDefinitionHandle handle); internal abstract CommonMessageProvider MessageProvider { get; } private bool TryGetMethodHandle(EmitBaseline baseline, Cci.IMethodDefinition def, out MethodDefinitionHandle handle) { if (this.TryGetMethodHandle(def, out handle)) { return true; } var mappedDef = (Cci.IMethodDefinition?)MapToPreviousSymbolMatcher.MapDefinition(def); if (mappedDef != null && baseline.MethodsAdded.TryGetValue(mappedDef, out int methodIndex)) { handle = MetadataTokens.MethodDefinitionHandle(methodIndex); return true; } handle = default; return false; } protected static IReadOnlyDictionary<SyntaxNode, int> CreateDeclaratorToSyntaxOrdinalMap(ImmutableArray<SyntaxNode> declarators) { var declaratorToIndex = new Dictionary<SyntaxNode, int>(); for (int i = 0; i < declarators.Length; i++) { declaratorToIndex.Add(declarators[i], i); } return declaratorToIndex; } protected abstract void GetStateMachineFieldMapFromMetadata( ITypeSymbolInternal stateMachineType, ImmutableArray<LocalSlotDebugInfo> localSlotDebugInfo, out IReadOnlyDictionary<EncHoistedLocalInfo, int> hoistedLocalMap, out IReadOnlyDictionary<Cci.ITypeReference, int> awaiterMap, out int awaiterSlotCount); protected abstract ImmutableArray<EncLocalInfo> GetLocalSlotMapFromMetadata(StandaloneSignatureHandle handle, EditAndContinueMethodDebugInformation debugInfo); protected abstract ITypeSymbolInternal? TryGetStateMachineType(EntityHandle methodHandle); internal VariableSlotAllocator? TryCreateVariableSlotAllocator(EmitBaseline baseline, Compilation compilation, IMethodSymbolInternal method, IMethodSymbolInternal topLevelMethod, DiagnosticBag diagnostics) { // Top-level methods are always included in the semantic edit list. Lambda methods are not. if (!mappedMethods.TryGetValue(topLevelMethod, out var mappedMethod)) { return null; } // TODO (bug https://github.com/dotnet/roslyn/issues/2504): // Handle cases when the previous method doesn't exist. if (!TryGetMethodHandle(baseline, (Cci.IMethodDefinition)method.GetCciAdapter(), out var previousHandle)) { // Unrecognized method. Must have been added in the current compilation. return null; } ImmutableArray<EncLocalInfo> previousLocals; IReadOnlyDictionary<EncHoistedLocalInfo, int>? hoistedLocalMap = null; IReadOnlyDictionary<Cci.ITypeReference, int>? awaiterMap = null; IReadOnlyDictionary<int, KeyValuePair<DebugId, int>>? lambdaMap = null; IReadOnlyDictionary<int, DebugId>? closureMap = null; int hoistedLocalSlotCount = 0; int awaiterSlotCount = 0; string? stateMachineTypeName = null; SymbolMatcher symbolMap; int methodIndex = MetadataTokens.GetRowNumber(previousHandle); DebugId methodId; // Check if method has changed previously. If so, we already have a map. if (baseline.AddedOrChangedMethods.TryGetValue(methodIndex, out var addedOrChangedMethod)) { methodId = addedOrChangedMethod.MethodId; MakeLambdaAndClosureMaps(addedOrChangedMethod.LambdaDebugInfo, addedOrChangedMethod.ClosureDebugInfo, out lambdaMap, out closureMap); if (addedOrChangedMethod.StateMachineTypeName != null) { // method is async/iterator kickoff method GetStateMachineFieldMapFromPreviousCompilation( addedOrChangedMethod.StateMachineHoistedLocalSlotsOpt, addedOrChangedMethod.StateMachineAwaiterSlotsOpt, out hoistedLocalMap, out awaiterMap); hoistedLocalSlotCount = addedOrChangedMethod.StateMachineHoistedLocalSlotsOpt.Length; awaiterSlotCount = addedOrChangedMethod.StateMachineAwaiterSlotsOpt.Length; // Kickoff method has no interesting locals on its own. // We use the EnC method debug information for hoisted locals. previousLocals = ImmutableArray<EncLocalInfo>.Empty; stateMachineTypeName = addedOrChangedMethod.StateMachineTypeName; } else { previousLocals = addedOrChangedMethod.Locals; } // All types that AddedOrChangedMethodInfo refers to have been mapped to the previous generation. // Therefore we don't need to fall back to metadata if we don't find the type reference, like we do in DefinitionMap.MapReference. symbolMap = MapToPreviousSymbolMatcher; } else { // Method has not changed since initial generation. Generate a map // using the local names provided with the initial metadata. EditAndContinueMethodDebugInformation debugInfo; StandaloneSignatureHandle localSignature; try { debugInfo = baseline.DebugInformationProvider(previousHandle); localSignature = baseline.LocalSignatureProvider(previousHandle); } catch (Exception e) when (e is InvalidDataException || e is IOException) { diagnostics.Add(MessageProvider.CreateDiagnostic( MessageProvider.ERR_InvalidDebugInfo, method.Locations.First(), method, MetadataTokens.GetToken(previousHandle), method.ContainingAssembly )); return null; } methodId = new DebugId(debugInfo.MethodOrdinal, 0); if (!debugInfo.Lambdas.IsDefaultOrEmpty) { MakeLambdaAndClosureMaps(debugInfo.Lambdas, debugInfo.Closures, out lambdaMap, out closureMap); } ITypeSymbolInternal? stateMachineType = TryGetStateMachineType(previousHandle); if (stateMachineType != null) { // method is async/iterator kickoff method var localSlotDebugInfo = debugInfo.LocalSlots.NullToEmpty(); GetStateMachineFieldMapFromMetadata(stateMachineType, localSlotDebugInfo, out hoistedLocalMap, out awaiterMap, out awaiterSlotCount); hoistedLocalSlotCount = localSlotDebugInfo.Length; // Kickoff method has no interesting locals on its own. // We use the EnC method debug information for hoisted locals. previousLocals = ImmutableArray<EncLocalInfo>.Empty; stateMachineTypeName = stateMachineType.Name; } else { // If the current method is async/iterator then either the previous method wasn't declared as async/iterator and it's updated to be one, // or it was but is not marked by the corresponding state machine attribute because it was missing in the compilation. // In the later case we need to report an error since we don't known how to map to the previous state machine. // The IDE already checked that the attribute type is present in the base compilation, but didn't validate that it is well-formed. // We don't have the base compilation to directly query for the attribute, only the source compilation. // But since constructor signatures can't be updated during EnC we can just check the current compilation. if (method.IsAsync) { if (compilation.CommonGetWellKnownTypeMember(WellKnownMember.System_Runtime_CompilerServices_AsyncStateMachineAttribute__ctor) == null) { ReportMissingStateMachineAttribute(diagnostics, method, AttributeDescription.AsyncStateMachineAttribute.FullName); return null; } } else if (method.IsIterator) { if (compilation.CommonGetWellKnownTypeMember(WellKnownMember.System_Runtime_CompilerServices_IteratorStateMachineAttribute__ctor) == null) { ReportMissingStateMachineAttribute(diagnostics, method, AttributeDescription.IteratorStateMachineAttribute.FullName); return null; } } try { previousLocals = localSignature.IsNil ? ImmutableArray<EncLocalInfo>.Empty : GetLocalSlotMapFromMetadata(localSignature, debugInfo); } catch (Exception e) when (e is UnsupportedSignatureContent || e is BadImageFormatException || e is IOException) { diagnostics.Add(MessageProvider.CreateDiagnostic( MessageProvider.ERR_InvalidDebugInfo, method.Locations.First(), method, MetadataTokens.GetToken(localSignature), method.ContainingAssembly )); return null; } } symbolMap = MapToMetadataSymbolMatcher; } return new EncVariableSlotAllocator( symbolMap, mappedMethod.SyntaxMap, mappedMethod.PreviousMethod, methodId, previousLocals, lambdaMap, closureMap, stateMachineTypeName, hoistedLocalSlotCount, hoistedLocalMap, awaiterSlotCount, awaiterMap, GetLambdaSyntaxFacts()); } protected abstract LambdaSyntaxFacts GetLambdaSyntaxFacts(); private void ReportMissingStateMachineAttribute(DiagnosticBag diagnostics, IMethodSymbolInternal method, string stateMachineAttributeFullName) { diagnostics.Add(MessageProvider.CreateDiagnostic( MessageProvider.ERR_EncUpdateFailedMissingAttribute, method.Locations.First(), MessageProvider.GetErrorDisplayString(method.GetISymbol()), stateMachineAttributeFullName)); } private static void MakeLambdaAndClosureMaps( ImmutableArray<LambdaDebugInfo> lambdaDebugInfo, ImmutableArray<ClosureDebugInfo> closureDebugInfo, out IReadOnlyDictionary<int, KeyValuePair<DebugId, int>> lambdaMap, out IReadOnlyDictionary<int, DebugId> closureMap) { var lambdas = new Dictionary<int, KeyValuePair<DebugId, int>>(lambdaDebugInfo.Length); var closures = new Dictionary<int, DebugId>(closureDebugInfo.Length); for (int i = 0; i < lambdaDebugInfo.Length; i++) { var lambdaInfo = lambdaDebugInfo[i]; lambdas[lambdaInfo.SyntaxOffset] = KeyValuePairUtil.Create(lambdaInfo.LambdaId, lambdaInfo.ClosureOrdinal); } for (int i = 0; i < closureDebugInfo.Length; i++) { var closureInfo = closureDebugInfo[i]; closures[closureInfo.SyntaxOffset] = closureInfo.ClosureId; } lambdaMap = lambdas; closureMap = closures; } private static void GetStateMachineFieldMapFromPreviousCompilation( ImmutableArray<EncHoistedLocalInfo> hoistedLocalSlots, ImmutableArray<Cci.ITypeReference?> hoistedAwaiters, out IReadOnlyDictionary<EncHoistedLocalInfo, int> hoistedLocalMap, out IReadOnlyDictionary<Cci.ITypeReference, int> awaiterMap) { var hoistedLocals = new Dictionary<EncHoistedLocalInfo, int>(); var awaiters = new Dictionary<Cci.ITypeReference, int>(Cci.SymbolEquivalentEqualityComparer.Instance); for (int slotIndex = 0; slotIndex < hoistedLocalSlots.Length; slotIndex++) { var slot = hoistedLocalSlots[slotIndex]; if (slot.IsUnused) { // Unused field. continue; } hoistedLocals.Add(slot, slotIndex); } for (int slotIndex = 0; slotIndex < hoistedAwaiters.Length; slotIndex++) { var slot = hoistedAwaiters[slotIndex]; if (slot == null) { // Unused awaiter. continue; } awaiters.Add(slot, slotIndex); } hoistedLocalMap = hoistedLocals; awaiterMap = awaiters; } } }
// Licensed to the .NET Foundation under one or more 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.IO; using System.Linq; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.Symbols; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Emit { internal abstract class DefinitionMap { protected readonly struct MappedMethod { public readonly IMethodSymbolInternal PreviousMethod; public readonly Func<SyntaxNode, SyntaxNode?>? SyntaxMap; public MappedMethod(IMethodSymbolInternal previousMethod, Func<SyntaxNode, SyntaxNode?>? syntaxMap) { PreviousMethod = previousMethod; SyntaxMap = syntaxMap; } } protected readonly IReadOnlyDictionary<IMethodSymbolInternal, MappedMethod> mappedMethods; protected abstract SymbolMatcher MapToMetadataSymbolMatcher { get; } protected abstract SymbolMatcher MapToPreviousSymbolMatcher { get; } protected DefinitionMap(IEnumerable<SemanticEdit> edits) { Debug.Assert(edits != null); this.mappedMethods = GetMappedMethods(edits); } private IReadOnlyDictionary<IMethodSymbolInternal, MappedMethod> GetMappedMethods(IEnumerable<SemanticEdit> edits) { var mappedMethods = new Dictionary<IMethodSymbolInternal, MappedMethod>(); foreach (var edit in edits) { // We should always "preserve locals" of iterator and async methods since the state machine // might be active without MoveNext method being on stack. We don't enforce this requirement here, // since a method may be incorrectly marked by Iterator/AsyncStateMachine attribute by the user, // in which case we can't reliably figure out that it's an error in semantic edit set. // We should also "preserve locals" of any updated method containing lambdas. The goal is to // treat lambdas the same as method declarations. Lambdas declared in a method body that escape // the method (are assigned to a field, added to an event, e.g.) might be invoked after the method // is updated and when it no longer contains active statements. If we didn't map the lambdas of // the updated body to the original lambdas we would run the out-of-date lambda bodies, // which would not happen if the lambdas were named methods. // TODO (bug https://github.com/dotnet/roslyn/issues/2504) // Note that in some cases an Insert might also need to map syntax. For example, a new constructor added // to a class that has field/property initializers with lambdas. These lambdas get "copied" into the constructor // (assuming it doesn't have "this" constructor initializer) and thus their generated names need to be preserved. if (edit.Kind == SemanticEditKind.Update && edit.PreserveLocalVariables) { RoslynDebug.AssertNotNull(edit.NewSymbol); RoslynDebug.AssertNotNull(edit.OldSymbol); if (GetISymbolInternalOrNull(edit.NewSymbol) is IMethodSymbolInternal newMethod && GetISymbolInternalOrNull(edit.OldSymbol) is IMethodSymbolInternal oldMethod) { mappedMethods.Add(newMethod, new MappedMethod(oldMethod, edit.SyntaxMap)); } } } return mappedMethods; } protected abstract ISymbolInternal? GetISymbolInternalOrNull(ISymbol symbol); internal Cci.IDefinition? MapDefinition(Cci.IDefinition definition) { return MapToPreviousSymbolMatcher.MapDefinition(definition) ?? (MapToMetadataSymbolMatcher != MapToPreviousSymbolMatcher ? MapToMetadataSymbolMatcher.MapDefinition(definition) : null); } internal Cci.INamespace? MapNamespace(Cci.INamespace @namespace) { return MapToPreviousSymbolMatcher.MapNamespace(@namespace) ?? (MapToMetadataSymbolMatcher != MapToPreviousSymbolMatcher ? MapToMetadataSymbolMatcher.MapNamespace(@namespace) : null); } internal bool DefinitionExists(Cci.IDefinition definition) => MapDefinition(definition) is object; internal bool NamespaceExists(Cci.INamespace @namespace) => MapNamespace(@namespace) is object; internal abstract bool TryGetTypeHandle(Cci.ITypeDefinition def, out TypeDefinitionHandle handle); internal abstract bool TryGetEventHandle(Cci.IEventDefinition def, out EventDefinitionHandle handle); internal abstract bool TryGetFieldHandle(Cci.IFieldDefinition def, out FieldDefinitionHandle handle); internal abstract bool TryGetMethodHandle(Cci.IMethodDefinition def, out MethodDefinitionHandle handle); internal abstract bool TryGetPropertyHandle(Cci.IPropertyDefinition def, out PropertyDefinitionHandle handle); internal abstract CommonMessageProvider MessageProvider { get; } private bool TryGetMethodHandle(EmitBaseline baseline, Cci.IMethodDefinition def, out MethodDefinitionHandle handle) { if (this.TryGetMethodHandle(def, out handle)) { return true; } var mappedDef = (Cci.IMethodDefinition?)MapToPreviousSymbolMatcher.MapDefinition(def); if (mappedDef != null && baseline.MethodsAdded.TryGetValue(mappedDef, out int methodIndex)) { handle = MetadataTokens.MethodDefinitionHandle(methodIndex); return true; } handle = default; return false; } protected static IReadOnlyDictionary<SyntaxNode, int> CreateDeclaratorToSyntaxOrdinalMap(ImmutableArray<SyntaxNode> declarators) { var declaratorToIndex = new Dictionary<SyntaxNode, int>(); for (int i = 0; i < declarators.Length; i++) { declaratorToIndex.Add(declarators[i], i); } return declaratorToIndex; } protected abstract void GetStateMachineFieldMapFromMetadata( ITypeSymbolInternal stateMachineType, ImmutableArray<LocalSlotDebugInfo> localSlotDebugInfo, out IReadOnlyDictionary<EncHoistedLocalInfo, int> hoistedLocalMap, out IReadOnlyDictionary<Cci.ITypeReference, int> awaiterMap, out int awaiterSlotCount); protected abstract ImmutableArray<EncLocalInfo> GetLocalSlotMapFromMetadata(StandaloneSignatureHandle handle, EditAndContinueMethodDebugInformation debugInfo); protected abstract ITypeSymbolInternal? TryGetStateMachineType(EntityHandle methodHandle); internal VariableSlotAllocator? TryCreateVariableSlotAllocator(EmitBaseline baseline, Compilation compilation, IMethodSymbolInternal method, IMethodSymbolInternal topLevelMethod, DiagnosticBag diagnostics) { // Top-level methods are always included in the semantic edit list. Lambda methods are not. if (!mappedMethods.TryGetValue(topLevelMethod, out var mappedMethod)) { return null; } // TODO (bug https://github.com/dotnet/roslyn/issues/2504): // Handle cases when the previous method doesn't exist. if (!TryGetMethodHandle(baseline, (Cci.IMethodDefinition)method.GetCciAdapter(), out var previousHandle)) { // Unrecognized method. Must have been added in the current compilation. return null; } ImmutableArray<EncLocalInfo> previousLocals; IReadOnlyDictionary<EncHoistedLocalInfo, int>? hoistedLocalMap = null; IReadOnlyDictionary<Cci.ITypeReference, int>? awaiterMap = null; IReadOnlyDictionary<int, KeyValuePair<DebugId, int>>? lambdaMap = null; IReadOnlyDictionary<int, DebugId>? closureMap = null; int hoistedLocalSlotCount = 0; int awaiterSlotCount = 0; string? stateMachineTypeName = null; SymbolMatcher symbolMap; int methodIndex = MetadataTokens.GetRowNumber(previousHandle); DebugId methodId; // Check if method has changed previously. If so, we already have a map. if (baseline.AddedOrChangedMethods.TryGetValue(methodIndex, out var addedOrChangedMethod)) { methodId = addedOrChangedMethod.MethodId; MakeLambdaAndClosureMaps(addedOrChangedMethod.LambdaDebugInfo, addedOrChangedMethod.ClosureDebugInfo, out lambdaMap, out closureMap); if (addedOrChangedMethod.StateMachineTypeName != null) { // method is async/iterator kickoff method GetStateMachineFieldMapFromPreviousCompilation( addedOrChangedMethod.StateMachineHoistedLocalSlotsOpt, addedOrChangedMethod.StateMachineAwaiterSlotsOpt, out hoistedLocalMap, out awaiterMap); hoistedLocalSlotCount = addedOrChangedMethod.StateMachineHoistedLocalSlotsOpt.Length; awaiterSlotCount = addedOrChangedMethod.StateMachineAwaiterSlotsOpt.Length; // Kickoff method has no interesting locals on its own. // We use the EnC method debug information for hoisted locals. previousLocals = ImmutableArray<EncLocalInfo>.Empty; stateMachineTypeName = addedOrChangedMethod.StateMachineTypeName; } else { previousLocals = addedOrChangedMethod.Locals; } // All types that AddedOrChangedMethodInfo refers to have been mapped to the previous generation. // Therefore we don't need to fall back to metadata if we don't find the type reference, like we do in DefinitionMap.MapReference. symbolMap = MapToPreviousSymbolMatcher; } else { // Method has not changed since initial generation. Generate a map // using the local names provided with the initial metadata. EditAndContinueMethodDebugInformation debugInfo; StandaloneSignatureHandle localSignature; try { debugInfo = baseline.DebugInformationProvider(previousHandle); localSignature = baseline.LocalSignatureProvider(previousHandle); } catch (Exception e) when (e is InvalidDataException || e is IOException) { diagnostics.Add(MessageProvider.CreateDiagnostic( MessageProvider.ERR_InvalidDebugInfo, method.Locations.First(), method, MetadataTokens.GetToken(previousHandle), method.ContainingAssembly )); return null; } methodId = new DebugId(debugInfo.MethodOrdinal, 0); if (!debugInfo.Lambdas.IsDefaultOrEmpty) { MakeLambdaAndClosureMaps(debugInfo.Lambdas, debugInfo.Closures, out lambdaMap, out closureMap); } ITypeSymbolInternal? stateMachineType = TryGetStateMachineType(previousHandle); if (stateMachineType != null) { // method is async/iterator kickoff method var localSlotDebugInfo = debugInfo.LocalSlots.NullToEmpty(); GetStateMachineFieldMapFromMetadata(stateMachineType, localSlotDebugInfo, out hoistedLocalMap, out awaiterMap, out awaiterSlotCount); hoistedLocalSlotCount = localSlotDebugInfo.Length; // Kickoff method has no interesting locals on its own. // We use the EnC method debug information for hoisted locals. previousLocals = ImmutableArray<EncLocalInfo>.Empty; stateMachineTypeName = stateMachineType.Name; } else { // If the current method is async/iterator then either the previous method wasn't declared as async/iterator and it's updated to be one, // or it was but is not marked by the corresponding state machine attribute because it was missing in the compilation. // In the later case we need to report an error since we don't known how to map to the previous state machine. // The IDE already checked that the attribute type is present in the base compilation, but didn't validate that it is well-formed. // We don't have the base compilation to directly query for the attribute, only the source compilation. // But since constructor signatures can't be updated during EnC we can just check the current compilation. if (method.IsAsync) { if (compilation.CommonGetWellKnownTypeMember(WellKnownMember.System_Runtime_CompilerServices_AsyncStateMachineAttribute__ctor) == null) { ReportMissingStateMachineAttribute(diagnostics, method, AttributeDescription.AsyncStateMachineAttribute.FullName); return null; } } else if (method.IsIterator) { if (compilation.CommonGetWellKnownTypeMember(WellKnownMember.System_Runtime_CompilerServices_IteratorStateMachineAttribute__ctor) == null) { ReportMissingStateMachineAttribute(diagnostics, method, AttributeDescription.IteratorStateMachineAttribute.FullName); return null; } } try { previousLocals = localSignature.IsNil ? ImmutableArray<EncLocalInfo>.Empty : GetLocalSlotMapFromMetadata(localSignature, debugInfo); } catch (Exception e) when (e is UnsupportedSignatureContent || e is BadImageFormatException || e is IOException) { diagnostics.Add(MessageProvider.CreateDiagnostic( MessageProvider.ERR_InvalidDebugInfo, method.Locations.First(), method, MetadataTokens.GetToken(localSignature), method.ContainingAssembly )); return null; } } symbolMap = MapToMetadataSymbolMatcher; } return new EncVariableSlotAllocator( symbolMap, mappedMethod.SyntaxMap, mappedMethod.PreviousMethod, methodId, previousLocals, lambdaMap, closureMap, stateMachineTypeName, hoistedLocalSlotCount, hoistedLocalMap, awaiterSlotCount, awaiterMap, GetLambdaSyntaxFacts()); } protected abstract LambdaSyntaxFacts GetLambdaSyntaxFacts(); private void ReportMissingStateMachineAttribute(DiagnosticBag diagnostics, IMethodSymbolInternal method, string stateMachineAttributeFullName) { diagnostics.Add(MessageProvider.CreateDiagnostic( MessageProvider.ERR_EncUpdateFailedMissingAttribute, method.Locations.First(), MessageProvider.GetErrorDisplayString(method.GetISymbol()), stateMachineAttributeFullName)); } private static void MakeLambdaAndClosureMaps( ImmutableArray<LambdaDebugInfo> lambdaDebugInfo, ImmutableArray<ClosureDebugInfo> closureDebugInfo, out IReadOnlyDictionary<int, KeyValuePair<DebugId, int>> lambdaMap, out IReadOnlyDictionary<int, DebugId> closureMap) { var lambdas = new Dictionary<int, KeyValuePair<DebugId, int>>(lambdaDebugInfo.Length); var closures = new Dictionary<int, DebugId>(closureDebugInfo.Length); for (int i = 0; i < lambdaDebugInfo.Length; i++) { var lambdaInfo = lambdaDebugInfo[i]; lambdas[lambdaInfo.SyntaxOffset] = KeyValuePairUtil.Create(lambdaInfo.LambdaId, lambdaInfo.ClosureOrdinal); } for (int i = 0; i < closureDebugInfo.Length; i++) { var closureInfo = closureDebugInfo[i]; closures[closureInfo.SyntaxOffset] = closureInfo.ClosureId; } lambdaMap = lambdas; closureMap = closures; } private static void GetStateMachineFieldMapFromPreviousCompilation( ImmutableArray<EncHoistedLocalInfo> hoistedLocalSlots, ImmutableArray<Cci.ITypeReference?> hoistedAwaiters, out IReadOnlyDictionary<EncHoistedLocalInfo, int> hoistedLocalMap, out IReadOnlyDictionary<Cci.ITypeReference, int> awaiterMap) { var hoistedLocals = new Dictionary<EncHoistedLocalInfo, int>(); var awaiters = new Dictionary<Cci.ITypeReference, int>(Cci.SymbolEquivalentEqualityComparer.Instance); for (int slotIndex = 0; slotIndex < hoistedLocalSlots.Length; slotIndex++) { var slot = hoistedLocalSlots[slotIndex]; if (slot.IsUnused) { // Unused field. continue; } hoistedLocals.Add(slot, slotIndex); } for (int slotIndex = 0; slotIndex < hoistedAwaiters.Length; slotIndex++) { var slot = hoistedAwaiters[slotIndex]; if (slot == null) { // Unused awaiter. continue; } awaiters.Add(slot, slotIndex); } hoistedLocalMap = hoistedLocals; awaiterMap = awaiters; } } }
-1
dotnet/roslyn
56,433
Only allow Contract.ThrowIfNull() to be called on nullable types
We had some places we were calling it on bools.
jasonmalinowski
"2021-09-16T01:20:43Z"
"2021-09-16T18:44:11Z"
736fc1b5e6e2847689c0154b3e5f23ea99dd56af
6d0f4e3f972ceb561b04574e7f957a4ff458e272
Only allow Contract.ThrowIfNull() to be called on nullable types. We had some places we were calling it on bools.
./src/Compilers/CSharp/Test/IOperation/IOperation/IOperationTests_IUnaryOperatorExpression.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.Syntax; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class IOperationTests_IUnaryOperatorExpression : SemanticModelTestBase { [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17595, "https://github.com/dotnet/roslyn/issues/17591")] public void Test_UnaryOperatorExpression_Type_Plus_System_SByte() { string source = @" class A { System.SByte Method() { System.SByte i = default(System.SByte); return /*<bind>*/+i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '+i') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'i') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.SByte, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Plus_System_Byte() { string source = @" class A { System.Byte Method() { System.Byte i = default(System.Byte); return /*<bind>*/+i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '+i') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'i') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Byte, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Plus_System_Int16() { string source = @" class A { System.Int16 Method() { System.Int16 i = default(System.Int16); return /*<bind>*/+i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '+i') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'i') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int16, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Plus_System_UInt16() { string source = @" class A { System.UInt16 Method() { System.UInt16 i = default(System.UInt16); return /*<bind>*/+i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '+i') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'i') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.UInt16, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Plus_System_Int32() { string source = @" class A { System.Int32 Method() { System.Int32 i = default(System.Int32); return /*<bind>*/+i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.Int32) (Syntax: '+i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Plus_System_UInt32() { string source = @" class A { System.UInt32 Method() { System.UInt32 i = default(System.UInt32); return /*<bind>*/+i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.UInt32) (Syntax: '+i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.UInt32) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Plus_System_Int64() { string source = @" class A { System.Int64 Method() { System.Int64 i = default(System.Int64); return /*<bind>*/+i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.Int64) (Syntax: '+i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int64) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Plus_System_UInt64() { string source = @" class A { System.UInt64 Method() { System.UInt64 i = default(System.UInt64); return /*<bind>*/+i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.UInt64) (Syntax: '+i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.UInt64) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Plus_System_Char() { string source = @" class A { System.Char Method() { System.Char i = default(System.Char); return /*<bind>*/+i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '+i') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'i') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Char, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Plus_System_Decimal() { string source = @" class A { System.Decimal Method() { System.Decimal i = default(System.Decimal); return /*<bind>*/+i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.Decimal) (Syntax: '+i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Decimal) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Plus_System_Single() { string source = @" class A { System.Single Method() { System.Single i = default(System.Single); return /*<bind>*/+i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.Single) (Syntax: '+i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Single) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Plus_System_Double() { string source = @" class A { System.Double Method() { System.Double i = default(System.Double); return /*<bind>*/+i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.Double) (Syntax: '+i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Double) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Plus_System_Boolean() { string source = @" class A { System.Boolean Method() { System.Boolean i = default(System.Boolean); return /*<bind>*/+i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '+i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Boolean, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Plus_System_Object() { string source = @" class A { System.Object Method() { System.Object i = default(System.Object); return /*<bind>*/+i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '+i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Object, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Minus_System_SByte() { string source = @" class A { System.SByte Method() { System.SByte i = default(System.SByte); return /*<bind>*/-i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '-i') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'i') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.SByte, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Minus_System_Byte() { string source = @" class A { System.Byte Method() { System.Byte i = default(System.Byte); return /*<bind>*/-i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '-i') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'i') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Byte, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Minus_System_Int16() { string source = @" class A { System.Int16 Method() { System.Int16 i = default(System.Int16); return /*<bind>*/-i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '-i') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'i') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int16, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Minus_System_UInt16() { string source = @" class A { System.UInt16 Method() { System.UInt16 i = default(System.UInt16); return /*<bind>*/-i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '-i') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'i') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.UInt16, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Minus_System_Int32() { string source = @" class A { System.Int32 Method() { System.Int32 i = default(System.Int32); return /*<bind>*/-i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Int32) (Syntax: '-i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Minus_System_UInt32() { string source = @" class A { System.UInt32 Method() { System.UInt32 i = default(System.UInt32); return /*<bind>*/-i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Int64, IsInvalid) (Syntax: '-i') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int64, IsInvalid, IsImplicit) (Syntax: 'i') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.UInt32, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Minus_System_Int64() { string source = @" class A { System.Int64 Method() { System.Int64 i = default(System.Int64); return /*<bind>*/-i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Int64) (Syntax: '-i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int64) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Minus_System_UInt64() { string source = @" class A { System.UInt64 Method() { System.UInt64 i = default(System.UInt64); return /*<bind>*/-i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '-i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.UInt64, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Minus_System_Char() { string source = @" class A { System.Char Method() { System.Char i = default(System.Char); return /*<bind>*/-i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '-i') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'i') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Char, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Minus_System_Decimal() { string source = @" class A { System.Decimal Method() { System.Decimal i = default(System.Decimal); return /*<bind>*/-i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Decimal) (Syntax: '-i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Decimal) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Minus_System_Single() { string source = @" class A { System.Single Method() { System.Single i = default(System.Single); return /*<bind>*/-i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Single) (Syntax: '-i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Single) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Minus_System_Double() { string source = @" class A { System.Double Method() { System.Double i = default(System.Double); return /*<bind>*/-i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Double) (Syntax: '-i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Double) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Minus_System_Boolean() { string source = @" class A { System.Boolean Method() { System.Boolean i = default(System.Boolean); return /*<bind>*/-i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '-i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Boolean, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Minus_System_Object() { string source = @" class A { System.Object Method() { System.Object i = default(System.Object); return /*<bind>*/-i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '-i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Object, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Plus_System_SByte() { string source = @" class A { System.SByte Method() { System.SByte i = default(System.SByte); return /*<bind>*/+Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '+Method()') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'Method()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvocationOperation ( System.SByte A.Method()) (OperationKind.Invocation, Type: System.SByte, IsInvalid) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Plus_System_Byte() { string source = @" class A { System.Byte Method() { System.Byte i = default(System.Byte); return /*<bind>*/+Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '+Method()') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'Method()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvocationOperation ( System.Byte A.Method()) (OperationKind.Invocation, Type: System.Byte, IsInvalid) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Plus_System_Int16() { string source = @" class A { System.Int16 Method() { System.Int16 i = default(System.Int16); return /*<bind>*/+Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '+Method()') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'Method()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvocationOperation ( System.Int16 A.Method()) (OperationKind.Invocation, Type: System.Int16, IsInvalid) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Plus_System_UInt16() { string source = @" class A { System.UInt16 Method() { System.UInt16 i = default(System.UInt16); return /*<bind>*/+Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '+Method()') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'Method()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvocationOperation ( System.UInt16 A.Method()) (OperationKind.Invocation, Type: System.UInt16, IsInvalid) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Plus_System_Int32() { string source = @" class A { System.Int32 Method() { System.Int32 i = default(System.Int32); return /*<bind>*/+Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.Int32) (Syntax: '+Method()') Operand: IInvocationOperation ( System.Int32 A.Method()) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Plus_System_UInt32() { string source = @" class A { System.UInt32 Method() { System.UInt32 i = default(System.UInt32); return /*<bind>*/+Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.UInt32) (Syntax: '+Method()') Operand: IInvocationOperation ( System.UInt32 A.Method()) (OperationKind.Invocation, Type: System.UInt32) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Plus_System_Int64() { string source = @" class A { System.Int64 Method() { System.Int64 i = default(System.Int64); return /*<bind>*/+Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.Int64) (Syntax: '+Method()') Operand: IInvocationOperation ( System.Int64 A.Method()) (OperationKind.Invocation, Type: System.Int64) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Plus_System_UInt64() { string source = @" class A { System.UInt64 Method() { System.UInt64 i = default(System.UInt64); return /*<bind>*/+Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.UInt64) (Syntax: '+Method()') Operand: IInvocationOperation ( System.UInt64 A.Method()) (OperationKind.Invocation, Type: System.UInt64) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Plus_System_Char() { string source = @" class A { System.Char Method() { System.Char i = default(System.Char); return /*<bind>*/+Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '+Method()') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'Method()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvocationOperation ( System.Char A.Method()) (OperationKind.Invocation, Type: System.Char, IsInvalid) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Plus_System_Decimal() { string source = @" class A { System.Decimal Method() { System.Decimal i = default(System.Decimal); return /*<bind>*/+Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.Decimal) (Syntax: '+Method()') Operand: IInvocationOperation ( System.Decimal A.Method()) (OperationKind.Invocation, Type: System.Decimal) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Plus_System_Single() { string source = @" class A { System.Single Method() { System.Single i = default(System.Single); return /*<bind>*/+Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.Single) (Syntax: '+Method()') Operand: IInvocationOperation ( System.Single A.Method()) (OperationKind.Invocation, Type: System.Single) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Plus_System_Double() { string source = @" class A { System.Double Method() { System.Double i = default(System.Double); return /*<bind>*/+Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.Double) (Syntax: '+Method()') Operand: IInvocationOperation ( System.Double A.Method()) (OperationKind.Invocation, Type: System.Double) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Plus_System_Boolean() { string source = @" class A { System.Boolean Method() { System.Boolean i = default(System.Boolean); return /*<bind>*/+Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '+Method()') Operand: IInvocationOperation ( System.Boolean A.Method()) (OperationKind.Invocation, Type: System.Boolean, IsInvalid) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Plus_System_Object() { string source = @" class A { System.Object Method() { System.Object i = default(System.Object); return /*<bind>*/+Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '+Method()') Operand: IInvocationOperation ( System.Object A.Method()) (OperationKind.Invocation, Type: System.Object, IsInvalid) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Minus_System_SByte() { string source = @" class A { System.SByte Method() { System.SByte i = default(System.SByte); return /*<bind>*/-Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '-Method()') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'Method()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvocationOperation ( System.SByte A.Method()) (OperationKind.Invocation, Type: System.SByte, IsInvalid) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Minus_System_Byte() { string source = @" class A { System.Byte Method() { System.Byte i = default(System.Byte); return /*<bind>*/-Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '-Method()') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'Method()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvocationOperation ( System.Byte A.Method()) (OperationKind.Invocation, Type: System.Byte, IsInvalid) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Minus_System_Int16() { string source = @" class A { System.Int16 Method() { System.Int16 i = default(System.Int16); return /*<bind>*/-Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '-Method()') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'Method()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvocationOperation ( System.Int16 A.Method()) (OperationKind.Invocation, Type: System.Int16, IsInvalid) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Minus_System_UInt16() { string source = @" class A { System.UInt16 Method() { System.UInt16 i = default(System.UInt16); return /*<bind>*/-Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '-Method()') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'Method()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvocationOperation ( System.UInt16 A.Method()) (OperationKind.Invocation, Type: System.UInt16, IsInvalid) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Minus_System_Int32() { string source = @" class A { System.Int32 Method() { System.Int32 i = default(System.Int32); return /*<bind>*/-Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Int32) (Syntax: '-Method()') Operand: IInvocationOperation ( System.Int32 A.Method()) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Minus_System_UInt32() { string source = @" class A { System.UInt32 Method() { System.UInt32 i = default(System.UInt32); return /*<bind>*/-Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Int64, IsInvalid) (Syntax: '-Method()') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int64, IsInvalid, IsImplicit) (Syntax: 'Method()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvocationOperation ( System.UInt32 A.Method()) (OperationKind.Invocation, Type: System.UInt32, IsInvalid) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Minus_System_Int64() { string source = @" class A { System.Int64 Method() { System.Int64 i = default(System.Int64); return /*<bind>*/-Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Int64) (Syntax: '-Method()') Operand: IInvocationOperation ( System.Int64 A.Method()) (OperationKind.Invocation, Type: System.Int64) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Minus_System_UInt64() { string source = @" class A { System.UInt64 Method() { System.UInt64 i = default(System.UInt64); return /*<bind>*/-Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '-Method()') Operand: IInvocationOperation ( System.UInt64 A.Method()) (OperationKind.Invocation, Type: System.UInt64, IsInvalid) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Minus_System_Char() { string source = @" class A { System.Char Method() { System.Char i = default(System.Char); return /*<bind>*/-Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '-Method()') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'Method()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvocationOperation ( System.Char A.Method()) (OperationKind.Invocation, Type: System.Char, IsInvalid) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Minus_System_Decimal() { string source = @" class A { System.Decimal Method() { System.Decimal i = default(System.Decimal); return /*<bind>*/-Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Decimal) (Syntax: '-Method()') Operand: IInvocationOperation ( System.Decimal A.Method()) (OperationKind.Invocation, Type: System.Decimal) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Minus_System_Single() { string source = @" class A { System.Single Method() { System.Single i = default(System.Single); return /*<bind>*/-Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Single) (Syntax: '-Method()') Operand: IInvocationOperation ( System.Single A.Method()) (OperationKind.Invocation, Type: System.Single) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Minus_System_Double() { string source = @" class A { System.Double Method() { System.Double i = default(System.Double); return /*<bind>*/-Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Double) (Syntax: '-Method()') Operand: IInvocationOperation ( System.Double A.Method()) (OperationKind.Invocation, Type: System.Double) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Minus_System_Boolean() { string source = @" class A { System.Boolean Method() { System.Boolean i = default(System.Boolean); return /*<bind>*/-Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '-Method()') Operand: IInvocationOperation ( System.Boolean A.Method()) (OperationKind.Invocation, Type: System.Boolean, IsInvalid) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Minus_System_Object() { string source = @" class A { System.Object Method() { System.Object i = default(System.Object); return /*<bind>*/-Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '-Method()') Operand: IInvocationOperation ( System.Object A.Method()) (OperationKind.Invocation, Type: System.Object, IsInvalid) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_LogicalNot_System_Boolean() { string source = @" class A { System.Boolean Method() { System.Boolean i = default(System.Boolean); return /*<bind>*/!i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Not) (OperationKind.Unary, Type: System.Boolean) (Syntax: '!i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Boolean) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_LogicalNot_System_Boolean() { string source = @" class A { System.Boolean Method() { System.Boolean i = default(System.Boolean); return /*<bind>*/!Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Not) (OperationKind.Unary, Type: System.Boolean) (Syntax: '!Method()') Operand: IInvocationOperation ( System.Boolean A.Method()) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_BitwiseNot_System_SByte() { string source = @" class A { System.SByte Method() { System.SByte i = default(System.SByte); return /*<bind>*/~i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '~i') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'i') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.SByte, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_BitwiseNot_System_Byte() { string source = @" class A { System.Byte Method() { System.Byte i = default(System.Byte); return /*<bind>*/~i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '~i') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'i') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Byte, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_BitwiseNot_System_Int16() { string source = @" class A { System.Int16 Method() { System.Int16 i = default(System.Int16); return /*<bind>*/~i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '~i') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'i') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int16, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_BitwiseNot_System_UInt16() { string source = @" class A { System.UInt16 Method() { System.UInt16 i = default(System.UInt16); return /*<bind>*/~i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '~i') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'i') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.UInt16, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_BitwiseNot_System_Int32() { string source = @" class A { System.Int32 Method() { System.Int32 i = default(System.Int32); return /*<bind>*/~i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: System.Int32) (Syntax: '~i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_BitwiseNot_System_UInt32() { string source = @" class A { System.UInt32 Method() { System.UInt32 i = default(System.UInt32); return /*<bind>*/~i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: System.UInt32) (Syntax: '~i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.UInt32) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_BitwiseNot_System_Int64() { string source = @" class A { System.Int64 Method() { System.Int64 i = default(System.Int64); return /*<bind>*/~i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: System.Int64) (Syntax: '~i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int64) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_BitwiseNot_System_UInt64() { string source = @" class A { System.UInt64 Method() { System.UInt64 i = default(System.UInt64); return /*<bind>*/~i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: System.UInt64) (Syntax: '~i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.UInt64) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_BitwiseNot_System_Char() { string source = @" class A { System.Char Method() { System.Char i = default(System.Char); return /*<bind>*/~i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '~i') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'i') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Char, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_BitwiseNot_System_Decimal() { string source = @" class A { System.Decimal Method() { System.Decimal i = default(System.Decimal); return /*<bind>*/~i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '~i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Decimal, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_BitwiseNot_System_Single() { string source = @" class A { System.Single Method() { System.Single i = default(System.Single); return /*<bind>*/~i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '~i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Single, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_BitwiseNot_System_Double() { string source = @" class A { System.Double Method() { System.Double i = default(System.Double); return /*<bind>*/~i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '~i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Double, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_BitwiseNot_System_Boolean() { string source = @" class A { System.Boolean Method() { System.Boolean i = default(System.Boolean); return /*<bind>*/~i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '~i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Boolean, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_BitwiseNot_System_Object() { string source = @" class A { System.Object Method() { System.Object i = default(System.Object); return /*<bind>*/~i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '~i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Object, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_BitwiseNot_System_SByte() { string source = @" class A { System.SByte Method() { System.SByte i = default(System.SByte); return /*<bind>*/~Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '~Method()') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'Method()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvocationOperation ( System.SByte A.Method()) (OperationKind.Invocation, Type: System.SByte, IsInvalid) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_BitwiseNot_System_Byte() { string source = @" class A { System.Byte Method() { System.Byte i = default(System.Byte); return /*<bind>*/~Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '~Method()') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'Method()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvocationOperation ( System.Byte A.Method()) (OperationKind.Invocation, Type: System.Byte, IsInvalid) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_BitwiseNot_System_Int16() { string source = @" class A { System.Int16 Method() { System.Int16 i = default(System.Int16); return /*<bind>*/~Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '~Method()') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'Method()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvocationOperation ( System.Int16 A.Method()) (OperationKind.Invocation, Type: System.Int16, IsInvalid) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_BitwiseNot_System_UInt16() { string source = @" class A { System.UInt16 Method() { System.UInt16 i = default(System.UInt16); return /*<bind>*/~Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '~Method()') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'Method()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvocationOperation ( System.UInt16 A.Method()) (OperationKind.Invocation, Type: System.UInt16, IsInvalid) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_BitwiseNot_System_Int32() { string source = @" class A { System.Int32 Method() { System.Int32 i = default(System.Int32); return /*<bind>*/~Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: System.Int32) (Syntax: '~Method()') Operand: IInvocationOperation ( System.Int32 A.Method()) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_BitwiseNot_System_UInt32() { string source = @" class A { System.UInt32 Method() { System.UInt32 i = default(System.UInt32); return /*<bind>*/~Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: System.UInt32) (Syntax: '~Method()') Operand: IInvocationOperation ( System.UInt32 A.Method()) (OperationKind.Invocation, Type: System.UInt32) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_BitwiseNot_System_Int64() { string source = @" class A { System.Int64 Method() { System.Int64 i = default(System.Int64); return /*<bind>*/~Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: System.Int64) (Syntax: '~Method()') Operand: IInvocationOperation ( System.Int64 A.Method()) (OperationKind.Invocation, Type: System.Int64) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_BitwiseNot_System_UInt64() { string source = @" class A { System.UInt64 Method() { System.UInt64 i = default(System.UInt64); return /*<bind>*/~Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: System.UInt64) (Syntax: '~Method()') Operand: IInvocationOperation ( System.UInt64 A.Method()) (OperationKind.Invocation, Type: System.UInt64) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_BitwiseNot_System_Char() { string source = @" class A { System.Char Method() { System.Char i = default(System.Char); return /*<bind>*/~Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '~Method()') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'Method()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvocationOperation ( System.Char A.Method()) (OperationKind.Invocation, Type: System.Char, IsInvalid) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_BitwiseNot_System_Decimal() { string source = @" class A { System.Decimal Method() { System.Decimal i = default(System.Decimal); return /*<bind>*/~Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '~Method()') Operand: IInvocationOperation ( System.Decimal A.Method()) (OperationKind.Invocation, Type: System.Decimal, IsInvalid) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_BitwiseNot_System_Single() { string source = @" class A { System.Single Method() { System.Single i = default(System.Single); return /*<bind>*/~Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '~Method()') Operand: IInvocationOperation ( System.Single A.Method()) (OperationKind.Invocation, Type: System.Single, IsInvalid) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_BitwiseNot_System_Double() { string source = @" class A { System.Double Method() { System.Double i = default(System.Double); return /*<bind>*/~Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '~Method()') Operand: IInvocationOperation ( System.Double A.Method()) (OperationKind.Invocation, Type: System.Double, IsInvalid) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_BitwiseNot_System_Boolean() { string source = @" class A { System.Boolean Method() { System.Boolean i = default(System.Boolean); return /*<bind>*/~Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '~Method()') Operand: IInvocationOperation ( System.Boolean A.Method()) (OperationKind.Invocation, Type: System.Boolean, IsInvalid) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_BitwiseNot_System_Object() { string source = @" class A { System.Object Method() { System.Object i = default(System.Object); return /*<bind>*/~Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '~Method()') Operand: IInvocationOperation ( System.Object A.Method()) (OperationKind.Invocation, Type: System.Object, IsInvalid) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Plus_dynamic() { string source = @" class A { dynamic Method() { dynamic i = default(dynamic); return /*<bind>*/+i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: dynamic) (Syntax: '+i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: dynamic) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Minus_dynamic() { string source = @" class A { dynamic Method() { dynamic i = default(dynamic); return /*<bind>*/-i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: dynamic) (Syntax: '-i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: dynamic) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_BitwiseNot_dynamic() { string source = @" class A { dynamic Method() { dynamic i = default(dynamic); return /*<bind>*/~i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: dynamic) (Syntax: '~i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: dynamic) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_LogicalNot_dynamic() { string source = @" class A { dynamic Method() { dynamic i = default(dynamic); return /*<bind>*/!i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Not) (OperationKind.Unary, Type: dynamic) (Syntax: '!i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: dynamic) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Plus_dynamic() { string source = @" class A { dynamic Method() { dynamic i = default(dynamic); return /*<bind>*/+Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: dynamic) (Syntax: '+Method()') Operand: IInvocationOperation ( dynamic A.Method()) (OperationKind.Invocation, Type: dynamic) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Minus_dynamic() { string source = @" class A { dynamic Method() { dynamic i = default(dynamic); return /*<bind>*/-Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: dynamic) (Syntax: '-Method()') Operand: IInvocationOperation ( dynamic A.Method()) (OperationKind.Invocation, Type: dynamic) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_BitwiseNot_dynamic() { string source = @" class A { dynamic Method() { dynamic i = default(dynamic); return /*<bind>*/~Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: dynamic) (Syntax: '~Method()') Operand: IInvocationOperation ( dynamic A.Method()) (OperationKind.Invocation, Type: dynamic) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_LogicalNot_dynamic() { string source = @" class A { dynamic Method() { dynamic i = default(dynamic); return /*<bind>*/!Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Not) (OperationKind.Unary, Type: dynamic) (Syntax: '!Method()') Operand: IInvocationOperation ( dynamic A.Method()) (OperationKind.Invocation, Type: dynamic) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Plus_Enum() { string source = @" class A { Enum Method() { Enum i = default(Enum); return /*<bind>*/+i/*</bind>*/; } } enum Enum { A, B } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '+i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: Enum, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Minus_Enum() { string source = @" class A { Enum Method() { Enum i = default(Enum); return /*<bind>*/-i/*</bind>*/; } } enum Enum { A, B } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '-i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: Enum, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_BitwiseNot_Enum() { string source = @" class A { Enum Method() { Enum i = default(Enum); return /*<bind>*/~i/*</bind>*/; } } enum Enum { A, B } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: Enum) (Syntax: '~i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: Enum) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Plus_Enum() { string source = @" class A { Enum Method() { Enum i = default(Enum); return /*<bind>*/+Method()/*</bind>*/; } } enum Enum { A, B } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '+Method()') Operand: IInvocationOperation ( Enum A.Method()) (OperationKind.Invocation, Type: Enum, IsInvalid) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Minus_Enum() { string source = @" class A { Enum Method() { Enum i = default(Enum); return /*<bind>*/-Method()/*</bind>*/; } } enum Enum { A, B } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '-Method()') Operand: IInvocationOperation ( Enum A.Method()) (OperationKind.Invocation, Type: Enum, IsInvalid) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_BitwiseNot_Enum() { string source = @" class A { Enum Method() { Enum i = default(Enum); return /*<bind>*/~Method()/*</bind>*/; } } enum Enum { A, B } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: Enum) (Syntax: '~Method()') Operand: IInvocationOperation ( Enum A.Method()) (OperationKind.Invocation, Type: Enum) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Plus_CustomType() { string source = @" class A { CustomType Method() { CustomType i = default(CustomType); return /*<bind>*/+i/*</bind>*/; } } public struct CustomType { public static CustomType operator +(CustomType x) { return x; } public static CustomType operator -(CustomType x) { return x; } public static CustomType operator !(CustomType x) { return x; } public static CustomType operator ~(CustomType x) { return x; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperatorMethod: CustomType CustomType.op_UnaryPlus(CustomType x)) (OperationKind.Unary, Type: CustomType) (Syntax: '+i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: CustomType) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Minus_CustomType() { string source = @" class A { CustomType Method() { CustomType i = default(CustomType); return /*<bind>*/-i/*</bind>*/; } } public struct CustomType { public static CustomType operator +(CustomType x) { return x; } public static CustomType operator -(CustomType x) { return x; } public static CustomType operator !(CustomType x) { return x; } public static CustomType operator ~(CustomType x) { return x; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperatorMethod: CustomType CustomType.op_UnaryNegation(CustomType x)) (OperationKind.Unary, Type: CustomType) (Syntax: '-i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: CustomType) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_BitwiseNot_CustomType() { string source = @" class A { CustomType Method() { CustomType i = default(CustomType); return /*<bind>*/~i/*</bind>*/; } } public struct CustomType { public static CustomType operator +(CustomType x) { return x; } public static CustomType operator -(CustomType x) { return x; } public static CustomType operator !(CustomType x) { return x; } public static CustomType operator ~(CustomType x) { return x; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperatorMethod: CustomType CustomType.op_OnesComplement(CustomType x)) (OperationKind.Unary, Type: CustomType) (Syntax: '~i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: CustomType) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_LogicalNot_CustomType() { string source = @" class A { CustomType Method() { CustomType i = default(CustomType); return /*<bind>*/!i/*</bind>*/; } } public struct CustomType { public static CustomType operator +(CustomType x) { return x; } public static CustomType operator -(CustomType x) { return x; } public static CustomType operator !(CustomType x) { return x; } public static CustomType operator ~(CustomType x) { return x; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Not) (OperatorMethod: CustomType CustomType.op_LogicalNot(CustomType x)) (OperationKind.Unary, Type: CustomType) (Syntax: '!i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: CustomType) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Plus_CustomType() { string source = @" class A { CustomType Method() { CustomType i = default(CustomType); return /*<bind>*/+Method()/*</bind>*/; } } public struct CustomType { public static CustomType operator +(CustomType x) { return x; } public static CustomType operator -(CustomType x) { return x; } public static CustomType operator !(CustomType x) { return x; } public static CustomType operator ~(CustomType x) { return x; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperatorMethod: CustomType CustomType.op_UnaryPlus(CustomType x)) (OperationKind.Unary, Type: CustomType) (Syntax: '+Method()') Operand: IInvocationOperation ( CustomType A.Method()) (OperationKind.Invocation, Type: CustomType) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Minus_CustomType() { string source = @" class A { CustomType Method() { CustomType i = default(CustomType); return /*<bind>*/-Method()/*</bind>*/; } } public struct CustomType { public static CustomType operator +(CustomType x) { return x; } public static CustomType operator -(CustomType x) { return x; } public static CustomType operator !(CustomType x) { return x; } public static CustomType operator ~(CustomType x) { return x; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperatorMethod: CustomType CustomType.op_UnaryNegation(CustomType x)) (OperationKind.Unary, Type: CustomType) (Syntax: '-Method()') Operand: IInvocationOperation ( CustomType A.Method()) (OperationKind.Invocation, Type: CustomType) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_BitwiseNot_CustomType() { string source = @" class A { CustomType Method() { CustomType i = default(CustomType); return /*<bind>*/~Method()/*</bind>*/; } } public struct CustomType { public static CustomType operator +(CustomType x) { return x; } public static CustomType operator -(CustomType x) { return x; } public static CustomType operator !(CustomType x) { return x; } public static CustomType operator ~(CustomType x) { return x; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperatorMethod: CustomType CustomType.op_OnesComplement(CustomType x)) (OperationKind.Unary, Type: CustomType) (Syntax: '~Method()') Operand: IInvocationOperation ( CustomType A.Method()) (OperationKind.Invocation, Type: CustomType) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_LogicalNot_CustomType() { string source = @" class A { CustomType Method() { CustomType i = default(CustomType); return /*<bind>*/!Method()/*</bind>*/; } } public struct CustomType { public static CustomType operator +(CustomType x) { return x; } public static CustomType operator -(CustomType x) { return x; } public static CustomType operator !(CustomType x) { return x; } public static CustomType operator ~(CustomType x) { return x; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Not) (OperatorMethod: CustomType CustomType.op_LogicalNot(CustomType x)) (OperationKind.Unary, Type: CustomType) (Syntax: '!Method()') Operand: IInvocationOperation ( CustomType A.Method()) (OperationKind.Invocation, Type: CustomType) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(18135, "https://github.com/dotnet/roslyn/issues/18135")] [WorkItem(18160, "https://github.com/dotnet/roslyn/issues/18160")] public void Test_UnaryOperatorExpression_Type_And_TrueFalse() { string source = @" public struct S { private int value; public S(int v) { value = v; } public static S operator |(S x, S y) { return new S(x.value - y.value); } public static S operator &(S x, S y) { return new S(x.value + y.value); } public static bool operator true(S x) { return x.value > 0; } public static bool operator false(S x) { return x.value <= 0; } } class C { public void M() { var x = new S(2); var y = new S(1); /*<bind>*/if (x && y) { }/*</bind>*/ } } "; string expectedOperationTree = @" IConditionalOperation (OperationKind.Conditional, Type: null) (Syntax: 'if (x && y) { }') Condition: IUnaryOperation (UnaryOperatorKind.True) (OperatorMethod: System.Boolean S.op_True(S x)) (OperationKind.Unary, Type: System.Boolean, IsImplicit) (Syntax: 'x && y') Operand: IBinaryOperation (BinaryOperatorKind.ConditionalAnd) (OperatorMethod: S S.op_BitwiseAnd(S x, S y)) (OperationKind.Binary, Type: S) (Syntax: 'x && y') Left: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: S) (Syntax: 'x') Right: ILocalReferenceOperation: y (OperationKind.LocalReference, Type: S) (Syntax: 'y') WhenTrue: IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ }') WhenFalse: null "; VerifyOperationTreeForTest<IfStatementSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(18135, "https://github.com/dotnet/roslyn/issues/18135")] [WorkItem(18160, "https://github.com/dotnet/roslyn/issues/18160")] public void Test_UnaryOperatorExpression_Type_Or_TrueFalse() { string source = @" public struct S { private int value; public S(int v) { value = v; } public static S operator |(S x, S y) { return new S(x.value - y.value); } public static S operator &(S x, S y) { return new S(x.value + y.value); } public static bool operator true(S x) { return x.value > 0; } public static bool operator false(S x) { return x.value <= 0; } } class C { public void M() { var x = new S(2); var y = new S(1); /*<bind>*/if (x || y) { }/*</bind>*/ } } "; string expectedOperationTree = @" IConditionalOperation (OperationKind.Conditional, Type: null) (Syntax: 'if (x || y) { }') Condition: IUnaryOperation (UnaryOperatorKind.True) (OperatorMethod: System.Boolean S.op_True(S x)) (OperationKind.Unary, Type: System.Boolean, IsImplicit) (Syntax: 'x || y') Operand: IBinaryOperation (BinaryOperatorKind.ConditionalOr) (OperatorMethod: S S.op_BitwiseOr(S x, S y)) (OperationKind.Binary, Type: S) (Syntax: 'x || y') Left: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: S) (Syntax: 'x') Right: ILocalReferenceOperation: y (OperationKind.LocalReference, Type: S) (Syntax: 'y') WhenTrue: IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ }') WhenFalse: null "; VerifyOperationTreeForTest<IfStatementSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_With_CustomType_NoRightOperator() { string source = @" class A { CustomType Method() { CustomType i = default(CustomType); return /*<bind>*/+i/*</bind>*/; } } public struct CustomType { } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '+i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: CustomType, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_With_CustomType_DerivedTypes() { string source = @" class A { BaseType Method() { var i = default(DerivedType); return /*<bind>*/+i/*</bind>*/; } } public class BaseType { public static BaseType operator +(BaseType x) { return new BaseType(); } } public class DerivedType : BaseType { } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperatorMethod: BaseType BaseType.op_UnaryPlus(BaseType x)) (OperationKind.Unary, Type: BaseType) (Syntax: '+i') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: BaseType, IsImplicit) (Syntax: 'i') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: DerivedType) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_With_CustomType_ImplicitConversion() { string source = @" class A { BaseType Method() { var i = default(DerivedType); return /*<bind>*/+i/*</bind>*/; } } public class BaseType { public static BaseType operator +(BaseType x) { return new BaseType(); } } public class DerivedType { public static implicit operator BaseType(DerivedType x) { return new BaseType(); } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '+i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: DerivedType, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_With_CustomType_ExplicitConversion() { string source = @" class A { BaseType Method() { var i = default(DerivedType); return /*<bind>*/+i/*</bind>*/; } } public class BaseType { public static BaseType operator +(BaseType x) { return new BaseType(); } } public class DerivedType { public static explicit operator BaseType(DerivedType x) { return new BaseType(); } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '+i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: DerivedType, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_With_CustomType_Malformed_Operator() { string source = @" class A { BaseType Method() { var i = default(BaseType); return /*<bind>*/+i/*</bind>*/; } } public class BaseType { public static BaseType operator +(int x) { return new BaseType(); } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '+i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: BaseType, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] [WorkItem(18160, "https://github.com/dotnet/roslyn/issues/18160")] public void Test_BinaryExpressionSyntax_Type_And_TrueFalse_Condition() { string source = @" public struct S { private int value; public S(int v) { value = v; } public static S operator |(S x, S y) { return new S(x.value - y.value); } public static S operator &(S x, S y) { return new S(x.value + y.value); } public static bool operator true(S x) { return x.value > 0; } public static bool operator false(S x) { return x.value <= 0; } } class C { public void M() { var x = new S(2); var y = new S(1); if (/*<bind>*/x && y/*</bind>*/) { } } } "; string expectedOperationTree = @" IBinaryOperation (BinaryOperatorKind.ConditionalAnd) (OperatorMethod: S S.op_BitwiseAnd(S x, S y)) (OperationKind.Binary, Type: S) (Syntax: 'x && y') Left: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: S) (Syntax: 'x') Right: ILocalReferenceOperation: y (OperationKind.LocalReference, Type: S) (Syntax: 'y') "; VerifyOperationTreeForTest<BinaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_IncrementExpression() { string source = @" class A { int Method() { var i = 1; return /*<bind>*/++i/*</bind>*/; } } "; string expectedOperationTree = @" IIncrementOrDecrementOperation (Prefix) (OperationKind.Increment, Type: System.Int32) (Syntax: '++i') Target: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_DecrementExpression() { string source = @" class A { int Method() { var i = 1; return /*<bind>*/--i/*</bind>*/; } } "; string expectedOperationTree = @" IIncrementOrDecrementOperation (Prefix) (OperationKind.Decrement, Type: System.Int32) (Syntax: '--i') Target: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Nullable() { string source = @" class A { void Method() { var i = /*<bind>*/(int?)1/*</bind>*/; } } "; string expectedOperationTree = @" IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32?) (Syntax: '(int?)1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') "; VerifyOperationTreeForTest<CastExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Pointer() { string source = @" class A { unsafe void Method() { int[] a = new int[5] {10, 20, 30, 40, 50}; fixed (int* p = &a[0]) { int* p2 = p; int p1 = /*<bind>*/*p2/*</bind>*/; } } } "; string expectedOperationTree = @" IOperation: (OperationKind.None, Type: null) (Syntax: '*p2') Children(1): ILocalReferenceOperation: p2 (OperationKind.LocalReference, Type: System.Int32*) (Syntax: 'p2') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void VerifyLiftedUnaryOperators1() { var source = @" class C { void F(int? x) { var y = /*<bind>*/-x/*</bind>*/; } }"; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus, IsLifted) (OperationKind.Unary, Type: System.Int32?) (Syntax: '-x') Operand: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'x') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void VerifyNonLiftedUnaryOperators1() { var source = @" class C { void F(int x) { var y = /*<bind>*/-x/*</bind>*/; } }"; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Int32) (Syntax: '-x') Operand: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void VerifyLiftedUserDefinedUnaryOperators1() { var source = @" struct C { public static C operator -(C c) { } void F(C? x) { var y = /*<bind>*/-x/*</bind>*/; } }"; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus, IsLifted) (OperatorMethod: C C.op_UnaryNegation(C c)) (OperationKind.Unary, Type: C?) (Syntax: '-x') Operand: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: C?) (Syntax: 'x') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void VerifyNonLiftedUserDefinedUnaryOperators1() { var source = @" struct C { public static C operator -(C c) { } void F(C x) { var y = /*<bind>*/-x/*</bind>*/; } }"; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperatorMethod: C C.op_UnaryNegation(C c)) (OperationKind.Unary, Type: C) (Syntax: '-x') Operand: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: C) (Syntax: 'x') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void LogicalNotFlow_01() { string source = @" class P { void M(bool a, bool b) /*<bind>*/{ GetArray()[0] = !(a || b); }/*</bind>*/ static bool[] GetArray() => null; } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'GetArray()[0]') Value: IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.Boolean) (Syntax: 'GetArray()[0]') Array reference: IInvocationOperation (System.Boolean[] P.GetArray()) (OperationKind.Invocation, Type: System.Boolean[]) (Syntax: 'GetArray()') Instance Receiver: null Arguments(0) Indices(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Jump if True (Regular) to Block[B3] IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b') Value: IUnaryOperation (UnaryOperatorKind.Not) (OperationKind.Unary, Type: System.Boolean, IsImplicit) (Syntax: 'b') Operand: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Next (Regular) Block[B4] Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a') Value: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False, IsImplicit) (Syntax: 'a') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'GetArray()[ ... !(a || b);') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'GetArray()[ ... !(a || b)') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Boolean, IsImplicit) (Syntax: 'GetArray()[0]') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Boolean, IsImplicit) (Syntax: 'a || b') Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void LogicalNotFlow_02() { var source = @" class C { bool F(bool f) /*<bind>*/{ return !f; }/*</bind>*/ }"; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (0) Next (Return) Block[B2] IUnaryOperation (UnaryOperatorKind.Not) (OperationKind.Unary, Type: System.Boolean) (Syntax: '!f') Operand: IParameterReferenceOperation: f (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'f') Block[B2] - Exit Predecessors: [B1] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void LogicalNotFlow_03() { var source = @" class C { bool F(bool f) /*<bind>*/{ return !!f; }/*</bind>*/ }"; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (0) Next (Return) Block[B2] IParameterReferenceOperation: f (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'f') Block[B2] - Exit Predecessors: [B1] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void DynamicNotFlow_01() { string source = @" class P { void M(dynamic a, dynamic b) /*<bind>*/{ a = !b; }/*</bind>*/ } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a = !b;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: dynamic) (Syntax: 'a = !b') Left: IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'a') Right: IUnaryOperation (UnaryOperatorKind.Not) (OperationKind.Unary, Type: dynamic) (Syntax: '!b') Operand: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'b') Next (Regular) Block[B2] Block[B2] - Exit Predecessors: [B1] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [Fact] [CompilerTrait(CompilerFeature.IOperation)] public void VerifyIndexOperator_Int() { var compilation = CreateCompilationWithIndexAndRange(@" class Test { void M(int arg) { var x = /*<bind>*/^arg/*</bind>*/; } }").VerifyDiagnostics(); string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Hat) (OperationKind.Unary, Type: System.Index) (Syntax: '^arg') Operand: IParameterReferenceOperation: arg (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'arg') "; var operation = (IUnaryOperation)VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(compilation, expectedOperationTree); Assert.Null(operation.OperatorMethod); } [Fact] [CompilerTrait(CompilerFeature.IOperation)] public void VerifyIndexOperator_NullableInt() { var compilation = CreateCompilationWithIndexAndRange(@" class Test { void M(int? arg) { var x = /*<bind>*/^arg/*</bind>*/; } }").VerifyDiagnostics(); string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Hat, IsLifted) (OperationKind.Unary, Type: System.Index?) (Syntax: '^arg') Operand: IParameterReferenceOperation: arg (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'arg') "; var operation = (IUnaryOperation)VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(compilation, expectedOperationTree); Assert.Null(operation.OperatorMethod); } [Fact] [CompilerTrait(CompilerFeature.IOperation)] public void VerifyIndexOperator_ConvertibleToInt() { var compilation = CreateCompilationWithIndexAndRange(@" class Test { void M(byte arg) { var x = /*<bind>*/^arg/*</bind>*/; } }").VerifyDiagnostics(); string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Hat) (OperationKind.Unary, Type: System.Index) (Syntax: '^arg') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsImplicit) (Syntax: 'arg') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IParameterReferenceOperation: arg (OperationKind.ParameterReference, Type: System.Byte) (Syntax: 'arg') "; var operation = (IUnaryOperation)VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(compilation, expectedOperationTree); Assert.Null(operation.OperatorMethod); } } }
// Licensed to the .NET Foundation under one or more 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.Syntax; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class IOperationTests_IUnaryOperatorExpression : SemanticModelTestBase { [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17595, "https://github.com/dotnet/roslyn/issues/17591")] public void Test_UnaryOperatorExpression_Type_Plus_System_SByte() { string source = @" class A { System.SByte Method() { System.SByte i = default(System.SByte); return /*<bind>*/+i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '+i') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'i') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.SByte, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Plus_System_Byte() { string source = @" class A { System.Byte Method() { System.Byte i = default(System.Byte); return /*<bind>*/+i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '+i') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'i') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Byte, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Plus_System_Int16() { string source = @" class A { System.Int16 Method() { System.Int16 i = default(System.Int16); return /*<bind>*/+i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '+i') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'i') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int16, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Plus_System_UInt16() { string source = @" class A { System.UInt16 Method() { System.UInt16 i = default(System.UInt16); return /*<bind>*/+i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '+i') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'i') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.UInt16, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Plus_System_Int32() { string source = @" class A { System.Int32 Method() { System.Int32 i = default(System.Int32); return /*<bind>*/+i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.Int32) (Syntax: '+i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Plus_System_UInt32() { string source = @" class A { System.UInt32 Method() { System.UInt32 i = default(System.UInt32); return /*<bind>*/+i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.UInt32) (Syntax: '+i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.UInt32) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Plus_System_Int64() { string source = @" class A { System.Int64 Method() { System.Int64 i = default(System.Int64); return /*<bind>*/+i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.Int64) (Syntax: '+i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int64) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Plus_System_UInt64() { string source = @" class A { System.UInt64 Method() { System.UInt64 i = default(System.UInt64); return /*<bind>*/+i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.UInt64) (Syntax: '+i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.UInt64) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Plus_System_Char() { string source = @" class A { System.Char Method() { System.Char i = default(System.Char); return /*<bind>*/+i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '+i') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'i') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Char, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Plus_System_Decimal() { string source = @" class A { System.Decimal Method() { System.Decimal i = default(System.Decimal); return /*<bind>*/+i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.Decimal) (Syntax: '+i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Decimal) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Plus_System_Single() { string source = @" class A { System.Single Method() { System.Single i = default(System.Single); return /*<bind>*/+i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.Single) (Syntax: '+i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Single) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Plus_System_Double() { string source = @" class A { System.Double Method() { System.Double i = default(System.Double); return /*<bind>*/+i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.Double) (Syntax: '+i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Double) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Plus_System_Boolean() { string source = @" class A { System.Boolean Method() { System.Boolean i = default(System.Boolean); return /*<bind>*/+i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '+i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Boolean, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Plus_System_Object() { string source = @" class A { System.Object Method() { System.Object i = default(System.Object); return /*<bind>*/+i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '+i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Object, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Minus_System_SByte() { string source = @" class A { System.SByte Method() { System.SByte i = default(System.SByte); return /*<bind>*/-i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '-i') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'i') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.SByte, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Minus_System_Byte() { string source = @" class A { System.Byte Method() { System.Byte i = default(System.Byte); return /*<bind>*/-i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '-i') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'i') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Byte, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Minus_System_Int16() { string source = @" class A { System.Int16 Method() { System.Int16 i = default(System.Int16); return /*<bind>*/-i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '-i') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'i') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int16, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Minus_System_UInt16() { string source = @" class A { System.UInt16 Method() { System.UInt16 i = default(System.UInt16); return /*<bind>*/-i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '-i') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'i') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.UInt16, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Minus_System_Int32() { string source = @" class A { System.Int32 Method() { System.Int32 i = default(System.Int32); return /*<bind>*/-i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Int32) (Syntax: '-i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Minus_System_UInt32() { string source = @" class A { System.UInt32 Method() { System.UInt32 i = default(System.UInt32); return /*<bind>*/-i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Int64, IsInvalid) (Syntax: '-i') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int64, IsInvalid, IsImplicit) (Syntax: 'i') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.UInt32, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Minus_System_Int64() { string source = @" class A { System.Int64 Method() { System.Int64 i = default(System.Int64); return /*<bind>*/-i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Int64) (Syntax: '-i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int64) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Minus_System_UInt64() { string source = @" class A { System.UInt64 Method() { System.UInt64 i = default(System.UInt64); return /*<bind>*/-i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '-i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.UInt64, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Minus_System_Char() { string source = @" class A { System.Char Method() { System.Char i = default(System.Char); return /*<bind>*/-i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '-i') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'i') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Char, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Minus_System_Decimal() { string source = @" class A { System.Decimal Method() { System.Decimal i = default(System.Decimal); return /*<bind>*/-i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Decimal) (Syntax: '-i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Decimal) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Minus_System_Single() { string source = @" class A { System.Single Method() { System.Single i = default(System.Single); return /*<bind>*/-i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Single) (Syntax: '-i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Single) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Minus_System_Double() { string source = @" class A { System.Double Method() { System.Double i = default(System.Double); return /*<bind>*/-i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Double) (Syntax: '-i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Double) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Minus_System_Boolean() { string source = @" class A { System.Boolean Method() { System.Boolean i = default(System.Boolean); return /*<bind>*/-i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '-i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Boolean, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Minus_System_Object() { string source = @" class A { System.Object Method() { System.Object i = default(System.Object); return /*<bind>*/-i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '-i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Object, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Plus_System_SByte() { string source = @" class A { System.SByte Method() { System.SByte i = default(System.SByte); return /*<bind>*/+Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '+Method()') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'Method()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvocationOperation ( System.SByte A.Method()) (OperationKind.Invocation, Type: System.SByte, IsInvalid) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Plus_System_Byte() { string source = @" class A { System.Byte Method() { System.Byte i = default(System.Byte); return /*<bind>*/+Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '+Method()') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'Method()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvocationOperation ( System.Byte A.Method()) (OperationKind.Invocation, Type: System.Byte, IsInvalid) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Plus_System_Int16() { string source = @" class A { System.Int16 Method() { System.Int16 i = default(System.Int16); return /*<bind>*/+Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '+Method()') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'Method()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvocationOperation ( System.Int16 A.Method()) (OperationKind.Invocation, Type: System.Int16, IsInvalid) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Plus_System_UInt16() { string source = @" class A { System.UInt16 Method() { System.UInt16 i = default(System.UInt16); return /*<bind>*/+Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '+Method()') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'Method()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvocationOperation ( System.UInt16 A.Method()) (OperationKind.Invocation, Type: System.UInt16, IsInvalid) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Plus_System_Int32() { string source = @" class A { System.Int32 Method() { System.Int32 i = default(System.Int32); return /*<bind>*/+Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.Int32) (Syntax: '+Method()') Operand: IInvocationOperation ( System.Int32 A.Method()) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Plus_System_UInt32() { string source = @" class A { System.UInt32 Method() { System.UInt32 i = default(System.UInt32); return /*<bind>*/+Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.UInt32) (Syntax: '+Method()') Operand: IInvocationOperation ( System.UInt32 A.Method()) (OperationKind.Invocation, Type: System.UInt32) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Plus_System_Int64() { string source = @" class A { System.Int64 Method() { System.Int64 i = default(System.Int64); return /*<bind>*/+Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.Int64) (Syntax: '+Method()') Operand: IInvocationOperation ( System.Int64 A.Method()) (OperationKind.Invocation, Type: System.Int64) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Plus_System_UInt64() { string source = @" class A { System.UInt64 Method() { System.UInt64 i = default(System.UInt64); return /*<bind>*/+Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.UInt64) (Syntax: '+Method()') Operand: IInvocationOperation ( System.UInt64 A.Method()) (OperationKind.Invocation, Type: System.UInt64) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Plus_System_Char() { string source = @" class A { System.Char Method() { System.Char i = default(System.Char); return /*<bind>*/+Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '+Method()') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'Method()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvocationOperation ( System.Char A.Method()) (OperationKind.Invocation, Type: System.Char, IsInvalid) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Plus_System_Decimal() { string source = @" class A { System.Decimal Method() { System.Decimal i = default(System.Decimal); return /*<bind>*/+Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.Decimal) (Syntax: '+Method()') Operand: IInvocationOperation ( System.Decimal A.Method()) (OperationKind.Invocation, Type: System.Decimal) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Plus_System_Single() { string source = @" class A { System.Single Method() { System.Single i = default(System.Single); return /*<bind>*/+Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.Single) (Syntax: '+Method()') Operand: IInvocationOperation ( System.Single A.Method()) (OperationKind.Invocation, Type: System.Single) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Plus_System_Double() { string source = @" class A { System.Double Method() { System.Double i = default(System.Double); return /*<bind>*/+Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.Double) (Syntax: '+Method()') Operand: IInvocationOperation ( System.Double A.Method()) (OperationKind.Invocation, Type: System.Double) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Plus_System_Boolean() { string source = @" class A { System.Boolean Method() { System.Boolean i = default(System.Boolean); return /*<bind>*/+Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '+Method()') Operand: IInvocationOperation ( System.Boolean A.Method()) (OperationKind.Invocation, Type: System.Boolean, IsInvalid) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Plus_System_Object() { string source = @" class A { System.Object Method() { System.Object i = default(System.Object); return /*<bind>*/+Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '+Method()') Operand: IInvocationOperation ( System.Object A.Method()) (OperationKind.Invocation, Type: System.Object, IsInvalid) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Minus_System_SByte() { string source = @" class A { System.SByte Method() { System.SByte i = default(System.SByte); return /*<bind>*/-Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '-Method()') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'Method()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvocationOperation ( System.SByte A.Method()) (OperationKind.Invocation, Type: System.SByte, IsInvalid) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Minus_System_Byte() { string source = @" class A { System.Byte Method() { System.Byte i = default(System.Byte); return /*<bind>*/-Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '-Method()') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'Method()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvocationOperation ( System.Byte A.Method()) (OperationKind.Invocation, Type: System.Byte, IsInvalid) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Minus_System_Int16() { string source = @" class A { System.Int16 Method() { System.Int16 i = default(System.Int16); return /*<bind>*/-Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '-Method()') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'Method()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvocationOperation ( System.Int16 A.Method()) (OperationKind.Invocation, Type: System.Int16, IsInvalid) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Minus_System_UInt16() { string source = @" class A { System.UInt16 Method() { System.UInt16 i = default(System.UInt16); return /*<bind>*/-Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '-Method()') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'Method()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvocationOperation ( System.UInt16 A.Method()) (OperationKind.Invocation, Type: System.UInt16, IsInvalid) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Minus_System_Int32() { string source = @" class A { System.Int32 Method() { System.Int32 i = default(System.Int32); return /*<bind>*/-Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Int32) (Syntax: '-Method()') Operand: IInvocationOperation ( System.Int32 A.Method()) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Minus_System_UInt32() { string source = @" class A { System.UInt32 Method() { System.UInt32 i = default(System.UInt32); return /*<bind>*/-Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Int64, IsInvalid) (Syntax: '-Method()') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int64, IsInvalid, IsImplicit) (Syntax: 'Method()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvocationOperation ( System.UInt32 A.Method()) (OperationKind.Invocation, Type: System.UInt32, IsInvalid) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Minus_System_Int64() { string source = @" class A { System.Int64 Method() { System.Int64 i = default(System.Int64); return /*<bind>*/-Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Int64) (Syntax: '-Method()') Operand: IInvocationOperation ( System.Int64 A.Method()) (OperationKind.Invocation, Type: System.Int64) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Minus_System_UInt64() { string source = @" class A { System.UInt64 Method() { System.UInt64 i = default(System.UInt64); return /*<bind>*/-Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '-Method()') Operand: IInvocationOperation ( System.UInt64 A.Method()) (OperationKind.Invocation, Type: System.UInt64, IsInvalid) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Minus_System_Char() { string source = @" class A { System.Char Method() { System.Char i = default(System.Char); return /*<bind>*/-Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '-Method()') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'Method()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvocationOperation ( System.Char A.Method()) (OperationKind.Invocation, Type: System.Char, IsInvalid) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Minus_System_Decimal() { string source = @" class A { System.Decimal Method() { System.Decimal i = default(System.Decimal); return /*<bind>*/-Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Decimal) (Syntax: '-Method()') Operand: IInvocationOperation ( System.Decimal A.Method()) (OperationKind.Invocation, Type: System.Decimal) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Minus_System_Single() { string source = @" class A { System.Single Method() { System.Single i = default(System.Single); return /*<bind>*/-Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Single) (Syntax: '-Method()') Operand: IInvocationOperation ( System.Single A.Method()) (OperationKind.Invocation, Type: System.Single) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Minus_System_Double() { string source = @" class A { System.Double Method() { System.Double i = default(System.Double); return /*<bind>*/-Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Double) (Syntax: '-Method()') Operand: IInvocationOperation ( System.Double A.Method()) (OperationKind.Invocation, Type: System.Double) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Minus_System_Boolean() { string source = @" class A { System.Boolean Method() { System.Boolean i = default(System.Boolean); return /*<bind>*/-Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '-Method()') Operand: IInvocationOperation ( System.Boolean A.Method()) (OperationKind.Invocation, Type: System.Boolean, IsInvalid) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Minus_System_Object() { string source = @" class A { System.Object Method() { System.Object i = default(System.Object); return /*<bind>*/-Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '-Method()') Operand: IInvocationOperation ( System.Object A.Method()) (OperationKind.Invocation, Type: System.Object, IsInvalid) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_LogicalNot_System_Boolean() { string source = @" class A { System.Boolean Method() { System.Boolean i = default(System.Boolean); return /*<bind>*/!i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Not) (OperationKind.Unary, Type: System.Boolean) (Syntax: '!i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Boolean) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_LogicalNot_System_Boolean() { string source = @" class A { System.Boolean Method() { System.Boolean i = default(System.Boolean); return /*<bind>*/!Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Not) (OperationKind.Unary, Type: System.Boolean) (Syntax: '!Method()') Operand: IInvocationOperation ( System.Boolean A.Method()) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_BitwiseNot_System_SByte() { string source = @" class A { System.SByte Method() { System.SByte i = default(System.SByte); return /*<bind>*/~i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '~i') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'i') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.SByte, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_BitwiseNot_System_Byte() { string source = @" class A { System.Byte Method() { System.Byte i = default(System.Byte); return /*<bind>*/~i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '~i') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'i') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Byte, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_BitwiseNot_System_Int16() { string source = @" class A { System.Int16 Method() { System.Int16 i = default(System.Int16); return /*<bind>*/~i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '~i') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'i') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int16, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_BitwiseNot_System_UInt16() { string source = @" class A { System.UInt16 Method() { System.UInt16 i = default(System.UInt16); return /*<bind>*/~i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '~i') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'i') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.UInt16, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_BitwiseNot_System_Int32() { string source = @" class A { System.Int32 Method() { System.Int32 i = default(System.Int32); return /*<bind>*/~i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: System.Int32) (Syntax: '~i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_BitwiseNot_System_UInt32() { string source = @" class A { System.UInt32 Method() { System.UInt32 i = default(System.UInt32); return /*<bind>*/~i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: System.UInt32) (Syntax: '~i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.UInt32) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_BitwiseNot_System_Int64() { string source = @" class A { System.Int64 Method() { System.Int64 i = default(System.Int64); return /*<bind>*/~i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: System.Int64) (Syntax: '~i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int64) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_BitwiseNot_System_UInt64() { string source = @" class A { System.UInt64 Method() { System.UInt64 i = default(System.UInt64); return /*<bind>*/~i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: System.UInt64) (Syntax: '~i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.UInt64) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_BitwiseNot_System_Char() { string source = @" class A { System.Char Method() { System.Char i = default(System.Char); return /*<bind>*/~i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '~i') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'i') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Char, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_BitwiseNot_System_Decimal() { string source = @" class A { System.Decimal Method() { System.Decimal i = default(System.Decimal); return /*<bind>*/~i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '~i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Decimal, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_BitwiseNot_System_Single() { string source = @" class A { System.Single Method() { System.Single i = default(System.Single); return /*<bind>*/~i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '~i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Single, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_BitwiseNot_System_Double() { string source = @" class A { System.Double Method() { System.Double i = default(System.Double); return /*<bind>*/~i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '~i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Double, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_BitwiseNot_System_Boolean() { string source = @" class A { System.Boolean Method() { System.Boolean i = default(System.Boolean); return /*<bind>*/~i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '~i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Boolean, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_BitwiseNot_System_Object() { string source = @" class A { System.Object Method() { System.Object i = default(System.Object); return /*<bind>*/~i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '~i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Object, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_BitwiseNot_System_SByte() { string source = @" class A { System.SByte Method() { System.SByte i = default(System.SByte); return /*<bind>*/~Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '~Method()') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'Method()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvocationOperation ( System.SByte A.Method()) (OperationKind.Invocation, Type: System.SByte, IsInvalid) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_BitwiseNot_System_Byte() { string source = @" class A { System.Byte Method() { System.Byte i = default(System.Byte); return /*<bind>*/~Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '~Method()') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'Method()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvocationOperation ( System.Byte A.Method()) (OperationKind.Invocation, Type: System.Byte, IsInvalid) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_BitwiseNot_System_Int16() { string source = @" class A { System.Int16 Method() { System.Int16 i = default(System.Int16); return /*<bind>*/~Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '~Method()') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'Method()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvocationOperation ( System.Int16 A.Method()) (OperationKind.Invocation, Type: System.Int16, IsInvalid) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_BitwiseNot_System_UInt16() { string source = @" class A { System.UInt16 Method() { System.UInt16 i = default(System.UInt16); return /*<bind>*/~Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '~Method()') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'Method()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvocationOperation ( System.UInt16 A.Method()) (OperationKind.Invocation, Type: System.UInt16, IsInvalid) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_BitwiseNot_System_Int32() { string source = @" class A { System.Int32 Method() { System.Int32 i = default(System.Int32); return /*<bind>*/~Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: System.Int32) (Syntax: '~Method()') Operand: IInvocationOperation ( System.Int32 A.Method()) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_BitwiseNot_System_UInt32() { string source = @" class A { System.UInt32 Method() { System.UInt32 i = default(System.UInt32); return /*<bind>*/~Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: System.UInt32) (Syntax: '~Method()') Operand: IInvocationOperation ( System.UInt32 A.Method()) (OperationKind.Invocation, Type: System.UInt32) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_BitwiseNot_System_Int64() { string source = @" class A { System.Int64 Method() { System.Int64 i = default(System.Int64); return /*<bind>*/~Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: System.Int64) (Syntax: '~Method()') Operand: IInvocationOperation ( System.Int64 A.Method()) (OperationKind.Invocation, Type: System.Int64) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_BitwiseNot_System_UInt64() { string source = @" class A { System.UInt64 Method() { System.UInt64 i = default(System.UInt64); return /*<bind>*/~Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: System.UInt64) (Syntax: '~Method()') Operand: IInvocationOperation ( System.UInt64 A.Method()) (OperationKind.Invocation, Type: System.UInt64) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_BitwiseNot_System_Char() { string source = @" class A { System.Char Method() { System.Char i = default(System.Char); return /*<bind>*/~Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '~Method()') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'Method()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvocationOperation ( System.Char A.Method()) (OperationKind.Invocation, Type: System.Char, IsInvalid) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_BitwiseNot_System_Decimal() { string source = @" class A { System.Decimal Method() { System.Decimal i = default(System.Decimal); return /*<bind>*/~Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '~Method()') Operand: IInvocationOperation ( System.Decimal A.Method()) (OperationKind.Invocation, Type: System.Decimal, IsInvalid) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_BitwiseNot_System_Single() { string source = @" class A { System.Single Method() { System.Single i = default(System.Single); return /*<bind>*/~Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '~Method()') Operand: IInvocationOperation ( System.Single A.Method()) (OperationKind.Invocation, Type: System.Single, IsInvalid) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_BitwiseNot_System_Double() { string source = @" class A { System.Double Method() { System.Double i = default(System.Double); return /*<bind>*/~Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '~Method()') Operand: IInvocationOperation ( System.Double A.Method()) (OperationKind.Invocation, Type: System.Double, IsInvalid) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_BitwiseNot_System_Boolean() { string source = @" class A { System.Boolean Method() { System.Boolean i = default(System.Boolean); return /*<bind>*/~Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '~Method()') Operand: IInvocationOperation ( System.Boolean A.Method()) (OperationKind.Invocation, Type: System.Boolean, IsInvalid) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_BitwiseNot_System_Object() { string source = @" class A { System.Object Method() { System.Object i = default(System.Object); return /*<bind>*/~Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '~Method()') Operand: IInvocationOperation ( System.Object A.Method()) (OperationKind.Invocation, Type: System.Object, IsInvalid) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Plus_dynamic() { string source = @" class A { dynamic Method() { dynamic i = default(dynamic); return /*<bind>*/+i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: dynamic) (Syntax: '+i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: dynamic) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Minus_dynamic() { string source = @" class A { dynamic Method() { dynamic i = default(dynamic); return /*<bind>*/-i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: dynamic) (Syntax: '-i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: dynamic) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_BitwiseNot_dynamic() { string source = @" class A { dynamic Method() { dynamic i = default(dynamic); return /*<bind>*/~i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: dynamic) (Syntax: '~i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: dynamic) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_LogicalNot_dynamic() { string source = @" class A { dynamic Method() { dynamic i = default(dynamic); return /*<bind>*/!i/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Not) (OperationKind.Unary, Type: dynamic) (Syntax: '!i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: dynamic) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Plus_dynamic() { string source = @" class A { dynamic Method() { dynamic i = default(dynamic); return /*<bind>*/+Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: dynamic) (Syntax: '+Method()') Operand: IInvocationOperation ( dynamic A.Method()) (OperationKind.Invocation, Type: dynamic) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Minus_dynamic() { string source = @" class A { dynamic Method() { dynamic i = default(dynamic); return /*<bind>*/-Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: dynamic) (Syntax: '-Method()') Operand: IInvocationOperation ( dynamic A.Method()) (OperationKind.Invocation, Type: dynamic) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_BitwiseNot_dynamic() { string source = @" class A { dynamic Method() { dynamic i = default(dynamic); return /*<bind>*/~Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: dynamic) (Syntax: '~Method()') Operand: IInvocationOperation ( dynamic A.Method()) (OperationKind.Invocation, Type: dynamic) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_LogicalNot_dynamic() { string source = @" class A { dynamic Method() { dynamic i = default(dynamic); return /*<bind>*/!Method()/*</bind>*/; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Not) (OperationKind.Unary, Type: dynamic) (Syntax: '!Method()') Operand: IInvocationOperation ( dynamic A.Method()) (OperationKind.Invocation, Type: dynamic) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Plus_Enum() { string source = @" class A { Enum Method() { Enum i = default(Enum); return /*<bind>*/+i/*</bind>*/; } } enum Enum { A, B } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '+i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: Enum, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Minus_Enum() { string source = @" class A { Enum Method() { Enum i = default(Enum); return /*<bind>*/-i/*</bind>*/; } } enum Enum { A, B } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '-i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: Enum, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_BitwiseNot_Enum() { string source = @" class A { Enum Method() { Enum i = default(Enum); return /*<bind>*/~i/*</bind>*/; } } enum Enum { A, B } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: Enum) (Syntax: '~i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: Enum) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Plus_Enum() { string source = @" class A { Enum Method() { Enum i = default(Enum); return /*<bind>*/+Method()/*</bind>*/; } } enum Enum { A, B } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '+Method()') Operand: IInvocationOperation ( Enum A.Method()) (OperationKind.Invocation, Type: Enum, IsInvalid) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Minus_Enum() { string source = @" class A { Enum Method() { Enum i = default(Enum); return /*<bind>*/-Method()/*</bind>*/; } } enum Enum { A, B } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '-Method()') Operand: IInvocationOperation ( Enum A.Method()) (OperationKind.Invocation, Type: Enum, IsInvalid) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_BitwiseNot_Enum() { string source = @" class A { Enum Method() { Enum i = default(Enum); return /*<bind>*/~Method()/*</bind>*/; } } enum Enum { A, B } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: Enum) (Syntax: '~Method()') Operand: IInvocationOperation ( Enum A.Method()) (OperationKind.Invocation, Type: Enum) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Plus_CustomType() { string source = @" class A { CustomType Method() { CustomType i = default(CustomType); return /*<bind>*/+i/*</bind>*/; } } public struct CustomType { public static CustomType operator +(CustomType x) { return x; } public static CustomType operator -(CustomType x) { return x; } public static CustomType operator !(CustomType x) { return x; } public static CustomType operator ~(CustomType x) { return x; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperatorMethod: CustomType CustomType.op_UnaryPlus(CustomType x)) (OperationKind.Unary, Type: CustomType) (Syntax: '+i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: CustomType) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_Minus_CustomType() { string source = @" class A { CustomType Method() { CustomType i = default(CustomType); return /*<bind>*/-i/*</bind>*/; } } public struct CustomType { public static CustomType operator +(CustomType x) { return x; } public static CustomType operator -(CustomType x) { return x; } public static CustomType operator !(CustomType x) { return x; } public static CustomType operator ~(CustomType x) { return x; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperatorMethod: CustomType CustomType.op_UnaryNegation(CustomType x)) (OperationKind.Unary, Type: CustomType) (Syntax: '-i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: CustomType) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_BitwiseNot_CustomType() { string source = @" class A { CustomType Method() { CustomType i = default(CustomType); return /*<bind>*/~i/*</bind>*/; } } public struct CustomType { public static CustomType operator +(CustomType x) { return x; } public static CustomType operator -(CustomType x) { return x; } public static CustomType operator !(CustomType x) { return x; } public static CustomType operator ~(CustomType x) { return x; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperatorMethod: CustomType CustomType.op_OnesComplement(CustomType x)) (OperationKind.Unary, Type: CustomType) (Syntax: '~i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: CustomType) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Type_LogicalNot_CustomType() { string source = @" class A { CustomType Method() { CustomType i = default(CustomType); return /*<bind>*/!i/*</bind>*/; } } public struct CustomType { public static CustomType operator +(CustomType x) { return x; } public static CustomType operator -(CustomType x) { return x; } public static CustomType operator !(CustomType x) { return x; } public static CustomType operator ~(CustomType x) { return x; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Not) (OperatorMethod: CustomType CustomType.op_LogicalNot(CustomType x)) (OperationKind.Unary, Type: CustomType) (Syntax: '!i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: CustomType) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Plus_CustomType() { string source = @" class A { CustomType Method() { CustomType i = default(CustomType); return /*<bind>*/+Method()/*</bind>*/; } } public struct CustomType { public static CustomType operator +(CustomType x) { return x; } public static CustomType operator -(CustomType x) { return x; } public static CustomType operator !(CustomType x) { return x; } public static CustomType operator ~(CustomType x) { return x; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperatorMethod: CustomType CustomType.op_UnaryPlus(CustomType x)) (OperationKind.Unary, Type: CustomType) (Syntax: '+Method()') Operand: IInvocationOperation ( CustomType A.Method()) (OperationKind.Invocation, Type: CustomType) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_Minus_CustomType() { string source = @" class A { CustomType Method() { CustomType i = default(CustomType); return /*<bind>*/-Method()/*</bind>*/; } } public struct CustomType { public static CustomType operator +(CustomType x) { return x; } public static CustomType operator -(CustomType x) { return x; } public static CustomType operator !(CustomType x) { return x; } public static CustomType operator ~(CustomType x) { return x; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperatorMethod: CustomType CustomType.op_UnaryNegation(CustomType x)) (OperationKind.Unary, Type: CustomType) (Syntax: '-Method()') Operand: IInvocationOperation ( CustomType A.Method()) (OperationKind.Invocation, Type: CustomType) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_BitwiseNot_CustomType() { string source = @" class A { CustomType Method() { CustomType i = default(CustomType); return /*<bind>*/~Method()/*</bind>*/; } } public struct CustomType { public static CustomType operator +(CustomType x) { return x; } public static CustomType operator -(CustomType x) { return x; } public static CustomType operator !(CustomType x) { return x; } public static CustomType operator ~(CustomType x) { return x; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperatorMethod: CustomType CustomType.op_OnesComplement(CustomType x)) (OperationKind.Unary, Type: CustomType) (Syntax: '~Method()') Operand: IInvocationOperation ( CustomType A.Method()) (OperationKind.Invocation, Type: CustomType) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Method_LogicalNot_CustomType() { string source = @" class A { CustomType Method() { CustomType i = default(CustomType); return /*<bind>*/!Method()/*</bind>*/; } } public struct CustomType { public static CustomType operator +(CustomType x) { return x; } public static CustomType operator -(CustomType x) { return x; } public static CustomType operator !(CustomType x) { return x; } public static CustomType operator ~(CustomType x) { return x; } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Not) (OperatorMethod: CustomType CustomType.op_LogicalNot(CustomType x)) (OperationKind.Unary, Type: CustomType) (Syntax: '!Method()') Operand: IInvocationOperation ( CustomType A.Method()) (OperationKind.Invocation, Type: CustomType) (Syntax: 'Method()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method') Arguments(0) "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(18135, "https://github.com/dotnet/roslyn/issues/18135")] [WorkItem(18160, "https://github.com/dotnet/roslyn/issues/18160")] public void Test_UnaryOperatorExpression_Type_And_TrueFalse() { string source = @" public struct S { private int value; public S(int v) { value = v; } public static S operator |(S x, S y) { return new S(x.value - y.value); } public static S operator &(S x, S y) { return new S(x.value + y.value); } public static bool operator true(S x) { return x.value > 0; } public static bool operator false(S x) { return x.value <= 0; } } class C { public void M() { var x = new S(2); var y = new S(1); /*<bind>*/if (x && y) { }/*</bind>*/ } } "; string expectedOperationTree = @" IConditionalOperation (OperationKind.Conditional, Type: null) (Syntax: 'if (x && y) { }') Condition: IUnaryOperation (UnaryOperatorKind.True) (OperatorMethod: System.Boolean S.op_True(S x)) (OperationKind.Unary, Type: System.Boolean, IsImplicit) (Syntax: 'x && y') Operand: IBinaryOperation (BinaryOperatorKind.ConditionalAnd) (OperatorMethod: S S.op_BitwiseAnd(S x, S y)) (OperationKind.Binary, Type: S) (Syntax: 'x && y') Left: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: S) (Syntax: 'x') Right: ILocalReferenceOperation: y (OperationKind.LocalReference, Type: S) (Syntax: 'y') WhenTrue: IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ }') WhenFalse: null "; VerifyOperationTreeForTest<IfStatementSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(18135, "https://github.com/dotnet/roslyn/issues/18135")] [WorkItem(18160, "https://github.com/dotnet/roslyn/issues/18160")] public void Test_UnaryOperatorExpression_Type_Or_TrueFalse() { string source = @" public struct S { private int value; public S(int v) { value = v; } public static S operator |(S x, S y) { return new S(x.value - y.value); } public static S operator &(S x, S y) { return new S(x.value + y.value); } public static bool operator true(S x) { return x.value > 0; } public static bool operator false(S x) { return x.value <= 0; } } class C { public void M() { var x = new S(2); var y = new S(1); /*<bind>*/if (x || y) { }/*</bind>*/ } } "; string expectedOperationTree = @" IConditionalOperation (OperationKind.Conditional, Type: null) (Syntax: 'if (x || y) { }') Condition: IUnaryOperation (UnaryOperatorKind.True) (OperatorMethod: System.Boolean S.op_True(S x)) (OperationKind.Unary, Type: System.Boolean, IsImplicit) (Syntax: 'x || y') Operand: IBinaryOperation (BinaryOperatorKind.ConditionalOr) (OperatorMethod: S S.op_BitwiseOr(S x, S y)) (OperationKind.Binary, Type: S) (Syntax: 'x || y') Left: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: S) (Syntax: 'x') Right: ILocalReferenceOperation: y (OperationKind.LocalReference, Type: S) (Syntax: 'y') WhenTrue: IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ }') WhenFalse: null "; VerifyOperationTreeForTest<IfStatementSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_With_CustomType_NoRightOperator() { string source = @" class A { CustomType Method() { CustomType i = default(CustomType); return /*<bind>*/+i/*</bind>*/; } } public struct CustomType { } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '+i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: CustomType, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_With_CustomType_DerivedTypes() { string source = @" class A { BaseType Method() { var i = default(DerivedType); return /*<bind>*/+i/*</bind>*/; } } public class BaseType { public static BaseType operator +(BaseType x) { return new BaseType(); } } public class DerivedType : BaseType { } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperatorMethod: BaseType BaseType.op_UnaryPlus(BaseType x)) (OperationKind.Unary, Type: BaseType) (Syntax: '+i') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: BaseType, IsImplicit) (Syntax: 'i') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: DerivedType) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_With_CustomType_ImplicitConversion() { string source = @" class A { BaseType Method() { var i = default(DerivedType); return /*<bind>*/+i/*</bind>*/; } } public class BaseType { public static BaseType operator +(BaseType x) { return new BaseType(); } } public class DerivedType { public static implicit operator BaseType(DerivedType x) { return new BaseType(); } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '+i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: DerivedType, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_With_CustomType_ExplicitConversion() { string source = @" class A { BaseType Method() { var i = default(DerivedType); return /*<bind>*/+i/*</bind>*/; } } public class BaseType { public static BaseType operator +(BaseType x) { return new BaseType(); } } public class DerivedType { public static explicit operator BaseType(DerivedType x) { return new BaseType(); } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '+i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: DerivedType, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_With_CustomType_Malformed_Operator() { string source = @" class A { BaseType Method() { var i = default(BaseType); return /*<bind>*/+i/*</bind>*/; } } public class BaseType { public static BaseType operator +(int x) { return new BaseType(); } } "; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '+i') Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: BaseType, IsInvalid) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] [WorkItem(18160, "https://github.com/dotnet/roslyn/issues/18160")] public void Test_BinaryExpressionSyntax_Type_And_TrueFalse_Condition() { string source = @" public struct S { private int value; public S(int v) { value = v; } public static S operator |(S x, S y) { return new S(x.value - y.value); } public static S operator &(S x, S y) { return new S(x.value + y.value); } public static bool operator true(S x) { return x.value > 0; } public static bool operator false(S x) { return x.value <= 0; } } class C { public void M() { var x = new S(2); var y = new S(1); if (/*<bind>*/x && y/*</bind>*/) { } } } "; string expectedOperationTree = @" IBinaryOperation (BinaryOperatorKind.ConditionalAnd) (OperatorMethod: S S.op_BitwiseAnd(S x, S y)) (OperationKind.Binary, Type: S) (Syntax: 'x && y') Left: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: S) (Syntax: 'x') Right: ILocalReferenceOperation: y (OperationKind.LocalReference, Type: S) (Syntax: 'y') "; VerifyOperationTreeForTest<BinaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_IncrementExpression() { string source = @" class A { int Method() { var i = 1; return /*<bind>*/++i/*</bind>*/; } } "; string expectedOperationTree = @" IIncrementOrDecrementOperation (Prefix) (OperationKind.Increment, Type: System.Int32) (Syntax: '++i') Target: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_DecrementExpression() { string source = @" class A { int Method() { var i = 1; return /*<bind>*/--i/*</bind>*/; } } "; string expectedOperationTree = @" IIncrementOrDecrementOperation (Prefix) (OperationKind.Decrement, Type: System.Int32) (Syntax: '--i') Target: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Nullable() { string source = @" class A { void Method() { var i = /*<bind>*/(int?)1/*</bind>*/; } } "; string expectedOperationTree = @" IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32?) (Syntax: '(int?)1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') "; VerifyOperationTreeForTest<CastExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Test_UnaryOperatorExpression_Pointer() { string source = @" class A { unsafe void Method() { int[] a = new int[5] {10, 20, 30, 40, 50}; fixed (int* p = &a[0]) { int* p2 = p; int p1 = /*<bind>*/*p2/*</bind>*/; } } } "; string expectedOperationTree = @" IOperation: (OperationKind.None, Type: null) (Syntax: '*p2') Children(1): ILocalReferenceOperation: p2 (OperationKind.LocalReference, Type: System.Int32*) (Syntax: 'p2') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void VerifyLiftedUnaryOperators1() { var source = @" class C { void F(int? x) { var y = /*<bind>*/-x/*</bind>*/; } }"; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus, IsLifted) (OperationKind.Unary, Type: System.Int32?) (Syntax: '-x') Operand: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'x') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void VerifyNonLiftedUnaryOperators1() { var source = @" class C { void F(int x) { var y = /*<bind>*/-x/*</bind>*/; } }"; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Int32) (Syntax: '-x') Operand: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void VerifyLiftedUserDefinedUnaryOperators1() { var source = @" struct C { public static C operator -(C c) { } void F(C? x) { var y = /*<bind>*/-x/*</bind>*/; } }"; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus, IsLifted) (OperatorMethod: C C.op_UnaryNegation(C c)) (OperationKind.Unary, Type: C?) (Syntax: '-x') Operand: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: C?) (Syntax: 'x') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void VerifyNonLiftedUserDefinedUnaryOperators1() { var source = @" struct C { public static C operator -(C c) { } void F(C x) { var y = /*<bind>*/-x/*</bind>*/; } }"; string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Minus) (OperatorMethod: C C.op_UnaryNegation(C c)) (OperationKind.Unary, Type: C) (Syntax: '-x') Operand: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: C) (Syntax: 'x') "; VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void LogicalNotFlow_01() { string source = @" class P { void M(bool a, bool b) /*<bind>*/{ GetArray()[0] = !(a || b); }/*</bind>*/ static bool[] GetArray() => null; } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'GetArray()[0]') Value: IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.Boolean) (Syntax: 'GetArray()[0]') Array reference: IInvocationOperation (System.Boolean[] P.GetArray()) (OperationKind.Invocation, Type: System.Boolean[]) (Syntax: 'GetArray()') Instance Receiver: null Arguments(0) Indices(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Jump if True (Regular) to Block[B3] IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b') Value: IUnaryOperation (UnaryOperatorKind.Not) (OperationKind.Unary, Type: System.Boolean, IsImplicit) (Syntax: 'b') Operand: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Next (Regular) Block[B4] Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a') Value: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False, IsImplicit) (Syntax: 'a') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'GetArray()[ ... !(a || b);') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'GetArray()[ ... !(a || b)') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Boolean, IsImplicit) (Syntax: 'GetArray()[0]') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Boolean, IsImplicit) (Syntax: 'a || b') Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void LogicalNotFlow_02() { var source = @" class C { bool F(bool f) /*<bind>*/{ return !f; }/*</bind>*/ }"; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (0) Next (Return) Block[B2] IUnaryOperation (UnaryOperatorKind.Not) (OperationKind.Unary, Type: System.Boolean) (Syntax: '!f') Operand: IParameterReferenceOperation: f (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'f') Block[B2] - Exit Predecessors: [B1] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void LogicalNotFlow_03() { var source = @" class C { bool F(bool f) /*<bind>*/{ return !!f; }/*</bind>*/ }"; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (0) Next (Return) Block[B2] IParameterReferenceOperation: f (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'f') Block[B2] - Exit Predecessors: [B1] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void DynamicNotFlow_01() { string source = @" class P { void M(dynamic a, dynamic b) /*<bind>*/{ a = !b; }/*</bind>*/ } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a = !b;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: dynamic) (Syntax: 'a = !b') Left: IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'a') Right: IUnaryOperation (UnaryOperatorKind.Not) (OperationKind.Unary, Type: dynamic) (Syntax: '!b') Operand: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'b') Next (Regular) Block[B2] Block[B2] - Exit Predecessors: [B1] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [Fact] [CompilerTrait(CompilerFeature.IOperation)] public void VerifyIndexOperator_Int() { var compilation = CreateCompilationWithIndexAndRange(@" class Test { void M(int arg) { var x = /*<bind>*/^arg/*</bind>*/; } }").VerifyDiagnostics(); string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Hat) (OperationKind.Unary, Type: System.Index) (Syntax: '^arg') Operand: IParameterReferenceOperation: arg (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'arg') "; var operation = (IUnaryOperation)VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(compilation, expectedOperationTree); Assert.Null(operation.OperatorMethod); } [Fact] [CompilerTrait(CompilerFeature.IOperation)] public void VerifyIndexOperator_NullableInt() { var compilation = CreateCompilationWithIndexAndRange(@" class Test { void M(int? arg) { var x = /*<bind>*/^arg/*</bind>*/; } }").VerifyDiagnostics(); string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Hat, IsLifted) (OperationKind.Unary, Type: System.Index?) (Syntax: '^arg') Operand: IParameterReferenceOperation: arg (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'arg') "; var operation = (IUnaryOperation)VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(compilation, expectedOperationTree); Assert.Null(operation.OperatorMethod); } [Fact] [CompilerTrait(CompilerFeature.IOperation)] public void VerifyIndexOperator_ConvertibleToInt() { var compilation = CreateCompilationWithIndexAndRange(@" class Test { void M(byte arg) { var x = /*<bind>*/^arg/*</bind>*/; } }").VerifyDiagnostics(); string expectedOperationTree = @" IUnaryOperation (UnaryOperatorKind.Hat) (OperationKind.Unary, Type: System.Index) (Syntax: '^arg') Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsImplicit) (Syntax: 'arg') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IParameterReferenceOperation: arg (OperationKind.ParameterReference, Type: System.Byte) (Syntax: 'arg') "; var operation = (IUnaryOperation)VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(compilation, expectedOperationTree); Assert.Null(operation.OperatorMethod); } } }
-1
dotnet/roslyn
56,433
Only allow Contract.ThrowIfNull() to be called on nullable types
We had some places we were calling it on bools.
jasonmalinowski
"2021-09-16T01:20:43Z"
"2021-09-16T18:44:11Z"
736fc1b5e6e2847689c0154b3e5f23ea99dd56af
6d0f4e3f972ceb561b04574e7f957a4ff458e272
Only allow Contract.ThrowIfNull() to be called on nullable types. We had some places we were calling it on bools.
./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
56,433
Only allow Contract.ThrowIfNull() to be called on nullable types
We had some places we were calling it on bools.
jasonmalinowski
"2021-09-16T01:20:43Z"
"2021-09-16T18:44:11Z"
736fc1b5e6e2847689c0154b3e5f23ea99dd56af
6d0f4e3f972ceb561b04574e7f957a4ff458e272
Only allow Contract.ThrowIfNull() to be called on nullable types. We had some places we were calling it on bools.
./src/ExpressionEvaluator/Core/Test/ResultProvider/Debugger/Engine/DkmMisc.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 #region Assembly Microsoft.VisualStudio.Debugger.Engine, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a // References\Debugger\v2.0\Microsoft.VisualStudio.Debugger.Engine.dll #endregion using System; namespace Microsoft.VisualStudio.Debugger { public delegate void DkmCompletionRoutine<TResult>(TResult result); public static class DkmComponentManager { public static bool ReportCurrentNonFatalException(Exception currentException, string implementationName) { return true; } } public enum DkmDataCreationDisposition { CreateNew, CreateAlways } } namespace Microsoft.VisualStudio.Debugger.Evaluation { public enum DkmEvaluationResultAccessType { None = 0, Public, Private, Protected, Internal, } public enum DkmEvaluationResultStorageType { None = 0 } public enum DkmEvaluationResultTypeModifierFlags { None = 0 } public class DkmDataAddress { } } namespace Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation { public class DkmCompiledClrInspectionQuery { } } namespace Microsoft.VisualStudio.Debugger.CallStack { public class DkmStackWalkFrame { } }
// Licensed to the .NET Foundation under one or more 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 #region Assembly Microsoft.VisualStudio.Debugger.Engine, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a // References\Debugger\v2.0\Microsoft.VisualStudio.Debugger.Engine.dll #endregion using System; namespace Microsoft.VisualStudio.Debugger { public delegate void DkmCompletionRoutine<TResult>(TResult result); public static class DkmComponentManager { public static bool ReportCurrentNonFatalException(Exception currentException, string implementationName) { return true; } } public enum DkmDataCreationDisposition { CreateNew, CreateAlways } } namespace Microsoft.VisualStudio.Debugger.Evaluation { public enum DkmEvaluationResultAccessType { None = 0, Public, Private, Protected, Internal, } public enum DkmEvaluationResultStorageType { None = 0 } public enum DkmEvaluationResultTypeModifierFlags { None = 0 } public class DkmDataAddress { } } namespace Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation { public class DkmCompiledClrInspectionQuery { } } namespace Microsoft.VisualStudio.Debugger.CallStack { public class DkmStackWalkFrame { } }
-1
dotnet/roslyn
56,433
Only allow Contract.ThrowIfNull() to be called on nullable types
We had some places we were calling it on bools.
jasonmalinowski
"2021-09-16T01:20:43Z"
"2021-09-16T18:44:11Z"
736fc1b5e6e2847689c0154b3e5f23ea99dd56af
6d0f4e3f972ceb561b04574e7f957a4ff458e272
Only allow Contract.ThrowIfNull() to be called on nullable types. We had some places we were calling it on bools.
./src/Compilers/Core/Portable/PEWriter/MemberRefComparer.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.Diagnostics.CodeAnalysis; using Roslyn.Utilities; namespace Microsoft.Cci { internal sealed class MemberRefComparer : IEqualityComparer<ITypeMemberReference> { private readonly MetadataWriter _metadataWriter; internal MemberRefComparer(MetadataWriter metadataWriter) { _metadataWriter = metadataWriter; } public bool Equals(ITypeMemberReference? x, ITypeMemberReference? y) { if (x == y) { return true; } RoslynDebug.Assert(x is object && y is object); if (x.GetContainingType(_metadataWriter.Context) != y.GetContainingType(_metadataWriter.Context)) { if (_metadataWriter.GetMemberReferenceParent(x) != _metadataWriter.GetMemberReferenceParent(y)) { return false; } } if (x.Name != y.Name) { return false; } var xf = x as IFieldReference; var yf = y as IFieldReference; if (xf != null && yf != null) { return _metadataWriter.GetFieldSignatureIndex(xf) == _metadataWriter.GetFieldSignatureIndex(yf); } var xm = x as IMethodReference; var ym = y as IMethodReference; if (xm != null && ym != null) { return _metadataWriter.GetMethodSignatureHandle(xm) == _metadataWriter.GetMethodSignatureHandle(ym); } return false; } public int GetHashCode(ITypeMemberReference memberRef) { int hash = Hash.Combine(memberRef.Name, _metadataWriter.GetMemberReferenceParent(memberRef).GetHashCode()); var fieldRef = memberRef as IFieldReference; if (fieldRef != null) { hash = Hash.Combine(hash, _metadataWriter.GetFieldSignatureIndex(fieldRef).GetHashCode()); } else { var methodRef = memberRef as IMethodReference; if (methodRef != null) { hash = Hash.Combine(hash, _metadataWriter.GetMethodSignatureHandle(methodRef).GetHashCode()); } } return hash; } } }
// Licensed to the .NET Foundation under one or more 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.Diagnostics.CodeAnalysis; using Roslyn.Utilities; namespace Microsoft.Cci { internal sealed class MemberRefComparer : IEqualityComparer<ITypeMemberReference> { private readonly MetadataWriter _metadataWriter; internal MemberRefComparer(MetadataWriter metadataWriter) { _metadataWriter = metadataWriter; } public bool Equals(ITypeMemberReference? x, ITypeMemberReference? y) { if (x == y) { return true; } RoslynDebug.Assert(x is object && y is object); if (x.GetContainingType(_metadataWriter.Context) != y.GetContainingType(_metadataWriter.Context)) { if (_metadataWriter.GetMemberReferenceParent(x) != _metadataWriter.GetMemberReferenceParent(y)) { return false; } } if (x.Name != y.Name) { return false; } var xf = x as IFieldReference; var yf = y as IFieldReference; if (xf != null && yf != null) { return _metadataWriter.GetFieldSignatureIndex(xf) == _metadataWriter.GetFieldSignatureIndex(yf); } var xm = x as IMethodReference; var ym = y as IMethodReference; if (xm != null && ym != null) { return _metadataWriter.GetMethodSignatureHandle(xm) == _metadataWriter.GetMethodSignatureHandle(ym); } return false; } public int GetHashCode(ITypeMemberReference memberRef) { int hash = Hash.Combine(memberRef.Name, _metadataWriter.GetMemberReferenceParent(memberRef).GetHashCode()); var fieldRef = memberRef as IFieldReference; if (fieldRef != null) { hash = Hash.Combine(hash, _metadataWriter.GetFieldSignatureIndex(fieldRef).GetHashCode()); } else { var methodRef = memberRef as IMethodReference; if (methodRef != null) { hash = Hash.Combine(hash, _metadataWriter.GetMethodSignatureHandle(methodRef).GetHashCode()); } } return hash; } } }
-1
dotnet/roslyn
56,433
Only allow Contract.ThrowIfNull() to be called on nullable types
We had some places we were calling it on bools.
jasonmalinowski
"2021-09-16T01:20:43Z"
"2021-09-16T18:44:11Z"
736fc1b5e6e2847689c0154b3e5f23ea99dd56af
6d0f4e3f972ceb561b04574e7f957a4ff458e272
Only allow Contract.ThrowIfNull() to be called on nullable types. We had some places we were calling it on bools.
./src/Scripting/Core/Hosting/AssemblyLoader/AssemblyLoadResult.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.Scripting.Hosting { /// <summary> /// The result of loading an assembly reference to the interactive session. /// </summary> internal struct AssemblyLoadResult { /// <summary> /// True if the assembly was loaded by the assembly loader, false if has been loaded before. /// </summary> public bool IsSuccessful { get; } /// <summary> /// Full path to the physical assembly file (might be a shadow-copy of the original assembly file). /// </summary> public string Path { get; } /// <summary> /// Original assembly file path. /// </summary> public string OriginalPath { get; } internal static AssemblyLoadResult CreateSuccessful(string path, string originalPath) { return new AssemblyLoadResult(path, originalPath, isSuccessful: true); } internal static AssemblyLoadResult CreateAlreadyLoaded(string path, string originalPath) { return new AssemblyLoadResult(path, originalPath, isSuccessful: false); } public AssemblyLoadResult(string path, string originalPath, bool isSuccessful) { Path = path; OriginalPath = originalPath; IsSuccessful = isSuccessful; } } }
// Licensed to the .NET Foundation under one or more 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.Scripting.Hosting { /// <summary> /// The result of loading an assembly reference to the interactive session. /// </summary> internal struct AssemblyLoadResult { /// <summary> /// True if the assembly was loaded by the assembly loader, false if has been loaded before. /// </summary> public bool IsSuccessful { get; } /// <summary> /// Full path to the physical assembly file (might be a shadow-copy of the original assembly file). /// </summary> public string Path { get; } /// <summary> /// Original assembly file path. /// </summary> public string OriginalPath { get; } internal static AssemblyLoadResult CreateSuccessful(string path, string originalPath) { return new AssemblyLoadResult(path, originalPath, isSuccessful: true); } internal static AssemblyLoadResult CreateAlreadyLoaded(string path, string originalPath) { return new AssemblyLoadResult(path, originalPath, isSuccessful: false); } public AssemblyLoadResult(string path, string originalPath, bool isSuccessful) { Path = path; OriginalPath = originalPath; IsSuccessful = isSuccessful; } } }
-1